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>houhre/applog<file_sep>/dailylog.go package applog import ( "fmt" "os" "path/filepath" "time" "github.com/robfig/cron" ) const ( SpecLog = "@daily" SpecLogHours = "@hourly" SpecLogMinute = "@every 1m" SpecLogSecond = "@every 10s" ) //Auto Daily Save Log Manager type AutoDailyLoger struct { dir string prefix string file *os.File cron *cron.Cron level string } func NewAutoDailyLoger(dir string, prefix string, level string) *AutoDailyLoger { c := cron.New() //init output 2006-01-02 15:04:05 name := fmt.Sprintf("%v.log", filepath.Join(dir, prefix+time.Now().Format("20060102"))) fmt.Println("dir = ", dir, " ,name = ", name) os.MkdirAll(dir, 0777) file, _ := os.OpenFile(name, os.O_CREATE|os.O_RDWR|os.O_APPEND, 0755) if file != nil { SetOutput(file) } lvl, err := ParseLevel(level) if err == nil { SetLevel(lvl) } SetFlags(Llongfile | LstdFlags) s := &AutoDailyLoger{ dir: dir, prefix: prefix, cron: c, file: file, } c.AddFunc(SpecLog, s.changeLogerFile) return s } func (s *AutoDailyLoger) Start() { s.cron.Start() Info("AutoDailyLoger start") } func (s *AutoDailyLoger) Stop() { s.cron.Stop() Info("AutoDailyLoger stop") if s.file != nil { s.file.Close() s.file = nil } } func (s *AutoDailyLoger) changeLogerFile() { //r std.mu.Unlock() if s.file != nil { s.file.Close() s.file = nil } name := fmt.Sprintf("%v.log", filepath.Join(s.dir, s.prefix+time.Now().Format("20060102"))) os.MkdirAll(s.dir, 0777) file, err := os.OpenFile(name, os.O_CREATE|os.O_RDWR|os.O_APPEND, 0755) fmt.Println("file error", file, file.Name(), err) if file != nil { SetOutput(file) s.file = file } Info("changeLogerFile OK!!!") } <file_sep>/logger.go package applog import ( "fmt" "io" "os" "runtime" "sync" "time" ) const CallPath = 3 type Logger struct { // The logs are `io.Copy`'d to this in a mutex. It's common to set this to a // file, or leave it default which is `os.Stderr`. You can also set this to // something more adventorous, such as logging to Kafka. Out io.Writer // Used to sync writing to the log. Locking is enabled by Default mu sync.Mutex // The logging level the logger should log at. This is typically (and defaults // to) `logrus.Info`, which allows Info(), Warn(), Error() and Fatal() to be // logged. `logrus.Debug` is useful in Level Level // properties flag int // for accumulating text to write buf []byte } type MutexWrap struct { lock sync.Mutex disabled bool } func (mw *MutexWrap) Lock() { if !mw.disabled { mw.lock.Lock() } } func (mw *MutexWrap) Unlock() { if !mw.disabled { mw.lock.Unlock() } } func (mw *MutexWrap) Disable() { mw.disabled = true } // It's recommended to make this a global instance called `log`. func New() *Logger { return &Logger{ Out: os.Stderr, Level: InfoLevel, flag: LstdFlags, } } // Cheap integer to fixed-width decimal ASCII. Give a negative width to avoid zero-padding. func itoa(buf *[]byte, i int, wid int) { // Assemble decimal in reverse order. var b [20]byte bp := len(b) - 1 for i >= 10 || wid > 1 { wid-- q := i / 10 b[bp] = byte('0' + i - q*10) bp-- i = q } // i < 10 b[bp] = byte('0' + i) *buf = append(*buf, b[bp:]...) } func (l *Logger) formatHeader(buf *[]byte, t time.Time, file string, line int) { //*buf = append(*buf, l.prefix...) if l.flag&LUTC != 0 { t = t.UTC() } if l.flag&(Ldate|Ltime|Lmicroseconds) != 0 { if l.flag&Ldate != 0 { year, month, day := t.Date() itoa(buf, year, 4) *buf = append(*buf, '/') itoa(buf, int(month), 2) *buf = append(*buf, '/') itoa(buf, day, 2) *buf = append(*buf, ' ') } if l.flag&(Ltime|Lmicroseconds) != 0 { hour, min, sec := t.Clock() itoa(buf, hour, 2) *buf = append(*buf, ':') itoa(buf, min, 2) *buf = append(*buf, ':') itoa(buf, sec, 2) if l.flag&Lmicroseconds != 0 { *buf = append(*buf, '.') itoa(buf, t.Nanosecond()/1e3, 6) } *buf = append(*buf, ' ') } } if l.flag&(Lshortfile|Llongfile) != 0 { if l.flag&Lshortfile != 0 { short := file for i := len(file) - 1; i > 0; i-- { if file[i] == '/' { short = file[i+1:] break } } file = short } *buf = append(*buf, file...) *buf = append(*buf, ':') itoa(buf, line, -1) *buf = append(*buf, ": "...) } } func (l *Logger) Output(calldepth int, s string) error { now := time.Now() var file string var line int l.mu.Lock() defer l.mu.Unlock() if l.flag&(Lshortfile|Llongfile) != 0 { // release lock while getting caller info - it's expensive. l.mu.Unlock() var ok bool _, file, line, ok = runtime.Caller(calldepth) if !ok { file = "???" line = 0 } l.mu.Lock() } l.buf = l.buf[:0] l.formatHeader(&l.buf, now, file, line) l.buf = append(l.buf, s...) if len(s) == 0 || s[len(s)-1] != '\n' { l.buf = append(l.buf, '\n') } _, err := l.Out.Write(l.buf) return err } func (l *Logger) Debugf(format string, args ...interface{}) { if l.Level >= DebugLevel { //fmt.Fprintf(l.Out, "[level=debug] "+format+"%s", args, "\n") l.Output(CallPath, fmt.Sprintf("[level=debug] "+format, args...)+"\n") //log.Printf("[level=debug] "+format, args, "\n") } } func (l *Logger) Infof(format string, args ...interface{}) { if l.Level >= InfoLevel { //fmt.Fprintf(l.Out, "[level=info] "+format+"%s", args, "\n") l.Output(CallPath, fmt.Sprintf("[level=info] "+format, args...)+"\n") } } func (l *Logger) Printf(format string, args ...interface{}) { //fmt.Fprintf(l.Out, format+"%s", args, "\n") l.Output(CallPath, fmt.Sprintf(format+"%s", args...)+"\n") } func (l *Logger) Warnf(format string, args ...interface{}) { if l.Level >= WarnLevel { //fmt.Fprintf(l.Out, "[level=warning] "+format+"%s", args, "\n") l.Output(CallPath, fmt.Sprintf("[level=warning] "+format, args...)+"\n") } } func (l *Logger) Warningf(format string, args ...interface{}) { if l.Level >= WarnLevel { //fmt.Fprintf(l.Out, "[level=warning] "+format+"%s", args, "\n") l.Output(CallPath, fmt.Sprintf("[level=warning] "+format, args...)+"\n") } } func (l *Logger) Errorf(format string, args ...interface{}) { if l.Level >= ErrorLevel { //fmt.Fprintf(l.Out, "[level=error] "+format+"%s", args, "\n") l.Output(CallPath, fmt.Sprintf("[level=error] "+format, args...)+"\n") } } func (l *Logger) Debug(args ...interface{}) { if l.Level >= DebugLevel { //fmt.Fprint(l.Out, "[level=debug] ", args, "\n") l.Output(CallPath, "[level=debug] "+fmt.Sprintln(args...)) } } func (l *Logger) Info(args ...interface{}) { if l.Level >= InfoLevel { //fmt.Fprint(l.Out, "[level=info] ", args, "\n") l.Output(CallPath, "[level=info] "+fmt.Sprintln(args...)) } } func (l *Logger) Print(args ...interface{}) { //fmt.Fprint(l.Out, args, "\n") l.Output(CallPath, fmt.Sprintln(args...)) } func (l *Logger) Warn(args ...interface{}) { if l.Level >= WarnLevel { //fmt.Fprint(l.Out, "[level=warning] ", args, "\n") l.Output(CallPath, "[level=warning] "+fmt.Sprintln(args...)) } } func (l *Logger) Warning(args ...interface{}) { if l.Level >= WarnLevel { //fmt.Fprint(l.Out, "[level=warning] ", args, "\n") l.Output(CallPath, "[level=warning] "+fmt.Sprintln(args...)) } } func (l *Logger) Error(args ...interface{}) { if l.Level >= ErrorLevel { //fmt.Fprint(l.Out, "[level=error] ", args, "\n") l.Output(CallPath, "[level=error] "+fmt.Sprintln(args...)) } } func (l *Logger) Debugln(args ...interface{}) { if l.Level >= DebugLevel { //fmt.Fprintln(l.Out, "[level=debug] ", args) l.Output(CallPath, "[level=debug] "+fmt.Sprintln(args...)) } } func (l *Logger) Infoln(args ...interface{}) { if l.Level >= InfoLevel { //fmt.Fprintln(l.Out, "[level=info] ", args) l.Output(CallPath, "[level=info] "+fmt.Sprintln(args...)) } } func (l *Logger) Println(args ...interface{}) { //fmt.Fprintln(l.Out, args) l.Output(CallPath, fmt.Sprintln(args...)) } func (l *Logger) Warnln(args ...interface{}) { if l.Level >= WarnLevel { //fmt.Fprintln(l.Out, "[level=warning] ", args) l.Output(CallPath, "[level=warning] "+fmt.Sprintln(args...)) } } func (l *Logger) Warningln(args ...interface{}) { if l.Level >= WarnLevel { //fmt.Fprintln(l.Out, "[level=warning] ", args) l.Output(CallPath, "[level=warning] "+fmt.Sprintln(args...)) } } func (l *Logger) Errorln(args ...interface{}) { if l.Level >= ErrorLevel { //fmt.Fprintln(l.Out, "[level=error] ", args) l.Output(CallPath, "[level=error] "+fmt.Sprintln(args...)) } } <file_sep>/README.md APPLog Designed by Golang # 日志记录服务, 可以定时切换日志文件 引用定时服务包 "github.com/robfig/cron" # Example import "applog" logger = applog.NewAutoDailyLoger("D:\log", "log", "info") logger.Start() defer logger.Stop()<file_sep>/logrus.go package applog import ( "fmt" "strings" ) // Level type type Level uint8 const ( // PanicLevel level, highest level of severity. Logs and then calls panic with the // message passed to Debug, Info, ... PanicLevel Level = iota // FatalLevel level. Logs and then calls `os.Exit(1)`. It will exit even if the // logging level is set to Panic. FatalLevel // ErrorLevel level. Logs. Used for errors that should definitely be noted. // Commonly used for hooks to send errors to an error tracking service. ErrorLevel // WarnLevel level. Non-critical entries that deserve eyes. WarnLevel // InfoLevel level. General operational entries about what's going on inside the // application. InfoLevel // DebugLevel level. Usually only enabled when debugging. Very verbose logging. DebugLevel ) // These flags define which text to prefix to each log entry generated by the Logger. const ( // Bits or'ed together to control what's printed. // There is no control over the order they appear (the order listed // here) or the format they present (as described in the comments). // The prefix is followed by a colon only when Llongfile or Lshortfile // is specified. // For example, flags Ldate | Ltime (or LstdFlags) produce, // 2009/01/23 01:23:23 message // while flags Ldate | Ltime | Lmicroseconds | Llongfile produce, // 2009/01/23 01:23:23.123123 /a/b/c/d.go:23: message Ldate = 1 << iota // the date in the local time zone: 2009/01/23 Ltime // the time in the local time zone: 01:23:23 Lmicroseconds // microsecond resolution: 01:23:23.123123. assumes Ltime. Llongfile // full file name and line number: /a/b/c/d.go:23 Lshortfile // final file name element and line number: d.go:23. overrides Llongfile LUTC // if Ldate or Ltime is set, use UTC rather than the local time zone LstdFlags = Ldate | Ltime // initial values for the standard logger ) // Convert the Level to a string. E.g. PanicLevel becomes "panic". func (level Level) String() string { switch level { case DebugLevel: return "debug" case InfoLevel: return "info" case WarnLevel: return "warning" case ErrorLevel: return "error" case FatalLevel: return "fatal" case PanicLevel: return "panic" } return "unknown" } // ParseLevel takes a string level and returns the Logrus log level constant. func ParseLevel(lvl string) (Level, error) { switch strings.ToLower(lvl) { case "panic": return PanicLevel, nil case "fatal": return FatalLevel, nil case "error": return ErrorLevel, nil case "warn", "warning": return WarnLevel, nil case "info": return InfoLevel, nil case "debug": return DebugLevel, nil } var l Level return l, fmt.Errorf("not a valid logrus Level: %q", lvl) } // The FieldLogger interface generalizes the Entry and Logger types type FieldLogger interface { Debugf(format string, args ...interface{}) Infof(format string, args ...interface{}) Printf(format string, args ...interface{}) Warnf(format string, args ...interface{}) Warningf(format string, args ...interface{}) Errorf(format string, args ...interface{}) Debug(args ...interface{}) Info(args ...interface{}) Print(args ...interface{}) Warn(args ...interface{}) Warning(args ...interface{}) Error(args ...interface{}) Debugln(args ...interface{}) Infoln(args ...interface{}) Println(args ...interface{}) Warnln(args ...interface{}) Warningln(args ...interface{}) Errorln(args ...interface{}) } <file_sep>/exported.go package applog import ( "fmt" "io" ) var ( // std is the name of the standard logger in stdlib `log` std = New() ) func init() { fmt.Println("applog init") } func StandardLogger() *Logger { return std } // SetOutput sets the standard logger output. func SetOutput(out io.Writer) { std.mu.Lock() defer std.mu.Unlock() std.Out = out } //When file is opened with appending mode, it's safe to //write concurrently to a file (within 4k message on Linux). //In these cases user can choose to disable the lock. func (logger *Logger) SetNoLock() { //logger.mu.Disable() } // SetLevel sets the standard logger level. func SetLevel(level Level) { std.mu.Lock() defer std.mu.Unlock() std.Level = level } // SetFlags sets the output flags for the logger. func SetFlags(flag int) { std.mu.Lock() defer std.mu.Unlock() std.flag = flag } // Debug logs a message at level Debug on the standard logger. func Debug(args ...interface{}) { std.Debug(args...) } // Print logs a message at level Info on the standard logger. func Print(args ...interface{}) { std.Print(args...) } // Info logs a message at level Info on the standard logger. func Info(args ...interface{}) { std.Info(args...) } // Warn logs a message at level Warn on the standard logger. func Warn(args ...interface{}) { std.Warn(args...) } // Warning logs a message at level Warn on the standard logger. func Warning(args ...interface{}) { std.Warning(args...) } // Error logs a message at level Error on the standard logger. func Error(args ...interface{}) { std.Error(args...) } // Debugf logs a message at level Debug on the standard logger. func Debugf(format string, args ...interface{}) { std.Debugf(format, args...) } // Printf logs a message at level Info on the standard logger. func Printf(format string, args ...interface{}) { std.Printf(format, args...) } // Infof logs a message at level Info on the standard logger. func Infof(format string, args ...interface{}) { std.Infof(format, args...) } // Warnf logs a message at level Warn on the standard logger. func Warnf(format string, args ...interface{}) { std.Warnf(format, args...) } // Warningf logs a message at level Warn on the standard logger. func Warningf(format string, args ...interface{}) { std.Warningf(format, args...) } // Errorf logs a message at level Error on the standard logger. func Errorf(format string, args ...interface{}) { std.Errorf(format, args...) } // Debugln logs a message at level Debug on the standard logger. func Debugln(args ...interface{}) { std.Debugln(args...) } // Println logs a message at level Info on the standard logger. func Println(args ...interface{}) { std.Println(args...) } // Infoln logs a message at level Info on the standard logger. func Infoln(args ...interface{}) { std.Infoln(args...) } // Warnln logs a message at level Warn on the standard logger. func Warnln(args ...interface{}) { std.Warnln(args...) } // Warningln logs a message at level Warn on the standard logger. func Warningln(args ...interface{}) { std.Warningln(args...) } // Errorln logs a message at level Error on the standard logger. func Errorln(args ...interface{}) { std.Errorln(args...) }
aab7ba17b7334bb3fdc662dc9dba6d5f454bba44
[ "Markdown", "Go" ]
5
Go
houhre/applog
c05e544719c317f1d175c81e586f7d3b9d6009c9
ead4fc6c32a908c62a16391d9321e3e035c6e6b5
refs/heads/main
<file_sep>import React, { useEffect, useState } from 'react'; export default function TodayDate(props) { const [intervalTime, setIntervalTime] = useState() const date = new Date(new Date().toLocaleString('en-US', { timeZone: props.TimeZone })); const Year = date.getFullYear(); const Month = date.getMonth(); const Months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]; const Day = date.getDay(); const Days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']; const NumDay = date.getDate(); const FullYear = `${Days[Day]} ${Months[Month]} ${NumDay} ${Year}`; const Hours = date.getHours(); const Minutes = date.getMinutes(); const Seconds = date.getSeconds(); let Time = `${Hours}:${Minutes}:${Seconds}`; if (Hours < 10) { if (Minutes < 10) { if (Seconds < 10) { Time = `0${Hours}:0${Minutes}:0${Seconds}`; } else { Time = `0${Hours}:0${Minutes}:${Seconds}`; } } else { if (Seconds < 10) { Time = `0${Hours}:${Minutes}:0${Seconds}`; } else { Time = `0${Hours}:${Minutes}:${Seconds}`; } } } else { if (Minutes < 10) { if (Seconds < 10) { Time = `${Hours}:0${Minutes}:0${Seconds}`; } else { Time = `${Hours}:0${Minutes}:${Seconds}`; } } else { if (Seconds < 10) { Time = `${Hours}:${Minutes}:0${Seconds}`; } else { Time = `${Hours}:${Minutes}:${Seconds}`; } } } useEffect(() => { const interval = setInterval(() => setIntervalTime(Time), 1000); return () => clearInterval(interval) }) return ( <React.Fragment> <p className='FullYear'>{FullYear}</p> <p className='Time'>{intervalTime}</p> </React.Fragment> ) };<file_sep>import React, { useEffect, useState } from 'react'; import TodayDate from './TodayDate'; /* TODO: *Need to work about the style of description. DONE *Add local time anywhere on its own. DONE *Add current location. DONE */ export default function Weather() { const [weather, setWeather] = useState({ City: '', Temp: '', Icon: '', Description: '' }) const API_key = '<KEY>'; const lang = 'en'; const [timeZone, setTimeZone] = useState(); const [locationAPI, setLocationAPI] = useState(`https://api.openweathermap.org/data/2.5/weather?lat=${31.771959}&lon=${35.217018}&appid=${API_key}&lang=${lang}`); const [todayDateCondition, setTodayDateCondition] = useState(); useEffect(() => { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition((position) => { console.log(position.coords) setLocationAPI(`https://api.openweathermap.org/data/2.5/weather?lat=${position.coords.latitude}&lon=${position.coords.longitude}&appid=${API_key}&lang=${lang}`); }) } else { console.log(`This browser don't support geolocation`); } }, []); useEffect( () => { // Returns the weather. fetch(locationAPI) .then((response) => { return response.json(); }) .then((data) => { fetch(`https://api.openweathermap.org/data/2.5/onecall?lat=${data.coord.lat}&lon=${data.coord.lon}&exclude=current&appid=${API_key}`) .then((response) => response.json()) .then((data2) => { setTimeZone(data2.timezone) }) setWeather({ City: data.name, Temp: `${Math.floor(data.main.temp - 273.15)}°C`, Icon: <img className='Icon' src={`https://openweathermap.org/img/wn/${data.weather[0].icon}@2x.png`} alt={data.weather[0].icon} />, Description: data.weather[0].description }) setTodayDateCondition(true) console.log(data) }) .catch((data) => { setWeather({ City: 'Not Found', }) setTodayDateCondition(false) throw data }) }, [locationAPI]); return ( <React.Fragment> <input type='text' className='InputSearch' placeholder='Search...' onKeyPress={e => { if (e.key === 'Enter') { setLocationAPI(`https://api.openweathermap.org/data/2.5/weather?q=${e.target.value}&lang=${lang}&appid=${API_key}&lang=${lang}`) } }} /> <p className='CityName'>{weather.City}</p> {todayDateCondition && <TodayDate TimeZone={timeZone} />} <p className='Description'>{weather.Description}</p> <div className='TempAndIcon'> <p className='Temp'>{weather.Temp}</p> {weather.Icon} </div> </React.Fragment > ) };
b77f858ff5f0e8e0d90e128614757f8dc55b385f
[ "JavaScript" ]
2
JavaScript
ElAv252/Weather-app
44947cd0bc7ff35c7af49ddeaea07d0e11d34aff
78cee30ba6f16fdcdc01577ef55f48dfff692290
refs/heads/main
<repo_name>hhavnursangappa/CPP-Projects<file_sep>/OpenCV-Projects/Document-Scanner/Scanner.cpp // Include necessary libraries #include "stdafx.h" #include <direct.h> #include <iostream> #include <opencv2/imgproc.hpp> #include <opencv2/highgui.hpp> #include <opencv2/imgcodecs.hpp> // Declare the namespaces to be used using namespace cv; using namespace std; // Define the global variables Mat img, imgCrop; Mat imgThresh, finalImage; vector<Point> bigContour; float imgWidth = 480.0; float imgHeight = 640.0; // Define the pre-processing function Mat preProcessing(Mat img) { Mat imgGray, imgCanny, imgDilate, imgErode; resize(img, img, Size(imgWidth, imgHeight)); cvtColor(img, imgGray, COLOR_BGR2GRAY); Canny(imgGray, imgCanny, 200, 200); Mat kernel = getStructuringElement(MORPH_RECT, Size(3, 3)); dilate(imgCanny, imgDilate, kernel); erode(imgDilate, imgErode, kernel); return imgErode; } // Define the getContours function vector<Point> getContours(Mat imgThresh, double minArea) { vector<vector<Point>> contours; vector<Vec4i> hierarchy; // Vector with 4 integers inside of it vector<Point> biggestContour; double areaCtr; double perimeter; int maxArea = 0; findContours(imgThresh, contours, hierarchy, RETR_EXTERNAL, CHAIN_APPROX_NONE); vector<vector<Point>> approx(contours.size()); vector<Rect> boundRect(contours.size()); for (int ii=0; ii < contours.size(); ii++) { areaCtr = contourArea(contours[ii]); if (areaCtr >= minArea) { perimeter = arcLength(contours[ii], true); approxPolyDP(contours[ii], approx[ii], 0.02*perimeter, true); if (areaCtr > maxArea && approx[ii].size() == 4) { biggestContour = { approx[ii][0], approx[ii][1], approx[ii][2], approx[ii][3] }; maxArea = areaCtr; } drawContours(img, approx, ii, Scalar(255, 0, 255), 3); } } return biggestContour; } // Define a funcion to re-arrange the points in the contour vector<Point> reShape(vector<Point> contour) { vector<Point> newPoints; vector <int> sumPoint, subPoint; for (int jj = 0; jj < contour.size(); jj++) { sumPoint.push_back(contour[jj].x + contour[jj].y); subPoint.push_back(contour[jj].x - contour[jj].y); } Point firstPoint = contour[min_element(sumPoint.begin(), sumPoint.end()) - sumPoint.begin()]; // top-left corner (0) Point fourthPoint = contour[max_element(sumPoint.begin(), sumPoint.end()) - sumPoint.begin()]; // bottom-right corner (3) Point secondPoint = contour[max_element(subPoint.begin(), subPoint.end()) - subPoint.begin()]; // top-right corner (1) Point thirdPoint = contour[min_element(subPoint.begin(), subPoint.end()) - subPoint.begin()]; // bottom-left corner (2) newPoints.push_back(firstPoint); newPoints.push_back(secondPoint); newPoints.push_back(thirdPoint); newPoints.push_back(fourthPoint); return newPoints; } // Define the warp correction function Mat warpCorrection(Mat img, vector<Point> contour) { Mat imgWarp; //Obtain the reshaped points vector<Point> cornerPoints = reShape(contour); // Define the source and destination points for warping Point2f pts1[4] = { cornerPoints[0], cornerPoints[1], cornerPoints[2], cornerPoints[3] }; Point2f pts2[4] = { {0.0f, 0.0f}, {imgWidth, 0.0f}, {0.0f, imgHeight}, {imgWidth, imgHeight} }; Mat matrix = getPerspectiveTransform(pts1, pts2); // Get the corrected image warpPerspective(img, imgWarp, matrix, Point(imgWidth, imgHeight)); return imgWarp; } // Define the main function int main() { VideoCapture vcap(0); string url = "http://192.168.0.101:8080/shot.jpg"; // url for accessing the video feed from the phone using IP-Webcam int count = 1; while (true) { if (vcap.open(url)) vcap.read(img); else cout << "Cannot open camera" << endl; // Pre-processing of the image imgThresh = preProcessing(img); // Detect and draw the contour bigContour = getContours(imgThresh, 1000); // Perform Warp correction on the image Mat finalImage = warpCorrection(img, bigContour); // Crop the image Rect roi = Rect(10, 10, imgWidth - (2 * 10), imgHeight - (2 * 10)); imgCrop = finalImage(roi); // Display the results imshow("Result", imgCrop); imshow("Original", img); // Save the image if (waitKey(1) == 's') { rectangle(img, Point(0, 190), Point(480, 390), Scalar(255, 0, 255), FILLED); putText(img, "Saved image", Point(100, 300), FONT_HERSHEY_COMPLEX, 0.7, Scalar(0, 0, 0), 2); if (_mkdir("results") == 0) imwrite("results\\Scrshot_" + to_string(count) + ".jpg", imgCrop); else cout << "File creation failed"; imshow("Original", img); waitKey(500); count += 1; } else if (waitKey(1) == 27) break; } }<file_sep>/README.md # README This repository contains all the CPP projects
3a22b01eb6471a96ac56be5813ff3b5af91dace7
[ "Markdown", "C++" ]
2
C++
hhavnursangappa/CPP-Projects
14d61dffcb1bcff24059535b4f1863769367de3c
10b05b935afae6db43b53855f1dfd28b82ea497e
refs/heads/master
<file_sep><?php // ******** INCLUDE TOP ********* // include 'top.php'; $thisURL = DOMAIN . PHP_SELF; // ****************** initialize variables ****************** // $email = ''; $password = ''; $newUserEmail = ''; $newUserPassword = ''; $newUserCheckPassword = ''; $firstName = ''; $lastName = ''; $phone = ''; // ****************** initialize error variables ****************** // $emailError = false; $passwordError = false; $newUserEmailError = false; $newUserPasswordError = false; $newUserCheckPasswordError = false; $firstNameError = false; $lastNameError = false; $phoneError = false; // ****************** initialize misc variables and arrays ****************** // $dataEntered = false; $records = false; $createAccountResults = false; $errorMsg = array(); // ******************* process for when form is submitted ******************** // if (isset($_POST['btnLogIn'])) { // ****************** security ****************** if (!securityCheck($thisURL)) { $msg = "<p>Security breach detected and reported.</p>"; die($msg); } // ******************* initialize data array ******************** // $data = array(); // ****************** sanitize data ****************** // $email = htmlentities($_POST["txtEmail"], ENT_QUOTES, "UTF-8"); $password = htmlentities($_POST["txtPassword"], ENT_QUOTES, "UTF-8"); // ****************** validate data ******************** // if ($email == '') { $errorMsg[] = 'Please enter your email.'; $emailError = true; } elseif (!verifyEmail($email)) { $errorMsg[] = 'Your email address appears to be incorrect.'; $emailError = true; } else { $data[] = $email; } if ($password == '') { $errorMsg[] = 'Please enter your password.'; $passwordError = true; } else { $data[] = $password; } if (!$errorMsg) { // IF DATA IS VALID // ******************* create query ****************** // $query = "SELECT * FROM tblUsers WHERE "; $query .= "fldUserEmail = ? AND "; $query .= "fldPassword = ?"; $records = []; // ******************* send query to mysql ******************** // if ($thisDatabaseReader->querySecurityOk($query,1,1)) { $query = $thisDatabaseReader->sanitizeQuery($query); $records = $thisDatabaseReader->select($query, $data); } if ($records) { // IF USER LOG IN SUCCESSFULL // ADD TO $_SESSION SUPER GLOBAL $_SESSION['user'] = $records[0]; } else { // NOT A USER $errorMsg[] = 'Your email and/or password appear to be incorrect.'; $emailError = true; $passwordError = true; } } // END IF DATA IS VALID } // END IF BUTTON LOG IN // ***************** PROCESS FOR CREATING ACCOUNT ****************** // if (isset($_POST['btnCreateAccount'])) { // ****************** security ****************** if (!securityCheck($thisURL)) { $msg = "<p>Security breach detected and reported.</p>"; die($msg); } // ******************* initialize data array ******************** // $data = array(); // ****************** sanitize data ****************** // $firstName = htmlentities($_POST["txtFirstName"], ENT_QUOTES, "UTF-8"); $lastName = htmlentities($_POST["txtLastName"], ENT_QUOTES, "UTF-8"); $newUserEmail = htmlentities($_POST["txtNewUserEmail"], ENT_QUOTES, "UTF-8"); $newUserPassword = htmlentities($_POST["txtNewUserPassword"], ENT_QUOTES, "UTF-8"); $newUserCheckPassword = htmlentities($_POST["txtNewUserCheckPassword"], ENT_QUOTES, "UTF-8"); $phone = htmlentities($_POST["txtPhone"], ENT_QUOTES, "UTF-8"); // ****************** validate data ******************** // $query = "SELECT * FROM tblUsers WHERE "; $query .= "fldUserEmail = ? "; $checkUserEmail = array($newUserEmail); // ******************* send query to mysql ******************** // if ($thisDatabaseReader->querySecurityOk($query,1)) { $query = $thisDatabaseReader->sanitizeQuery($query); $createAccountResults = $thisDatabaseReader->select($query, $checkUserEmail); } if ($createAccountResults) { // IF ALREADY A USER $errorMsg[] = "Sorry, there is already an account with that email."; $newUserEmailError = true; } if ($firstName == '') { $errorMsg[] = 'Please enter your first name.'; $firstNameError = true; } elseif (!verifyAlphaNum($firstName)) { $errorMsg[] = "Your first name appears to have extra characters."; $firstNameError = true; } else { $data[] = $firstName; } if ($lastName == '') { $errorMsg[] = 'Please enter your last name.'; } elseif (!verifyAlphaNum($lastName)) { $errorMsg[] = "Your first name appears to have extra characters."; $lastNameError = true; } else { $data[] = $lastName; } if ($newUserEmail == '') { $errorMsg[] = 'Please enter your email.'; } elseif (!verifyEmail($newUserEmail)) { $errorMsg[] = 'Your email address appears to be incorrect.'; $newUserEmailError = true; } else { $data[] = $newUserEmail; } if ($newUserPassword == '') { $errorMsg[] = 'Please enter your password.'; $newUserPassword = true; } else { $data[] = $newUserPassword; } if ($newUserPassword != $newUserCheckPassword) { $errorMsg[] = 'Passwords do not match.'; } if ($newUserCheckPassword = '') { $errorMsg[] = 'Please Re-Enter your password.'; $newUserCheckPasswordError = true; } if ($phone == '') { $errorMsg[] = 'Please enter your phone number.'; } else { $data[] = $phone; } if (!$errorMsg) { // IF DATA IS VALID // ****************** send data to database ****************** try { $thisDatabaseWriter->db->beginTransaction(); // ************* CREATE QUERY ************** // $query2 = "INSERT INTO tblUsers SET "; $query2 .= "fldUserFirstName = ?, "; $query2 .= "fldUserLastName = ?, "; $query2 .= "fldUserEmail = ?, "; $query2 .= "fldPassword = ?, "; $query2 .= "fldUserPhone = ?"; if ($thisDatabaseWriter->querySecurityOk($query2, 0)) { $query2 = $thisDatabaseWriter->sanitizeQuery($query2); $dataEntered = $thisDatabaseWriter->insert($query2, $data); $primaryKey = $thisDatabaseWriter->lastInsert(); } // ****************** commit changes ****************** $dataEntered = $thisDatabaseWriter->db->commit(); } catch (PDOException $e) { $thisDatabase->db->rollback(); $errorMsg[] = "There was a problem accepting your data."; } // ***************** SEND MAIL TO NEW USER ******************* // $message = "<p>Thank you for joining Book Barter, " . $firstName . "!</p><p>You may now log in and upload books!</p>"; $to = $newUserEmail; $cc = ''; $bcc = ''; $from = 'Book Barter <<EMAIL>>'; $subject = 'Thank You for Creating an Account!'; $mailed = sendMail($to, $cc, $bcc, $from, $subject, $message); } // END IF DATA IS VALID } // END IF CREATE ACCOUNT BUTTON if ($records) { // IF LOG IN SUCCESSFULL print '<h3 class="single-title">Welcome Back!</h3>'; } elseif ($dataEntered) { // IF CREATE ACCOUNT SUCCESSFULL print '<h3 class="single-title">Thank you for joining Book Barter, ' . $firstName . '!</h3><h3 class="single-title">You may now log in and upload books!</h3>'; } else { // IF DATA NOT ENTERED if ($errorMsg) { // DISPLAY ERROR MESSAGES print '<p class="errors">There is a problem with your form.<br>Please fix the following mistakes:</p>'; print '<ul class="errors">' . PHP_EOL; foreach ($errorMsg as $err) { print '<li>' . $err . '</li>' . PHP_EOL; } print '</ul>' . PHP_EOL; } ?> <!-- ***************** DISPLAY FORMS ****************** --> <!-- ****** LOG IN FORM ***** --> <h3>Log In</h3> <form action="<?php print PHP_SELF; ?>" method="post" id="log-in"> <!-- ***************** email text box ****************** --> <input type="text" placeholder="Email" maxlength="60" id="txtEmail" name="txtEmail" <?php print ' value="' . $email . '"'; ?> ><br> <!-- ***************** password text box ****************** --> <input type="password" placeholder="<PASSWORD>" maxlength="60" id="txtPassword" name="txtPassword" <?php print ' value="' . $password . '"'; ?> ><br> <!-- ***************** submit button ****************** --> <input type="submit" name="btnLogIn" value="Log In" tabindex="900" id="btnLogIn"> </form> <p id="or">OR</p> <!-- ******** CREATE ACCOUNT FORM ******* --> <h3>Create Account</h3> <form action="<?php print PHP_SELF; ?>" method="post" id="create-account"> <!-- ***************** first name text box ****************** --> <input type="text" placeholder="First Name" maxlength="60" id="txtFirstName" name="txtFirstName" <?php print ' value="' . $firstName . '"'; ?> ><br> <!-- ***************** last name text box ****************** --> <input type="text" placeholder="Last Name" maxlength="60" id="txtLastName" name="txtLastName" <?php print ' value="' . $lastName . '"'; ?> ><br> <!-- ***************** email text box ****************** --> <input type="text" placeholder="Email" maxlength="60" id="txtNewUserEmail" name="txtNewUserEmail" <?php print ' value="' . $newUserEmail . '"'; ?> ><br> <!-- ***************** password text box ****************** --> <input type="password" placeholder="<PASSWORD>" maxlength="60" id="txtNewUserPassword" name="txtNewUserPassword" <?php print ' value="' . $newUserPassword . '"'; ?> ><br> <!-- ***************** check password text box ****************** --> <input type="password" placeholder="Re-Enter Password" maxlength="60" id="txtNewUserCheckPassword" name="txtNewUserCheckPassword" <?php print ' value="' . $newUserCheckPassword . '"'; ?> ><br> <!-- ***************** phone text box ****************** --> <input type="text" placeholder="XXX-XXX-XXXX" maxlength="60" id="txtPhone" name="txtPhone" <?php print ' value="' . $phone . '"'; ?> ><br> <!-- ***************** submit button ****************** --> <input type="submit" name="btnCreateAccount" value="Create Account" tabindex="900" id="btnCreateAccount"> </form> <?php } // END IF DATA NOT ENTERED // ******** INCLUDE FOOTER ******* // include 'footer.php'; ?><file_sep><!-- ###################### Main Navigation ########################## --> <nav> <ol> <?php print '<li '; if ($PATH_PARTS['filename'] == 'index') { print ' class="activePage" '; } print '><a href="index.php">Home</a></li>'; print '<li '; if ($PATH_PARTS['filename'] == 'search') { print ' class="activePage" '; } print '><a href="search.php">Search</a></li>'; print '<li '; if ($PATH_PARTS['filename'] == 'upload') { print ' class="activePage" '; } print '><a href="upload.php">Upload</a></li>'; if (!empty($_SESSION)) { // IF THERE IS A USER if ($_SESSION['user']["pmkUserId"]) { // GET USER ID THROUGH SESSION SUPER GLOBAL print '<li '; if ($PATH_PARTS['filename'] == 'my-uploads') { print ' class="activePage" '; } print '><a href="my-uploads.php">My Uploads</a></li>'; } } // END IF IS USER if (!empty($_SESSION)) { // IF THERE IS A USER if ($_SESSION['user']["pmkUserId"]) { // GET USER ID THROUGH SESSION SUPER GLOBAL print '<li '; if ($PATH_PARTS['filename'] == 'log-out') { print ' class="activePage" '; } print '><a href="log-out.php">Log Out</a></li>'; } } else { // IF NOT A USER print '<li '; if ($PATH_PARTS['filename'] == 'log-in') { print ' class="activePage" '; } print '><a href="log-in.php">Log In</a></li>'; } // END IF NOT A USER print '<li '; if ($PATH_PARTS['filename'] == 'tables') { print ' class="activePage" '; } print '><a href="tables.php">Tables</a></li>'; ?> </ol> </nav> <!-- #################### Ends Main Navigation ########################## --> <file_sep><?php include 'top.php'; $thisURL = DOMAIN . PHP_SELF; // ****************** initialize variables ****************** $pmkItemId = -1; $title = ''; $authorFirstName = ''; $authorLastName = ''; $ISBN = ''; $subject = ''; $type = ''; // ****************** initialize error variables ****************** // $titleError = false; $authorFirstNameError = false; $authorLastNameError = false; $ISBNError = false; $subjectError = false; $typeError = false; // ****************** initialize misc variables ****************** // $dataEntered = false; $dataDeleted = false; $tagDeleted = false; $tagsDeleted = false; $mailed = false; $update = false; // ****************** initialize arrays ****************** // $tags = array(); $tagsData = array(); $errorMsg = array(); $data = array(); //************** if edit show what was previously put ******************// if (isset($_GET['id'])) { $pmkItemId = (int) htmlentities($_GET["id"], ENT_QUOTES, "UTF-8"); // ****************** create query to display info which will be updated ****************** // $query = 'SELECT fldTitle, fldAuthorFirstName, fldAuthorLastName, fldISBNNumber, fldSubject, fldType '; $query .= 'FROM tblBooks WHERE pmkItemId = ?'; $data[] = $pmkItemId; if ($thisDatabaseReader->querySecurityOk($query, 1)) { $query = $thisDatabaseReader->sanitizeQuery($query); $book = $thisDatabaseReader->select($query, $data); } $title = $book[0]['fldTitle']; $authorFirstName = $book[0]['fldAuthorFirstName']; $authorLastName = $book[0]['fldAuthorLastName']; $ISBN = $book[0]['fldISBNNumber']; $subject = $book[0]['fldSubject']; $type = $book[0]['fldType']; $query = 'DELETE FROM tblBooksTags WHERE pfkItemId = ?'; if ($thisDatabaseWriter->querySecurityOk($query, 1)) { $query = $thisDatabaseWriter->sanitizeQuery($query); $tagsResults = $thisDatabaseWriter->delete($query, $data); } } //************** process for when code is submitted ****************** // if (isset($_POST['btnSubmit'])) { // ****************** security ****************** // if (!securityCheck($thisURL)) { $msg = "<p>Security breach detected and reported.</p>"; die($msg); } // ****************** sanitize data ****************** // $pmkItemId = (int) htmlentities($_POST["hidItemId"], ENT_QUOTES, "UTF-8"); if ($pmkItemId > 0) { $update = true; } $data[] = $_SESSION['user']["pmkUserId"]; $title = htmlentities($_POST["txtTitle"], ENT_QUOTES, "UTF-8"); $data[] = $title; $authorFirstName = htmlentities($_POST["txtAuthorFirstName"], ENT_QUOTES, "UTF-8"); $data[] = $authorFirstName; $authorLastName = htmlentities($_POST["txtAuthorLastName"], ENT_QUOTES, "UTF-8"); $data[] = $authorLastName; $ISBN = htmlentities($_POST["txtISBN"], ENT_QUOTES, "UTF-8"); $data[] = $ISBN; $subject = htmlentities($_POST["lstSubject"], ENT_QUOTES, "UTF-8"); $data[] = $subject; if (isset($_POST["radType"])) { $type = htmlentities($_POST["radType"], ENT_QUOTES, "UTF-8"); $data[] = $type; } else { $errorMsg[] = "Please enter the type of book you are uploading."; $typeError = true; } // **************** save tags to tags data array ***************** // if (isset($_POST["chkhardback"])){ $chkHardBack = htmlentities($_POST["chkhardback"], ENT_QUOTES, "UTF-8"); $tagsData[] =$chkHardBack; } if (isset($_POST["chklooseleaf"])){ $chkLooseLeaf = htmlentities($_POST["chklooseleaf"], ENT_QUOTES, "UTF-8"); $tagsData[] =$chkLooseLeaf; } if (isset($_POST["chkoptional"])){ $chkOptional = htmlentities($_POST["chkoptional"], ENT_QUOTES, "UTF-8"); $tagsData[] =$chkOptional; } if (isset($_POST["chkrequired"])){ $chkRequired = htmlentities($_POST["chkrequired"], ENT_QUOTES, "UTF-8"); $tagsData[] =$chkRequired; } // ****************** validation ***************** // if ($title == '') { $errorMsg[] = 'Please add a title.'; $titleError = true; } if ($authorFirstName == '') { $errorMsg[] = "Please enter the author's first name"; $authorFirstNameError = true; } elseif (!verifyAlphaNum($authorFirstName)) { $errorMsg[] = "The author's first name appears to have extra character."; $authorFirstNameError = true; } if ($authorLastName == '') { $errorMsg[] = "Please enter the author's last name."; $authorLastNameError = true; } elseif (!verifyAlphaNum($authorLastName)) { $errorMsg[] = "The author's last name appears to have extra character."; $authorLastNameError = true; } if ($ISBN == '') { $errorMsg[] = "Please enter the ISBN Number."; $ISBNError = true; } if ($subject == '') { $errorMsg[] = "Please enter the subject the book is used for."; $subjectError = true; } // ****************** check to see if form has passed validation ****************** // if (!$errorMsg) { print "<!-- PROCESSED FORM THAT HAS PASSED VALIDATION -->"; if (DEBUG) { print "<h2>Your Form has been Submitted</h2>"; } // ****************** send data to database ****************** // try { $thisDatabaseWriter->db->beginTransaction(); // ****************** create query for updating or inserting ****************** // if ($update) { $query = "UPDATE tblBooks SET "; } else { $query = "INSERT INTO tblBooks SET "; } $query .= "fnkUserId = ?, "; $query .= "fldTitle = ?, "; $query .= "fldAuthorFirstName = ?, "; $query .= "fldAuthorLastName = ?, "; $query .= "fldISBNNumber = ?, "; $query .= "fldSubject = ?, "; $query .= "fldType = ? "; if (DEBUG) { $thisDatabaseWriter->TestSecurityQuery($query, 0); print_r($data); } if ($update) { $query .= "WHERE pmkItemId = ?"; $data[] = $pmkItemId; if ($thisDatabaseWriter->querySecurityOk($query, 1)) { $query = $thisDatabaseWriter->sanitizeQuery($query); $results = $thisDatabaseWriter->update($query, $data); } } else { if ($thisDatabaseWriter->querySecurityOk($query, 0)) { $query = $thisDatabaseWriter->sanitizeQuery($query); $results = $thisDatabaseWriter->insert($query, $data); $pmkItemId = $thisDatabaseWriter->lastInsert(); } } $query = 'INSERT INTO tblBooksTags SET pfkItemId = ?, pfkTag = ?'; foreach($tagsData as $tagData) { $insert = array($pmkItemId, $tagData); if ($thisDatabaseWriter->querySecurityOk($query, 0)) { $query = $thisDatabaseWriter->sanitizeQuery($query); $tagResults = $thisDatabaseWriter->insert($query, $insert); if (DEBUG) { print "<p>pmk= " . $pmkItemId; } } } // ****************** commit changes ****************** // $dataEntered = $thisDatabaseWriter->db->commit(); } catch (PDOException $e) { $thisDatabase->db->rollback(); $errorMsg[] = "There was a problem accepting your data."; } } } // ******************* Process for deleting record ********************* // if (isset($_POST['btnDelete'])) { // ****************** security ****************** // if (!securityCheck($thisURL)) { $msg = "<p>Security breach detected and reported.</p>"; die($msg); } // ****************** sanitize data ****************** // $pmkItemId = (int) htmlentities($_POST["hidItemId"], ENT_QUOTES, "UTF-8"); $title = htmlentities($_POST["txtTitle"], ENT_QUOTES, "UTF-8"); $authorFirstName = htmlentities($_POST["txtAuthorFirstName"], ENT_QUOTES, "UTF-8"); $authorLastName = htmlentities($_POST["txtAuthorLastName"], ENT_QUOTES, "UTF-8"); $ISBN = htmlentities($_POST["txtISBN"], ENT_QUOTES, "UTF-8"); $subject = htmlentities($_POST["lstSubject"], ENT_QUOTES, "UTF-8"); if (isset($_POST["radType"])) { $type = htmlentities($_POST["radType"], ENT_QUOTES, "UTF-8"); } try { $thisDatabaseWriter->db->beginTransaction(); // ****************** create query for deleting records ****************** // $query = 'DELETE FROM tblBooks WHERE pmkItemId = ?'; $data[] = $pmkItemId; if ($thisDatabaseWriter->querySecurityOk($query, 1)) { $query = $thisDatabaseWriter->sanitizeQuery($query); $results = $thisDatabaseWriter->delete($query, $data); } $dataDeleted = $thisDatabaseWriter->db->commit(); } catch (PDOException $e) { $thisDatabaseWriter->db->rollback(); } } // ****************** check to see if the data has been entered to the database ****************** if ($dataEntered) { if ($update) { // IF RECORD UPDATED print "<h3>Updated:</h3>"; print '<h4>' . $title . '<br>'; print $authorFirstName . ' ' . $authorLastName . '<br>'; print $ISBN . '<br>'; print $subject . '<br>'; print $type . '</h4>'; } else { // IF RECORD SAVED print "<h3>Saved:</h3>"; print '<h4>' . $title . '<br>'; print $authorFirstName . ' ' . $authorLastName . '<br>'; print $ISBN . '<br>'; print $subject . '<br>'; print $type . '</h4>'; } } elseif ($dataDeleted) { // IF RECORD DELETED print '<h3>Deleted:</h3>'; print '<h4>' . $title . '<br>'; print $authorFirstName . ' ' . $authorLastName . '<br>'; print $ISBN . '<br>'; print $subject . '<br>'; print $type . '</h4>'; } else { if (!empty($_SESSION)) { // IF USER // ****************** display error messages ****************** if ($errorMsg) { print '<p class="errors">There is a problem with your form.<br>Please fix the following mistakes:</p>'; print '<ul class="errors">' . PHP_EOL; foreach ($errorMsg as $err) { print '<li>' . $err . '</li>' . PHP_EOL; } print '</ul>' . PHP_EOL; } ?> <!-- ****************** DISPLAY FORM ****************** --> <h2>Upload A Textbook</h2> <form action="<?php print PHP_SELF; ?>" method="post" id="upload"> <input type="hidden" name="hidItemId" value=" <?php print $pmkItemId; ?> "> <fieldset> <legend>Book Info:</legend> Title:<input type="text" placeholder="Title" maxlength="30" id="txtTitle" name="txtTitle" <?php if ($titleError) { print ' class="mistake"'; } print ' value="' . $title . '"'; ?> ><br> Author First Name:<input type="text" placeholder="<NAME>" maxlength="20" id="txtAuthorFirstName" name="txtAuthorFirstName" <?php if ($authorFirstNameError) { print ' class="mistake"'; } print ' value="' . $authorFirstName . '"'; ?> ><br> Author Last Name:<input type="text" placeholder="<NAME>" maxlength="20" id="txtAuthorLastName" name="txtAuthorLastName" <?php if ($authorLastNameError) { print ' class="mistake"'; } print ' value="' . $authorLastName . '"'; ?> ><br> ISBN Number:<input type="text" placeholder="ISBN" maxlength="30" id="txtISBN" name="txtISBN" <?php if ($ISBNError) { print ' class="mistake"'; } print ' value="' . $ISBN . '"'; ?> ><br> <?php $query = 'SELECT pmkSubject FROM tblSubjects'; if ($thisDatabaseReader->querySecurityOk($query, 0)) { $query = $thisDatabaseReader->sanitizeQuery($query); $schoolSubjects = $thisDatabaseReader->select($query, ''); } ?> <label for="lstSubject">Subject <select name="lstSubject"> <option value=""></option> <?php foreach ($schoolSubjects as $schoolSubject) { print '<option '; if ($subject == $schoolSubject['pmkSubject']) { print ' selected="selected" '; } print 'name="lstSchoolSubject" '; print 'value="' . $schoolSubject["pmkSubject"] . '">' . $schoolSubject["pmkSubject"]; print '</option>'; } ?> <option value="Other">Other</option> </select><br> </label> <input type="radio" id="radType" name="radType" value="Book" <?php if ($typeError) { print ' class="mistake"'; } ?> >Book<br> <input type="radio" id="radType" name="radType" value="eBook" <?php if ($typeError) { print ' class="mistake"'; } ?> >eBook<br> <input type="radio" id="radType" name="radType" value="Other" <?php if ($typeError) { print ' class="mistake"'; } ?> >Other<br> <!-- ****************** check box for book tags ****************** --> <?php $query = 'SELECT pmkTag, fldDefaultValue FROM tblTags'; if ($thisDatabaseReader->querySecurityOk($query, 0)) { $query = $thisDatabaseReader->sanitizeQuery($query); $tags = $thisDatabaseReader->select($query, ''); } // ********* display tags ********** // if (is_array($tags)) { foreach ($tags as $tag) { print "\t" . '<label for="chk' . str_replace(" ", "", $tag["pmkTag"]) . '"><input type="checkbox" '; print ' id="chk' . str_replace(" ", "", $tag["pmkTag"]) . '" '; print ' name="chk' . str_replace(" ", "", $tag["pmkTag"]) . '" '; if ($tag["fldDefaultValue"] == 1) { print ' checked '; } print 'value="' . $tag["pmkTag"] . '">' . $tag["pmkTag"]; print '</label>' . PHP_EOL; } } ?> </fieldset> <input type="submit" name="btnSubmit" value="Upload" tabindex="900" id="btnSubmit"> </form> <?php if (isset($_GET['id'])) { ?> <form action="<?php print PHP_SELF; ?>" method="post" id="frmDelete"> <input type="hidden" name="hidItemId" value="<?php print $pmkItemId; ?>"> <input type="hidden" name="txtTitle" value="<?php print $title; ?>"> <input type="hidden" name="txtAuthorFirstName" value="<?php print $authorFirstName; ?>"> <input type="hidden" name="txtAuthorLastName" value="<?php print $authorLastName; ?>"> <input type="hidden" name="txtISBN" value="<?php print $ISBN; ?>"> <input type="hidden" name="lstSubject" value="<?php print $subject; ?>"> <input type="hidden" name="radType" value="<?php print $type; ?>"> <input type="submit" name="btnDelete" value="Delete" tabindex="1900" id="btnDelete"> </form> <?php } // END IF ISSET GET } else { // IF NOT USER print '<h3 class="single-title">You must log in or create an account to upload a book.</h3>'; } // END IF NOT USER } // IF NO DATA INPUT // INCLUDE FOOTER include 'footer.php'; ?><file_sep><?php // Include top include 'top.php'; if (isset($_GET['id'])) { // GET ITEM ID THROUGH GET ARRAY // ********* SAVE ITEM ID TO VARIABLE ********* // $pmkItemId = (int) htmlentities($_GET["id"], ENT_QUOTES, "UTF-8"); //*********** CREATE QUERY ************ // $query = 'SELECT pmkItemId, fnkUserId, fldTitle, fldAuthorFirstName, fldAuthorLastName, fldISBNNumber, fldSubject, fldType '; $query .= 'FROM tblBooks WHERE pmkItemId = ?'; $data = array($pmkItemId); if ($thisDatabaseReader->querySecurityOk($query, 1)) { $query = $thisDatabaseReader->sanitizeQuery($query); $records = $thisDatabaseReader->select($query, $data); } // ************* CREATE TAGS QUERY ************ // $query2 = 'SELECT pfkTag FROM tblBooksTags JOIN tblBooks ON pmkItemId = pfkItemId WHERE pmkItemId = ?'; if ($thisDatabaseReader->querySecurityOk($query2, 1)) { $query2 = $thisDatabaseReader->sanitizeQuery($query2); $tags = $thisDatabaseReader->select($query2, $data); } // ************ CREATE USER QUERY ************** // $query3 = 'SELECT fldUserFirstName, fldUserEmail, fldUserPhone FROM tblUsers '; $query3 .= 'JOIN tblBooks ON pmkUserId = fnkUserId WHERE pmkItemId = ?'; if ($thisDatabaseReader->querySecurityOk($query3, 1)) { $query3 = $thisDatabaseReader->sanitizeQuery($query3); $users = $thisDatabaseReader->select($query3, $data); } print '<ul id="books">'; if (is_array($records)) { // IF RECORDS IS ARRAY foreach ($records as $record) { // DISPLAY ALL RECORDS print '<li>'; print '<ul>'; print '<li><strong>Title:</strong> ' . $record['fldTitle'] . '</li>'; print '<li><strong>Author:</strong> ' . $record['fldAuthorFirstName'] . ' ' . $record['fldAuthorLastName'] . '</li>'; print '<li><strong>ISBN:</strong> ' . $record['fldISBNNumber'] . '</li>'; print '<li><strong>Subject:</strong> ' . $record['fldSubject'] . '</li>'; print '<li><strong>Type:</strong> ' . $record['fldType'] . '</li>'; print '<li><strong>Tags:</strong> '; foreach($tags as $tag) { print $tag['pfkTag'] . ', '; } print '</li>'; print '<li><br></li>'; foreach ($users as $user) { print '<li><strong>Contact:</strong></li>'; print '<li><strong>Name:</strong> ' . $user['fldUserFirstName'] . '</li>'; print '<li><strong>Email:</strong> ' . $user['fldUserEmail'] . '</li>'; print '<li><strong>Phone:</strong> ' . $user['fldUserPhone'] . '</li>'; } if (!empty($_SESSION)) { // IF IS USER if ($_SESSION['user']["pmkUserId"] == $record['fnkUserId']) { // IF USER WHO UPLOADED THIS BOOK print '<li><a href="upload.php?id=' . $record['pmkItemId'] . '">Edit</a></li>'; } } print '</ul>'; print '</li>'; } // END DISPLAY ALL RECORDS } // END IF RECORDS IS ARRAY print '</ul>'; } // INCLUDE FOOTER include 'footer.php'; ?><file_sep><?php // Include top include 'top.php'; // Initialize variables $records = array(); $i = 0; // create query showing most recent 6 records $query = 'SELECT pmkItemId, fnkUserId, fldTitle, fldAuthorFirstName, fldAuthorLastName, fldISBNNumber, fldSubject FROM tblBooks '; $query .= 'ORDER BY pmkItemId DESC LIMIT 6'; if ($thisDatabaseReader->querySecurityOk($query, 0,1)) { $query = $thisDatabaseReader->sanitizeQuery($query); $records = $thisDatabaseReader->select($query, ''); } ?> <h2>Text Books</h2> <ul id="books"> <?php if (is_array($records)) { // IF RECORDS IS ARRAY foreach ($records as $record) { // DISPLAY EACH RECORD $i++; if ($i % 2 != 0) { print '<br>'; } print '<li>'; print '<ul>'; print '<li><strong>Title:</strong> ' . $record['fldTitle'] . '</li>'; print '<li><strong>Author:</strong> ' . $record['fldAuthorFirstName'] . ' ' . $record['fldAuthorLastName'] . '</li>'; print '<li><strong>ISBN:</strong> ' . $record['fldISBNNumber'] . '</li>'; print '<li><strong>Subject:</strong> ' . $record['fldSubject'] . '</li>'; print '<li><a href="view-book.php?id=' . $record['pmkItemId'] . '">View</a></li>'; if (!empty($_SESSION)) { // IF IS USER if ($_SESSION['user']["pmkUserId"] == $record['fnkUserId']) { // GET USER ID THROUGH SESSION SUPER GLOBAL print '<li><a href="upload.php?id=' . $record['pmkItemId'] . '">Edit</a></li>'; } } // END IF IS USER print '</ul>'; print '</li>'; } } print '</ul>'; // ********** INCLUDE FOOTER ********** // include 'footer.php'; ?><file_sep><?php // Include top include 'top.php'; // Initialize variables $records = array(); $i = 0; // create query $query = 'SELECT pmkItemId, fnkUserId, fldTitle, fldAuthorFirstName, fldAuthorLastName, fldISBNNumber, fldSubject, fldType '; $query .= 'FROM tblBooks '; $query .= 'WHERE fnkUserId = ? '; $query .= 'ORDER BY pmkItemId DESC'; // ******** GET USER ID THROUGH SESSION SUPER GLOBAL ********* // $userData = array($_SESSION['user']['pmkUserId']); if ($thisDatabaseReader->querySecurityOk($query, 1,1)) { $query = $thisDatabaseReader->sanitizeQuery($query); $records = $thisDatabaseReader->select($query, $userData); } ?> <!-- ********* DISPLAY MY BOOKS ********** --> <h2>My Books</h2> <ul id="books"> <?php if (is_array($records)) { // IF RECORDS IS ARRAY foreach ($records as $record) { // DISPLAY EACH RECORD $i++; if ($i % 2 != 0) { // ADDS LINE BREAK FOR EVERY TWO RECORDS print '<br>'; } print '<li>'; print '<ul>'; print '<li><strong>Title:</strong> ' . $record['fldTitle'] . '</li>'; print '<li><strong>Author:</strong> ' . $record['fldAuthorFirstName'] . ' ' . $record['fldAuthorLastName'] . '</li>'; print '<li><strong>ISBN:</strong> ' . $record['fldISBNNumber'] . '</li>'; print '<li><strong>Subject:</strong> ' . $record['fldSubject'] . '</li>'; print '<li><strong>Type:</strong> ' . $record['fldType'] . '</li>'; if (!empty($_SESSION)) { // IF IS USER if ($_SESSION['user']["pmkUserId"] == $record['fnkUserId']) { // GET USER ID THROUGH SESSION SUPER GLOBAL print '<li><a href="upload.php?id=' . $record['pmkItemId'] . '">Edit</a></li>'; } } // END IF USER print '</ul>'; print '</li>'; } } print '</ul>'; ?> <?php // *********** DISPLAY FOOTER ********** // include 'footer.php'; ?><file_sep><!-- %%%%%%%%%%%%%%%%%%%%%% Page header %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% --> <header> <img src="bookbarterlogo.jpg" alt="Book Barter Logo"> <?php include 'nav.php'; ?> </header> <!-- %%%%%%%%%%%%%%%%%%%%% Ends Page header %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% --><file_sep><?php // passwords for your database $dbReader="xxxx"; $dbWriter="xxxx"; $dbAdmin="xxxx"; ?><file_sep><?php session_start(); ?> <!DOCTYPE html> <html lang="en"> <head> <title>Final Project</title> <meta charset="utf-8"> <meta name="author" content="<NAME>"> <meta name="description" content="Final Project CS148"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="custom.css" type="text/css" media="screen"> <?php // %^%^%^%^%^%^%^%^%^%^%^%^%^%^%^%^%^%^%^%^%^%^%^%^%^%^%^%^%^%^%^%^%^%^%^%^%^% print '<!-- begin including libraries -->'; include 'lib/constants.php'; include 'lib/security.php'; include 'lib/validation-functions.php'; include LIB_PATH . '/Connect-With-Database.php'; include 'lib/mail-message.php'; print '<!-- libraries complete-->'; ?> </head> <!-- ********************** Body section ********************** --> <?php print '<body id="' . $PATH_PARTS['filename'] . '">'; include 'header.php'; ?><file_sep><?php // ******** INCLUDE TOP ******** // include 'top.php'; $thisURL = DOMAIN . PHP_SELF; // INITIALIZE logged out variable $loggedOut = false; // ********* PROCESS TO LOG OUT ********* // if (isset($_POST['btnLogOut'])) { // IF LOG OUT BUTTON CLICKED // ****************** security ****************** if (!securityCheck($thisURL)) { $msg = "<p>Security breach detected and reported.</p>"; die($msg); } // ******** END SESSION SUPER GLOBAL ******** // session_destroy(); // SET LOGGEDOUT TO TRUE $loggedOut = true; } // END LOG OUT PROCESS if ($loggedOut) { // IF LOG OUT SUCCESS print '<h3 class="single-title">You have logged out.</h3>'; } else { ?> <h3>Are you sure you want to log out?</h3> <!-- ********* DISPLAY LOG OUT FORM ******** --> <form action="<?php print PHP_SELF; ?>" method="post" id="log-out"> <!-- ***************** log out button ****************** --> <input type="submit" name="btnLogOut" value="Log Out" tabindex="900" id="btnLogOut"> </form> <?php } // END IF NOT LOGGED OUT // ******** INCLUDE FOOTER ******** // include 'footer.php'; ?><file_sep># BookBarter BookBarter was my final project for my Database and Web Design Class. <file_sep><?php include 'top.php'; $thisURL = DOMAIN . PHP_SELF; // ******************* initialize variables ******************** // $universityName = ''; $title = ''; $authorFirstName = ''; $authorLastName = ''; $ISBN = ''; $subject = ''; $type = ''; // ******************* initialize error flags ******************** // $titleError = false; $authorFirstNameError = false; $authorLastNameError = false; $ISBNError = false; $errorMsg = array(); // ******************* process for when form is submitted ******************** // if (isset($_POST['btnSubmit'])) { // ****************** security ****************** if (!securityCheck($thisURL)) { $msg = "<p>Security breach detected and reported.</p>"; die($msg); } // ******************* initialize data array ******************** // $data = array(); // ****************** sanitize data ****************** // $title = htmlentities($_POST["txtTitle"], ENT_QUOTES, "UTF-8"); $authorFirstName = htmlentities($_POST["txtAuthorFirstName"], ENT_QUOTES, "UTF-8"); $authorLastName = htmlentities($_POST["txtAuthorLastName"], ENT_QUOTES, "UTF-8"); $ISBN = htmlentities($_POST["txtISBN"], ENT_QUOTES, "UTF-8"); $subject = htmlentities($_POST["lstSubject"], ENT_QUOTES, "UTF-8"); if (isset($_POST["radType"])) { $type = htmlentities($_POST["radType"], ENT_QUOTES, "UTF-8"); } // ****************** validate data ******************** // if ($title == '' AND $authorFirstName == '' AND $authorLastName == '' AND $ISBN == '' AND $subject == '') { // IF NO DATA ENTERED print '<p>Search too broad. Please enter some information.</p>'; ?> <!-- ***************** display form ****************** --> <h2>Search</h2> <form action="<?php print PHP_SELF; ?>" method="post" id="search"> <!-- ***************** title text box ****************** --> <input type="text" placeholder="Title" maxlength="60" id="txtTitle" name="txtTitle" <?php if ($titleError) { print ' class="mistake"'; } print ' value="' . $title . '"'; ?> ><br> <!-- ***************** author first text box ****************** --> <input type="text" placeholder="<NAME>" maxlength="20" id="txtAuthorFirstName" name="txtAuthorFirstName" <?php if ($authorFirstNameError) { print ' class="mistake"'; } print ' value="' . $authorFirstName . '"'; ?> ><br> <!-- ***************** author last name text box ****************** --> <input type="text" placeholder="<NAME>" maxlength="20" id="txtAuthorLastName" name="txtAuthorLastName" <?php if ($authorLastNameError) { print ' class="mistake"'; } print ' value="' . $authorLastName . '"'; ?> ><br> <!-- ***************** isbn text box ****************** --> <input type="text" placeholder="ISBN" maxlength="30" id="txtISBN" name="txtISBN" <?php if ($ISBNError) { print ' class="mistake"'; } print ' value="' . $ISBN . '"'; ?> ><br> <!-- ***************** subject list box ****************** --> <?php // ************ query for selecting subjects *****************// $query = 'SELECT pmkSubject FROM tblSubjects'; if ($thisDatabaseReader->querySecurityOk($query, 0)) { $query = $thisDatabaseReader->sanitizeQuery($query); $schoolSubjects = $thisDatabaseReader->select($query, ''); } ?> <label for="lstSubject">Subject <select name="lstSubject"> <option value=""></option> <?php foreach ($schoolSubjects as $schoolSubject) { print '<option '; if ($subject == $schoolSubject['pmkSubject']) { print ' selected="selected" '; } print 'name="lstSchoolSubject" '; print 'value="' . $schoolSubject["pmkSubject"] . '">' . $schoolSubject["pmkSubject"]; print '</option>'; } ?> <option value="Other">Other</option> </select><br> </label> <!-- ***************** type radio buttons ****************** --> <input type="radio" name="radType" value="Book"/>Book<br> <input type="radio" name="radType" value="eBook"/>eBook<br> <input type="radio" name="radType" value="Other"/>Other<br> <!-- ***************** submit button ****************** --> <input type="submit" name="btnSubmit" value="Search" tabindex="900" id="btnSubmit"> </form> <?php } else { // IF DATA ENTERED // ****************** create query ****************** // $query = "SELECT * FROM tblBooks WHERE "; // ******************* initialize conditions variable ******************** // $CONDITIONS = 0; // ******************* validate and add to data array and query ******************** // if ($title != '') { $query .= "fldTitle LIKE ? "; $data[] = "%$title%"; } if ($authorFirstName != '') { if ($title != '') { $query .= "AND "; $CONDITIONS++; } $query .= "fldAuthorFirstName LIKE ? "; $data[] = "%$authorFirstName%"; } if ($authorLastName != '') { if ($title != '' OR $authorFirstName != '') { $query .= "AND "; $CONDITIONS++; } $query .= "fldAuthorLastName LIKE ? "; $data[] = "%$authorLastName%"; } if ($ISBN != '') { if ($title != '' OR $authorFirstName != '' OR $authorLastName != '') { $query .= "AND "; $CONDITIONS++; } $query .= "fldISBNNumber LIKE ? "; $data[] = "%$ISBN%"; } if ($subject != '') { if ($title != '' OR $authorFirstName != '' OR $authorLastName != '' OR $ISBN != '') { $query .= "AND "; $CONDITIONS++; } $query .= "fldSubject LIKE ? "; $data[] = "%$subject%"; } if (isset($_POST["radType"])) { if ($title != '' OR $authorFirstName != '' OR $authorLastName != '' OR $ISBN != '' OR $subject != '') { $query .= "AND "; $CONDITIONS++; } $query .= "fldType LIKE ? "; $data[] = "%$type%"; } // ******************* send query to mysql ******************** // if ($thisDatabaseReader->querySecurityOk($query,1,$CONDITIONS)) { $query = $thisDatabaseReader->sanitizeQuery($query); $records = $thisDatabaseReader->select($query, $data); } // ******************* check for no results ******************** // if (!$records) { print '<p id="failed-search">Sorry, no results found.</p>'; } else { print "<h2>Search Results:</h2>"; // ******************* display search results ******************** // print '<ul id="books">'; $i = 0; if (is_array($records)) { // IF RECORDS IS ARRAY foreach ($records as $record) { // DISPLAY EACH RECORD $i++; if ($i % 2 != 0) { // ADD LINE BREAK IF DIVISIBLE BY 2 print '<br>'; } print '<li>'; print '<ul>'; print '<li><strong>Title:</strong> ' . $record['fldTitle'] . '</li>'; print '<li><strong>Author:</strong> ' . $record['fldAuthorFirstName'] . ' ' . $record['fldAuthorLastName'] . '</li>'; print '<li><strong>ISBN:</strong> ' . $record['fldISBNNumber'] . '</li>'; print '<li><strong>Subject:</strong> ' . $record['fldSubject'] . '</li>'; print '<li><a href="view-book.php?id=' . $record['pmkItemId'] . '">View</a></li>'; if (!empty($_SESSION)) { // IF IS USER if ($_SESSION['user']["pmkUserId"] == $record['fnkUserId']) { // GET USER ID THROUGH SESSION SUPER GLOBAL print '<li><a href="upload.php?id=' . $record['pmkItemId'] . '">Edit</a></li>'; } } print '</ul>'; print '</li>'; } } print '</ul>'; } } } else { // IF NO DATA IN INPUT YET ?> <!-- ***************** display form ****************** --> <h2>Search</h2> <form action="<?php print PHP_SELF; ?>" method="post" id="search"> <!-- ***************** title text box ****************** --> <input type="text" placeholder="Title" maxlength="60" id="txtTitle" name="txtTitle" <?php if ($titleError) { print ' class="mistake"'; } print ' value="' . $title . '"'; ?> ><br> <!-- ***************** author first text box ****************** --> <input type="text" placeholder="<NAME>" maxlength="20" id="txtAuthorFirstName" name="txtAuthorFirstName" <?php if ($authorFirstNameError) { print ' class="mistake"'; } print ' value="' . $authorFirstName . '"'; ?> ><br> <!-- ***************** author last name text box ****************** --> <input type="text" placeholder="<NAME>" maxlength="20" id="txtAuthorLastName" name="txtAuthorLastName" <?php if ($authorLastNameError) { print ' class="mistake"'; } print ' value="' . $authorLastName . '"'; ?> ><br> <!-- ***************** isbn text box ****************** --> <input type="text" placeholder="ISBN" maxlength="30" id="txtISBN" name="txtISBN" <?php if ($ISBNError) { print ' class="mistake"'; } print ' value="' . $ISBN . '"'; ?> ><br> <!-- ***************** subject list box ****************** --> <?php // ************ query for selecting subjects *****************// $query = 'SELECT pmkSubject FROM tblSubjects'; if ($thisDatabaseReader->querySecurityOk($query, 0)) { $query = $thisDatabaseReader->sanitizeQuery($query); $schoolSubjects = $thisDatabaseReader->select($query, ''); } ?> <label for="lstSubject">Subject <select name="lstSubject"> <option value=""></option> <?php foreach ($schoolSubjects as $schoolSubject) { print '<option '; if ($subject == $schoolSubject['pmkSubject']) { print ' selected="selected" '; } print 'name="lstSchoolSubject" '; print 'value="' . $schoolSubject["pmkSubject"] . '">' . $schoolSubject["pmkSubject"]; print '</option>'; } ?> <option value="Other">Other</option> </select><br> </label> <!-- ***************** type radio buttons ****************** --> <input type="radio" name="radType" value="Book"/>Book<br> <input type="radio" name="radType" value="eBook"/>eBook<br> <input type="radio" name="radType" value="Other"/>Other<br> <!-- ***************** submit button ****************** --> <input type="submit" name="btnSubmit" value="Search" tabindex="900" id="btnSubmit"> </form> <?php } // END IF NO DATA IN INPUT // *********** INCLUDE FOOTER *********** // include 'footer.php'; ?>
5aabff35622cf174f57db6864ce5740c301086b1
[ "Markdown", "PHP" ]
12
PHP
bodubs/BookBarter
c31ae8e4c9648fa32f31715c4fc0ee42f6289af9
cc5a40816ebc99065898a52f74ce24285db2f449
refs/heads/master
<repo_name>rrtoledo/mimc<file_sep>/mimc.py from random import randint import pytest try: # pysha3 from sha3 import keccak_256 except ImportError: # pycryptodome from Crypto.Hash import keccak keccak_256 = lambda *args: keccak.new(*args, digest_bits=256) ##### SOME HASHES # sha3("Clearmatics"): 14220067918847996031108144435763672811050758065945364308986253046354060608451 # sha3("Clearmatics_add"): 7655352919458297598499032567765357605187604397960652899494713742188031353302 # sha3("Clearmatics_sn"): 38594890471543702135425523844252992926779387339253565328142220201141984377400 # sha3("Clearmatics_pk"): 20715549373167656640519441333099474211916836972862576858009333815040496998894 class MiMC7: iv = b"mimc" def __init__(self, prime=21888242871839275222246405745257275088548364400416034343698204186575808495617, iv = b"mimc"): self.prime = prime self.iv = iv print("p = "+str(self.prime)) print("iv = "+str(iv)) def MiMCRound(self, message, key, rc): xored = (message + key + rc) % self.prime return xored ** 7 % self.prime def encrypt(self, message, ek, iv = iv, rounds = 91): round_constant = self.sha3_256(iv) #in the paper the first round constant is 0 res = self.toInt(message) % self.prime key = self.toInt(ek) % self.prime for i in range(rounds): round_constant = self.sha3_256(round_constant) res = self.MiMCRound(res, key, self.toInt(round_constant)) return (res + key) % self.prime def hash(self, messages, iv): hash = 0 key = self.toInt(iv) % self.prime if len(messages) == 0: return else: for i in range(len(messages)): hash = self.encrypt(messages[i], key) % self.prime key = ( self.toInt(messages[i]) + hash + key) % self.prime return key def toInt(self, value): if type(value) != int: if type(value) == bytes: return int.from_bytes(value, "big") elif type(value) == str: return int.from_bytes(bytes(value, "utf8"), "big") else: return -1 else : return value def to_bytes(self, *args): for i, _ in enumerate(args): if isinstance(_, str): yield _.encode('ascii') elif not isinstance(_, int) and hasattr(_, 'to_bytes'): # for 'F_p' or 'FQ' class etc. yield _.to_bytes('big') elif isinstance(_, bytes): yield _ else: # Try conversion to integer first? yield int(_).to_bytes(32, 'big') def sha3_256(self, *args): data = b''.join(self.to_bytes(*args)) hashed = keccak_256(data).digest() return int.from_bytes(hashed, 'big') def all_tests(self): print("\nRunning tests") m1 = 3703141493535563179657531719960160174296085208671919316200479060314459804651 m2 = 134551314051432487569247388144051420116740427803855572138106146683954151557 m3 = 918403109389145570117360101535982733651217667914747213867238065296420114726 res = 0 if (self.sha3_256(b"Clearmatics") != 14220067918847996031108144435763672811050758065945364308986253046354060608451): print("SHA3 error:", self.sha3_256(b"Clearmatics"), "instead of", 14220067918847996031108144435763672811050758065945364308986253046354060608451) res += 1 if (self.encrypt(m1,m2) != 11437467823393790387399137249441941313717686441929791910070352316474327319704): print("Encrypt error:", self.encrypt(m1,m2), "instead of", 11437467823393790387399137249441941313717686441929791910070352316474327319704) res +=2 if (self.hash([m1, m2], m3) != 15683951496311901749339509118960676303290224812129752890706581988986633412003): print("Hash error", self.hash([m1, m2], m3), "instead of", 15683951496311901749339509118960676303290224812129752890706581988986633412003) res +=4 if res == 0: print("Tests passed") def generate_random_hash(self, verbose = 1): m0 = randint(0, self.prime-1) m1 = randint(0, self.prime-1) iv = randint(0, self.prime-1) h = self.hash([m0,m1], iv) if verbose < 5: print("\n-------------------- Generate random hash") print("h = mimc_hash([m0, m1], iv)") print("m0:", m0) print("m1:", m1) print("iv:", iv) print("h:", h) return m0, m1, iv, h def generate_left_imbricated_hash(self, verbose = 1): m0, m1, iv, h = self.generate_random_hash(verbose) m2 = randint(0, self.prime-1) iv2 = randint(0, self.prime-1) h2 = self.hash([h, m2], iv2) if verbose < 5: print("\n-------------------- Generate imbricated hash") print("h' = mimc_hash([h, m2], iv2)") print("h:", h) print("m2:", m2) print("iv2:", iv2) print("h:", h2) return h2 def generate_right_imbricated_hash(self, verbose = 1): m0, m1, iv, h = self.generate_random_hash(verbose) m2 = randint(0, self.prime-1) iv2 = randint(0, self.prime-1) h2 = self.hash([m2, h], iv2) if verbose < 5: print("\n-------------------- Generate imbricated hash") print("h' = mimc_hash([h, m2], iv2)") print("h:", h) print("m2:", m2) print("iv2:", iv2) print("h:", h2) return h2 def generate_tree(self, depth=2, iv = 14220067918847996031108144435763672811050758065945364308986253046354060608451, verbose = 1): if depth >10: print("tree too deep") return print("\n-------------------- Generate tree of depth", depth) leaves = [] print("\nLeaves") for i in range(2**depth): leaf = self.generate_imbricated_hash(verbose) leaves.append(leaf) if verbose >= 5: print(leaf) nodes = [leaves] for i in range(1,depth+1): if i != depth: print("\nLevel "+str(depth-i)) else: print("\nRoot") level = [] for j in range(len(nodes[i-1])//2): level.append(self.hash([nodes[i-1][2*j], nodes[i-1][2*j+1]], iv)) print(level[j]) nodes.append(level) return nodes def test_sha3(): m = MiMC7() assert m.sha3_256(b"Clearmatics") == 14220067918847996031108144435763672811050758065945364308986253046354060608451 def test_encrypt(): m = MiMC7() m1 = 3703141493535563179657531719960160174296085208671919316200479060314459804651 m2 = 134551314051432487569247388144051420116740427803855572138106146683954151557 assert m.encrypt(m1,m2) == 11437467823393790387399137249441941313717686441929791910070352316474327319704 def test_hash(): m = MiMC7() m1 = 3703141493535563179657531719960160174296085208671919316200479060314459804651 m2 = 134551314051432487569247388144051420116740427803855572138106146683954151557 m3 = 918403109389145570117360101535982733651217667914747213867238065296420114726 assert m.hash([m1, m2], m3) == 15683951496311901749339509118960676303290224812129752890706581988986633412003 def main(depth=2, verbose=1): m = MiMC7() m.all_tests() m.generate_imbricated_hash() m.generate_tree(depth=depth, verbose = verbose) if __name__ == "__main__": import sys sys.exit(main())
81f0c026554aff7d23ddd8a7367f44bfb7c5a4ed
[ "Python" ]
1
Python
rrtoledo/mimc
4701e7b6f1831063b9a48ba9d5abfbf533d50013
e5fecb710254cba67d6b188a3cf182bcb9c7d396
refs/heads/master
<file_sep>Android_LengKeng ================ LengKeng Group<file_sep>// date create // author <NAME> package lengkeng.group.vatcandidong; import lengkeng.group.Grid.Grid; import lengkeng.group.Student.ReuseMoveModifier; import org.anddev.andengine.entity.IEntity; import org.anddev.andengine.entity.modifier.IEntityModifier.IEntityModifierListener; import org.anddev.andengine.entity.sprite.AnimatedSprite; import org.anddev.andengine.opengl.buffer.BufferObjectManager; import org.anddev.andengine.opengl.texture.region.TiledTextureRegion; import org.anddev.andengine.util.modifier.IModifier; import org.anddev.andengine.util.modifier.ease.EaseLinear; public class VatCanDiDong extends AnimatedSprite { private ReuseMoveModifier reuseMoveModifier; private float Velocity = 300; private int Direction = 2 ; private boolean runEnable = true; private boolean finishStep = true; private IEntityModifierListener modifierListener = new IEntityModifierListener(){ @Override public void onModifierFinished(IModifier<IEntity> pModifier, IEntity pItem) { // TODO Auto-generated method stub finishStep = true; } @Override public void onModifierStarted(IModifier<IEntity> pModifier, IEntity pItem) { // TODO Auto-generated method stub switch(Direction){ case 0: // len animate(new long[]{100,100,100}, new int[]{9,10,11}, 0); break; case 1: // phai animate(new long[]{100,100,100}, new int[]{6,7,8}, 0); break; case 2: // xuong animate(new long[]{100,100,100}, new int[]{0,1,2}, 0); break; case 3: // trai animate(new long[]{100,100,100}, new int[]{3,4,5}, 0); break; } finishStep = false; } }; public VatCanDiDong(float pX, float pY, TiledTextureRegion pTiledTextureRegion){ super(pX, pY, pTiledTextureRegion); reuseMoveModifier = new ReuseMoveModifier(2, pX, pY, pX, pY, modifierListener, EaseLinear.getInstance()); this.registerEntityModifier(reuseMoveModifier); // this.animate(50); } public void setVelocity(float velocity){ Velocity = velocity; } public float getVelocity(){ return Velocity; } public void setDirection(int direction){ this.Direction = direction; } public int getDirection(){ return this.Direction; } public void setRunEnable(boolean value){ runEnable = value; } public boolean getRunEnable(){ return runEnable; } private float getDuration(final float x, final float y){ float d = (float) Math.sqrt((this.getX() - x)*(this.getX() - x) + (this.getY() - y)*(this.getY() - y)) / this.Velocity; return (float) (d+0.001); } public void move(){ if(finishStep){ int mCol = Grid.getCol(this.getX()); int mRow = Grid.getRow(this.getY()); int nextCol = mCol; int nextRow = mRow; if (runEnable) { this.caculateDirection(); switch (Direction){ case 0: nextRow --; break; case 1: nextCol ++; break; case 2: nextRow ++; break; case 3: nextCol --; break; default: break; } int x = Grid.getPosX(nextCol); int y = Grid.getPosY(nextRow); reuseMoveModifier.restart(getDuration(x,y), this.getX(), x, this.getY(), y); } } } public boolean checkCollision(int mCol, int mRow){ // kiem tra va cham voi chuong ngai vat va bien gioi Grid int nextCol = mCol; int nextRow = mRow; switch (Direction){ case 0: nextRow --; break; case 1: nextCol ++; break; case 2: nextRow ++; break; case 3: nextCol --; break; default: break; } if (nextCol == -1 || nextCol == Grid.NUM_COLUMN ) return true; if (nextRow == -1 || nextRow == Grid.NUM_ROW) return true; if (Grid.checkBlock(nextRow, nextCol)) return true; return false; } public void caculateDirection(){ // tinh toan huong di cua chuong nagi vat di dong int mCol = Grid.getCol(this.getX()); int mRow = Grid.getRow(this.getY()); // while(this.checkCollision(mCol, mRow)){ if(this.checkCollision(mCol, mRow)){ switch (Direction){ case 0: Direction = 1; break; case 1: Direction = 2; break; case 2: Direction = 3; break; case 3: Direction = 0; break; default: break; } } } public void removeMe() { this.setIgnoreUpdate(true); this.setVisible(false); this.reset(); this.detachSelf(); BufferObjectManager.getActiveInstance().unloadBufferObject(this.getVertexBuffer()); } } <file_sep>package lengkeng.group.Level_1; import java.util.Random; import lengkeng.group.GeneralClass.AnimatedItem; import lengkeng.group.Grid.Grid; import lengkeng.group.LevelManager.LevelManager; import org.anddev.andengine.engine.handler.timer.ITimerCallback; import org.anddev.andengine.engine.handler.timer.TimerHandler; import org.anddev.andengine.entity.sprite.AnimatedSprite; import org.anddev.andengine.entity.sprite.AnimatedSprite.IAnimationListener; public class RandomSprite { static Random rand = new Random(); public static void createSpriteSpawnTimeHandler(){ // 1s tao ra 1 target TimerHandler spriteTimerHandler; float mEffectSpawnDelay = 1.0f; spriteTimerHandler = new TimerHandler(mEffectSpawnDelay,true, new ITimerCallback(){ @Override public void onTimePassed(TimerHandler pTimerHandler){ addBook(); // addClock(); } }); LevelManager.getEngine().registerUpdateHandler(spriteTimerHandler); TimerHandler spriteTimerHandler_; float mEffectSpawnDelay_ = 10.0f; spriteTimerHandler_ = new TimerHandler(mEffectSpawnDelay_,true, new ITimerCallback(){ @Override public void onTimePassed(TimerHandler pTimerHandler){ // addBook(); addClock(); } }); LevelManager.getEngine().registerUpdateHandler(spriteTimerHandler_); } public static void addBook(){ // them dich int x; int y; // x : cot ---------------------- // y : hang --------------------- x = rand.nextInt(Grid.NUM_COLUMN); y = rand.nextInt(Grid.NUM_ROW); if(!Grid.checkItem(y, x) && !Grid.checkBlock(y, x)){ Grid.setItem(y, x, true); final AnimatedItem book; book = Level_1_Class_Scene.bookPool.obtainPoolItem(); book.animate(100, 10, new IAnimationListener () { @Override public void onAnimationEnd(final AnimatedSprite pAnimatedSprite) { LevelManager.getEngine().runOnUpdateThread(new Runnable() { @Override public void run() { Level_1_Class_Scene.bookPool.recyclePoolItem(book); } }); } }); book.setPosition(Grid.COLUMN[x]+5, Grid.ROW[y]+5); if(!book.isAttachToScene()){ LevelManager.getScene().attachChild(book); book.setAttachToScene(true); } } } public static void addClock(){ // them dich int x; int y; // x : cot ---------------------- // y : hang --------------------- x = rand.nextInt(Grid.NUM_COLUMN); y = rand.nextInt(Grid.NUM_ROW); if(!Grid.checkItem(y, x) && !Grid.checkBlock(y, x)){ Grid.setItem(y, x, true); final AnimatedItem clock; clock = Level_1_Class_Scene.ClockPool.obtainPoolItem(); clock.animate(100, 10, new IAnimationListener () { @Override public void onAnimationEnd(final AnimatedSprite pAnimatedSprite) { LevelManager.getEngine().runOnUpdateThread(new Runnable() { @Override public void run() { Level_1_Class_Scene.ClockPool.recyclePoolItem(clock); } }); } }); clock.setPosition(Grid.COLUMN[x]+5, Grid.ROW[y]+5); if(!clock.isAttachToScene()){ LevelManager.getScene().attachChild(clock); clock.setAttachToScene(true); } } } }
5cbf124271982ff14ff828db39962b8c8d0d6350
[ "Markdown", "Java" ]
3
Markdown
dragonbk91/Android_LengKeng
51de9ce37170abd10c019ffbcf58121bf17e85a8
ebf1231d8e82b810c755f8ab814101c6cf676ad4
refs/heads/dev
<file_sep>export * from './getOwn'; <file_sep>import AddConnectionForm from './add-connection-form/add-connection-form'; import AddDraftForm from './add-draft-form/add-draft-form'; import AddLineForm from './add-line-form/add-line-form'; import AddStationForm from './add-station-form/add-station-form'; import DeleteConnectionForm from './delete-connection-form/delete-connection-form'; import DeleteDraftForm from './delete-draft-form/delete-draft-form'; import DeleteLineForm from './delete-line-form/delete-line-form'; import DeleteStationForm from './delete-station-form/delete-station-form'; import EditConnectionForm from './edit-connection-form/edit-connection-form'; import EditDraftForm from './edit-draft-form/edit-draft-form'; import EditLineForm from './edit-line-form/edit-line-form'; import EditStationForm from './edit-station-form/edit-station-form'; import ImportDraftForm from './import-draft-form/import-draft-form'; export { AddDraftForm, AddLineForm, AddStationForm, DeleteDraftForm, DeleteStationForm, EditDraftForm, EditLineForm, EditStationForm, DeleteLineForm, AddConnectionForm, EditConnectionForm, DeleteConnectionForm, ImportDraftForm }; <file_sep>import { Icon } from 'components/shared'; import React from 'react'; import { Link } from 'react-router-dom'; import headerOptions from './headerOptions.json'; const header = (props) => { const { options, optionsName, showYear, town, year } = props; const _options = options || headerOptions[optionsName]; return ( <header className="ms-header ms-header-dark"> <div className="container container-full"> <div className="ms-title"> <a href="index.html"> <img src="assets/img/demo/logo-header.png" alt="" /> <span className="ms-logo animated zoomInDown animation-delay-5">T</span> <h1 className="animated fadeInRight animation-delay-6">Tube History<span> Map</span></h1> <div className="current-year">Year <span className="year">{year}</span></div> </a> </div> <div className="header-right"> {_options.showShareMenu ? ( <div className="share-menu"> <ul className="share-menu-list"> <li className="animated fadeInRight animation-delay-3"> <a href="" onClick={e => { e.preventDefault() }} className="btn-circle btn-google"> <Icon name="google" /> </a> </li> <li className="animated fadeInRight animation-delay-2"> <a href="" onClick={e => { e.preventDefault() }} className="btn-circle btn-facebook"> <Icon name="facebook" /> </a> </li> <li className="animated fadeInRight animation-delay-1"> <a href="" onClick={e => { e.preventDefault() }} className="btn-circle btn-twitter"> <Icon name="twitter" /> </a> </li> </ul> <a href="" onClick={e => { e.preventDefault() }} className="btn-circle btn-circle-primary animated zoomInDown animation-delay-7"> <Icon name="share" /> </a> </div> ) : null} {_options.showYear ? ( <a href="" onClick={e => { e.preventDefault(); props.onToggleYearSelector(); }} className="toggle-year-link btn-circle btn-circle-primary no-focus animated zoomInDown animation-delay-8" data-toggle="modal"> <Icon name="calendar" /> </a> ) : null} {_options.showPrint && town ? ( <Link to={`/${town.url}/${year}/print`} target="_blank" className="toggle-year-link btn-circle btn-circle-primary no-focus animated zoomInDown animation-delay-8" data-toggle="modal"> <Icon name="image" /> </Link> ) : null} {_options.showSearch ? ( <form className="search-form animated zoomInDown animation-delay-9"> <input id="search-box" type="text" className="search-input" placeholder="Search..." name="q" /> <label htmlFor="search-box"> <Icon name="search" /> </label> </form> ) : null} {_options.showTowns ? ( <Link to="/towns" className="btn-ms-menu btn-circle btn-circle-primary ms-toggle-left animated zoomInDown animation-delay-10"> <Icon name="globe" /> </Link> ) : null} {_options.showUser ? ( <a href="" className="btn-ms-menu btn-circle btn-circle-primary ms-toggle-left animated zoomInDown animation-delay-10"> <Icon name="account" /> </a> ) : null} </div> </div> <div className={`current-year ${showYear ? 'shown' : null}`}> Year <span className="year">{year}</span> {/* <div className="current-year-wrapper"> </div> */} </div> </header> ) } export default header; <file_sep>import Snackbar from 'node-snackbar/dist/snackbar'; const sharedConfig = { pos: 'bottom-right' } export const info = (text) => { Snackbar.show({ ...sharedConfig, text, customClass: 'secondary' }); }; export const warning = (text) => { Snackbar.show({ ...sharedConfig, text, customClass: 'warning' }); }; export const error = (text) => { Snackbar.show({ ...sharedConfig, text, customClass: 'error' }); };<file_sep>import Api from 'http/admin'; import { put } from 'redux-saga/effects'; import { searchParamsChangeStart, updateStationFail, updateStationSuccess } from 'store/admin/actions'; import { info } from 'util/notification'; export function* updateStationSagaStart(action) { try { yield Api.station.update(action.station); yield put(updateStationSuccess()); yield put(searchParamsChangeStart()); info('Station updated succesully'); } catch (err) { yield put(updateStationFail(err)); } }<file_sep>import { LineBadge } from 'components/shared'; import React from 'react'; import { getLinesFromStation } from 'util/data'; const stationsInfoHeader = ({ element }) => { return ( <div className="lines-info-header"> <div className="d-flex justify-content-between"> <div> {element.name} </div> <div> {getLinesFromStation(element).map(l => { return <LineBadge key={l._id} line={l} extraClass="ml-10" /> })} </div> </div> </div> ) } export default stationsInfoHeader;<file_sep>export * from './clearDraft'; export * from './finishAction'; export * from './startAction'; <file_sep>import React from 'react'; const BasicModal1 = () => <div>This is basic modal 1</div> export default BasicModal1;<file_sep>import { Button, ColorSelector, FormField, Input } from 'components/shared'; import React, { useEffect } from 'react'; import useForm from 'react-hook-form'; const EditLineForm = ({ actionObj, onSubmit, onCancel }) => { const { register, handleSubmit, errors, setValue, setError } = useForm(); useEffect(() => { register({ name: 'colour' }, { required: 'You must enter a color' }); register({ name: 'fontColour' }, { required: 'You must enter a font color' }); }, [register]); const handleSelectorChange = (name, selectedOption) => { console.log(name, selectedOption); setValue(name, selectedOption); setError(name, null); } const processSubmit = (formData) => { onSubmit({ ...formData, _id: actionObj._id }); } setValue('colour', actionObj.colour); setValue('fontColour', actionObj.fontColour); return ( <form className="form" onSubmit={handleSubmit(processSubmit)}> <FormField label="Key" error={errors.key && errors.key.message} > <Input name="key" formRef={register} defaultValue={actionObj.key} extraClass={errors.key && 'input-error'} required /> </FormField> <FormField label="Name" error={errors.name && errors.name.message} > <Input name="name" formRef={register} defaultValue={actionObj.name} extraClass={errors.name && 'input-error'} required /> </FormField> <FormField label="Short name" error={errors.shortName && errors.shortName.message} > <Input name="shortName" formRef={register} defaultValue={actionObj.shortName} extraClass={errors.shortName && 'input-error'} required /> </FormField> <FormField label="Year" error={errors.year && errors.year.message} > <Input name="year" type="number" formRef={register} defaultValue={actionObj.year} extraClass={errors.year && 'input-error'} required /> </FormField> <FormField label="Color" error={errors.colour && errors.colour.message} > <ColorSelector name="colour" color={actionObj.colour} onChange={(value) => handleSelectorChange('colour', value)} /> </FormField> <FormField label="Font Color" error={errors.fontColour && errors.fontColour.message} > <ColorSelector name="fontColour" color={actionObj.fontColour} onChange={(value) => handleSelectorChange('fontColour', value)} /> </FormField> <div className="row"> <div className="col-lg-6"> <Button submit color="secondary" inverse text="Edit line" block /> </div> <div className="col-lg-6"> <Button color="secondary" text="Cancel" outline block onClick={onCancel} /> </div> </div> </form> ); }; export default EditLineForm;<file_sep> import axios from '../axios'; export default class User { // Login static login = (email, password) => { return axios.get(`login?email=${email}&password=${password}`); } // SignUp static signUp = (email, password, name) => { return axios.post(`signup?email=${email}&password=${password}&name=${name}`); } // Get own user info static getOwn = () => { return axios.get(`user`); } // Get user info static getUser = (userId) => { return axios.get(`user/${userId}`); } }<file_sep>import * as actionTypes from './actionTypes'; export const updateStationStart = (station) => { return { type: actionTypes.UPDATE_STATION_START, station }; }; export const updateStationSuccess = () => { return { type: actionTypes.UPDATE_STATION_SUCCESS }; }; export const updateStationFail = (error) => { return { type: actionTypes.UPDATE_STATION_FAIL, error }; };<file_sep>export const initMapSuccess = (state, action) => { return { ...state, loading: false, town: action.town, year: action.year, draft: action.draft, stations: action.stations } } export const setYear = (state, action) => { return { ...state, year: action.year } }<file_sep>import Slider from 'rc-slider'; import Tooltip from 'rc-tooltip'; import React from 'react'; import Toggle from '../toggle/toggle'; const SliderRange = Slider.Range; const Handle = Slider.Handle; const handle = (props) => { const { value, dragging, index, ...restProps } = props; return ( <Tooltip prefixCls="rc-slider-tooltip" overlay={value} placement="bottom" key={index} > <Handle value={value} {...restProps} /> </Tooltip> ); }; class Range extends React.Component { constructor(props) { super(props); const { config } = this.props; this.state = { show: config.enabled, min: config.min, max: config.max, value: config.value }; } handleChange = (value) => { const { onChange } = this.props; this.setState({ value }); const externalValue = value ? { min: value[0], max: value[1] } : null; onChange(externalValue); } handleToggle = (value) => { const { config } = this.props; if (!value) { this.handleChange(null); } else { this.handleChange(config.value); } this.setState({ show: value }); } render() { const { config } = this.props; const { max, min, show, value } = this.state; return ( <div className="range form-group"> {config.enabled === undefined ? <label>{config.label}</label> : <Toggle label={config.label} value={config.enabled} onToggle={this.handleToggle} styleType={config.toggleType} />} {show ? ( <div> <div className="current-values"> <span>{value[0]}</span> <span> - </span> <span>{value[1]}</span> </div> <div className="slider-wrapper"> <SliderRange min={min} max={max} defaultValue={value} handle={handle} onAfterChange={(val) => this.handleChange(val)} /> </div> </div> ) : null} </div> ); } } export default Range;<file_sep>import axios from '../axios'; export default class Generation { exportDraftUrl = `${process.env.REACT_APP_API_URL}/generation/export/draft`; // Import draft static importDraft = (draftId, file) => { const fd = new FormData(); fd.append('File[]', file); return axios.post(`/generation/import/draft/${draftId}`, fd, { headers: { 'Content-Type': 'multipart/form-data' } }); } } <file_sep>export * from './initMap'; export * from './initMapDraft'; <file_sep>import Api from 'http/admin'; import { put, select } from 'redux-saga/effects'; import { searchParamsChangeFail, searchParamsChangeSuccess } from 'store/admin/actions'; import { error } from 'util/notification'; import { getDefaultPagination, getDefaultSearchParams } from 'util/searchDefaults'; export function* searchParamsChangeSagaStart(action) { try { const state = yield select(); const elementsType = action.elementsType || state.admin.elementsType; let searchParams = action.searchParams || state.admin.searchParams; if (!searchParams) { searchParams = getDefaultSearchParams(elementsType); } let pagination = action.pagination || state.admin.pagination; if (!pagination || action.elementsType !== state.admin.elementsType || action.searchParams !== state.admin.searchParams) { pagination = getDefaultPagination(elementsType); } const response = yield Api[elementsType].search(state.admin.draft._id, searchParams, pagination); yield put(searchParamsChangeSuccess(elementsType, response.data, searchParams)); } catch (err) { error('Something went wrong!'); yield put(searchParamsChangeFail(err)); } }<file_sep> import axios from '../axios'; export default class Connection { // Get connections by year range in draft - Auth static getConnectionsWithAuth = (draftId, yearTo, yearFrom) => { return axios.get(`${draftId}/private/connection/year/${yearTo}/${yearFrom}`); } // Get connections by year range in draft - Public static getConnections = (draftId, yearTo, yearFrom) => { return axios.get(`${draftId}/connection/year/${yearTo}/${yearFrom}`); } }<file_sep>import { Button, CollapseList } from 'components/shared'; import React from 'react'; import StationsFilter from './stations-filter/stations-filter'; import StationsInfoContent from './stations-info-content/stations-info-content'; import StationsInfoHeader from './stations-info-header/stations-info-header'; const stationsInfo = (props) => { const { draftId, stations, viewStationStations, onChangeParams, onAddStation, onEditStation, onDeleteStation } = props; return ( <div className="stations-info"> <div className="flex flex-row flex-space-between mb-30"> <StationsFilter draftId={draftId} onChangeParams={onChangeParams} /> <div> <Button text="Add station" icon="add" outline onClick={onAddStation} /> </div> </div> <CollapseList elements={stations} hoverType="secondary" header={StationsInfoHeader} content={StationsInfoContent} actions={{ viewStationStations, onEditStation, onDeleteStation }} {...props} /> </div> ) } export default stationsInfo;<file_sep>import { Button, FormField, Input, LineSelector, StationSelector } from 'components/shared'; import React, { useEffect } from 'react'; import useForm from 'react-hook-form'; const EditConnectionForm = ({ actionObj, draftId, onSubmit, onCancel }) => { const { register, handleSubmit, errors, setValue, setError } = useForm(); useEffect(() => { register({ name: 'line' }, { required: 'You must enter a line' }); register({ name: 'from' }, { required: 'You must enter a station' }); register({ name: 'to' }, { required: 'You must enter a station' }); }, [register]); const handleSelectorChange = (name, selectedOption) => { setValue(name, selectedOption); setError(name, null); } const processSubmit = (formData) => { onSubmit({ _id: actionObj._id, line: formData.line._id, stations: [ formData.from._id, formData.to._id ], year: formData.year, yearEnd: formData.yearEnd }); } return ( <form className="form" onSubmit={handleSubmit(processSubmit)}> <FormField label="Line" error={errors.line && errors.line.message} > <LineSelector draftId={draftId} defaultValue={actionObj.line._id} onChange={(value) => handleSelectorChange('line', value)} /> </FormField> <FormField label="From" error={errors.from && errors.from.message} > <StationSelector draftId={draftId} defaultValue={actionObj.stations[0]._id} onChange={(value) => handleSelectorChange('from', value)} /> </FormField> <FormField label="To" error={errors.to && errors.to.message} > <StationSelector draftId={draftId} defaultValue={actionObj.stations[1]._id} onChange={(value) => handleSelectorChange('to', value)} /> </FormField> <FormField label="Year" error={errors.year && errors.year.message} > <Input name="year" type="number" formRef={register} defaultValue={actionObj.year} extraClass={errors.year && 'input-error'} required /> </FormField> <FormField label="Year End" error={errors.yearEnd && errors.yearEnd.message} > <Input name="yearEnd" type="number" formRef={register} defaultValue={actionObj.yearEnd} extraClass={errors.yearEnd && 'input-error'} /> </FormField> <div className="row"> <div className="col-lg-6"> <Button submit color="secondary" inverse text="Confirm" block /> </div> <div className="col-lg-6"> <Button color="secondary" text="Cancel" outline block onClick={onCancel} /> </div> </div> </form> ); }; export default EditConnectionForm;<file_sep>export const ADD_CONNECTION_START = 'ADD_CONNECTION_START'; export const ADD_CONNECTION_SUCCESS = 'ADD_CONNECTION_SUCCESS'; export const ADD_CONNECTION_FAIL = 'ADD_CONNECTION_FAIL'; export const UPDATE_CONNECTION_START = 'UPDATE_CONNECTION_START'; export const UPDATE_CONNECTION_SUCCESS = 'UPDATE_CONNECTION_SUCCESS'; export const UPDATE_CONNECTION_FAIL = 'UPDATE_CONNECTION_FAIL'; export const DELETE_CONNECTION_START = 'DELETE_CONNECTION_START'; export const DELETE_CONNECTION_SUCCESS = 'DELETE_CONNECTION_SUCCESS'; export const DELETE_CONNECTION_FAIL = 'DELETE_CONNECTION_FAIL';<file_sep>import { Button } from 'components/shared'; import React from 'react'; const dataPresentation = () => { return ( <div className="showroom-data-presentation"> <h1 className="right-line mb-40">Data presentation</h1> <div className="row"> <div className="col"> <div className="showroom-element showroom-link"> <Button to="/showroom/data-presentation/collapses" text="Collapses" type="link" color="secondary" /> </div> </div> <div className="col"> <div className="showroom-element showroom-link"> <Button to="/showroom/data-presentation/badges" text="Badges" type="link" color="secondary" /> </div> </div> <div className="col"> <div className="showroom-element showroom-link"> <Button to="/showroom/data-presentation/country-labels" text="Country labels" type="link" color="secondary" /> </div> </div> <div className="col"> <div className="showroom-element showroom-link"> <Button to="/showroom/data-presentation/icons" text="Icons" type="link" color="secondary" /> </div> </div> <div className="col"> <div className="showroom-element showroom-link"> <Button to="/showroom/data-presentation/loading-spinners" text="Loading spinners" type="link" color="secondary" /> </div> </div> <div className="col"> <div className="showroom-element showroom-link"> <Button to="/showroom/data-presentation/paginations" text="Paginations" type="link" color="secondary" /> </div> </div> <div className="col"> <div className="showroom-element showroom-link"> <Button to="/showroom/data-presentation/panels" text="Panels" type="link" color="secondary" /> </div> </div> <div className="col"> <div className="showroom-element showroom-link"> <Button to="/showroom/data-presentation/tabs" text="Tabs" type="link" color="secondary" /> </div> </div> </div> </div> ) } export default dataPresentation;<file_sep>import axios from '../axios'; export default class Country { // Get countries static getCountries = () => { return axios.get(`countries`); } } <file_sep>import React from 'react'; import BasicForm from './forms/basic-form'; import BasicFormWithSelector from './forms/basic-form-selector'; class Forms extends React.Component { render() { return ( <div className="showroom-forms"> <h1 className="right-line mb-40">Forms</h1> <div className="row"> <div className="col-3"> <div className="showroom-element"> <label>Basic form</label> <BasicForm /> </div> </div> <div className="col-3"> <div className="showroom-element"> <label>Basic form with selector</label> <BasicFormWithSelector /> </div> </div> </div> </div> ) } } export default Forms; <file_sep>import { takeEvery } from "redux-saga/effects"; import * as actionTypes from "store/admin/actions/generation/actionTypes"; import { importDraftSagaStart } from './workers'; export const generationSagas = [ takeEvery(actionTypes.IMPORT_DRAFT_START, importDraftSagaStart) ];<file_sep>import { Icon } from 'components/shared'; import PropTypes from 'prop-types'; import React from 'react'; import { Link } from 'react-router-dom'; const NoResultsBox = ({ noDrafts, className }) => { return ( <div className={`noresults-box ${className}`}> {!noDrafts && ( <Link to="/admin/create-draft"> <Icon name="add" color="secondary" size="lg" /> <span>Create your first draft</span> </Link> )} {noDrafts && ( <div><span>You need to create a draft in order to publish it</span></div> )} </div> ) } NoResultsBox.defaultProps = { noDrafts: false, className: '' }; NoResultsBox.propTypes = { noDrafts: PropTypes.bool, className: PropTypes.string }; export default NoResultsBox; <file_sep>import { push } from 'connected-react-router'; import Api from 'http/admin'; import { put } from 'redux-saga/effects'; import { loginFail, loginSuccess } from 'store/auth/actions'; export function* loginSagaStart(action) { try { const response = yield Api.user.login(action.email, action.password); Api.setAuthToken(response.data.token); localStorage.setItem('auth', response.data.token); yield put(push('/admin')); yield put(loginSuccess()); } catch (err) { yield put(loginFail(err)); } }<file_sep>export * from './user-picture/user-picture'; <file_sep>import { takeEvery } from "redux-saga/effects"; import * as actionTypes from "store/admin/actions/search/actionTypes"; import { searchParamsChangeSagaStart } from './workers'; export const searchSagas = [ takeEvery(actionTypes.SEARCH_PARAMS_CHANGE_START, searchParamsChangeSagaStart) ]; <file_sep>import { removeAuthToken, setAuthToken } from './authToken'; import Connection from './connection/connection'; import Country from './country/country'; import Draft from './draft/draft'; import Generation from './generation/generation'; import Line from './line/line'; import Station from './station/station'; import Town from './town/town'; import User from './user/user'; export default { connection: Connection, country: Country, draft: Draft, generation: Generation, line: Line, station: Station, town: Town, user: User, setAuthToken, removeAuthToken } <file_sep>import Api from 'http/admin'; import { put, select } from 'redux-saga/effects'; import { addStationFail, addStationSuccess, getDraftStart, searchParamsChangeStart } from 'store/admin/actions'; import { error, info } from 'util/notification'; export function* addStationSagaStart(action) { try { const state = yield select(); yield Api.station.add(state.admin.draft._id, { ...action.station, order: 99 }); yield put(addStationSuccess()); yield put(getDraftStart(state.admin.draft._id)); yield put(searchParamsChangeStart()); info('Station was created succesully'); } catch (err) { error('Something went wrong!'); yield put(addStationFail(err)); } }<file_sep>import { push } from 'connected-react-router'; import Api from 'http/admin'; import { put } from 'redux-saga/effects'; import { addDraftFail, addDraftSuccess } from 'store/admin/actions'; import { error, info } from 'util/notification'; export function* addDraftSagaStart(action) { try { yield Api.draft.add(action.town, action.draft); yield put(addDraftSuccess()); yield put(push('/admin')); info('Draft was created succesully'); } catch (err) { error('Something went wrong!'); yield put(addDraftFail(err)); } }<file_sep>import Api from 'http/admin'; import pagination from 'http/admin/defaultParams/pagination'; import PropTypes from 'prop-types'; import React from 'react'; import Select from '../select/select'; import LineDropdown from './line-dropdown/line-dropdown'; import LineSelected from './line-selected/line-selected'; import selectConfig from './line-selector.config.json'; const searchParams = { select: "shortName colour", populate: "" } const allLinesOption = { _id: null, shortName: 'All lines', colour: '#ffffff' }; class LineSelector extends React.Component { constructor(props) { super(props); this.state = { lines: [], initialLine: null }; this.handleOnChange = this.handleOnChange.bind(this); this.handleInputChange = this.handleInputChange.bind(this); this.remoteSearch = this.remoteSearch.bind(this); } async componentDidMount() { const { allLinesOpt, defaultValue, draftId, remoteSearch } = this.props; if (!remoteSearch) { const res = await Api.line.search(draftId, { ...searchParams, filter: {} }, pagination); const lines = res.data.elements; if (allLinesOpt) { lines.unshift(allLinesOption) } this.setState({ lines: res.data.elements, initialLine: lines.find(l => l._id === defaultValue) }) } else { await this.getInitialLine(defaultValue); } } async getInitialLine(lineId) { const { draftId } = this.props; const res = await Api.line.search(draftId, { ...searchParams, filter: { _id: lineId } }, pagination); this.setState({ initialLine: res.data.elements[0] }) } handleOnChange(line) { const { onChange } = this.props; onChange(line); } handleInputChange(str) { const { remoteSearch } = this.props; if (remoteSearch) { this.remoteSearch(str) } } async remoteSearch(str) { if (!str || str.length < 2) { this.setState({ lines: [] }) return; } const { draftId } = this.props; const res = await Api.line.search(draftId, { ...searchParams, filter: { name: str } }, pagination); this.setState({ lines: res.data.elements }) } render() { const { lines, initialLine } = this.state; const { allLinesOpt, className } = this.props; const getSelectedElement = () => { if (initialLine) { return initialLine; } if (allLinesOpt) { return allLinesOpt; } return null; } return ( <div className={`line-selector ${className}`}> <Select config={{ ...selectConfig, remote: true }} options={lines} dropdown={LineDropdown} selected={LineSelected} selectedElement={getSelectedElement()} onChange={this.handleOnChange} onInputChange={this.handleInputChange} /> </div> ) } } LineSelector.defaultProps = { allLinesOpt: false, remoteSearch: false, defaultValue: null, className: '', onChange: () => { } }; LineSelector.propTypes = { draftId: PropTypes.string.isRequired, remoteSearch: PropTypes.bool, allLinesOpt: PropTypes.bool, defaultValue: PropTypes.string, className: PropTypes.string, onChange: PropTypes.func }; export default LineSelector;<file_sep>import Api from 'http/admin'; import { put } from 'redux-saga/effects'; import { deleteLineFail, deleteLineSuccess, searchParamsChangeStart } from 'store/admin/actions'; import { error, info } from 'util/notification'; export function* deleteLineSagaStart(action) { try { yield Api.line.delete(action.lineId); yield put(deleteLineSuccess()); yield put(searchParamsChangeStart()); info('Line was deleteded succesully'); } catch (err) { error('Something went wrong!'); yield put(deleteLineFail(err)); } }<file_sep>import React from 'react'; import Select from '../select/select'; import TownDropdown from './town-dropdown/town-dropdown'; import TownSelected from './town-selected/town-selected'; import selectConfig from './town-selector.config.json'; const TownSelector = ({ towns, onChange }) => { return ( <div className="town-selector"> {towns.length ? ( <Select config={{ ...selectConfig }} options={towns} dropdown={TownDropdown} selected={TownSelected} onChange={onChange} /> ) : null} </div> ) } export default TownSelector;<file_sep>import { Button, FormField, Input } from 'components/shared'; import React from 'react'; import Dropzone from 'react-dropzone'; class ImportDraftForm extends React.Component { constructor(props) { super(props); this.state = { file: null } this.handleFileSelected = this.handleFileSelected.bind(this); this.processSubmit = this.processSubmit.bind(this); } handleFileSelected(files) { this.setState({ file: files[0] }); } processSubmit(event) { const { actionObj, onSubmit } = this.props; event.preventDefault() const { file } = this.state; onSubmit({ file, _id: actionObj._id }); } render() { const { onCancel } = this.props; const { file } = this.state; return ( <div> <h4 className="text-center">Warning - This will erase existing data for this draft (lines, stations and connections)</h4> <form className="form mt-40" onSubmit={this.processSubmit}> <Dropzone onDrop={this.handleFileSelected} multiple={false} accept="application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"> {({ getRootProps, getInputProps }) => ( <section> <div {...getRootProps()}> <input {...getInputProps()} /> <FormField label="File" > <Input name="file" value={file && file.name} required readOnly /> </FormField> </div> </section> )} </Dropzone> <div className="row"> <div className="col-lg-6"> <Button submit color="warning" text="Import data" outline block /> </div> <div className="col-lg-6"> <Button color="secondary" text="Cancel" outline block onClick={onCancel} /> </div> </div> </form> </div> ); } }; export default ImportDraftForm;<file_sep>import Api from 'http/admin'; import { put } from "redux-saga/effects"; import * as actions from "store/auth/actions"; export function* signUpSagaStart(action) { try { const response = yield Api.user.signUp(action.email, action.password, action.name); Api.setAuthToken(response.data.token); localStorage.setItem('auth', response.data.token); yield put(actions.signUpSuccess()); yield put(actions.loginStart(action.email, action.password)); } catch (err) { yield put(actions.signUpFail(err)); } }<file_sep>import Api from 'http/admin'; import { put } from 'redux-saga/effects'; import { deleteConnectionFail, deleteConnectionSuccess, searchParamsChangeStart } from 'store/admin/actions'; import { error, info } from 'util/notification'; export function* deleteConnectionSagaStart(action) { try { yield Api.connection.delete(action.connectionId); yield put(deleteConnectionSuccess()); yield put(searchParamsChangeStart()); info('Connection was deleteded succesully'); } catch (err) { error('Something went wrong!'); yield put(deleteConnectionFail(err)); } }<file_sep>export * from './map.google.service'; export * from './map.google.service.old'; export * from './search.google.service'; <file_sep>import * as actionTypes from './actionTypes'; export const addLineStart = (line) => { return { type: actionTypes.ADD_LINE_START, line }; }; export const addLineSuccess = () => { return { type: actionTypes.ADD_LINE_SUCCESS }; }; export const addLineFail = (error) => { return { type: actionTypes.ADD_LINE_FAIL, error }; };<file_sep>export const IMPORT_DRAFT_START = 'IMPORT_DRAFT_START'; export const IMPORT_DRAFT_SUCCESS = 'IMPORT_DRAFT_SUCCESS'; export const IMPORT_DRAFT_FAIL = 'IMPORT_DRAFT_FAIL'; <file_sep>export { addConnectionSagaStart } from './addConnection'; export { deleteConnectionSagaStart } from './deleteConnection'; export { updateConnectionSagaStart } from './updateConnection'; <file_sep>import { Badge, Button, InfoElement, Translation } from 'components/shared'; import React from 'react'; const linesInfoContent = ({ element, actions }) => { const i18nPrefix = 'ADMIN.TOWN.LINES'; return ( <div className="lines-info-content"> <div className="row mb-20"> <div className="col-lg-12 col-md-12"> <h4 className="secondary right-line right-line-secondary mb-20"><Translation prefix={i18nPrefix} id="LINE_INFO" /></h4> <div className="row"> <div className="col-lg-8"> <InfoElement prefix={i18nPrefix} id="NAME" value={element.name} /> <InfoElement prefix={i18nPrefix} id="YEAR" value={element.year && <Badge text={element.year} />} /> <InfoElement prefix={i18nPrefix} id="STATIONS" value={element.stationsAmount} /> <InfoElement prefix={i18nPrefix} id="DISTANCE" value={element.distance} /> </div> <div className="col-lg-4"> <InfoElement prefix={i18nPrefix} id="COLOR" value={<Badge backgroundColor={element.colour} text={element.colour} />} /> <InfoElement prefix={i18nPrefix} id="FONT" value={<Badge backgroundColor={element.fontColour} text={element.fontColour} border />} /> </div> </div> </div> </div> <div className="row"> <div className="col-md-4 mb-sm-10"> <Button fontColor={element.fontColour} backgroundColor={element.colour} hover="primary" block text={<Translation prefix={i18nPrefix} id="VIEW_STATIONS" />} onClick={() => actions.viewLineStations(element)} /> </div> <div className="col-md-4 mb-sm-10"> <Button color="secondary" text={<Translation prefix={i18nPrefix} id="EDIT_LINE" />} block outline onClick={() => actions.onEditLine(element)} /> </div> <div className="col-md-4 mb-sm-10"> <Button color="danger" text={<Translation prefix={i18nPrefix} id="DELETE_LINE" />} block outline onClick={() => actions.onDeleteLine(element)} /> </div> </div> </div> ) } export default linesInfoContent;<file_sep>export * from './addConnection'; export * from './deleteConnection'; export * from './updateConnection'; <file_sep>import { all } from "redux-saga/effects"; import { mainSagas } from './main'; export function* watchPublic() { yield all([ ...mainSagas ]) } <file_sep>import * as actionTypes from './actionTypes'; export const deleteLineStart = (lineId) => { return { type: actionTypes.DELETE_LINE_START, lineId }; }; export const deleteLineSuccess = () => { return { type: actionTypes.DELETE_LINE_SUCCESS }; }; export const deleteLineFail = (error) => { return { type: actionTypes.DELETE_LINE_FAIL, error }; };<file_sep>import { all } from "redux-saga/effects"; import { connectionSagas } from './connection'; import { draftSagas } from './draft'; import { generationSagas } from './generation'; import { lineSagas } from './line'; import { searchSagas } from './search'; import { stationSagas } from './station'; import { townSagas } from './town'; import { userSagas } from './user'; export function* watchAdmin() { yield all([ ...userSagas, ...townSagas, ...draftSagas, ...lineSagas, ...stationSagas, ...connectionSagas, ...generationSagas, ...searchSagas ]) } <file_sep>import { Button } from 'components/shared'; import React from 'react'; const ModalWithProps = ({ name, onClick }) => { return ( <div> <div className="mb-20">This is a modal with props - Name: {name}</div> <Button text="Print console log" onClick={onClick} /> </div> ) } export default ModalWithProps;<file_sep>import { Icon } from 'components/shared'; import PropTypes from 'prop-types'; import React from 'react'; class CollapseList extends React.Component { constructor(props) { super(props); this.state = { activeElementId: null }; this.setActiveElement = this.setActiveElement.bind(this); } setActiveElement(element) { const { activeElementId } = this.state; const { onElementSelected, onActiveElementChanged } = this.props; const activeId = activeElementId !== element._id ? element._id : null; if (onActiveElementChanged) { onActiveElementChanged(activeId); } else { this.setState({ activeElementId: activeId }); } if (onElementSelected && activeId) { onElementSelected(activeId); } } render() { const { actions, elements, extraClass, type, header, hoverType, content, activeElementContent, externalActiveElementId } = this.props; const { activeElementId } = this.state; const Header = header; const Content = content; const currentActiveElementId = externalActiveElementId || activeElementId; return ( <ul className={`collapse-list collapse-list-${type || 'default'} ${hoverType ? `collapse-list-hover-${hoverType}` : ''} ${extraClass}`}> {elements.map((el, i) => ( <li key={i}> <div className={`collapse-list-element ${currentActiveElementId === el._id ? 'active' : ''}`}> <div className="collapse-list-header"> <a onClick={() => this.setActiveElement(el)}> <div className="collapse-list-header-container"> <Header element={el} /> <Icon name="angle-down" /> </div> </a> </div> <div className="collapse-list-content"> <Content element={activeElementContent || el} actions={actions} {...this.props} /> </div> </div> </li> ) )} </ul> ) } } CollapseList.defaultProps = { hoverType: null }; CollapseList.propTypes = { hoverType: PropTypes.string }; export default CollapseList;<file_sep>import * as actionTypes from './actionTypes'; export const deleteDraftStart = (draftId) => { return { type: actionTypes.DELETE_DRAFT_START, draftId }; }; export const deleteDraftSuccess = () => { return { type: actionTypes.DELETE_DRAFT_SUCCESS }; }; export const deleteDraftFail = (error) => { return { type: actionTypes.DELETE_DRAFT_FAIL, error }; };<file_sep>import { Button, FormField, Input, TownSelector } from 'components/shared'; import React, { useEffect } from 'react'; import useForm from 'react-hook-form'; const AddDraftForm = ({ towns, onSubmit }) => { const { register, handleSubmit, errors, setValue, setError } = useForm(); useEffect(() => { register({ name: 'town' }, { required: true }); }, [register]); const handleSelectorChange = (name, selectedOption) => { setValue(name, selectedOption); setError(name, null); } return ( <form className="form" onSubmit={handleSubmit(onSubmit)}> <FormField label="Name" error={errors.name && errors.name.message} > <Input name="name" formRef={register} extraClass={errors.name && 'input-error'} required /> </FormField> <FormField label="Description" error={errors.description && errors.description.message} > <Input name="description" formRef={register} extraClass={errors.password && 'input-error'} required /> </FormField> <FormField label="Town" error={errors.town && 'You must select a town'} > <TownSelector towns={towns} name="town" onChange={(selectedOptions) => handleSelectorChange('town', selectedOptions)} /> </FormField> <Button submit color="secondary" text="Create draft" /> </form> ); }; export default AddDraftForm;<file_sep>export const getLinesFromStation = (station) => { const result = []; station.connections.forEach(c => { if (result.findIndex(l => l._id === c.line._id) === -1) { result.push(c.line); } }); return result; } export const hasErrors = (errors) => { return Object.keys(errors).length > 0 && errors.constructor === Object; } export const filterStationsAndConnectionsByYear = (stations, year) => { return stations .filter(station => station.year <= year) .map(station => { return { ...station, connections: station.connections.filter(con => con.year <= year && (!con.yearEnd || con.yearEnd > year)) } }); } export const getStationMarkerColor = (station) => { const colors = station.connections.reduce((_colors, con) => { return _colors.includes(con.line.colour) ? _colors : [..._colors, con.line.colour]; }, []) return colors.length === 1 ? colors[0] : '#ffffff' }<file_sep>import { removeAuthToken, setAuthToken } from './authToken'; import Connection from './connection/connection'; import Draft from './draft/draft'; import Station from './station/station'; import Town from './town/town'; import User from './user/user'; export default { connection: Connection, station: Station, town: Town, draft: Draft, user: User, setAuthToken, removeAuthToken } <file_sep>import LinesInfo from 'components/admin/admin-town/lines-info/lines-info'; import { Pagination } from 'components/shared'; import React from 'react'; import { connect } from 'react-redux'; import { finishAction, searchParamsChangeStart, startAction } from 'store/admin/actions'; class AdminLinesPanel extends React.Component { constructor(props) { super(props); this.search = this.search.bind(this); this.changePage = this.changePage.bind(this); this.addLineStart = this.addLineStart.bind(this); this.editLineStart = this.editLineStart.bind(this); this.deleteLineStart = this.deleteLineStart.bind(this); } componentDidMount() { this.search(); } search(page) { const { searchParams, pagination, searchLines } = this.props; const _pagination = page ? { ...pagination, page } : pagination; searchLines(searchParams, _pagination); } changePage(page) { this.search(page); } addLineStart() { const { _startAction } = this.props; _startAction('addLine'); } editLineStart(line) { const { _startAction } = this.props; _startAction('editLine', line); } deleteLineStart(lineId) { const { _startAction } = this.props; _startAction('deleteLine', lineId); } render() { const { elementsType, lines, pagination } = this.props; return ( <div className="admin-lines-panel"> {elementsType === 'line' ? ( <LinesInfo lines={lines} onAddLine={this.addLineStart} onEditLine={this.editLineStart} onDeleteLine={this.deleteLineStart} /> ) : null} {lines.length ? ( <Pagination color="secondary" pagination={pagination} onPageChange={this.changePage} /> ) : null} </div> ) } } const mapStateToProps = state => { return { elementsType: state.admin.elementsType, lines: state.admin.elements, searchParams: state.admin.searchParams, pagination: state.admin.pagination }; }; const mapDispatchToProps = dispatch => { return { _startAction: (actionName, actionObj) => dispatch(startAction(actionName, actionObj)), _finishAction: () => dispatch(finishAction()), searchLines: (searchParams, pagination) => dispatch(searchParamsChangeStart(searchParams, pagination, 'line')) } }; export default connect(mapStateToProps, mapDispatchToProps)(AdminLinesPanel); <file_sep>import { Button, FormField, Input } from 'components/shared'; import PropTypes from 'prop-types'; import React from 'react'; import useForm from 'react-hook-form'; const LoginForm = (props) => { const { onSubmit } = props; const { register, handleSubmit, errors } = useForm(); return ( <form className="form" onSubmit={handleSubmit(onSubmit)}> <FormField label="Email Address" error={errors.email && errors.email.message} > <Input type="email" name="email" formRef={register} extraClass={errors.email && 'input-error'} clearable required /> </FormField> <FormField label="Password" error={errors.password && errors.password.message} > <Input type="password" name="password" formRef={register} extraClass={errors.password && 'input-error'} required /> </FormField> <Button submit color="primary" text="Login" extraClass="mb-20" /> </form> ); }; LoginForm.propTypes = { onSubmit: PropTypes.func.isRequired }; export default LoginForm;<file_sep>import React from 'react'; import SelectDropdown from './select-dropdown/select-dropdown'; class Select extends React.Component { constructor(props) { const { defaultValue } = props; super(props); this.state = { selectedOption: defaultValue || null, expanded: false } this.showDropdown = this.showDropdown.bind(this); this.selectOption = this.selectOption.bind(this); } // static getDerivedStateFromProps(props, currentState) { // debugger // if (currentState.value !== props.value) { // return { selectedOption: props.value }; // } // return null; // } componentDidUpdate(prevProps) { const { value } = this.props; if (value !== prevProps.value) { this.selectOption(value); } } showDropdown() { const { noDropdown, onDropdownOpen } = this.props; if (!noDropdown) { this.setState({ expanded: true }); } if (onDropdownOpen) { onDropdownOpen(); } } selectOption(option) { const { config, onChange } = this.props; this.setState({ selectedOption: option, expanded: false }); const selectedOption = option && option[config.options.key] === 'none' ? null : option; onChange(config.options.value && selectedOption ? selectedOption[config.options.value] : selectedOption); } close() { this.setState({ expanded: false }); } render() { const { externalExpanded, noDropdown, selected, selectedElement } = this.props; const { expanded, selectedOption } = this.state; const Selected = selected; return ( <div className={`dropdown bootstrap-select form-control ${expanded ? 'show' : ''}`}> <button type="button" className="btn btn-lg btn-select dropdown-toggle" onClick={this.showDropdown} aria-expanded={!expanded} > <Selected selectedOption={selectedOption || selectedElement} /> </button> {!noDropdown && ( <SelectDropdown expanded={expanded} onSelectOption={(opt) => this.selectOption(opt)} onClose={() => this.close()} {...this.props} /> )} {(expanded || externalExpanded) && noDropdown} </div> ) } } export default Select;<file_sep>import { DraftCard, MapCard, TownCard } from './cards'; import NoResultsBox from './noresults-box/noresults-box'; import UserPicture from './user/user-picture/user-picture'; export { DraftCard, MapCard, NoResultsBox, TownCard, UserPicture }; <file_sep>import axios from '../axios'; export default class Town { // Get towns static getAll = () => { return axios.get(`town/all`); } // Get town info static get = (townIdOrName) => { return axios.get(`town/${townIdOrName}`); } // Add town static add = (town) => { return axios.post('town', town); } // Update town static update = (town) => { return axios.put(`town/${town._id}`, town); } // Delete town static delete = (townId) => { return axios.delete(`town/${townId}`); } } <file_sep>const modes = require('./side-bar-modes.json'); export const getPrevSideBarMode = (mode) => { return getPrevSideBar(mode, 'prev'); } export const getPrevSideBarModeLabel = (mode) => { return getPrevSideBar(mode, 'prevLabel'); } const getPrevSideBar = (mode, property) => { if (!mode) { return null; } return modes.find(m => m.mode === mode)[property]; } <file_sep>export const searchPlace = async (searchServicestr) => { return new Promise((resolve, reject) => { new window.google.maps.places.PlacesService(document.createElement('div')).textSearch({ query: searchServicestr, type: 'transit_station' }, (predictions, status) => { if (status !== window.google.maps.places.PlacesServiceStatus.OK) { reject(status); } resolve(predictions); }); }); } export const getPlaceDetails = async (placeId) => { return new Promise((resolve, reject) => { new window.google.maps.places.PlacesService(document.createElement('div')).getDetails({ placeId }, (placeResult, placesServiceStatus) => { if (placesServiceStatus !== window.google.maps.places.PlacesServiceStatus.OK) { reject(placesServiceStatus); } resolve(placeResult); }); }); }<file_sep>export const ADD_LINE_START = 'ADD_LINE_START'; export const ADD_LINE_SUCCESS = 'ADD_LINE_SUCCESS'; export const ADD_LINE_FAIL = 'ADD_LINE_FAIL'; export const UPDATE_LINE_START = 'UPDATE_LINE_START'; export const UPDATE_LINE_SUCCESS = 'UPDATE_LINE_SUCCESS'; export const UPDATE_LINE_FAIL = 'UPDATE_LINE_FAIL'; export const DELETE_LINE_START = 'DELETE_LINE_START'; export const DELETE_LINE_SUCCESS = 'DELETE_LINE_SUCCESS'; export const DELETE_LINE_FAIL = 'DELETE_LINE_FAIL';<file_sep>import React from 'react'; const connectionsInfoHeader = ({ element }) => { return ( <div className="lines-info-header" style={{ borderLeft: `10px solid ${element.line.colour}` }}> <span>{element.stations[0].name} - {element.stations[1].name}</span> </div> ) } export default connectionsInfoHeader;<file_sep>import SignUpForm from 'components/public/auth/signup/signup-form/signup-form'; import { Button, Panel } from 'components/shared'; import React from 'react'; import { connect } from 'react-redux'; import { withRouter } from "react-router-dom"; import * as actions from 'store/auth/actions'; class Signup extends React.Component { render() { const { signup } = this.props; return ( <div className="flex flex-center full-page bg-secondary"> <Panel extraClass="animated fadeInUp animation-delay-7" width={650} > <h1 className="secondary mb-40">Signup</h1> <SignUpForm onSubmit={signup} /> <div> <span className="secondary">Do you have already an account?</span> <Button type="link" to="/login" color="secondary" text="Login" extraClass="ml-5" /> </div> </Panel> </div> ) } } const mapStateToProps = state => { return { loading: state.auth.loading }; }; const mapDispatchToProps = dispatch => { return { signup: (formData) => dispatch(actions.signUpStart(formData.email, formData.password, formData.name)) } }; export default connect(mapStateToProps, mapDispatchToProps)(withRouter(Signup));<file_sep>import React from 'react'; const collapse = (props) => { const { active, content, header, type } = props; return ( <div className={`card card-code card-${type || 'default'} ${active ? 'active' : ''}`}> <div className="card-header card-code-header" role="tab" id="codeHead1"> <h4 className="panel-title card-code-title"> <a onClick={() => { props.onSelected(props.selectionId) }} className={`withripple ${active ? 'collapsed' : ''}`}> {header} </a> </h4> </div> <div className={`card-collapse collapse ${active ? 'show' : ''}`}> {content} </div> </div> ) } export default collapse<file_sep>import React from 'react'; import { Scrollbars } from 'react-custom-scrollbars'; const lineConnections = (props) => { const { line, onStationSelected } = props; const drawStation = (connectionId, station, year, lastItem) => { return ( <li key={connectionId} className={`stations-path-item ${lastItem ? 'last-item' : ''}`}> <div className="stations-path-year left">{year}</div> <div className="station-path-track left" style={{ borderLeftColor: line.colour }}> {station.markerIcon !== 'multiple' ? <i className="station-path-track-bar" style={{ backgroundColor: line.colour }} /> : null } </div> {station.markerIcon === 'multiple' ? <div className="station-path-circle left" style={{ backgroundColor: line.colour }} /> : null } <div className="stations-path-name left" onClick={() => onStationSelected(station)}><div>{station.name}</div></div> <div className="clearfix" /> </li> ) } return ( <div className="line-connections"> <div className="connections-header">Stations</div> <Scrollbars autoHeight autoHeightMin={200} autoHeightMax={400}> <div className="stations-container"> <ul className="stations-path"> {line.connections.map(c => { return drawStation(c._id, c.stations[0], c.year); })} {drawStation(0, line.connections[line.connections.length - 1].stations[1], line.connections[line.connections.length - 1].year, true)} </ul> </div> </Scrollbars> </div> ); }; export default lineConnections;<file_sep>import * as actionTypes from './actionTypes'; export const loginStart = (email, password) => { return { type: actionTypes.LOGIN_START, email, password }; }; export const loginSuccess = () => { return { type: actionTypes.LOGIN_SUCCESS }; }; export const loginFail = (error) => { return { type: actionTypes.LOGIN_FAIL, error }; }; <file_sep>import Api from 'http/admin'; import { put } from 'redux-saga/effects'; import { searchParamsChangeStart, updateConnectionFail, updateConnectionSuccess } from 'store/admin/actions'; import { info } from 'util/notification'; export function* updateConnectionSagaStart(action) { try { yield Api.connection.update(action.connection); yield put(updateConnectionSuccess()); yield put(searchParamsChangeStart()); info('Connection updated succesully'); } catch (err) { yield put(updateConnectionFail(err)); } }<file_sep>import { takeEvery } from "redux-saga/effects"; import * as actionTypes from "store/admin/actions/station/actionTypes"; import { addStationSagaStart, deleteStationSagaStart, updateStationSagaStart } from './workers'; export const stationSagas = [ takeEvery(actionTypes.ADD_STATION_START, addStationSagaStart), takeEvery(actionTypes.UPDATE_STATION_START, updateStationSagaStart), takeEvery(actionTypes.DELETE_STATION_START, deleteStationSagaStart) ];<file_sep>import React from 'react'; const defaultDropdown = (props) => { const { activeIndex, index, option } = props; return ( <a role="option" onClick={() => props.onSelectOption(props.option)} className={`dropdown-item ${activeIndex === index ? 'active' : ''}`} aria-disabled="false" aria-selected="true" > <span>{option.name}</span> </a> ) } export default defaultDropdown;<file_sep>export { addLineSagaStart } from './addLine'; export { deleteLineSagaStart } from './deleteLine'; export { updateLineSagaStart } from './updateLine'; <file_sep>import ConnectionsInfo from 'components/admin/admin-town/connections-info/connections-info'; import { Pagination } from 'components/shared'; import React from 'react'; import { connect } from 'react-redux'; import { finishAction, searchParamsChangeStart, startAction } from 'store/admin/actions'; class AdminConnectionsPanel extends React.Component { constructor(props) { super(props); this.search = this.search.bind(this); this.changePage = this.changePage.bind(this); this.changeSearchParams = this.changeSearchParams.bind(this); this.addConnectionStart = this.addConnectionStart.bind(this); this.editConnectionStart = this.editConnectionStart.bind(this); this.deleteConnectionStart = this.deleteConnectionStart.bind(this); } componentDidMount() { this.search(); } search(params, page) { const { searchParams, pagination, searchConnections } = this.props; const _pagination = page ? { ...pagination, page } : pagination; const _searchParams = params ? Object.assign({}, searchParams, params) : searchParams; searchConnections(_searchParams, _pagination); } changePage(page) { this.search(null, page); } changeSearchParams(searchParams) { this.search(searchParams); } addConnectionStart() { const { _startAction } = this.props; _startAction('addConnection'); } editConnectionStart(connection) { const { _startAction } = this.props; _startAction('editConnection', connection); } deleteConnectionStart(connectionId) { const { _startAction } = this.props; _startAction('deleteConnection', connectionId); } render() { const { draft, elementsType, connections, pagination } = this.props; return ( <div className="admin-connections-panel"> {elementsType === 'connection' ? ( <ConnectionsInfo draftId={draft._id} connections={connections} onAddConnection={this.addConnectionStart} onEditConnection={this.editConnectionStart} onDeleteConnection={this.deleteConnectionStart} onChangeParams={this.changeSearchParams} /> ) : null} {connections.length ? ( <Pagination color="secondary" pagination={pagination} onPageChange={this.changePage} /> ) : null} </div> ) } } const mapStateToProps = state => { return { draft: state.admin.draft, elementsType: state.admin.elementsType, connections: state.admin.elements, searchParams: state.admin.searchParams, pagination: state.admin.pagination }; }; const mapDispatchToProps = dispatch => { return { _startAction: (actionName, actionObj) => dispatch(startAction(actionName, actionObj)), _finishAction: () => dispatch(finishAction()), searchConnections: (searchParams, pagination) => dispatch(searchParamsChangeStart(searchParams, pagination, 'connection')) } }; export default connect(mapStateToProps, mapDispatchToProps)(AdminConnectionsPanel); <file_sep>import Form from './form'; import FormChanges from './form-changes/form-changes'; import FormField from './form-field/form-field'; export { Form, FormChanges, FormField }; <file_sep>import { all, takeEvery } from "redux-saga/effects"; import * as actionTypes from "store/auth/actions/actionTypes"; import { loginSagaStart, signUpSagaStart } from './workers'; const authSagas = [ takeEvery(actionTypes.LOGIN_START, loginSagaStart), takeEvery(actionTypes.SIGNUP_START, signUpSagaStart) ]; export function* watchAuth() { yield all([ ...authSagas ]) }<file_sep>import Api from 'http/admin'; import { put, select } from 'redux-saga/effects'; import { addConnectionFail, addConnectionSuccess, getDraftStart, searchParamsChangeStart } from 'store/admin/actions'; import { error, info } from 'util/notification'; export function* addConnectionSagaStart(action) { try { const state = yield select(); yield Api.connection.add(state.admin.draft._id, { ...action.connection, order: 99 }); yield put(addConnectionSuccess()); yield put(getDraftStart(state.admin.draft._id)); yield put(searchParamsChangeStart()); info('Connection was created succesully'); } catch (err) { error('Something went wrong!'); yield put(addConnectionFail(err)); } }<file_sep>import React, { Component } from 'react'; import { addLocaleData, IntlProvider } from 'react-intl'; import intlEN from 'react-intl/locale-data/en'; import intlES from 'react-intl/locale-data/es'; import { withRouter } from 'react-router-dom'; import flattenMessages from 'util/flattenMessages'; import routes from './routes'; addLocaleData([...intlEN, ...intlES]); class App extends Component { constructor(props) { let lang = localStorage.getItem('lang'); if (!lang) { lang = 'en'; localStorage.setItem('lang', lang); } super(props); this.state = { locale: lang, messages: flattenMessages(require(`./i18n/${lang}.json`)) } } changeLanguage(lang) { this.setState({ locale: lang, messages: flattenMessages(require(`./i18n/${lang}.json`)) }); } render() { const { history } = this.props; const { locale, messages } = this.state; return ( <IntlProvider key={locale} locale={locale} messages={messages}> <div className="ms-site-container"> {routes(history)} </div> </IntlProvider> ); } } export default withRouter(App); <file_sep>import { updateObject } from 'shared/utility'; import * as mainActions from 'store/public/actions/main/actionTypes'; import * as mainReducers from './main/main'; const initialState = { loading: false, year: null, town: null, draft: null, stations: [] }; const defaultStart = (state) => { return updateObject(state, { loading: true }); }; const defaultSuccess = (state) => { return updateObject(state, { loading: false, action: null, actionObj: null }); }; const defaultFail = (state) => { return updateObject(state, { loading: false }); }; const checkActionType = (action, type) => { return action.endsWith(type); } export const publicReducer = (state = initialState, action) => { switch (action.type) { // Default ones case checkActionType(action.type, 'START'): return defaultStart(state); case checkActionType(action.type, 'SUCCESS'): return defaultSuccess(state); case checkActionType(action.type, 'FAIL'): return defaultFail(state); // Main case mainActions.INIT_MAP_START: return defaultStart(state, action); case mainActions.INIT_MAP_SUCCESS: return mainReducers.initMapSuccess(state, action); case mainActions.INIT_MAP_FAIL: return defaultFail(state, action); case mainActions.INIT_MAP_DRAFT_START: return defaultStart(state, action); case mainActions.INIT_MAP_DRAFT_SUCCESS: return mainReducers.initMapSuccess(state, action); case mainActions.INIT_MAP_DRAFT_FAIL: return defaultFail(state, action); case mainActions.SET_YEAR: return mainReducers.setYear(state, action); default: return state; } };<file_sep>import * as actions from 'actions/main'; import { Header } from 'components/shared'; import React from 'react'; import { connect } from 'react-redux'; import { withRouter } from "react-router-dom"; import MapWrapper from '../MapWrapper/MapWrapper'; class PrintPreview extends React.Component { componentDidMount() { const { match, onInit } = this.props; const town = match.params.town; const year = parseInt(match.params.year, 10); onInit(town, year); } render() { const { town, year } = this.props; return ( <div className="print-preview"> <Header optionsName="print" /> <div className="page"> <MapWrapper mode="print" /> {town && year ? ( <div className="print-display-info-container"> <div className="print-display-info"> <div className="print-display-info-town">{town.name}</div> <div className="print-display-info-country">{town.country}</div> <div className="print-display-info-year">{year}</div> </div> </div> ) : null} </div> </div> ) } } const mapStateToProps = state => { return { town: state.main.town, year: state.main.year, previousYear: state.main.previousYear, maxYearLoaded: state.main.maxYearLoaded, lines: state.main.lines, selectedLine: state.main.selectedLine, stations: state.main.stations, connections: state.main.connections, sideBarMode: state.main.sideBarMode, loading: state.main.loading }; }; const mapDispatchToProps = dispatch => { return { onInit: (town, year) => dispatch(actions.loadInitStart(town, year)), onYearChange: (townId, year, previousYear, maxYearLoaded) => dispatch(actions.changeYearStart(townId, year, previousYear, maxYearLoaded)) } }; export default connect(mapStateToProps, mapDispatchToProps)(withRouter(PrintPreview)); <file_sep>export * from './getTowns'; <file_sep>import React from 'react'; import { getImage } from 'shared/image'; const countryDropdown = (props) => { const { activeIndex, index, option } = props; return ( <a role="option" onClick={() => props.onSelectOption(props.option)} className={`dropdown-country-item dropdown-item ${activeIndex === index ? 'active' : ''}`} aria-disabled="false" aria-selected="true" > <img className="country-flag" alt={option.code} src={getImage(`countries/${option.code.toLowerCase()}.png`, 'countries/default.png')} /><span className="country-name">{option.name}</span> </a> ) } export default countryDropdown;<file_sep>import { Button, LoadingSpinner } from 'components/shared'; import React from 'react'; class LoadingSpinners extends React.Component { constructor(props) { super(props); this.state = { loading1: null, loading2: null, loading3: null, loading4: null, loading5: null }; this.toggleLoading = this.toggleLoading.bind(this); } toggleLoading(loadingId) { this.setState(prevState => { return { [loadingId]: !prevState[loadingId] } }); } render() { const { loading1, loading2, loading3, loading4, loading5 } = this.state; return ( <div className="showroom-loading-spinner"> <h1 className="right-line mb-4">Loading spinner</h1> <div className="row"> <div className="col"> <div className="showroom-element"> <label>Light background</label> <div className="pos-relative"> <LoadingSpinner loading={loading1} /> <div className="showroom-sample-div" /> </div> <Button text={loading1 ? 'Stop spinner' : 'Start spinner'} color="secondary" extraClass="mt-30" onClick={() => this.toggleLoading('loading1')} /> </div> </div> <div className="col"> <div className="showroom-element"> <label>Dark background</label> <div className="pos-relative"> <LoadingSpinner background="dark" loading={loading2} /> <div className="showroom-sample-div" /> </div> <Button text={loading2 ? 'Stop spinner' : 'Start spinner'} color="secondary" extraClass="mt-30" onClick={() => this.toggleLoading('loading2')} /> </div> </div> <div className="col"> <div className="showroom-element"> <label>Secondary spinner</label> <div className="pos-relative"> <LoadingSpinner color="secondary" loading={loading3} /> <div className="showroom-sample-div" /> </div> <Button text={loading3 ? 'Stop spinner' : 'Start spinner'} color="secondary" extraClass="mt-30" onClick={() => this.toggleLoading('loading3')} /> </div> </div> <div className="col"> <div className="showroom-element"> <label>Inverse spinner</label> <div className="pos-relative"> <LoadingSpinner inverse loading={loading4} /> <div className="showroom-sample-div" /> </div> <Button text={loading4 ? 'Stop spinner' : 'Start spinner'} color="secondary" extraClass="mt-30" onClick={() => this.toggleLoading('loading4')} /> </div> </div> <div className="col"> <div className="showroom-element"> <label>Shadow without spinner</label> <div className="pos-relative"> <LoadingSpinner inverse noSpinner loading={loading5} /> <div className="showroom-sample-div" /> </div> <Button text={loading4 ? 'Stop spinner' : 'Start spinner'} color="secondary" extraClass="mt-30" onClick={() => this.toggleLoading('loading5')} /> </div> </div> </div> </div> ) } } export default LoadingSpinners;<file_sep>import PropTypes from 'prop-types'; import React from 'react'; const icon = (props) => { const { color, extraClass, name, size } = props; return ( <i className={`icon icon-${name} ${size ? `icon-${size}` : ''} ${color ? `icon-${color}` : ''} ${extraClass}`} /> ) } icon.defaultProps = { color: null, size: null, extraClass: '' }; icon.propTypes = { color: PropTypes.oneOf(['primary', 'secondary', 'light']), name: PropTypes.string.isRequired, size: PropTypes.oneOf(['sm', 'md', 'lg']), extraClass: PropTypes.string }; export default icon;<file_sep>export const GET_DRAFT_START = 'GET_DRAFT_START'; export const GET_DRAFT_SUCCESS = 'GET_DRAFT_SUCCESS'; export const GET_DRAFT_FAIL = 'GET_DRAFT_FAIL'; export const ADD_DRAFT_START = 'ADD_DRAFT_START'; export const ADD_DRAFT_SUCCESS = 'ADD_DRAFT_SUCCESS'; export const ADD_DRAFT_FAIL = 'ADD_DRAFT_FAIL'; export const UPDATE_DRAFT_START = 'UPDATE_DRAFT_START'; export const UPDATE_DRAFT_SUCCESS = 'UPDATE_DRAFT_SUCCESS'; export const UPDATE_DRAFT_FAIL = 'UPDATE_DRAFT_FAIL'; export const DELETE_DRAFT_START = 'DELETE_DRAFT_START'; export const DELETE_DRAFT_SUCCESS = 'DELETE_DRAFT_SUCCESS'; export const DELETE_DRAFT_FAIL = 'DELETE_DRAFT_FAIL';<file_sep>export * from './town'; <file_sep>import React from 'react'; const placeSelected = (props) => { const { selectedOption } = props; return ( <div className="filter-option"> <div className="filter-option-inner"> <div className="filter-option-inner-inner"> {selectedOption ? selectedOption.name : 'Type a place'} </div> </div> </div> ) } export default placeSelected;<file_sep>export * from './station'; <file_sep>import * as actionTypes from './actionTypes'; export const finishAction = () => { return { type: actionTypes.FINISH_ACTION }; }; <file_sep>import Api from 'http/admin'; import { put, select } from 'redux-saga/effects'; import { addLineFail, addLineSuccess, getDraftStart, searchParamsChangeStart } from 'store/admin/actions'; import { error, info } from 'util/notification'; export function* addLineSagaStart(action) { try { const state = yield select(); yield Api.line.add(state.admin.draft._id, { ...action.line, order: 99 }); yield put(addLineSuccess()); yield put(getDraftStart(state.admin.draft._id)); yield put(searchParamsChangeStart()); info('Line was created succesully'); } catch (err) { error('Something went wrong!'); yield put(addLineFail(err)); } }<file_sep>import { Button, CollapseList } from 'components/shared'; import React from 'react'; import ConnectionsFilter from './connections-filter/connections-filter'; import ConnectionsInfoContent from './connections-info-content/connections-info-content'; import ConnectionsInfoHeader from './connections-info-header/connections-info-header'; const connectionsInfo = (props) => { const { draftId, connections, onAddConnection, onEditConnection, onDeleteConnection, onChangeParams } = props; return ( <div className="connections-info"> <div className="flex flex-row flex-space-between mb-30"> <ConnectionsFilter draftId={draftId} onChangeParams={onChangeParams} /> <Button text="Add connection" icon="add" outline onClick={onAddConnection} /> </div> <CollapseList elements={connections} hoverType="secondary" header={ConnectionsInfoHeader} content={ConnectionsInfoContent} actions={{ onEditConnection, onDeleteConnection }} {...props} /> </div> ) } export default connectionsInfo;<file_sep>export const updateObject = (oldObject, updatedProperties) => { return { ...oldObject, ...updatedProperties }; }; export const getDefaultValue = (type) => { switch (type) { case 'string': return ''; case 'number': return ''; default: return null; } } export const applyTypeToValue = (value, type) => { if (value === null || value === undefined) { return value; } switch (type) { case 'string': return String(value); case 'number': return parseInt(value, 10); default: return value; } } export const transformDistance = (value) => { return value ? `${value.toLocaleString()} m` : ''; } export const groupBy = (arr, groupProperty, itemsProperty, sort) => { if (!itemsProperty) { // Object result return arr.reduce((rv, x) => { (rv[x[groupProperty]] = rv[x[groupProperty]] || []).push(x); return rv; }, {}); } // Array result const result = []; arr.map(e => { const resultElement = result.find(rE => rE[groupProperty] === e[groupProperty]); if (resultElement) { resultElement[itemsProperty].push(e); } else { result.push({ [groupProperty]: e[groupProperty], [itemsProperty]: [e] }); } return null; }); return sort ? result.sort((a, b) => a[groupProperty] - b[groupProperty]) : result; } export const sortBy = (arr, property) => { return !property ? arr.sort((a, b) => a[property] - b[property]) : arr; } export const splitByRows = (arr, size) => arr.reduce((chunks, el, i) => (i % size ? chunks[chunks.length - 1].push(el) : chunks.push([el])) && chunks, [])<file_sep>const defaultStyle = require('./default.json'); const print = require('./print.json'); const style1950 = require('./0-1950.json'); const style19512019 = require('./1951-2019.json'); export default { defaultStyle, print, style_0_1950: style1950, style_1951_2019: style19512019 }; <file_sep>export const GET_TOWNS_START = 'GET_TOWNS_START'; export const GET_TOWNS_SUCCESS = 'GET_TOWNS_SUCCESS'; export const GET_TOWNS_FAIL = 'GET_TOWNS_FAIL'; <file_sep>import React from 'react'; import { Redirect, Route, Switch } from 'react-router-dom'; import Buttons from './Buttons/Buttons'; import Badges from './Data-Presentation/Badges/Badges'; import Collapses from './Data-Presentation/Collapses/Collapses'; import CountryLabels from './Data-Presentation/Country-Labels/Country-Labels'; import DataPresentation from './Data-Presentation/Data-Presentation'; import Icons from './Data-Presentation/Icons/Icons'; import LoadingSpinners from './Data-Presentation/Loading-Spinners/Loading-Spinners'; import Paginations from './Data-Presentation/Paginations/Paginations'; import Panels from './Data-Presentation/Panels/Panels'; import Tabs from './Data-Presentation/Tabs/Tabs'; import Forms from './Forms/Forms'; import Headers from './Headers/Headers'; import Index from './Index/Index'; import Inputs from './Inputs/Inputs'; import Layout from './Layout/Layout'; import Modals from './Layout/Modals/Modals'; const baseUrl = '/showroom'; const routes = ( <Switch> <Route path={`${baseUrl}/buttons`} component={Buttons} /> <Route path={`${baseUrl}/data-presentation`} exact component={DataPresentation} /> <Route path={`${baseUrl}/data-presentation/collapses`} component={Collapses} /> <Route path={`${baseUrl}/data-presentation/country-labels`} component={CountryLabels} /> <Route path={`${baseUrl}/data-presentation/badges`} component={Badges} /> <Route path={`${baseUrl}/data-presentation/icons`} component={Icons} /> <Route path={`${baseUrl}/data-presentation/loading-spinners`} component={LoadingSpinners} /> <Route path={`${baseUrl}/data-presentation/paginations`} component={Paginations} /> <Route path={`${baseUrl}/data-presentation/panels`} component={Panels} /> <Route path={`${baseUrl}/data-presentation/tabs`} component={Tabs} /> <Route path={`${baseUrl}/forms`} component={Forms} /> <Route path={`${baseUrl}/inputs`} component={Inputs} /> <Route path={`${baseUrl}/headers`} component={Headers} /> <Route path={`${baseUrl}/layout`} exact component={Layout} /> <Route path={`${baseUrl}/layout/modals`} component={Modals} /> <Route path={`${baseUrl}`} component={Index} /> <Redirect to={`${baseUrl}`} /> </Switch> ); export default routes;<file_sep>import DraftCard from './draft-card/draft-card'; import MapCard from './map-card/map-card'; import TownCard from './town-card/town-card'; export { DraftCard, MapCard, TownCard }; <file_sep>import { getLinesFromStation, hasErrors } from './data'; export default { getLinesFromStation, hasErrors }<file_sep>import { TownLogo } from 'components/shared'; import React from 'react'; import StationConnections from './station-connections/station-connections'; const stationInfo = (props) => { const { onStationSelected, station, town } = props; return ( <div className="station-info"> <div className="station-name"><TownLogo town={town} />{station.name}</div> <div className="station-year"> <div className="station-year-label">Year</div> <div className="float-right"> <div className="station-year-value">{station.year}</div> <div className="station-year-rating">27th oldest of 359</div> </div> </div> <StationConnections connections={station.connections} onStationSelected={onStationSelected} /> </div> ) } export default stationInfo;<file_sep>import React from 'react'; import { getImage } from 'shared/image'; const selectedTownLabel = (option) => { return ( <React.Fragment> <img className="country-flag" alt={option.url} src={getImage(`countries/${option.country.code.toLowerCase()}.png`, 'countries/default.png')} /> <span className="country-name">{option.name}</span> </React.Fragment> ) } const townSelected = (props) => { const { selectedOption } = props; return ( <div className="selected-country filter-option"> <div className="filter-option-inner"> <div className="filter-option-inner-inner"> {selectedOption ? selectedTownLabel(selectedOption) : 'Type a town'} </div> </div> </div> ) } export default townSelected;<file_sep>import { Badge } from 'components/shared'; import React from 'react'; const LineBadge = (props) => { const { line, extraClass } = props; return ( <Badge text={line.shortName} backgroundColor={line.colour} fontColor={line.fontColour} extraClass={extraClass} /> ) } export default LineBadge;<file_sep>import { Button } from 'components/shared'; import React from 'react'; const layout = () => { return ( <div className="showroom-layout"> <h1 className="right-line mb-4">Layout</h1> <div className="row"> <div className="col"> <div className="showroom-element showroom-link"> <Button to="/showroom/layout/modals" text="Modals" type="link" color="secondary" /> </div> </div> </div> </div> ) } export default layout;<file_sep>import axios from '../axios'; export default class Draft { // Get draft with town static getDraftWithTown = (draftId) => { return axios.get(`draft/${draftId}`); } } <file_sep>import { CollapseList } from 'components/shared'; import React from 'react'; import lines from './data/lines.json'; const fakeHeader = ({ element }) => { return ( <div> <span>{element.name}</span> </div> ) } const fakeContent = () => { return ( <div> This is fake content </div> ) } class Collapses extends React.Component { constructor(props) { super(props); this.state = { combinedSelected: null }; this.handleCombinedChanged = this.handleCombinedChanged.bind(this); } handleCombinedChanged(combinedSelected) { this.setState((prevState) => { return { combinedSelected: prevState.combinedSelected === combinedSelected ? null : combinedSelected } }); } render() { const { combinedSelected } = this.state; return ( <div className="showroom-collapses"> <h1 className="right-line mb-40">Collapses</h1> <div className="row"> <div className="col"> <div className="showroom-element"> <label>Plain</label> <CollapseList elements={lines.slice(0, 9)} header={fakeHeader} content={fakeContent} /> </div> </div> <div className="col"> <div className="showroom-element"> <label>Primary</label> <CollapseList type="primary" elements={lines.slice(0, 9)} header={fakeHeader} content={fakeContent} /> </div> </div> <div className="col"> <div className="showroom-element"> <label>Secondary</label> <CollapseList type="secondary" elements={lines.slice(0, 9)} header={fakeHeader} content={fakeContent} /> </div> </div> <div className="col"> <div className="showroom-element"> <label>Combined</label> <CollapseList type="primary" extraClass="mb-40" elements={lines.slice(0, 4)} header={fakeHeader} content={fakeContent} externalActiveElementId={combinedSelected} onActiveElementChanged={this.handleCombinedChanged} /> <CollapseList type="secondary" extraClass="mb-40" elements={lines.slice(4, 9)} header={fakeHeader} content={fakeContent} externalActiveElementId={combinedSelected} onActiveElementChanged={this.handleCombinedChanged} /> <CollapseList elements={lines.slice(9, 14)} header={fakeHeader} content={fakeContent} externalActiveElementId={combinedSelected} onActiveElementChanged={this.handleCombinedChanged} /> </div> </div> </div> </div> ) } } export default Collapses;<file_sep>import ButtonGroup from './button-group/button-group'; import Button from './button/button'; export { Button, ButtonGroup }; <file_sep>export const distance = (value, unity = 'km') => { switch (unity) { case 'km': return `${(value / 1000)} ${unity}`; default: return value; } }<file_sep>// import * as actions from 'actions/main'; import { Overlay } from 'components/shared'; import { initMapTown, restoreMapState, updateMap, zoomToPoint } from 'map/map.google.service.old'; import React from 'react'; import { connect } from 'react-redux'; const showMapAnimations = (process.env.REACT_APP_MAP_ANIMATIONS === 'true'); class MapWrapper extends React.Component { componentDidUpdate(prevProps) { const { connections, mode, previousYear, stations, town, year } = this.props; if (prevProps.town !== town) { this.map = initMapTown('map-container', town, mode); updateMap(this.map, town, mode, stations, connections, year, previousYear, this.showStation); } } showStation = (station) => { const { onStationSelected } = this.props; const mapState = showMapAnimations ? zoomToPoint(this.map, station.geometry.coordinates) : null; onStationSelected(station, mapState); } render() { const { connections, mapState, mode, loading, onClearMapState, previousYear, sideBarState, stations, town, year } = this.props; if (!loading && this.map && stations && connections) { updateMap(this.map, town, mode, stations, connections, year, previousYear, this.showStation); } if (process.env.REACT_APP_MAP_ANIMATIONS && !sideBarState.open && mapState) { restoreMapState(this.map, mapState); onClearMapState(); } return ( <div className="map-wrapper"> <Overlay show={sideBarState.open} /> <div id="map-container" className={mode} /> </div> ) } } const mapStateToProps = state => { return { town: state.main.town, year: state.main.year, previousYear: state.main.previousYear, stations: state.main.stations, connections: state.main.connections, selectedStation: state.main.selectedStation, sideBarState: state.main.sideBarState, mapState: state.main.mapState }; }; const mapDispatchToProps = () => { return { onStationSelected: (station) => { console.log(station) }, onClearMapState: () => { } } }; export default connect(mapStateToProps, mapDispatchToProps)(MapWrapper);<file_sep>import { Button } from 'components/shared'; import React from 'react'; import Modal from 'react-modal'; const CustomModal = (props) => { const { modalContent, onClose } = props; const ModalContent = modalContent; // eslint-disable-next-line no-unneeded-ternary const isOpen = modalContent ? true : false; return ( <div> <Modal className="m0dal animated zoomIn animated-3x" overlayClassName="m0dal-overlay" isOpen={isOpen} ariaHideApp={false} > {isOpen && <ModalContent {...props} />} <Button type="link" text="" icon="close" color="secondary" extraClass="close-button" onClick={onClose} /> </Modal> </div> ) } export default CustomModal;<file_sep>import { ButtonGroup } from 'components/shared'; import React from 'react'; const booleanSelector = (props) => { const { options, size } = props; return <ButtonGroup options={options} size={size} /> } export default booleanSelector;<file_sep>import * as actionTypes from './actionTypes'; export const signUpStart = (email, password, name) => { return { type: actionTypes.SIGNUP_START, email, password, name }; }; export const signUpSuccess = () => { return { type: actionTypes.SIGNUP_SUCCESS }; }; export const signUpFail = (error) => { return { type: actionTypes.SIGNUP_FAIL, error }; }; <file_sep>import { Icon } from 'components/shared'; import React from 'react'; import onClickOutside from "react-onclickoutside"; class ModalContent extends React.Component { handleClickOutside() { const { onClose } = this.props; onClose(); } render() { const { content, header, onClose } = this.props; return ( <div className="modal-content"> <div className="modal-header"> <h3 className="modal-title secondary">{header}</h3> <button type="button" className="close" onClick={onClose}> <span aria-hidden="true"> <Icon name="close" /> </span> </button> </div> <div className="modal-body"> {content} </div> </div> ) } } export default onClickOutside(ModalContent);<file_sep>import { Badge, CountryLabel, Icon } from 'components/shared'; import PropTypes from 'prop-types'; import React from 'react'; const TownCard = ({ town: { name, imgCard, country, year }, type, className }) => { return ( <div className={`town-card town-card-${type} ${className}`}> <div> <img className="town-img" src={imgCard} alt={name} /> </div> <div className="info-panel flex flex-space-between p-10"> <div> <div className="town-name">{name}</div> <div><CountryLabel country={country} /></div> </div> <div className="text-right"> <Badge text={year} color={type === 'published' ? 'secondary' : 'primary'} /> {type === 'town' ? ( <div className="town-counters"> <span className="counter-number">2</span> <Icon name="person" size="sm" /> </div> ) : ( <div className="draft-counters"> <span className="counter-number">11</span> <Icon name="lines" size="sm" /> <span className="counter-number">148</span> <Icon name="tube-logo" size="sm" /> </div> )} </div> </div> </div> ) } TownCard.defaultProps = { className: '', type: 'town' }; TownCard.propTypes = { town: PropTypes.shape({ name: PropTypes.string, imgCard: PropTypes.string, year: PropTypes.number, alias: PropTypes.string, country: PropTypes.shape({ code: PropTypes.string, name: PropTypes.string }) }).isRequired, type: PropTypes.oneOf(['published', 'draft', 'town']), className: PropTypes.string }; export default TownCard; <file_sep>import axios from '../axios'; export default class Town { // Get town static getTown = (townUrl) => { return axios.get(`town/${townUrl}`); } // Get published draft in town static getPublishedDraft = (townId) => { return axios.get(`town/${townId}/active-draft`); } } <file_sep>import * as actionTypes from './actionTypes'; export const updateLineStart = (line) => { return { type: actionTypes.UPDATE_LINE_START, line }; }; export const updateLineSuccess = () => { return { type: actionTypes.UPDATE_LINE_SUCCESS }; }; export const updateLineFail = (error) => { return { type: actionTypes.UPDATE_LINE_FAIL, error }; };<file_sep>import { Translation } from 'components/shared'; import React from 'react'; const infoElement = (props) => { const { prefix, id, value } = props; return ( <div className="info-element"> <div className="info-element-name"><Translation prefix={prefix} id={id} /></div> <div className="info-element-value">{value}</div> </div> ) } export default infoElement;<file_sep>import londonLogo from 'assets/img/towns/london_logo.png'; import madridLogo from 'assets/img/towns/madrid_logo.png'; import newYorkLogo from 'assets/img/towns/new-york_logo.png'; import stockholmLogo from 'assets/img/towns/stockholm_logo.png'; import React from 'react'; const logos = { 'london': londonLogo, 'madrid': madridLogo, 'new-york': newYorkLogo, 'stockholm': stockholmLogo } const townLogo = ({ townUrl }) => { return <img alt="" src={logos[townUrl]} /> } export default townLogo;<file_sep> import { getStationMarkerColor } from 'util/data'; import styles from './styles/styles'; const mapConfig = require('./config/map.config.json'); const connectionConfig = require('./config/connection.config.json'); export const initMap = (selector, center, zoom, year, marker) => { const centerMap = { lat: center.coordinates[1], lng: center.coordinates[0] }; const map = new window.google.maps.Map(document.getElementById(selector), { ...mapConfig, center: centerMap, zoom }); if (year) { applyYearStyle(map, year); } if (marker) { // eslint-disable-next-line no-new new window.google.maps.Marker({ position: centerMap, map, icon: new window.google.maps.MarkerImage(require(`assets/img/towns/stockholm_logo_24.png`)), }); } map.stations = []; map.connections = []; return map; } export const initMapForPlaceSearch = (selector, place, onGeometryChange) => { const map = new window.google.maps.Map(document.getElementById(selector), { center: place.geometry.location, zoom: 15 }); const marker = new window.google.maps.Marker({ disableDefaultUI: false, position: place.geometry.location, map, icon: new window.google.maps.MarkerImage(require(`assets/img/markers/default_station.png`)), title: place.name }); map.addListener('click', (event) => { marker.setPosition(event.latLng); onGeometryChange(event.latLng); }); map.markers = [marker]; return (map); } export const addStations = (map, stations) => { const bounds = new window.google.maps.LatLngBounds(); let counter = 0; map.stations = stations.map(station => { const marker = new window.google.maps.Marker({ position: convertPointArrayToMapPoint(station.geometry.coordinates), data: { year: station.year }, map, icon: pinSymbol(getStationMarkerColor(station)), title: station.name }); station.connections.map(con => { const samePathConnections = map.connections.filter(c => c.data.name === `${con.stations[0]._id}-${con.stations[1]._id}`); if (samePathConnections.find(c => c.data.colour === con.line.colour)) { return null; } // eslint-disable-next-line no-new map.connections.push(new window.google.maps.Polyline({ ...connectionConfig, map, data: { name: `${con.stations[0]._id}-${con.stations[1]._id}`, year: con.year, colour: con.line.colour }, path: con.stations.map(s => convertPointArrayToMapPoint(s.geometry.coordinates)), strokeColor: con.line.colour, strokeWeight: connectionConfig.strokeWeight * getStrokeRatio(samePathConnections.length), zIndex: 1000 - counter })); // eslint-disable-next-line no-plusplus counter++; return null; }); bounds.extend(marker.getPosition()); return marker; }) map.fitBounds(bounds); } const applyYearStyle = (map, year, mode) => { let setMapTypeId = null; const defaultStyle = mode === 'print' ? styles.defaultStyle.concat(styles.print) : styles.defaultStyle; const getYearStyleForYear = (_year) => { let style; Object.keys(styles).forEach(key => { if (key.split('_')[1] <= year && key.split('_')[2] >= _year) { setMapTypeId = key; style = new window.google.maps.StyledMapType(defaultStyle.concat(styles[key]), { name: key }); } }); return style; } const styledMapType = getYearStyleForYear(year); if (styledMapType) { map.mapTypes.set(setMapTypeId, styledMapType); map.setMapTypeId(setMapTypeId); } } const convertPointArrayToMapPoint = (coordinates) => { return new window.google.maps.LatLng(coordinates[1], coordinates[0]); } const pinSymbol = (color) => { return { path: 'M-20,0a20,20 0 1,0 40,0a20,20 0 1,0 -40,0', fillColor: color, fillOpacity: 1, strokeColor: '#000', strokeWeight: 1, scale: 0.25, }; } const getStrokeRatio = (connectionNumber) => { switch (connectionNumber) { case 0: return 1; case 1: return 2; case 2: return 4; default: return 1; } } <file_sep>export * from './addStation'; export * from './deleteStation'; export * from './updateStation'; <file_sep>import React from 'react'; import { FormattedMessage } from 'react-intl'; const Translation = ({ prefix, id }) => { return <FormattedMessage id={`${prefix}.${id}`} /> } export default Translation;<file_sep>import { Panel } from 'components/shared'; import React from 'react'; const panels = () => { return ( <div className="showroom-buttons"> <h1 className="right-line mb-4">Panels</h1> <div className="row"> <div className="col-4"> <div className="showroom-element"> <label>White</label> <Panel> This is a panel </Panel> </div> </div> <div className="col-4"> <div className="showroom-element"> <label>Primary</label> <Panel background="primary" > This is a panel </Panel> </div> </div> <div className="col-4"> <div className="showroom-element"> <label>Secondary</label> <Panel background="secondary" > This is a panel </Panel> </div> </div> </div> <div className="row"> <div className="col-4"> <div className="showroom-element"> <label>With primary header</label> <Panel header="Header primary" headerColor="primary" > This is a panel </Panel> </div> </div> <div className="col-4"> <div className="showroom-element"> <label>With secondary header</label> <Panel header="Header secondary" headerColor="secondary" > This is a panel </Panel> </div> </div> </div> </div> ) } export default panels;<file_sep>import React from 'react'; const headers = () => { return ( <div className="showroom-headers"> <h1 className="right-line mb-40">Headers</h1> <h1 className="right-line mb-20">This is a header H1</h1> <h1 className="primary right-line mb-20">This is a primary header H1</h1> <h1 className="primary right-line right-line-secondary mb-20">This is a primary header H1 with secondary right line</h1> <h1 className="secondary right-line mb-20">This is a secondary header H1</h1> <h1 className="secondary right-line right-line-primary mb-20">This is a secondary header H1 with primary right line</h1> <h1 className="mb-40">This is a header H1 without right line</h1> <h2 className="right-line mb-20">This is a header H2</h2> <h3 className="right-line mb-20">This is a header H3</h3> <h4 className="right-line mb-20">This is a header H4</h4> <h5 className="right-line mb-20">This is a header H5</h5> <h6 className="right-line mb-20">This is a header H6</h6> </div> ) } export default headers;<file_sep>import React from 'react'; import onClickOutside from "react-onclickoutside"; class SelectDropdown extends React.Component { constructor(props) { super(props); this.state = { options: [], filteredOptions: [], activeIndex: null, searchStr: '' } this.filter = this.filter.bind(this); this.select = this.select.bind(this); this.getDropDownStyle = this.getDropDownStyle.bind(this); } componentDidMount() { this.filter(''); } componentWillReceiveProps(nextProps) { if (nextProps.expanded && this.searchInput) { this.searchInput.focus(); } if (nextProps.options) { const options = this.generateOptions(nextProps.options); this.setState({ options, filteredOptions: options }); } return true; } getDropDownStyle() { const { config } = this.props; return !config.dropDownHeight ? null : { maxHeight: config.dropDownHeight, overflowY: 'auto' }; } handleOnKeyDown = (evt) => { const { activeIndex, filteredOptions } = this.state; switch (evt.key) { case 'ArrowDown': if (activeIndex < filteredOptions.length - 1) { this.setState((prevState) => ({ activeIndex: prevState.activeIndex + 1 })); } break; case 'ArrowUp': if (activeIndex > 0) { this.setState((prevState) => ({ activeIndex: prevState.activeIndex - 1 })); } break; case 'Enter': this.select(filteredOptions[activeIndex]); evt.preventDefault(); break; default: break; } } generateOptions = (options) => { return [ ...this.getNoneOption(), ...options ]; } getNoneOption = () => { const { config } = this.props; return config.noneLabel ? [{ [config.options.key]: 'none', [config.options.label]: config.noneLabel }] : []; } handleClickOutside() { const { onClose } = this.props; onClose(); } filter(str) { const { config } = this.props; if (!config.remote) { this.filterLocally(str); } else { this.filterRemote(str); } } filterLocally(value) { const { config } = this.props; const { options } = this.state; let filteredOptions; if (value.length < (config.minStr || 3)) { filteredOptions = [...options]; } else { filteredOptions = options.filter(opt => opt[config.options.label].toLowerCase()[config.onlyStartsWith ? 'startsWith' : 'includes'](value.toLowerCase())); } this.setState({ filteredOptions, searchStr: value }); } filterRemote(value) { const { onInputChange } = this.props; onInputChange(value); this.setState({ searchStr: value }); } select(opt) { const { config, onSelectOption } = this.props; if (config.enableSearch) { this.setState((prevState) => ({ searchStr: '', filteredOptions: prevState.options })); } onSelectOption(opt[config.options.key] === 'none' ? null : opt); this.filter(''); } render() { const { config, dropdown, expanded } = this.props; const { activeIndex, filteredOptions, searchStr } = this.state; const Dropdown = dropdown; return ( <div className={`select-dropdown dropdown-menu ${expanded ? 'show' : ''}`} x-placement="bottom-start" tabIndex="0"> {config.enableSearch ? <div className="bs-searchbox"> <input type="text" ref={(input) => { this.searchInput = input; }} className="form-control" value={searchStr} onChange={(evt) => this.filter(evt.target.value)} onKeyDown={this.handleOnKeyDown} aria-label="Search" /> </div> : null} <div className="inner show" role="listbox" aria-expanded={expanded} tabIndex="-1"> <ul className="dropdown-menu inner show" style={this.getDropDownStyle()}> {filteredOptions && filteredOptions.slice(0, config.maxElements || 10).map((opt, index) => { return ( <li key={index} className=""> <Dropdown option={opt} activeIndex={activeIndex} index={index} onSelectOption={(o) => this.select(o)} /> </li> ) })} </ul> </div> </div> ) } } export default onClickOutside(SelectDropdown); <file_sep>import defaultPagination from './searchDefaults/defaultPagination.json'; import defaultSearchParamsConnection from './searchDefaults/defaultSearchParams_connection.json'; import defaultSearchParamsLine from './searchDefaults/defaultSearchParams_line.json'; import defaultSearchParamsStation from './searchDefaults/defaultSearchParams_station.json'; export const getDefaultPagination = (elementsType) => { if (elementsType === 'line' || elementsType === 'station' || elementsType === 'connection') { return defaultPagination; } return null; } export const getDefaultSearchParams = (elementsType) => { switch (elementsType) { case 'line': return defaultSearchParamsLine; case 'station': return defaultSearchParamsStation; case 'connection': return defaultSearchParamsConnection; default: return null; } }<file_sep>import Badge from './badge/badge'; import CollapseList from './collapse-list/collapse-list'; import Collapse from './collapse/collapse'; import CountryLabel from './country-label/country-label'; import Icon from './icon/icon'; import InfoElement from './info-element/info-element'; import LineBadge from './line-badge/line-badge'; import LoadingSpinner from './loading-spinner/loading-spinner'; import Pagination from './pagination/pagination'; import Panel from './panel/panel'; import Slider from './slider/slider'; import TabMenu from './tab-menu/tab-menu'; import TownLogo from './town-logo/town-logo'; export { Badge, CollapseList, Collapse, CountryLabel, Icon, InfoElement, LineBadge, LoadingSpinner, Pagination, Panel, Slider, TabMenu, TownLogo, }; <file_sep>// import * as actions from 'actions/main'; import { Overlay } from 'components/shared'; import { addStations, initMap } from 'map/map.google.service'; import React from 'react'; import { connect } from 'react-redux'; import { filterStationsAndConnectionsByYear } from 'util/data'; class MapWrapper extends React.Component { componentDidUpdate(prevProps) { const { year, town, stations, } = this.props; if (prevProps.town !== town) { this.map = initMap('map-container', town.center, town.zoom, year); } if (prevProps.year !== year) { addStations(this.map, filterStationsAndConnectionsByYear(stations, year)); } } render() { const { mode } = this.props; return ( <div className="map-wrapper"> <Overlay show={false} /> <div id="map-container" className={mode} /> </div> ) } } const mapStateToProps = state => { return { town: state.public.town, year: state.public.year, stations: state.public.stations, connections: state.public.connections }; }; const mapDispatchToProps = () => { return { onClearMapState: () => { } } }; export default connect(mapStateToProps, mapDispatchToProps)(MapWrapper);<file_sep>import { YearSelector } from 'components/shared'; import React from 'react'; import { connect } from 'react-redux'; import { withRouter } from "react-router-dom"; import { initMapDraftStart, initMapStart } from 'store/public/actions'; import MapWrapper from '../MapWrapper/MapWrapper'; class Main extends React.Component { componentDidMount() { const { match, onInit, onInitDraft } = this.props; if (match.params.draftId) { onInitDraft(match.params.draftId, parseInt(match.params.year, 10)); } else { onInit(match.params.town, parseInt(match.params.year, 10)); } } render() { return ( <div> <YearSelector year="2019" showYearSelector onYearChange={(year) => console.log(year)} /> <MapWrapper mode="main" /> </div> ) } } const mapStateToProps = state => { return { town: state.public.town }; }; const mapDispatchToProps = dispatch => { return { onInit: (townUrl, year) => dispatch(initMapStart(townUrl, year)), onInitDraft: (dratfId, year) => dispatch(initMapDraftStart(dratfId, year)) } }; export default connect(mapStateToProps, mapDispatchToProps)(withRouter(Main)); <file_sep>import { Button, FormField, Input, PlaceSelector } from 'components/shared'; import React, { useEffect } from 'react'; import useForm from 'react-hook-form'; const AddStationForm = ({ onSubmit, onCancel }) => { const { register, handleSubmit, errors, setValue, setError } = useForm(); useEffect(() => { register({ name: 'geometry' }, { required: 'You must enter a position' }); }, [register]); const handleSelectorChange = (name, selectedOption) => { setValue(name, selectedOption); setError(name, null); } const processSubmit = (formData) => { onSubmit({ ...formData }); } return ( <form className="form" onSubmit={handleSubmit(processSubmit)}> <FormField label="Name" error={errors.name && errors.name.message} > <Input name="name" formRef={register} extraClass={errors.name && 'input-error'} required /> </FormField> <FormField label="Year" error={errors.year && errors.year.message} > <Input name="year" type="number" formRef={register} extraClass={errors.year && 'input-error'} required /> </FormField> <FormField label="Year End" error={errors.yearEnd && errors.yearEnd.message} > <Input name="yearEnd" type="number" formRef={register} extraClass={errors.yearEnd && 'input-error'} /> </FormField> <FormField label="Position" error={errors.geometry && errors.geometry.message} > <PlaceSelector onChange={(value) => handleSelectorChange('geometry', value)} /> </FormField> <div className="row"> <div className="col-lg-6"> <Button submit color="secondary" inverse text="Add station" block /> </div> <div className="col-lg-6"> <Button color="secondary" text="Cancel" outline block onClick={onCancel} /> </div> </div> </form> ); }; export default AddStationForm;<file_sep>import { takeEvery } from "redux-saga/effects"; import * as actionTypes from "store/admin/actions/draft/actionTypes"; import { addDraftSagaStart, deleteDraftSagaStart, getDraftSagaStart, updateDraftSagaStart } from './workers'; export const draftSagas = [ takeEvery(actionTypes.ADD_DRAFT_START, addDraftSagaStart), takeEvery(actionTypes.GET_DRAFT_START, getDraftSagaStart), takeEvery(actionTypes.UPDATE_DRAFT_START, updateDraftSagaStart), takeEvery(actionTypes.DELETE_DRAFT_START, deleteDraftSagaStart) ];<file_sep>import { Footer, Header } from 'components/shared'; import React from 'react'; import { withRouter } from "react-router-dom"; import routes from './routes'; class Showroom extends React.Component { render() { return ( <React.Fragment> <Header optionsName="admin" /> <main className="showroom"> <div className="container"> {routes} </div> </main> <Footer /> </React.Fragment> ); } } export default withRouter(Showroom);<file_sep>export { addDraftSagaStart } from './addDraft'; export { deleteDraftSagaStart } from './deleteDraft'; export { getDraftSagaStart } from './getDraft'; export { updateDraftSagaStart } from './updateDraft'; <file_sep>export const SEARCH_PARAMS_CHANGE_START = 'SEARCH_PARAMS_CHANGE_START'; export const SEARCH_PARAMS_CHANGE_SUCCESS = 'SEARCH_PARAMS_CHANGE_SUCCESS'; export const SEARCH_PARAMS_CHANGE_FAIL = 'SEARCH_PARAMS_CHANGE_FAIL'; <file_sep>import { takeEvery } from "redux-saga/effects"; import * as actionTypes from "store/admin/actions/line/actionTypes"; import { addLineSagaStart, deleteLineSagaStart, updateLineSagaStart } from './workers'; export const lineSagas = [ takeEvery(actionTypes.ADD_LINE_START, addLineSagaStart), takeEvery(actionTypes.UPDATE_LINE_START, updateLineSagaStart), takeEvery(actionTypes.DELETE_LINE_START, deleteLineSagaStart) ];<file_sep> import axios from '../axios'; const defaultPagination = require('../defaultParams/pagination.json'); const searchConnectionsParams = require('../defaultParams/searchConnections.json'); export default class Connection { // Search connections static search = (draftId, searchParams, pagination) => { return axios.post(`${draftId}/connection/search`, { filter: searchParams.filter, sort: { name: 1 }, populate: searchConnectionsParams.populate, pagination: pagination || defaultPagination }); } // Get full info from connection static get = (connectionId) => { return axios.get(`connection/${connectionId}`); } // Add connection static add = (draftId, connection) => { return axios.post(`${draftId}/connection`, connection); } // Update connection static update = (connection) => { return axios.put(`connection/${connection._id}`, connection); } // Delete connection static delete = (connectionId) => { return axios.delete(`connection/${connectionId}`); } }<file_sep>export const townInUser = (town, user) => { let result = false; user.towns.forEach(t => { if (t.town._id === town._id) { result = true; } }); return result; }<file_sep>export { importDraftSagaStart } from './importDraft'; <file_sep>import Api from 'http/admin'; import { put } from 'redux-saga/effects'; import { deleteStationFail, deleteStationSuccess, searchParamsChangeStart } from 'store/admin/actions'; import { error, info } from 'util/notification'; export function* deleteStationSagaStart(action) { try { yield Api.station.delete(action.stationId); yield put(deleteStationSuccess()); yield put(searchParamsChangeStart()); info('Station was deleteded succesully'); } catch (err) { error('Something went wrong!'); yield put(deleteStationFail(err)); } }<file_sep>export * from './addLine'; export * from './deleteLine'; export * from './updateLine'; <file_sep>import React from 'react'; const linesInfoHeader = ({ element }) => { return ( <div className="lines-info-header" style={{ borderLeft: `10px solid ${element.colour}` }}> <span>{element.name}</span> </div> ) } export default linesInfoHeader;<file_sep>export * from './initMap'; export * from './initMapDraft'; export * from './setYear'; <file_sep>// import * as actions from 'actions/main'; import { Header, LoadingSpinner, YearSelector } from 'components/shared'; import React from 'react'; import { connect } from 'react-redux'; import { withRouter } from "react-router-dom"; import MapWrapper from '../MapWrapper/MapWrapper'; import Sidebar from '../SideBar/SideBar'; class Main extends React.Component { constructor(props) { super(props); this.state = { showYearSelector: true }; } componentDidMount() { const { match, onInit } = this.props; const town = match.params.town; const year = parseInt(match.params.year, 10); onInit(town, year); } yearChange = (_year) => { const { history, maxYearLoaded, onYearChange, town, year } = this.props; history.push(`/${town.url}/${_year}`); onYearChange(town._id, _year, year, maxYearLoaded); } toggleYearSelector = () => { this.setState(prevState => ({ showYearSelector: !prevState.showYearSelector })); } render() { const { loading, town, year } = this.props; const { showYearSelector } = this.state; return ( <div> {loading ? <LoadingSpinner /> : null} {year ? <YearSelector year={year} showYearSelector={showYearSelector} onYearChange={(_year) => { this.yearChange(_year) }} /> : null} <Header optionsName="main" onToggleYearSelector={() => { this.toggleYearSelector() }} showYear={!showYearSelector} town={town} year={year} /> <Sidebar /> <MapWrapper mode="main" /> </div> ) } } const mapStateToProps = state => { return { town: state.main.town, year: state.main.year, previousYear: state.main.previousYear, maxYearLoaded: state.main.maxYearLoaded, lines: state.main.lines, selectedLine: state.main.selectedLine, stations: state.main.stations, connections: state.main.connections, sideBarMode: state.main.sideBarMode, loading: state.main.loading }; }; const mapDispatchToProps = () => { return { onInit: (town, year) => { console.log(town, year) }, onYearChange: (townId, year, previousYear, maxYearLoaded) => { console.log(townId, year, previousYear, maxYearLoaded) } } }; export default connect(mapStateToProps, mapDispatchToProps)(withRouter(Main)); <file_sep> import axios from '../axios'; export default class User { // Login static login = (email, password) => { return axios.get(`login?email=${email}&password=${password}`); } // SignUp static signUp = (email, password, name) => { return axios.post(`signup?email=${email}&password=${password}&name=${name}`); } }<file_sep>import Api from 'http/admin'; import { put } from 'redux-saga/effects'; import { getOwnUserFail, getOwnUserSuccess } from 'store/admin/actions'; export function* getOwnUserSagaStart() { try { const response = yield Api.user.getOwn(); yield put(getOwnUserSuccess(response.data)); } catch (err) { yield put(getOwnUserFail(err)); } }<file_sep>export const handleError = (err) => { if (err.response.status === 401) { return '/login'; } return null; }<file_sep>import { Button } from 'components/shared'; import React from 'react'; import useForm from 'react-hook-form'; const DeleteConnectionForm = ({ actionObj, onSubmit, onCancel }) => { const { handleSubmit } = useForm(); const processSubmit = () => { onSubmit(actionObj._id); } return ( <div> <h4 className="text-center">Are you sure you want to delete this connection?</h4> <form className="form mt-40" onSubmit={handleSubmit(processSubmit)}> <div className="row"> <div className="col-lg-6"> <Button submit color="danger" text="Confirm" outline block /> </div> <div className="col-lg-6"> <Button color="secondary" text="Cancel" outline block onClick={onCancel} /> </div> </div> </form> </div> ); }; export default DeleteConnectionForm;<file_sep>import * as actionTypes from './actionTypes'; export const importDraftStart = (draftId, file) => { return { type: actionTypes.IMPORT_DRAFT_START, draftId, file }; }; export const importDraftSuccess = () => { return { type: actionTypes.IMPORT_DRAFT_SUCCESS }; }; export const importDraftFail = (error) => { return { type: actionTypes.IMPORT_DRAFT_FAIL, error }; };<file_sep>export const START_ACTION = 'START_ACTION'; export const FINISH_ACTION = 'FINISH_ACTION'; export const CLEAR_DRAFT = 'CLEAR_DRAFT'; export const CLEAR_PAGINATION_SEARCHPARAMS = 'CLEAR_PAGINATION_SEARCHPARAMS'; <file_sep>import { takeEvery } from "redux-saga/effects"; import * as actionTypes from "store/admin/actions/user/actionTypes"; import { getOwnUserSagaStart } from './workers'; export const userSagas = [ takeEvery(actionTypes.USER_GET_OWN_START, getOwnUserSagaStart) ];<file_sep>import { Icon, Panel } from 'components/shared'; import PropTypes from 'prop-types'; import React from 'react'; class TabMenu extends React.Component { constructor(props) { super(props); this.state = { menuElementWidth: null, activeTab: this.getInitialActiveTab(), menuHeaderStyle: null }; this.menuHeader = React.createRef(); this.setActiveTab = this.setActiveTab.bind(this); this.updateMenuHeaderStyle = this.updateMenuHeaderStyle.bind(this); } componentDidMount() { const { tabs } = this.props; const width = this.menuHeader.current.clientWidth / tabs.length this.setState({ menuElementWidth: width }); this.updateMenuHeaderStyle(width); } getInitialActiveTab() { const { activeTab, tabs } = this.props; return activeTab ? tabs.findIndex(t => t.id === activeTab) + 1 : 1; } setActiveTab(activeTab) { const { onTabChange, tabs } = this.props; this.setState({ activeTab }); this.updateMenuHeaderStyle(null, activeTab); if (onTabChange) { onTabChange(tabs[activeTab - 1].id); } } updateMenuHeaderStyle(_menuElementWidth, _activeTab) { const { menuElementWidth, activeTab } = this.state; const width = _menuElementWidth || menuElementWidth; const tab = _activeTab || activeTab; if (width) { this.setState({ menuHeaderStyle: { left: (tab - 1) * width, width } }); } } render() { const { children, panel, tabs, type } = this.props; const { activeTab, menuHeaderStyle } = this.state; return ( <div className="tab-menu"> <ul className={`tab-menu-header tab-menu-header-${type}`} ref={this.menuHeader}> {tabs.map((tab, i) => { return ( <li key={i} className={`tab-menu-header-item ${i + 1 === activeTab ? 'active' : ''}`}> <a onClick={() => this.setActiveTab(i + 1)}> <Icon name={tab.icon} /> <span>{tab.name}</span> </a> </li> ) })} <span className={`tab-menu-header-indicator ${panel !== 'white' ? 'tab-menu-header-indicator-white' : ''}`} style={menuHeaderStyle} /> </ul> <Panel background={panel} > {children[activeTab - 1]} </Panel> </div> ) } } TabMenu.defaultProps = { activeTab: null, panel: 'white', type: 'secondary', tabs: [], onTabChange: null }; TabMenu.propTypes = { activeTab: PropTypes.string, panel: PropTypes.oneOf(['white', 'primary', 'secondary']), type: PropTypes.oneOf(['primary', 'secondary']), tabs: PropTypes.arrayOf(PropTypes.object), onTabChange: PropTypes.func }; export default TabMenu;<file_sep>import React from 'react'; const overlay = (props) => { const { show } = props; return <div className={`overlay ${show ? 'shown' : ''}`} /> } export default overlay;<file_sep>import { Button } from 'components/shared'; import React from 'react'; const index = () => { return ( <div className="showroom-index"> <h1 className="right-line mb-4">Showroom</h1> <div className="row"> <div className="col"> <div className="showroom-element showroom-link"> <Button to="/showroom/layout" text="Layout" type="link" color="secondary" /> </div> </div> <div className="col"> <div className="showroom-element showroom-link"> <Button to="/showroom/headers" text="Headers" type="link" color="secondary" /> </div> </div> <div className="col"> <div className="showroom-element showroom-link"> <Button to="/showroom/buttons" text="Buttons and Links" type="link" color="secondary" /> </div> </div> <div className="col"> <div className="showroom-element showroom-link"> <Button to="/showroom/data-presentation" text="Data presentation" type="link" color="secondary" /> </div> </div> <div className="col"> <div className="showroom-element showroom-link"> <Button to="/showroom/forms" text="Forms" type="link" color="secondary" /> </div> </div> <div className="col"> <div className="showroom-element showroom-link"> <Button to="/showroom/inputs" text="Inputs" type="link" color="secondary" /> </div> </div> </div> </div> ); } export default index;<file_sep>import Login from 'containers/Auth/Login/Login'; import Signup from 'containers/Auth/Signup/Signup'; import Public from 'containers/Public/Public'; import React from 'react'; import { Redirect, Route, Switch } from 'react-router-dom'; const Admin = React.lazy(() => import('containers/Admin/Admin')); const Showroom = React.lazy(() => import('containers/Showroom/Showroom')); const lazyComponent = (Component, history) => { return props => ( <React.Suspense fallback={<div>Loading...</div>}> <Component history={history} {...props} /> </React.Suspense> ); } const routes = (history) => ( <Switch> <Route path="/login" exact component={Login} /> <Route path="/signup" exact component={Signup} /> <Route path="/admin" component={lazyComponent(Admin, history)} /> <Route path="/showroom" component={lazyComponent(Showroom, history)} /> <Route path="/" component={lazyComponent(Public)} /> <Redirect to="/admin" /> </Switch> ); export default routes; <file_sep>export const startAction = (state, action) => { return { ...state, actionPanelInitiated: true, action: action.actionName, actionObj: action.actionObj } } export const finishAction = (state) => { return { ...state, action: null, actionObj: null } } export const clearDraft = (state) => { return { ...state, actionPanelInitiated: false, action: null, actionObj: null, draft: null, elements: [], searchParams: null, pagination: null } } <file_sep>import * as actionTypes from './actionTypes'; export const deleteStationStart = (stationId) => { return { type: actionTypes.DELETE_STATION_START, stationId }; }; export const deleteStationSuccess = () => { return { type: actionTypes.DELETE_STATION_SUCCESS }; }; export const deleteStationFail = (error) => { return { type: actionTypes.DELETE_STATION_FAIL, error }; };<file_sep>import { AddDraftForm } from 'components/admin/forms'; import React from 'react'; import { connect } from 'react-redux'; import { withRouter } from "react-router-dom"; import { addDraftStart, getTownsStart } from 'store/admin/actions'; class AddDraft extends React.Component { constructor(props) { super(props); this.handleSubmit = this.handleSubmit.bind(this); } handleSubmit(formData) { const { addDraft } = this.props; addDraft(formData.town._id, { name: formData.name, description: formData.description }); } render() { const { towns, getTowns } = this.props; if (!towns) { getTowns(); } return ( <div className="admin-user-container"> <div className="container"> <h1 className="right-line mb-4">Create draft</h1> <div className="row"> <div className="col-lg-3"> {towns && ( <AddDraftForm towns={towns} onSubmit={this.handleSubmit} /> )} </div> </div> </div> </div> ) } }; const mapStateToProps = state => { return { towns: state.admin.towns }; }; const mapDispatchToProps = dispatch => { return { getTowns: () => dispatch(getTownsStart()), addDraft: (town, draft) => dispatch(addDraftStart(town, draft)) } }; export default connect(mapStateToProps, mapDispatchToProps)(withRouter(AddDraft));<file_sep>import { Translation } from 'components/shared'; import PropTypes from 'prop-types'; import React from 'react'; const formField = (props) => { const { children, error, label, prefix, id } = props; const getLabel = () => id ? <Translation prefix={prefix} id={id} /> : label; return ( <div className="field"> {label || id ? <label className="label">{getLabel()}</label> : null} <div className="control"> {children} </div> <div className="error-msg">{error}</div> </div> ) } formField.defaultProps = { error: null, label: null, prefix: null, id: null }; formField.propTypes = { error: PropTypes.string, label: PropTypes.string, prefix: PropTypes.string, id: PropTypes.string }; export default formField;<file_sep>import { Badge } from 'components/shared'; import React from 'react'; import { getContrastColor } from 'util/color'; const ColorSelected = (props) => { const { selectedOption } = props; return ( <div className="filter-option"> <div className="filter-option-inner"> <div className="filter-option-inner-inner"> {(selectedOption && <Badge text={selectedOption.hex} backgroundColor={selectedOption.hex} fontColor={getContrastColor(selectedOption.hex)} block border /> ) || 'Select a color'} </div> </div> </div> ) } export default ColorSelected;<file_sep>import Api from 'http/admin'; import { put } from 'redux-saga/effects'; import { getTownsFail, getTownsSuccess } from 'store/admin/actions'; export function* getTownsSagaStart() { try { const response = yield Api.town.getAll(); yield put(getTownsSuccess(response.data)); } catch (err) { yield put(getTownsFail(err)); } }<file_sep>import { Button } from 'components/shared'; import { convertMapPointToPointArray, convertPointArrayToMapPoint, initMapForPlaceSearch, searchPlace } from 'map'; import React from 'react'; import Select from '../select/select'; import PlaceDropdown from './place-dropdown/place-dropdown'; import PlaceSelected from './place-selected/place-selected'; import selectConfig from './place-selector.config.json'; class PlaceSelector extends React.Component { constructor(props) { super(props); const { defaultValue } = this.props; this.state = { predictions: [], selectedPlace: null, mapHidden: !!defaultValue, value: defaultValue }; this.toggleMap = this.toggleMap.bind(this); } componentDidMount() { const { value } = this.state; if (value) { initMapForPlaceSearch('place-search-map-container', this.generatePlaceFromState(), this.handleOnGeometryChange); } } componentDidUpdate(prevProps, prevState) { const { selectedPlace } = this.state; if (selectedPlace !== prevState.selectedPlace) { initMapForPlaceSearch('place-search-map-container', selectedPlace, this.handleOnGeometryChange); } } handleOnInputChange = (str) => { if (str.length >= 3) { searchPlace(str) .then(predictions => { this.setState({ predictions }); }) .catch(err => err !== 'ZERO_RESULTS' ? console.log(err) : null); } } handleOnChange = (place) => { const { onChange } = this.props; const geometry = this.getGeometryFromLocation(place.geometry.location); this.setState({ selectedPlace: place, value: geometry }); onChange(geometry); } handleOnGeometryChange = (location) => { const { onChange } = this.props; const geometry = this.getGeometryFromLocation(location) this.setState({ value: geometry }); onChange(geometry); } getGeometryFromLocation = (location) => { return { type: 'Point', coordinates: convertMapPointToPointArray(location) }; } generatePlaceFromState = () => { const { value } = this.state; return { geometry: { location: convertPointArrayToMapPoint(value.coordinates) } }; } toggleMap() { this.setState((prevState) => { return { mapHidden: !prevState.mapHidden }; }) } render() { const { predictions, value, mapHidden } = this.state; const { defaultName } = this.props; return ( <div className="place-search"> <Select config={{ ...selectConfig }} options={predictions} dropdown={PlaceDropdown} selected={PlaceSelected} onInputChange={this.handleOnInputChange} onChange={this.handleOnChange} value={defaultName} /> {value ? ( <React.Fragment> <div id="place-search-map-container" className={mapHidden ? 'map-hidden' : ''} /> <div className="flex flex-horizontal-end"> <Button type="link" text={mapHidden ? 'Show map' : 'Hide map'} color="secondary" onClick={this.toggleMap} /> </div> </React.Fragment> ) : null} </div> ) } } export default PlaceSelector;<file_sep>import PropTypes from 'prop-types'; import React from 'react'; import { getContrastColor } from 'util/color'; const badge = (props) => { const { block, border, color, backgroundColor, fontColor, extraClass, text } = props; const style = (backgroundColor || fontColor) ? { backgroundColor, color: fontColor || getContrastColor(backgroundColor) } : null; if (border && fontColor) { style.borderColor = fontColor; } return ( <span className={`badge badge-${color} ${block ? 'badge-block' : ''} ${border ? 'badge-border' : ''} ${extraClass}`} style={style} > {text} </span> ) } badge.defaultProps = { block: false, border: false, color: 'primary', backgroundColor: null, fontColor: null, extraClass: '' }; badge.propTypes = { block: PropTypes.bool, border: PropTypes.bool, color: PropTypes.oneOf(['primary', 'secondary']), backgroundColor: PropTypes.string, fontColor: PropTypes.string, extraClass: PropTypes.string, text: PropTypes.oneOfType([ PropTypes.string, PropTypes.number ]).isRequired, }; export default badge;<file_sep>import Api from 'http/admin'; import { put } from 'redux-saga/effects'; import { getDraftFail, getDraftSuccess } from 'store/admin/actions'; export function* getDraftSagaStart(action) { try { const response = yield Api.draft.get(action.draftId); yield put(getDraftSuccess(response.data)); } catch (err) { yield put(getDraftFail(err)); } }<file_sep> import React from 'react'; import CountUp from 'react-countup'; const townInfoCard = (props) => { const { infoElement, initiate } = props; return ( <div className="town-info-card"> <a onClick={() => props.onModeSelected(props.infoElement.mode)}> <div className="info-icon"> {/* <FontAwesomeIcon icon={infoElement.icon} /> */} </div> <div className="counter"> {!initiate ? <CountUp delay={0.5} start={infoElement.counterStart} end={infoElement.value} /> : infoElement.value} </div> {infoElement.label} </a> </div> ) } export default townInfoCard;<file_sep>import * as actionTypes from './actionTypes'; export const getTownsStart = () => { return { type: actionTypes.GET_TOWNS_START }; }; export const getTownsSuccess = (towns) => { return { type: actionTypes.GET_TOWNS_SUCCESS, towns }; }; export const getTownsFail = (error) => { return { type: actionTypes.GET_TOWNS_FAIL, error }; };<file_sep>export const getTownsSuccess = (state, action) => { return { ...state, loading: false, towns: action.towns } }<file_sep>import { push } from 'connected-react-router'; import Api from 'http/admin'; import { put } from 'redux-saga/effects'; import { deleteDraftFail, deleteDraftSuccess, finishAction } from 'store/admin/actions'; import { error, info } from 'util/notification'; export function* deleteDraftSagaStart(action) { try { yield Api.draft.delete(action.draftId); yield put(deleteDraftSuccess()); yield put(finishAction()); yield put(push('/admin')); info('Draft was deleteded succesully'); } catch (err) { error('Something went wrong!'); yield put(deleteDraftFail(err)); } }<file_sep>export * from './draft'; <file_sep>import React from 'react'; import ModalContent from './modal-content/modal-content'; class Modal extends React.Component { shouldComponentUpdate(nextProps) { const { children, show } = this.props; return nextProps.show !== show || nextProps.children !== children; } render() { const { content, header, onClose, show } = this.props; return ( <div className={`modal ${show ? 'show' : ''}`} tabIndex="-1" role="dialog" aria-labelledby="myModalLabel"> <div className="modal-dialog animated zoomIn animated-3x" role="document"> <ModalContent onClose={onClose} header={header} content={content} /> </div> </div> ) } } export default Modal;<file_sep>import axios from '../axios'; export default class Station { // Get stations by year range in draft - Auth static getStationsWithAuth = (draftId) => { return axios.get(`${draftId}/private/stations`); } // Get stations by year range in draft - Public static getStations = (draftId) => { return axios.get(`${draftId}/stations`); } } <file_sep>import React from 'react'; import Select from '../select/select'; import DefaultDropdown from './default-dropdown/default-dropdown'; import DefaultSelected from './default-selected/default-selected'; import selectConfig from './selector.config.json'; class Selector extends React.Component { constructor(props) { super(props); this.handleOnChange = this.handleOnChange.bind(this); } handleOnChange(option) { const { onChange } = this.props; if (onChange) { onChange(option); } } render() { const { config, options, defaultValue } = this.props; return ( <div className="line-selector"> <Select config={config || selectConfig} options={options} dropdown={DefaultDropdown} selected={DefaultSelected} onChange={this.handleOnChange} defaultValue={defaultValue} /> </div> ) } } export default Selector;<file_sep>import axios from '../axios'; const defaultPagination = require('../defaultParams/pagination.json'); const searchStationsParams = require('../defaultParams/searchStations.json'); export default class Station { // Search stations static search = (draftId, searchParams, pagination) => { return axios.post(`${draftId}/station/search`, { filter: searchParams.filter, sort: { name: 1 }, select: searchParams.select || searchStationsParams.select, populate: searchParams.populate || searchStationsParams.populate, pagination: pagination || defaultPagination }); } // Get full info from station static get = (stationId) => { return axios.get(`station/${stationId}`); } // Add station static add = (draftId, station) => { return axios.post(`${draftId}/station`, station); } // Update station static update = (station) => { return axios.put(`station/${station._id}`, station); } // Delete station static delete = (stationId) => { return axios.delete(`station/${stationId}`); } } <file_sep>import tubeLogo from 'assets/img/icons/tube_alt.png'; import { BooleanSelector } from 'components/shared'; import React from 'react'; import LineConnections from './line-connections/line-connections'; const lineInfo = (props) => { const { line, onStationSelected, year } = props; const handleAction = () => { } return ( <div className="line-info"> <div className="line-name" style={{ backgroundColor: line.colour, color: line.fontColour }}> <img className="line-logo" alt="" src={tubeLogo} />{line.name} </div> <div className="line-info-year"> <BooleanSelector options={[{ label: year, action: handleAction, active: false }, { label: 'Now', action: handleAction, active: true }]} /> </div> <LineConnections line={line} onStationSelected={onStationSelected} /> </div> ) } export default lineInfo;<file_sep>import React from 'react'; const footer = () => { return ( <footer className="ms-footer"> <div className="container"> <p>Development & Design by <NAME> - 2019</p> </div> </footer> ) } export default footer;<file_sep>import { TownLogo } from 'components/shared'; import React from 'react'; const stationSelected = (props) => { const { selectedOption } = props; return ( <div className="selected-station filter-option"> <div className="filter-option-inner"> <div className="filter-option-inner-inner"> {selectedOption ? <div> {selectedOption.draft && selectedOption.draft.town ? <TownLogo townUrl={selectedOption.draft.town.url} /> : null} <span className="station-name">{selectedOption.name}</span> </div> : 'Select a station'} </div> </div> </div> ) } export default stationSelected;<file_sep>import { DraftCard, MapCard } from 'components/admin'; import { Button, LoadingSpinner, TabMenu } from 'components/shared'; import React from 'react'; import { connect } from 'react-redux'; import { withRouter } from "react-router-dom"; import { finishAction, getDraftStart, startAction } from 'store/admin/actions'; import ActionsPanel from './ActionsPanel/ActionsPanel'; import AdminConnectionsPanel from './AdminConnectionsPanel/AdminConnectionsPanel'; import AdminLinesPanel from './AdminLinesPanel/AdminLinesPanel'; import AdminStationsPanel from './AdminStationsPanel/AdminStationsPanel'; const tabHeaders = [ { id: 'lines', name: 'Lines', icon: 'lines' }, { id: 'stations', name: 'Stations', icon: 'tube-logo' }, { id: 'connections', name: 'Connections', icon: 'connection' } ]; class AdminDraft extends React.Component { constructor(props) { super(props); this.closeActionPanel = this.closeActionPanel.bind(this); this.editDraft = this.editDraft.bind(this); this.deleteDraft = this.deleteDraft.bind(this); this.importDraft = this.importDraft.bind(this); } componentDidMount() { const { match: { params }, getDraft } = this.props; if (params.draftId) { getDraft(params.draftId); } } closeActionPanel() { const { _finishAction } = this.props; _finishAction(); } editDraft() { const { draft, _startAction } = this.props; _startAction('editDraft', { _id: draft._id, name: draft.name, description: draft.description }); } deleteDraft() { const { draft, _startAction } = this.props; _startAction('deleteDraft', { _id: draft._id, name: draft.name }); } importDraft() { const { draft, _startAction } = this.props; _startAction('importDraft', { _id: draft._id }); } render() { const { match: { params }, action, actionObj, actionPanelInitiated, draft, loading, loadingElements } = this.props; return ( <div className="admin-user-container"> <div className="container"> {draft && ( <React.Fragment> <h1 className="right-line mb-1">{draft.name}</h1> <h5 className="mb-4">{draft.description}</h5> <div className="row"> <div className="col-lg-3"> <div> <LoadingSpinner noSpinner loading={action && !loading} className="pr-30" /> <DraftCard lines={draft.linesAmount} stations={draft.stationsAmount} town={draft.town} type={draft.isPublished ? 'published' : 'draft'} /> <MapCard center={draft.town.center} zoom={3} marker={draft.town.url} className="mt-20" disableMap /> <Button color="secondary" text="View draft on map" block outline className="mt-20" icon="map" href={`/draft/${draft._id}/2019`} newPage /> <Button color="secondary" text="Request publication" block outline icon="publish" /> <Button color="secondary" text="Edit draft" block outline icon="edit" onClick={this.editDraft} /> <Button color="secondary" text="Import draft" block outline className="mt-20" icon="upload" onClick={this.importDraft} /> <Button color="secondary" text="Export draft" block outline icon="download" href={`${process.env.REACT_APP_ADMIN_API_URL}/generation/export/draft/${draft.exportId}`} /> <Button color="danger" text="Delete draft" block outline className="mt-20" icon="delete" onClick={this.deleteDraft} /> </div> </div> <div className="col-lg-6"> <LoadingSpinner noSpinner loading={(action && !loading) || loadingElements} className="pr-30" /> <TabMenu type="secondary" tabs={tabHeaders} activeTab={params.tab || 'lines'} > <AdminLinesPanel /> <AdminStationsPanel /> <AdminConnectionsPanel connections={draft.connections} /> </TabMenu> </div> <div className="col-lg-3"> {actionPanelInitiated && <ActionsPanel action={action} actionObj={actionObj} onCancel={this.closeActionPanel} />} </div> </div> </React.Fragment>)} </div> </div> ) } }; const mapStateToProps = state => { return { loading: state.admin.loading, loadingElements: state.admin.loadingElements, actionPanelInitiated: state.admin.actionPanelInitiated, action: state.admin.action, actionObj: state.admin.actionObj, draft: state.admin.draft }; }; const mapDispatchToProps = dispatch => { return { _startAction: (actionName, actionObj) => dispatch(startAction(actionName, actionObj)), _finishAction: () => dispatch(finishAction()), getDraft: (draftId) => dispatch(getDraftStart(draftId)) } }; export default connect(mapStateToProps, mapDispatchToProps)(withRouter(AdminDraft));<file_sep>import { ColorSelector, CountrySelector, Input, LineSelector, PlaceSelector, Selector, StationSelector, TownSelector } from 'components/shared'; import React from 'react'; import lines from './data/lines.json'; import stations from './data/stations.json'; import towns from './data/towns.json'; class Inputs extends React.Component { constructor(props) { super(props); this.state = { option: null, country: null, town: null, line: null, place: null, station: null, color: null, color2: null } this.handleSelect = this.handleSelect.bind(this); } handleSelect(element, value) { this.setState({ [element]: value }); } render() { const { country, line, option, place, station, town, color, color2 } = this.state; return ( <div className="showroom-selectors"> <h1 className="right-line mb-4">Inputs</h1> <div className="row"> <div className="col-2"> <div className="showroom-element"> <label>Text input</label> <Input name="input1" /> </div> </div> <div className="col-2"> <div className="showroom-element"> <label>Text input with placeholder</label> <Input name="input2" placeholder="Type something" /> </div> </div> <div className="col-2"> <div className="showroom-element"> <label>Text input clearable</label> <Input name="input3" clearable /> </div> </div> <div className="col-2"> <div className="showroom-element"> <label>Text input with initial value</label> <Input name="input4" value="<NAME>" /> </div> </div> <div className="col-2"> <div className="showroom-element"> <label>Text input disabled</label> <Input name="input5" disabled /> </div> </div> </div> <div className="row"> <div className="col-2"> <div className="showroom-element"> <label>Primary input</label> <Input name="input6" /> </div> </div> <div className="col-2"> <div className="showroom-element"> <label>Secondary input</label> <Input name="input7" backgroundColor="secondary" /> </div> </div> <div className="col-2"> <div className="showroom-element"> <label>White input</label> <Input name="input8" backgroundColor="white" /> </div> </div> <div className="col-2"> <div className="showroom-element"> <label>Primary text color</label> <Input name="input9" color="primary" /> </div> </div> <div className="col-2"> <div className="showroom-element"> <label>Secondary text color</label> <Input name="input10" color="secondary" /> </div> </div> <div className="col-2"> <div className="showroom-element"> <label>White text color</label> <Input name="input11" color="white" /> </div> </div> </div> <div className="row"> <div className="col"> <div className="showroom-element"> <label>Selector</label> <Selector options={lines} onChange={(value) => this.handleSelect('option', value)} /> <div className="showroom-result"> <span>{option ? `Option selected: ${option.name}` : ''}</span> </div> </div> </div> <div className="col"> <div className="showroom-element"> <label>LineSelector</label> <LineSelector lines={lines} onChange={(value) => this.handleSelect('line', value)} /> <div className="showroom-result"> <span>{line ? `Line selected: ${line.name}` : ''}</span> </div> </div> </div> <div className="col"> <div className="showroom-element"> <label>CountrySelector</label> <CountrySelector onChange={(value) => this.handleSelect('country', value)} /> <div className="showroom-result"> <span>{country ? `Country selected: ${country.name}` : ''}</span> </div> </div> </div> <div className="col"> <div className="showroom-element"> <label>TownSelector</label> <TownSelector towns={towns} onChange={(value) => this.handleSelect('town', value)} /> <div className="showroom-result"> <span>{town ? `Town selected: ${town.name}` : ''}</span> </div> </div> </div> <div className="col"> <div className="showroom-element"> <label>StationSelector</label> <StationSelector stations={stations.map(st => { return { ...st, town: { url: 'london' } } })} onChange={(value) => this.handleSelect('station', value)} /> <div className="showroom-result"> <span>{station ? `Station selected: ${station.name}` : ''}</span> </div> </div> </div> </div> <div className="row"> <div className="col-3"> <div className="showroom-element"> <label>PlaceSelector</label> <PlaceSelector onChange={(value) => this.handleSelect('place', value)} /> <div className="showroom-result"> <span>{place ? `Place selected: ${place.coordinates[0]} - ${place.coordinates[1]}` : ''}</span> </div> </div> </div> <div className="col-3"> <div className="showroom-element"> <label>ColorSelector</label> <ColorSelector name="color" onChange={(value) => this.handleSelect('color', value)} /> <div className="showroom-result"> <span>{color ? `Color selected: ${color}` : ''}</span> </div> </div> </div> <div className="col-3"> <div className="showroom-element"> <label>Text input with initial value</label> <Input name="input4" value="<NAME>" /> </div> </div> <div className="col-3"> <div className="showroom-element"> <label>ColorSelector with initial color</label> <ColorSelector name="color" color="#F78DA7" onChange={(value) => this.handleSelect('color2', value)} /> <div className="showroom-result"> <span>{color2 ? `Color selected: ${color2}` : ''}</span> </div> </div> </div> </div> </div> ); } } export default Inputs;<file_sep>export const USER_GET_OWN_START = 'USER_GET_OWN_START'; export const USER_GET_OWN_SUCCESS = 'USER_GET_OWN_SUCCESS'; export const USER_GET_OWN_FAIL = 'USER_GET_OWN_FAIL'; <file_sep>import * as actionTypes from './actionTypes'; export const initMapDraftStart = (draftId, year) => { return { type: actionTypes.INIT_MAP_DRAFT_START, draftId, year }; }; export const initMapDraftSuccess = (town, year, draft, stations) => { return { type: actionTypes.INIT_MAP_DRAFT_SUCCESS, town, year, draft, stations }; }; export const initMapDraftFail = (error) => { return { type: actionTypes.INIT_MAP_DRAFT_FAIL, error }; };<file_sep>import axios from '../axios'; const defaultPagination = require('../defaultParams/pagination.json'); const searchDraftsParams = require('../defaultParams/searchDrafts.json'); export default class Draft { // Search drafts static search = (searchParams, pagination) => { return axios.post('draft/search', { filter: searchParams, sort: { name: 1 }, populate: searchDraftsParams.populate, pagination: pagination || defaultPagination }); } // Get draft summary static get = (draftId) => { return axios.get(`draft/${draftId}`); } // Add draft static add = (town, draft) => { return axios.post(`${town}/draft`, draft); } // Update draft static update = (draft) => { return axios.put(`draft/${draft._id}`, draft); } // Delete draft static delete = (draftId) => { return axios.delete(`draft/${draftId}`); } // Request publication static requestPublication = (draftId) => { return axios.put(`draft/${draftId}/publish-request`); } // Publish draft static publish = (draftId) => { return axios.put(`draft/${draftId}/publish`); } // Unpublish draft static unpublish = (draftId) => { return axios.put(`draft/${draftId}/unpublish`); } // Duplicate draft static duplicate = (draftId) => { return axios.put(`draft/${draftId}/duplicate`); } // Add manager to draft static addManager = (draftId, userId) => { return axios.put(`draft/${draftId}/add-manager/${userId}`); } // Remove manager from draft static removeManager = (draftId, userId) => { return axios.put(`draft/${draftId}/remove-manager/${userId}`); } }<file_sep>import { Button, CollapseList } from 'components/shared'; import React from 'react'; import LinesInfoContent from './lines-info-content/lines-info-content'; import LinesInfoHeader from './lines-info-header/lines-info-header'; const linesInfo = (props) => { const { lines, viewLineStations, onAddLine, onEditLine, onDeleteLine } = props; return ( <div className="lines-info"> <div className="d-flex justify-content-end mb-30"> <Button text="Add line" icon="add" outline onClick={onAddLine} /> </div> <CollapseList elements={lines} hoverType="secondary" header={LinesInfoHeader} content={LinesInfoContent} actions={{ viewLineStations, onEditLine, onDeleteLine }} {...props} /> </div> ) } export default linesInfo;<file_sep>import { DraftCard, NoResultsBox, TownCard, UserPicture } from 'components/admin'; import { Button, CountryLabel, Slider } from 'components/shared'; import React from 'react'; import { connect } from 'react-redux'; import { Link, withRouter } from "react-router-dom"; import { clearDraft, getTownsStart } from 'store/admin/actions'; import { showDate } from 'util/date'; class AdminHome extends React.Component { componentDidMount() { const { _clearDraft, getTowns } = this.props; _clearDraft(); getTowns(); } render() { const { user, towns } = this.props; return ( <div className="admin-user-container"> <div className="container"> <h1 className="right-line mb-4">Admin</h1> {user && ( <div className="row"> <div className="col-lg-3"> <div className="card"> <div className="ms-hero-bg-primary ms-hero-img-coffee"> <h3 className="color-white index-1 text-center no-m pt-4">{user.firstName} {user.lastName}</h3> <div className="color-medium index-1 text-center np-m">{user.type}</div> <UserPicture user={user} /> </div> <div className="card-body mt-20 pt-4 text-center"> <CountryLabel country={user.country} /> <p className="mt-20">Manager since: {showDate(user.registrationDate)}</p> </div> </div> <Button color="secondary" text="Edit user" block outline /> </div> <div className="col-lg-9"> {user && user.drafts && ( <div className="mb-20"> <h3 className="mb-10">Your published drafts ({user.drafts.filter(d => d.isPublished).length})</h3> <Slider items={3}> {user.drafts.filter(d => d.isPublished).map(draft => ( <div className="pr-15" key={draft._id}> <Link to={`/admin/draft/${draft._id}`}> <DraftCard lines={draft.linesAmount} stations={draft.stationsAmount} town={draft.town} type="published" /> </Link> </div>) )} {!user.drafts.length && <NoResultsBox className="ml-15" noDrafts={!user.drafts.legnth} />} </Slider> </div> )} {user && user.drafts && ( <div className="mb-20"> <div className="flex flex-space-between"> <h3 className="mb-10">Your other drafts ({user.drafts.filter(d => !d.isPublished).length})</h3> <Button type="link" text="Create new draft" icon="add" color="secondary" size="lg" to="/admin/create-draft" /> </div> <Slider items={4}> {user.drafts.filter(d => !d.isPublished).map(draft => ( <div className="pr-15" key={draft._id}> <Link to={`/admin/draft/${draft._id}`}> <DraftCard lines={draft.linesAmount} stations={draft.stationsAmount} town={draft.town} type="draft" /> </Link> </div>) )} {!user.drafts.length && <NoResultsBox className="ml-15" />} </Slider> </div> )} {towns && ( <div className="mb-20"> <h3 className="mb-10">All towns ({towns.length})</h3> <Slider items={4}> {towns.map(town => <div className="pr-15" key={town._id}><a href={`/admin/town/${town.url}`}><TownCard town={town} /></a></div>)} </Slider> </div> )} </div> </div> )} </div> </div> ) } }; const mapStateToProps = state => { return { user: state.admin.user, towns: state.admin.towns, loading: state.admin.loading }; }; const mapDispatchToProps = dispatch => { return { _clearDraft: () => dispatch(clearDraft()), getTowns: () => dispatch(getTownsStart()), } }; export default connect(mapStateToProps, mapDispatchToProps)(withRouter(AdminHome));<file_sep>export * from './searchParamsChange'; <file_sep>import { Button, FormField, Input } from 'components/shared'; import React from 'react'; import useForm from 'react-hook-form'; const EditDraftForm = ({ actionObj, onSubmit, onCancel }) => { const { register, handleSubmit, errors } = useForm(); const processSubmit = (formData) => { onSubmit({ ...formData, _id: actionObj._id }); } return ( <form className="form" onSubmit={handleSubmit(processSubmit)}> <FormField label="Name" error={errors.name && errors.name.message} > <Input name="name" formRef={register} defaultValue={actionObj.name} extraClass={errors.name && 'input-error'} required /> </FormField> <FormField label="Description" error={errors.description && errors.description.message} > <Input name="description" formRef={register} defaultValue={actionObj.description} extraClass={errors.description && 'input-error'} required /> </FormField> <div className="row"> <div className="col-lg-6"> <Button submit color="secondary" inverse text="Confirm" block /> </div> <div className="col-lg-6"> <Button color="secondary" text="Cancel" outline block onClick={onCancel} /> </div> </div> </form> ); }; export default EditDraftForm;<file_sep>import React from 'react'; const userPicture = (props) => { const { user } = props; return ( <div className="user-picture img-avatar-circle"> {user && user.photo ? <img src="assets/img/demo/avatar1.jpg" alt="..." /> : <div className="user-picture-letters">{user.firstName[0]}{user.lastName[0]}</div>} </div> ) } export default userPicture; <file_sep>import React from 'react'; const lineSelected = (props) => { const { selectedOption } = props; const borderStyle = selectedOption ? { borderLeft: `5px solid ${selectedOption.colour}`, } : null; const innerStyle = selectedOption ? { paddingLeft: 8, } : null; return ( <div className="filter-option"> <div className="filter-option-inner" style={borderStyle}> <div className="filter-option-inner-inner" style={innerStyle}> {selectedOption ? selectedOption.shortName : 'Select a line'} </div> </div> </div> ) } export default lineSelected;<file_sep>import { Icon } from 'components/shared'; import PropTypes from 'prop-types'; import React from 'react'; import regexPatterns from 'util/regex'; class Input extends React.Component { constructor(props) { super(props); const { value } = this.props; this.input = null; this.setInputRef = element => { this.input = element; }; this.state = { isFocused: false, currentValue: value || '' } this.getHtmlType = this.getHtmlType.bind(this); this.handleOnFocus = this.handleOnFocus.bind(this); this.handleOnBlur = this.handleOnBlur.bind(this); this.handleOnChange = this.handleOnChange.bind(this); this.handleOnClick = this.handleOnClick.bind(this); this.clearValue = this.clearValue.bind(this); this.setValue = this.setValue.bind(this); this.formRefValidation = this.formRefValidation.bind(this); } getHtmlType() { const { type } = this.props; if (type === 'email') { return 'text'; } return type; } setValue(value) { this.setState({ currentValue: value }); } handleOnFocus() { this.setState({ isFocused: true }); } handleOnBlur() { this.setState({ isFocused: false }); } handleOnChange(evt) { const { onChange } = this.props; evt.persist(); this.setValue(evt.target.value); if (onChange) { onChange(evt.target.value); } } handleOnClick(evt) { const { onClick } = this.props; evt.persist(); if (onClick) { onClick(evt); } } clearValue() { const { onChange } = this.props; this.setValue(''); onChange(''); } formRefValidation() { const { required, type, customPattern } = this.props; let validation = { required: required && 'You must enter a value' }; if (type === 'email') { validation = { ...validation, pattern: regexPatterns.email } } if (type === 'password') { validation = { ...validation, pattern: regexPatterns.password } } if (customPattern) { validation = { ...validation, pattern: customPattern } } return validation; } render() { const { backgroundColor, color, clearable, defaultValue, formRef, disabled, readOnly, extraClass, name, placeholder, value } = this.props; const { isFocused, currentValue } = this.state; return ( <div className={`custom-input ${isFocused ? 'is-focused' : ''}`}> {formRef ? ( <input ref={formRef(this.formRefValidation())} defaultValue={defaultValue} className={`input-bg-${backgroundColor} ${color ? `input-text-${color}` : ''} ${extraClass}`} type={this.getHtmlType()} name={name} placeholder={placeholder} disabled={disabled} readOnly={readOnly} onFocus={this.handleOnFocus} onBlur={this.handleOnBlur} onChange={this.handleOnChange} onClick={this.handleOnClick} noValidate /> ) : <input value={value || currentValue} className={`input-bg-${backgroundColor} ${color ? `input-text-${color}` : ''} ${extraClass}`} type={this.getHtmlType()} name={name} placeholder={placeholder} disabled={disabled} readOnly={readOnly} onFocus={this.handleOnFocus} onBlur={this.handleOnBlur} onChange={this.handleOnChange} onClick={this.handleOnClick} noValidate /> } {clearable && (value || currentValue) ? <a onClick={this.clearValue} className="clear-cross"><Icon name="close" /></a> : null} </div> ) } } Input.defaultProps = { backgroundColor: 'primary', color: 'secondary', clearable: false, formRef: null, disabled: false, readOnly: false, extraClass: '', placeholder: null, required: false, customPattern: null, type: 'text', onChange: null, onClick: null }; Input.propTypes = { backgroundColor: PropTypes.oneOf(['primary', 'secondary', 'white']), color: PropTypes.oneOf(['primary', 'secondary', 'white']), clearable: PropTypes.bool, formRef: PropTypes.func, disabled: PropTypes.bool, readOnly: PropTypes.bool, extraClass: PropTypes.string, name: PropTypes.string.isRequired, placeholder: PropTypes.string, required: PropTypes.bool, customPattern: PropTypes.object, type: PropTypes.oneOf(['text', 'number', 'email', 'password', 'file']), onChange: PropTypes.func, onClick: PropTypes.func, }; export default Input;<file_sep>const yearValidation = (value) => { if (!value) { return 'Year is mandatory' } return parseFloat(value) >= 1800 && parseFloat(value) <= 2019 || 'Year must be between 1800 and 2019'; } export default { yearValidation }<file_sep>import { LineSelector, StationSelector } from 'components/shared'; import React, { useState } from 'react'; const ConnectionsFilter = ({ draftId, onChangeParams }) => { const [currentFilter, setCurrentFilter] = useState(''); const changeFilter = (param) => { const filter = Object.assign({}, currentFilter, param); setCurrentFilter(filter); onChangeParams({ filter }); } const handleLineChange = (line) => { changeFilter({ line: line._id }) } const handleStationChange = (station) => { changeFilter({ station: station._id }) } return ( <div className="connections-filter-basic flex flex-column"> <div className="flex flex-row"> <LineSelector draftId={draftId} className="w-180" onChange={handleLineChange} allLinesOpt /> <StationSelector draftId={draftId} className="w-180 ml-15" onChange={handleStationChange} /> </div> </div> ) } export default ConnectionsFilter;<file_sep>import { push } from 'connected-react-router'; import Api from 'http/admin'; import { put } from 'redux-saga/effects'; import { getDraftStart, importDraftFail, importDraftSuccess, searchParamsChangeStart } from 'store/admin/actions'; import { error, info } from 'util/notification'; export function* importDraftSagaStart(action) { try { yield Api.generation.importDraft(action.draftId, action.file); yield put(importDraftSuccess()); yield put(push(`/admin/draft/${action.draftId}/lines`)); yield put(getDraftStart(action.draftId)); yield put(searchParamsChangeStart()); info('Draft was imported succesully'); } catch (err) { error('Something went wrong!'); yield put(importDraftFail(err)); } }
4f3b3795a8784be6f83867a2ddaa79f05031297e
[ "JavaScript", "TypeScript" ]
182
JavaScript
pabloibanezcom/tube-map-history.web
89fa6466eb2e02df122bd352b9e66909c5ba638d
22ab053fe8f36f7690549167e5d457cd1c2c4c3d
refs/heads/master
<repo_name>frco9/Soutenance-PFE<file_sep>/js/index.js function nextItem(){ var press = jQuery.Event("keypress"); press.ctrlKey = false; press.which = 115; $(document).trigger(press); } function prevItem(){ var press = jQuery.Event("keypress"); press.ctrlKey = false; press.which = 122; $(document).trigger(press); } $(document).ready(function () { $(document).on('impress:stepactivate', function (event) { var target = $(event.target); var body = $(document.body); body.removeClass( 'white-bg gray-bg red-bg orange-bg green-bg purple-bg blue-bg yellow-bg light-yellow-bg black-bg'); if (target.hasClass('white')) body.addClass('white-bg'); else if (target.hasClass('gray')) body.addClass('gray-bg'); else if (target.hasClass('red')) body.addClass('red-bg'); else if (target.hasClass('orange')) body.addClass('orange-bg'); else if (target.hasClass('black')) body.addClass('black-bg'); else if (target.hasClass('green')) body.addClass('green-bg'); else if (target.hasClass('purple')) body.addClass('purple-bg'); else if (target.hasClass('blue')) body.addClass('blue-bg'); else if (target.hasClass('yellow')) body.addClass('yellow-bg'); else if (target.hasClass('light-yellow')) body.addClass('light-yellow-bg'); }); for (var s in steps) steps[s](); impress().init(); impressConsole().init(css="lib/css/impressConsole.css"); impressConsole().registerKeyEvent([115], nextItem, window); impressConsole().registerKeyEvent([122], prevItem, window); }) <file_sep>/README.md Soutenance PFE ============== Il s'agit d'une presentation détaillant le travail de réalistion d'un SDK pour l'application Wittiz, et de son intégration au sein de l'application de messagerie instantanée Libon. Elle a été créée à l'occasion de ma soutenance de Projet de fin d'étude, dans le cadre de mes études à l'ENSEIRB-MATMECA de Bordeaux et de mon stage chez Orange OLPS. Pour la voir en ligne, cliquez [ici](http://frco9.github.io/Soutenance-PFE), il vous faut un naviagateur moderne (Chrome) et l'affichage n'est pas optimisé pour les smartphones. Pour naviguer utilisez les flèches directionnelles et les touches `Z` et `S` sur certaine slides. Pour le contrôle sur mobile via [remote-impress](https://github.com/edjafarov/remote-impress), ce rendre dans le dossier `remote-impress`, puis installer les dependances avec `npm install`, enfin lancer le serveur local `node remote.js` après avoir rechargé la présentation, un QR code devrait apparaître. Credit ------ Cette presentation a été réalisé en utilisant la librairie [impress.js](https://github.com/impress/impress.js) ainsi que deux modules [impress-console](https://github.com/regebro/impress-console) afin d'avoir les notes de présentation dans une autre fenêtre, et [remote-impress](https://github.com/edjafarov/remote-impress) pour le controle des slides sur telephone. D'un point de vu technique, cette présentation utilise une partie des styles CSS et du code JS de la présentation [Triangulation](https://github.com/mkacz91/Triangulations) par <NAME>. License ------- Ce projet est disponible sous les termes de la licence MIT. <file_sep>/js/chartCompetitor.js function getRandomColor() { var letters = '0123456789ABCDEF'.split(''); var color = '#'; for (var i = 0; i < 6; i++ ) { color += letters[Math.floor(Math.random() * 16)]; } return color; } var imCompetitorData = [ { value: 700, color:"#F7464A", highlight: "#FF5A5E", label: "WhatsApp" }, { value: 600, color: getRandomColor(), highlight: "#FFC870", label: "Facebook Messenger" }, { value: 576, color: "#46BFBD", highlight: "#5AD3D1", label: "QQ Mobile" }, { value: 500, color: getRandomColor(), highlight: "#FFC870", label: "WeChat" }, { value: 300, color: getRandomColor(), highlight: "#FFC870", label: "Skype" }, { value: 236, color: getRandomColor(), highlight: "#FFC870", label: "Viber" }, { value: 181, color: getRandomColor(), highlight: "#FFC870", label: "LINE" }, { value: 200, color: getRandomColor(), highlight: "#FFC870", label: "Kik" }, { value: 91, color: getRandomColor(), highlight: "#FFC870", label: "BlackBerry Messenger" }, { value: 48, color: getRandomColor(), highlight: "#FFC870", label: "KakaoTalk" }, { value: 20, color: getRandomColor(), highlight: "#FFC870", label: "Autres" } ]
42dfa3bdd5ba1ae4ca891a1baf5f23c1412f5c8b
[ "JavaScript", "Markdown" ]
3
JavaScript
frco9/Soutenance-PFE
fdff3456a44b4470052d19b6c343bc1ea7afb227
1ccf1f93b469337f5fededf4873dde772239c02d
refs/heads/master
<repo_name>florenzen/JakBox<file_sep>/index.js /** * @format */ import {AppRegistry} from 'react-native'; import JakBox from './out/JakBox'; <file_sep>/copy-to-android #!/bin/bash target="Was Ist Was - Amphibien und Reptilien - Haie" #target="Was Ist Was - Das Wetter - Die Jahrezeiten" dir="/Users/florenz/Dropbox/Hoerspiele/Was Ist Was/$target" find "$dir" -type f | ( while read f; do echo "push $f" adb push "$f" "/storage/emulated/0/Music/$target" done) <file_sep>/README.md # JakBox Android audio player for kids <file_sep>/notes.md # Notes ## Development * Build watcher: ```bash yarn fable-splitter -c splitter.config.js -w --define DEBUG ``` * Run: ```bash export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_51.jdk/Contents/Home npx react-native run-android ``` * SQLite file on emulator device: `/data/data/com.jakbox/databases/repo.sqlite` ```bash adb pull /data/data/com.jakbox/databases/repo.sqlite ~/tmp/repo1.sqlite ``` ## Tasks * Store duration of track * Store first available track cover as album cover
edd7c0da2e9134f8267d6d561a3d16a569cc6e24
[ "JavaScript", "Markdown", "Shell" ]
4
JavaScript
florenzen/JakBox
3eb5d37cfdae398958b479586acb8e47ee9066c0
38af9e8d63125fdb2b945da891811f8bed4ea4a5
refs/heads/master
<repo_name>Bukkit-fr/xWarp<file_sep>/src/main/java/de/xzise/xwarp/list/GlobalMap.java package de.xzise.xwarp.list; import java.util.HashMap; import java.util.Map; import de.xzise.xwarp.WarpObject; public class GlobalMap<globalMapObject extends WarpObject<?>> { private final Map<String, globalMapObject> all = new HashMap<String, globalMapObject>(); public void put(globalMapObject warpObject) { this.all.put(warpObject.getCreator().toLowerCase(), warpObject); } public void delete(globalMapObject warp) { this.all.remove(warp.getCreator().toLowerCase()); } public globalMapObject getWarpObject(String playerName) { if (this.all.size() == 1) { return this.all.values().iterator().next(); } else if (playerName != null && !playerName.isEmpty()) { return this.all.get(playerName.toLowerCase()); } else { return null; } } public void clear() { this.all.clear(); } }<file_sep>/pom.xml <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/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>de.xzise.bukkit</groupId> <artifactId>xWarp</artifactId> <version>3.0.0</version> <name>xWarp</name> <dependencies> <dependency> <groupId>org.bukkit</groupId> <artifactId>bukkit</artifactId> <version>0.0.1-SNAPSHOT</version> </dependency> <dependency> <groupId>de.xzise.bukkitutil</groupId> <artifactId>bukkitutil</artifactId> <version>[0.1.0,)</version> <type>jar</type> <scope>compile</scope> </dependency> <dependency> <groupId>com.google.guava</groupId> <artifactId>guava-collections</artifactId> <version>r03</version> <type>jar</type> <scope>compile</scope> </dependency> </dependencies> <build> <finalName>${project.name}</finalName> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>2.3.2</version> <configuration> <source>1.6</source> <target>1.6</target> <encoding>UTF-8</encoding> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-resources-plugin</artifactId> <version>2.4.3</version> <configuration> <encoding>UTF-8</encoding> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-jar-plugin</artifactId> <version>2.3.1</version> <configuration> <archive> <manifestEntries> <Class-Path>../lib/BukkitPluginUtilities.jar ../lib/sqlitejdbc-v056.jar</Class-Path> </manifestEntries> </archive> </configuration> </plugin> </plugins> </build> </project>
b3ade5edf3aeaa3c87b7e4f10790c35c3485cfae
[ "Java", "Maven POM" ]
2
Java
Bukkit-fr/xWarp
d397b0fa10cca7e42fa91eb5941b6f33619b1cfb
9112f48845c46b3e43f8e36a81e168b18f345514
refs/heads/main
<file_sep>[HOST] host = 127.0.0.1 port = 5000 [DEBUG] debug = True <file_sep># Blockchain implementation using Python. This is a implementation of a basic blockchain structure in python, with all the description, and documentation of it's working and things. **NOTE**: It used to be a basic interaction API for finding the hashs, POW and the info. Currently it's revamped into a full stack website with dummy payments mining and a better UI. ## Definition, and Representation of Blockchain The structure of a dummy blockchain, which is accessed like JSON or a dict. ```python block = { 'index': 1, 'timestamp': 1506057125.900785, 'transactions': [ { 'sender': "8527147fe1f5426f9dd545de4b27ee00", 'recipient': "a<PASSWORD>", 'amount': 5, } ], 'proof': 324984774000, 'previous_hash': "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824" } ``` Each new block contains within itself, the hash of the previous Block. This is crucial because it’s what gives blockchains immutability: If an attacker corrupted an earlier Block in the chain then all subsequent blocks will contain incorrect hashes. ### Creating new Blocks When our Blockchain is instantiated we’ll need to seed it with a genesis block—a block with no predecessors. We’ll also need to add a “proof” to our genesis block which is the result of mining (or proof of work). ### Understanding Proof of Work A Proof of Work algorithm (PoW) is how new Blocks are created or mined on the blockchain. The goal of PoW is to discover a number which solves a problem. The number must be difficult to find but easy to verify—computationally speaking—by anyone on the network. This is the core idea behind Proof of Work. Let’s decide that the hash of some integer x multiplied by another y must end in 0. So, `hash(x * y) = ac23dc...0` And for this simplified example, let’s fix `x = 5`. Implementing this in Python: ```python from hashlib import sha256 x = 5 y = 0 # We don't know what y should be yet... while sha256(f'{x*y}'.encode()).hexdigest()[-1] != "0": y += 1 print(f'The solution is y = {y}') ``` The solution here is `y = 21`. Since, the produced hash ends in `0`: ``` hash(5 * 21) = 1253e9373e...5e3600155e860 ``` In Bitcoin, the Proof of Work algorithm is called **Hashcash**. And it’s not too different from our basic example above. It’s the algorithm that miners race to solve in order to create a new block. In general, the difficulty is determined by the number of characters searched for in a string. The miners are then rewarded for their solution by receiving a coin—in a transaction. The network is able to easily verify their solution. This is what the request for a transaction will look like. It’s what the user sends to the server: ```json { "sender": "my address", "recipient": "someone else's address", "amount": 5 } ``` ## More Project Info ### Tech Stack used - `Flask` - A HTTP Gateway to expose our blockchain structure externally. - `Requests` - A medium to check the HTTP Endpoint request and return JSON response. ### TODOs Planned: No TODOs Planned yet. ## How to run the project? - Clone the repo: `git clone https://github.com/janaSunrise/blockchain-python` - Install pipenv: `pip3 install pipenv` - Make a env with Pipenv: `pipenv sync` - Run the servers: - Run the miner server using `python -m frontend` - Run the clients using `python -m client <PORT-HERE>` You can visit the site, Play with the server, client and more, OR Use postman to Play and Mess with the HTTP and JSON responses! <div align="center"> Made by <NAME> with ❤️ </div> <file_sep>import binascii import hashlib import json from collections import OrderedDict from time import time from urllib.parse import urlparse from uuid import uuid4 import Crypto import Crypto.Random import requests from Crypto.Hash import SHA from Crypto.PublicKey import RSA from Crypto.Signature import PKCS1_v1_5 MINING_SENDER = "THE BLOCKCHAIN" MINING_REWARD = 1 MINING_DIFFICULTY = 2 class Blockchain: def __init__(self): self.chain = [] self.transactions = [] self.nodes = set() self.node_id = str(uuid4()).replace("-", "") self.new_block(0, "00") def new_block(self, nonce: int, previous_hash: str) -> dict: """ Create a new Block in the Blockchain :param proof: <int> The proof given by the Proof of Work algorithm :param previous_hash: (Optional) <str> Hash of previous Block :return: <dict> New Block """ block = { "index": len(self.chain) + 1, "timestamp": time(), "transactions": self.transactions, "nonce": nonce, "previous_hash": previous_hash or self.hash(self.chain[-1]), } # Reset the current list of transactions self.transactions = [] self.chain.append(block) return block def new_transaction(self, sender: str, recipient: str, amount: int) -> int: """ Creates a new transaction to go into the next mined Block :param sender: <str> Address of the Sender :param recipient: <str> Address of the Recipient :param amount: <int> Amount :return: <int> The index of the Block that will hold this transaction """ self.transactions.append( {"sender": sender, "recipient": recipient, "amount": amount,} ) return self.last_block["index"] + 1 @staticmethod def hash(block: dict) -> str: """ Creates a SHA-256 hash of a Block :param block: <dict> Block :return: <str> """ # We must make sure that the Dictionary is Ordered, or we'll have inconsistent hashes block_string = json.dumps(block, sort_keys=True).encode() return hashlib.sha256(block_string).hexdigest() @property def last_block(self): """ Returns the last Block in the chain. """ return self.chain[-1] def proof_of_work(self) -> int: """ Simple Proof of Work Algorithm: - Find a number p' such that hash(pp') contains leading 4 zeroes, where p is the previous p' - p is the previous proof, and p' is the new proof :param last_proof: <int> :return: <int> """ last_block = self.chain[-1] last_hash = self.hash(last_block) nonce = 0 while self.valid_proof(self.transactions, last_hash, nonce) is False: nonce += 1 return nonce @staticmethod def valid_proof(transactions, last_hash, nonce, difficulty=MINING_DIFFICULTY): """ Check if a hash value satisfies the mining conditions. This function is used within the proof_of_work function. """ guess = (str(transactions) + str(last_hash) + str(nonce)).encode() guess_hash = hashlib.sha256(guess).hexdigest() return guess_hash[:difficulty] == "0" * difficulty def register_node(self, address: str) -> None: """ Add a new node to the list of nodes :param address: <str> Address of node. Eg. 'http://192.168.0.5:5000' :return: None """ parsed_url = urlparse(address) if parsed_url.netloc: self.nodes.add(parsed_url.netloc) elif parsed_url.path: # Accepts an URL without scheme like '192.168.0.5:5000'. self.nodes.add(parsed_url.path) else: raise ValueError("Invalid URL") @staticmethod def verify_transaction_signature(sender_address, signature, transaction): """ Check that the provided signature corresponds to transaction signed by the public key (sender_address) """ public_key = RSA.importKey(binascii.unhexlify(sender_address)) verifier = PKCS1_v1_5.new(public_key) hash = SHA.new(str(transaction).encode("utf8")) return verifier.verify(hash, binascii.unhexlify(signature)) def submit_transaction(self, sender_address, recipient_address, value, signature): """Add a transaction to transactions array if the signature verified""" transaction = OrderedDict( { "sender_address": sender_address, "recipient_address": recipient_address, "value": value, } ) if sender_address == MINING_SENDER: self.transactions.append(transaction) return len(self.chain) + 1 else: transaction_verification = self.verify_transaction_signature( sender_address, signature, transaction ) if transaction_verification: self.transactions.append(transaction) return len(self.chain) + 1 else: return False def valid_chain(self, chain: list) -> bool: """ Determine if a given blockchain is valid :param chain: <list> A blockchain :return: <bool> True if valid, False if not """ last_block = chain[0] current_index = 1 while current_index < len(chain): block = chain[current_index] if block["previous_hash"] != self.hash(last_block): return False transactions = block["transactions"][:-1] transaction_elements = ["sender_address", "recipient_address", "value"] transactions = [ OrderedDict((k, transaction[k]) for k in transaction_elements) for transaction in transactions ] if not self.valid_proof( transactions, block["previous_hash"], block["nonce"], MINING_DIFFICULTY ): return False last_block = block current_index += 1 return True def resolve_conflicts(self) -> bool: """ This is our Consensus Algorithm, it resolves conflicts by replacing our chain with the longest one in the network. :return: <bool> True if our chain was replaced, False if not """ neighbours = self.nodes new_chain = None # We're only looking for chains longer than ours max_length = len(self.chain) # Grab and verify the chains from all the nodes in our network for node in neighbours: response = requests.get(f"http://{node}/chain") if response.status_code == 200: length = response.json()["length"] chain = response.json()["chain"] # Check if the length is longer and the chain is valid if length > max_length and self.valid_chain(chain): max_length = length new_chain = chain # Replace our chain if we discovered a new, valid chain longer than ours if new_chain: self.chain = new_chain return True return False <file_sep>from configparser import ConfigParser from .app import app # Get the config for the Flask app config = ConfigParser() config.read("config.ini") if __name__ == "__main__": app.run( host=config.get("HOST", "host"), port=config.getint("HOST", "port"), debug=config.getboolean("DEBUG", "debug"), ) <file_sep>[[source]] url = "https://pypi.org/simple" verify_ssl = true name = "pypi" [packages] flask = "*" requests = "*" flask-cors = "*" pycryptodome = "*" [dev-packages] [scripts] frontend = "python -m blockchain" client = "python -m client" <file_sep>""" The structure of a blockchain, Which is accessed like JSON or a dict. """ block = { "index": 1, "timestamp": 1506057125.900785, "transactions": [ { "sender": "8527147fe1f5426f9dd545de4b27ee00", "recipient": "a77f5cdfa2934df3954a5c7c7da5df1f", "amount": 5, } ], "proof": 324984774000, "previous_hash": "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824", } <file_sep>from flask import Flask, jsonify, request, render_template from flask_cors import CORS from uuid import uuid4 from .blockchain import Blockchain, MINING_REWARD, MINING_SENDER # Initialize Flask app app = Flask(__name__) CORS(app) # Define blockchain Variables blockchain = Blockchain() node_identifier = str(uuid4()).replace("-", "") @app.route("/") def index(): return render_template("./index.html") @app.route("/configure") def configure(): return render_template("./configure.html") @app.route("/transactions/new", methods=["POST"]) def new_transaction(): values = request.form required = ["sender_address", "recipient_address", "amount", "signature"] if not all(k in values for k in required): return "Missing values", 400 transaction_result = blockchain.submit_transaction( values["sender_address"], values["recipient_address"], values["amount"], values["signature"], ) if transaction_result == False: response = {"message": "Invalid Transaction!"} return jsonify(response), 406 else: response = { "message": "Transaction will be added to Block " + str(transaction_result) } return jsonify(response), 201 @app.route("/transactions/get", methods=["GET"]) def get_transactions(): transactions = blockchain.transactions response = {"transactions": transactions} return jsonify(response), 200 @app.route("/chain", methods=["GET"]) def full_chain(): response = { "chain": blockchain.chain, "length": len(blockchain.chain), } return jsonify(response), 200 @app.route("/mine", methods=["GET"]) def mine(): # We run the proof of work algorithm to get the next proof... last_block = blockchain.chain[-1] nonce = blockchain.proof_of_work() print(last_block) # We must receive a reward for finding the proof. blockchain.submit_transaction( sender_address=MINING_SENDER, recipient_address=blockchain.node_id, value=MINING_REWARD, signature="", ) # Forge the new Block by adding it to the chain previous_hash = blockchain.hash(last_block) block = blockchain.new_block(nonce, previous_hash) response = { "message": "New Block Forged", "block_number": block["index"], "transactions": block["transactions"], "nonce": block["nonce"], "previous_hash": block["previous_hash"], } return jsonify(response), 200 @app.route("/nodes/register", methods=["POST"]) def register_nodes(): values = request.form nodes = values.get("nodes").replace(" ", "").split(",") if nodes is None: return "Error: Please supply a valid list of nodes", 400 for node in nodes: blockchain.register_node(node) response = { "message": "New nodes have been added", "total_nodes": [node for node in blockchain.nodes], } return jsonify(response), 201 @app.route("/nodes/resolve", methods=["GET"]) def consensus(): replaced = blockchain.resolve_conflicts() if replaced: response = {"message": "Our chain was replaced", "new_chain": blockchain.chain} else: response = {"message": "Our chain is authoritative", "chain": blockchain.chain} return jsonify(response), 200 @app.route("/nodes/get", methods=["GET"]) def get_nodes(): nodes = list(blockchain.nodes) response = {"nodes": nodes} return jsonify(response), 200 <file_sep>from collections import OrderedDict import binascii from Crypto.Hash import SHA from Crypto.PublicKey import RSA from Crypto.Signature import PKCS1_v1_5 class Transaction: def __init__(self, sender_address, sender_private_key, recipient_address, value): self.sender_address = sender_address self.sender_private_key = sender_private_key self.recipient_address = recipient_address self.value = value def __getattr__(self, attr): return self.data[attr] def to_dict(self): return OrderedDict( { "sender_address": self.sender_address, "recipient_address": self.recipient_address, "value": self.value, } ) def sign_transaction(self): """Sign transaction with private key""" private_key = RSA.importKey(binascii.unhexlify(self.sender_private_key)) signer = PKCS1_v1_5.new(private_key) hash = SHA.new(str(self.to_dict()).encode("utf8")) return binascii.hexlify(signer.sign(hash)).decode("ascii")
822b8865ffd45b30cc7f1ee0533b7c6250b58dbe
[ "Markdown", "TOML", "Python", "INI" ]
8
INI
tearitco/blockchain-python
b09579f42abe4e34d9338bb319db9b3d437b1d6d
69c36e8e5ae3513a9c0e676c33da9876541dff95
refs/heads/master
<repo_name>SilverJun/ACM<file_sep>/Sprite_Player.h #pragma once #include "Sprite.h" class CSprite_Player : public CSprite { public: CSprite_Player(); ~CSprite_Player(); virtual void Update() override; }; <file_sep>/Scene_MusicSelect.h #pragma once #include "Scene.h" #define MAX_MUSIC 3 enum eMusicBox{ PlayList, music1, music2, music3, music4 }; class CScene_MusicSelect : public CScene { public: CScene_MusicSelect(); ~CScene_MusicSelect(); virtual void Init() override; virtual void Update() override; virtual void Release() override; private: SDL_Rect MenuBox[MAX_MUSIC + 1]; char MenuString[MAX_MUSIC + 1][100]; }; <file_sep>/Scene_MainMenu.cpp #include "stdafx.h" #include "Scene_MainMenu.h" #include "Director.h" #include "SceneManager.h" #include "TimeManager.h" #include "EventManager.h" #include "TextManager.h" CScene_MainMenu::CScene_MainMenu() : CScene(sMainMenu) { SetSceneBGImage("ACM.PNG"); MenuBox[Start] = { 100, 650, 0, 50 }; MenuBox[Rule] = { 0, 650, 0, 50 }; MenuBox[Score] = { 0, 650, 0, 50 }; MenuBox[Credit] = { 0, 650, 0, 50 }; MenuBox[Exit] = { 0, 650, 0, 50 }; strcpy(MenuString[Start], "게임시작"); strcpy(MenuString[Rule], "게임규칙"); strcpy(MenuString[Score], "점수"); strcpy(MenuString[Credit], "제작자"); strcpy(MenuString[Exit], "게임종료"); MenuBox[Start].w = (strlen(MenuString[Start]) - 1) * 25; MenuBox[Rule].w = (strlen(MenuString[Rule]) - 1) * 25; MenuBox[Score].w = (strlen(MenuString[Score]) - 1) * 25; MenuBox[Credit].w = (strlen(MenuString[Credit]) - 1) * 25; MenuBox[Exit].w = (strlen(MenuString[Exit]) - 1) * 25; MenuBox[Rule].x = MenuBox[Start].w + MenuBox[Start].x + 30; MenuBox[Score].x = MenuBox[Rule].w + MenuBox[Rule].x + 30; MenuBox[Credit].x = MenuBox[Score].w + MenuBox[Score].x + 30; MenuBox[Exit].x = MenuBox[Credit].w + MenuBox[Credit].x + 30; } CScene_MainMenu::~CScene_MainMenu() { Release(); } void CScene_MainMenu::Init() { for (int i = 0; i < 5; i++) { g_TextManager->CreateText(MenuString[i], &MenuBox[i]); } bool b; g_SoundManager->pChannel[eBGMChannel]->isPlaying(&b); if (!b) { g_SoundManager->MakeSound(eMainMenuSound, eMainMenu); g_SoundManager->PlaySound(eBGMChannel, eMainMenuSound); } if (g_SoundManager->SongMap.find(eEffectMusic) != g_SoundManager->SongMap.end()) { g_SoundManager->DestroySound(eEffectMusic); } g_SoundManager->MakeSound(eEffectMusic, eEffect_Click); } void CScene_MainMenu::Update() { if (g_EventManager->g_Event.button.button == SDL_BUTTON_LEFT) { if (g_EventManager->CheckCollition_by_mouse(MenuBox[Start])) { g_SoundManager->PlaySound(eChannel2, eEffectMusic); g_SoundManager->pChannel[eBGMChannel]->stop(); g_SoundManager->DestroySound(eMainMenuSound); g_SceneManager->SetScene(sMusicSelect); } else if (g_EventManager->CheckCollition_by_mouse(MenuBox[Rule])) { g_SoundManager->PlaySound(eChannel2, eEffectMusic); g_SceneManager->SetScene(sRule); } else if (g_EventManager->CheckCollition_by_mouse(MenuBox[Score])) { g_SoundManager->PlaySound(eChannel2, eEffectMusic); g_SceneManager->SetScene(sScore); } else if (g_EventManager->CheckCollition_by_mouse(MenuBox[Credit])) { g_SoundManager->PlaySound(eChannel2, eEffectMusic); g_SceneManager->SetScene(sCredit); } else if (g_EventManager->CheckCollition_by_mouse(MenuBox[Exit])) { g_SoundManager->PlaySound(eChannel2, eEffectMusic); g_Director->GameDone = true; } } } void CScene_MainMenu::Release() { //g_SoundManager->DestroySound(eMainMenuSound); g_TextManager->DestroyTextAll(); } <file_sep>/Scene_GameEnd.h #pragma once #include "Scene.h" class CScene_GameEnd : public CScene { public: CScene_GameEnd(); ~CScene_GameEnd(); virtual void Init() override; virtual void Update() override; virtual void Release() override; private: int nowScore, BestScore; char strScore[5][50]; SDL_Rect ScoreBox[5]; fstream ScoreFile; }; <file_sep>/SceneManager.cpp #include "StdAfx.h" #include "SceneManager.h" #include "TimeManager.h" #include "Scene_MainMenu.h" #include "Scene_MusicSelect.h" #include "Scene_Game.h" #include "Scene_Rule.h" #include "Scene_Score.h" #include "Scene_Credit.h" #include "Scene_GameEnd.h" CSceneManager::CSceneManager(void) { thisScene = nullptr; } CSceneManager::~CSceneManager(void) { } void CSceneManager::SetParam(int n) { Param = n; } void CSceneManager::SetScene(int idx) { if (thisScene != nullptr) delete thisScene; switch (idx) { case 0: //thisScene = new CScene; //SceneIdx = 0; break; case sMainMenu: thisScene = new CScene_MainMenu; SceneIdx = sMainMenu; break; case sMusicSelect: thisScene = new CScene_MusicSelect; SceneIdx = sMusicSelect; break; case sGame: thisScene = new CScene_Game; SceneIdx = sGame; break; case sRule: thisScene = new CScene_Rule; SceneIdx = sRule; break; case sScore: thisScene = new CScene_Score; SceneIdx = sScore; break; case sCredit: thisScene = new CScene_Credit; SceneIdx = sCredit; break; case sGameEnd: thisScene = new CScene_GameEnd; SceneIdx = sCredit; break; default: break; } thisScene->Init(); } void CSceneManager::Init() { SceneIdx = 1; SetScene(1); } void CSceneManager::Update() { thisScene->Update(); g_TimeManager->Update(); } void CSceneManager::Render() { thisScene->Render(); } void CSceneManager::Release() { if (thisScene != nullptr) delete thisScene; } <file_sep>/Scene_Score.cpp #include "stdafx.h" #include "SceneManager.h" #include "TextManager.h" #include "EventManager.h" #include "Scene_Score.h" CScene_Score::CScene_Score() : CScene(sScore) { ScoreFile.open("./Data/Score.txt", ios::in); ScoreFile >> BestScore; ScoreFile.close(); ScoreBox[0] = { 300, 120, 0, 60 }; ScoreBox[1] = { 100, 200, 0, 40 }; ScoreBox[2] = { 100, 300, 0, 50 }; ScoreBox[3] = { 20, 20, 0, 50 }; } CScene_Score::~CScene_Score() { Release(); } void CScene_Score::Init() { sprintf(strScore[0], "*점수*"); sprintf(strScore[1], "※통합 점수관리로 제일 높은 점수만 저장됩니다."); sprintf(strScore[2], "최고점수 %d", BestScore); sprintf(strScore[3], "메인메뉴로"); ScoreBox[0].w = (strlen(strScore[0]) - 1) * 30; ScoreBox[1].w = (strlen(strScore[1]) - 1) * 20; ScoreBox[2].w = (strlen(strScore[2]) - 1) * 25; ScoreBox[3].w = (strlen(strScore[3]) - 1) * 10; for (int i = 0; i < 4; i++) { g_TextManager->CreateText(strScore[i], &ScoreBox[i]); } } void CScene_Score::Update() { if (g_EventManager->g_Event.button.button == SDL_BUTTON_LEFT) { if (g_EventManager->CheckCollition_by_mouse(ScoreBox[3])) { g_SceneManager->SetScene(sMainMenu); } } } void CScene_Score::Release() { g_TextManager->DestroyTextAll(); } <file_sep>/Sprite_SpawnNote.cpp #include "stdafx.h" #include "Sprite_SpawnNote.h" CSprite_SpawnNote::CSprite_SpawnNote() : CSprite("SpawnNote", 100,100,0,0,100,100) { SetSpriteImage("SpawnNote.png"); SetSpriteRect((WINDOW_DEFAULT_W / 2 - 50),(WINDOW_DEFAULT_H / 2 - 50)); } CSprite_SpawnNote::~CSprite_SpawnNote() { } void CSprite_SpawnNote::Update() { } <file_sep>/Sprite_Bar.cpp #include "stdafx.h" #include "DrawManager.h" #include "SoundManager.h" #include "Sprite_Bar.h" CSprite_Bar::CSprite_Bar() : CSprite("Bar", 400, 30, 0, 0, 400, 30) { SetSpriteImage("Bar.png"); SetSpriteRect(400, 30); } CSprite_Bar::~CSprite_Bar() { } void CSprite_Bar::Update() { unsigned int time; g_SoundManager->pChannel[eChannel1]->getPosition(&time, FMOD_TIMEUNIT_MS); NowTime = time; g_SoundManager->SongMap[eGameTheme]->getLength(&time, FMOD_TIMEUNIT_MS); EndTime = time; NowX = (NowTime * 400 / EndTime); SDL_SetRenderDrawColor(g_DrawManager->pRenderer, 0, 0, 0, 255); DrawBox = {400, 30, NowX, 30}; SDL_RenderFillRect(g_DrawManager->pRenderer, &DrawBox); } <file_sep>/Scene_MainMenu.h #pragma once #include "Scene.h" enum eMenuBox{Start, Rule, Score, Credit, Exit}; class CScene_MainMenu : public CScene { public: CScene_MainMenu(); ~CScene_MainMenu(); virtual void Init() override; virtual void Update() override; virtual void Release() override; private: SDL_Rect MenuBox[5]; char MenuString[5][100]; }; <file_sep>/Sprite_Bar.h #pragma once #include "Sprite.h" class CSprite_Bar : public CSprite { public: CSprite_Bar(); ~CSprite_Bar(); virtual void Update() override; private: clock_t NowTime; clock_t EndTime; int NowX; SDL_Rect DrawBox; }; <file_sep>/Scene_GameEnd.cpp #include "stdafx.h" #include "TextManager.h" #include "SceneManager.h" #include "SoundManager.h" #include "EventManager.h" #include "Scene_GameEnd.h" CScene_GameEnd::CScene_GameEnd() : CScene(sGameEnd) { ScoreFile.open("./Data/Score.txt", ios::in); ScoreFile >> BestScore >> nowScore; ScoreFile.close(); ScoreBox[0] = { 300, 120, 0, 60 }; ScoreBox[1] = { 100, 200, 0, 50 }; ScoreBox[2] = { 100, 300, 0, 50 }; ScoreBox[3] = { 100, 400, 0, 50 }; ScoreBox[4] = { 20, 20, 0, 50 }; } CScene_GameEnd::~CScene_GameEnd() { Release(); } void CScene_GameEnd::Init() { sprintf(strScore[0], "*Result*"); sprintf(strScore[1], "점수 %d", nowScore); if (nowScore > BestScore) { sprintf(strScore[2], "지난 최고점수 %d", BestScore); sprintf(strScore[3], "최고기록 갱신!"); BestScore = nowScore; } else { sprintf(strScore[2], "최고점수 %d", BestScore); sprintf(strScore[3], "분발해야겠네요~"); } sprintf(strScore[4], "메인메뉴로"); ScoreBox[0].w = (strlen(strScore[0]) - 1) * 30; ScoreBox[1].w = (strlen(strScore[1]) - 1) * 25; ScoreBox[2].w = (strlen(strScore[2]) - 1) * 25; ScoreBox[3].w = (strlen(strScore[3]) - 1) * 25; ScoreBox[4].w = (strlen(strScore[4]) - 1) * 10; for (int i = 0; i < 5; i++) { g_TextManager->CreateText(strScore[i], &ScoreBox[i]); } g_SoundManager->DestroySound(eEffectMusic); g_SoundManager->MakeSound(eEffectMusic, eEffect_GameEnd); g_SoundManager->PlaySound(eChannel2, eEffectMusic); } void CScene_GameEnd::Update() { if (g_EventManager->g_Event.button.button == SDL_BUTTON_LEFT) { if (g_EventManager->CheckCollition_by_mouse(ScoreBox[4])) { g_SceneManager->SetScene(sMainMenu); } } } void CScene_GameEnd::Release() { ScoreFile.open("./Data/Score.txt", ios::out); ScoreFile << BestScore; ScoreFile.close(); g_TextManager->DestroyTextAll(); } <file_sep>/stdafx.h // stdafx.h : 자주 사용하지만 자주 변경되지는 않는 // 표준 시스템 포함 파일 및 프로젝트 관련 포함 파일이 // 들어 있는 포함 파일입니다. // #pragma once #include <iostream> #include <fstream> #include <memory> #include <algorithm> #include <vector> #include <deque> #include <unordered_map> #include <ctime> #include <cmath> #include <mutex> #include <Windows.h> #include <conio.h> //======== 추가 라이브러리 헤더 ======== #include <SDL.h> #include <SDL_image.h> #include <SDL_ttf.h> #include <fmod.hpp> enum eKey { Up, Down, Left, Right, Space, esc, n1, n2, n3, n4 }; enum eScene { sMainMenu = 1, sMusicSelect, sGame, sGameEnd, sRule, sScore, sCredit }; enum eChannel { eBGMChannel, eChannel1, eChannel2 }; enum eSound { eMainMenuSound, eMusicSelectSound, eEffectMusic, eGameTheme }; enum eNote { note_Normal, note_FourWayNormal, note_Spiral_Left, note_Spiral_Right, note_Random, note_NormalSpiral, note_FourWaySpiral, note_EightWaySpiral }; enum eSong { eMainMenu, eYour_Addiction, eEnglish_Listening, eCircles, eEffect_Click, eEffect_ComboBreak, eEffect_GameEnd }; #define WINDOW_DEFAULT_W 1024 #define WINDOW_DEFAULT_H 768 using namespace std; <file_sep>/Scene_Credit.h #pragma once #include "Scene.h" class CScene_Credit : public CScene { public: CScene_Credit(); ~CScene_Credit(); virtual void Init() override; virtual void Update() override; virtual void Release() override; private: SDL_Rect CreditBox[5]; char CreditString[5][100]; //SDL_Rect }; <file_sep>/Scene_Rule.cpp #include "stdafx.h" #include "SceneManager.h" #include "SoundManager.h" #include "EventManager.h" #include "TextManager.h" #include "Scene_Rule.h" CScene_Rule::CScene_Rule() : CScene(sRule) { RuleBox[0] = { 300, 120, 0, 60 }; RuleBox[1] = { 100, 200, 0, 40 }; RuleBox[2] = { 400, 300, 0, 40 }; RuleBox[3] = { 500, 400, 0, 40 }; RuleBox[4] = { 300, 600, 0, 40 }; RuleBox[5] = { 20, 20, 0, 50 }; } CScene_Rule::~CScene_Rule() { Release(); } void CScene_Rule::Init() { sprintf(strRule[0], "*How To Play*"); sprintf(strRule[1], "노래에 맞게 탄막이 나옵니다."); sprintf(strRule[2], "탄막을 피하며 점수를 쌓으세요."); sprintf(strRule[3], "마우스로 플레이합니다."); sprintf(strRule[4], "탄막을 맞지 않은 시간에 비례해 점수를 얻습니다."); sprintf(strRule[5], "메인메뉴로"); RuleBox[0].w = (strlen(strRule[0]) - 1) * 30; RuleBox[1].w = (strlen(strRule[1]) - 1) * 10; RuleBox[2].w = (strlen(strRule[2]) - 1) * 10; RuleBox[3].w = (strlen(strRule[3]) - 1) * 10; RuleBox[4].w = (strlen(strRule[4]) - 1) * 10; RuleBox[5].w = (strlen(strRule[5]) - 1) * 10; for (int i = 0; i < 6; i++) { g_TextManager->CreateText(strRule[i], &RuleBox[i]); } } void CScene_Rule::Update() { if (g_EventManager->g_Event.button.button == SDL_BUTTON_LEFT) { if (g_EventManager->CheckCollition_by_mouse(RuleBox[5])) { g_SceneManager->SetScene(sMainMenu); } } } void CScene_Rule::Release() { g_TextManager->DestroyTextAll(); } <file_sep>/Sprite_Player.cpp #include "stdafx.h" #include "EventManager.h" #include "Sprite_Player.h" CSprite_Player::CSprite_Player() : CSprite("Player", 29, 29, 5, 5, 19, 19) { SetSpriteImage("Player.png"); } CSprite_Player::~CSprite_Player() { } void CSprite_Player::Update() { SpriteMask.x = SpriteRect.x + 5; SpriteMask.y = SpriteRect.y + 5; } <file_sep>/Scene_Game.cpp #include "stdafx.h" #include "SceneManager.h" #include "TimeManager.h" #include "EventManager.h" #include "TextManager.h" #include "SoundManager.h" #include "ResourceManager.h" #include "Scene_Game.h" #include "Sprite_Player.h" #include "Sprite_SpawnNote.h" #include "Sprite_Bar.h" enum {eSpawnNote, ePlayer, eBar}; CScene_Game::CScene_Game() : CScene(sThisScene) { SetSong(static_cast<eSong>(g_SceneManager->Param)); } CScene_Game::~CScene_Game() { Release(); } void CScene_Game::SetSong(eSong Song) { ThisSong = Song; switch (ThisSong) { case eYour_Addiction: SinkFile.open("./Resource/Duelle_amp_CiRRO-Your_Addiction_Culture_Code_Remix.txt"); break; case eEnglish_Listening: SinkFile.open("./Resource/English_Listening_Type_B.txt"); //SetSceneBGImage("Duelle_amp_CiRRO-Your_Addiction_Culture_Code_Remix.jpg"); break; case eCircles: SinkFile.open("./Resource/KDrew - Circles (Original Mix).txt"); //SetSceneBGImage("Duelle_amp_CiRRO-Your_Addiction_Culture_Code_Remix.jpg"); break; default: break; } //SetSceneBGImage("Duelle_amp_CiRRO-Your_Addiction_Culture_Code_Remix.jpg"); if (SceneBGImage != nullptr) { SDL_FreeSurface(SceneBGImage); } SceneBGImage = IMG_Load_RW(g_ResourceManager->LoadItem("Duelle_amp_CiRRO-Your_Addiction_Culture_Code_Remix.jpg"), 0); SceneBGTexture = SDL_CreateTextureFromSurface(g_DrawManager->pRenderer, SceneBGImage); SDL_FreeSurface(SceneBGImage); } void CScene_Game::Init() { addSprite(new CSprite_SpawnNote()); vSprite[eSpawnNote]->Update(); addSprite(new CSprite_Player()); addSprite(new CSprite_Bar()); SDL_ShowCursor(0); g_SoundManager->DestroySound(eEffectMusic); g_SoundManager->MakeSound(eGameTheme, ThisSong); g_SoundManager->MakeSound(eEffectMusic, eEffect_ComboBreak); unsigned int time; g_SoundManager->SongMap[eGameTheme]->getLength(&time, FMOD_TIMEUNIT_MS); GameEndTime = time; ScoreTime = 100; xScoreTime = 1000; xScore = 1.0f; SinkFile >> SinkTime >> NoteType >> CommonSink.Rotation >> CommonSink.Speed; g_TimeManager->Update(); g_SoundManager->PlaySound(eChannel1, eGameTheme); //interval = 10; CommonSink.Rotation = 0; CommonSink.Rotation_Rate = 15; CommonSink.Speed = 10; CommonSink.Speed_Rate = 0; NormalSink = CommonSink; FourWaySink = CommonSink; SpiralSink = CommonSink; RandomSink = CommonSink; SpiralWay = note_Spiral_Left; bIsSpiral = false; bIsRandomNote = false; bIsGameEnd = false; Score = 0; ScoreBox[0] = { 20, 20, 0, 50 }; ScoreBox[1] = { 20, 80, 0, 50 }; sprintf(strScore[0], "점수 %d", Score); sprintf(strScore[1], "x%.1f", xScore); ScoreBox[0].w = (strlen(strScore[0]) - 1) * 25; ScoreBox[1].w = (strlen(strScore[1]) - 1) * 25; g_TextManager->SetColor(255, 255, 255); g_TextManager->CreateText(strScore[0], &ScoreBox[0]); g_TextManager->CreateText(strScore[1], &ScoreBox[1]); } void CScene_Game::Update() { //GameEndTime; //CurTime = g_TimeManager->GetTime() - OldTime; unsigned int time; g_SoundManager->pChannel[eChannel1]->getPosition(&time, FMOD_TIMEUNIT_MS); CurTime = time; for (int i = 0; i < vNote.size(); ) //노트처리 반복문 { vNote[i]->Update(); if (!g_EventManager->CheckCollition(*vNote[i]->GetSpriteRect(), SceneBGRect)) //스크린 밖으로 나가면 동적해제 { delete vNote[i]; swap(vNote[i], vNote.back()); vNote.pop_back(); } else if (g_EventManager->CheckCollition_by_Circle(vSprite[ePlayer],vNote[i])) //플레이어와 맞으면 동적해제 { if (vNote[i]->GetNoteType() == note_Random) { Score -= 1500; } else { xScore = 0.9f; } delete vNote[i]; swap(vNote[i], vNote.back()); vNote.pop_back(); g_SoundManager->PlaySound(eChannel2, eEffectMusic); //xScoreTime = CurTime; } else { i++; } } if (!g_EventManager->CheckCollition_by_mouse(*vSprite[eSpawnNote]->GetSpriteRect())) //플레이어 스프라이트가 가운데 스폰노트 스프라이트를 뚫지 않도록 셋팅 { if (g_EventManager->CheckCollition_by_mouse(SceneBGRect)) { vSprite[ePlayer]->SetSpriteX(g_EventManager->g_Event.motion.x - 14); vSprite[ePlayer]->SetSpriteY(g_EventManager->g_Event.motion.y - 14); } } vSprite[eSpawnNote]->Update(); vSprite[ePlayer]->Update(); if (CurTime > SinkTime) //노트가 나와야 하는 타이밍 { switch (NoteType) { case note_Normal: bIsRandomNote = false; NormalSink.Rotation = GetMouseRotation(); NormalSink.Speed = CommonSink.Speed; vNote.push_back(new CSprite_Note(note_Normal, NormalSink.Rotation, 0.f, NormalSink.Speed, 0.f)); bIsSpiral = false; bIsRandomNote = true; break; case note_FourWayNormal: bIsRandomNote = false; FourWaySink.Rotation = CommonSink.Rotation; FourWaySink.Speed = CommonSink.Speed; vNote.push_back(new CSprite_Note(note_FourWayNormal, FourWaySink.Rotation, 0.f, FourWaySink.Speed, 0.f)); vNote.push_back(new CSprite_Note(note_FourWayNormal, FourWaySink.Rotation + 90, 0.f, FourWaySink.Speed, 0.f)); vNote.push_back(new CSprite_Note(note_FourWayNormal, FourWaySink.Rotation + 180, 0.f, FourWaySink.Speed, 0.f)); vNote.push_back(new CSprite_Note(note_FourWayNormal, FourWaySink.Rotation + 270, 0.f, FourWaySink.Speed, 0.f)); FourWaySink.Rotation += 45; bIsSpiral = false; bIsRandomNote = true; break; case note_Spiral_Left: SpiralSink.Rotation = CommonSink.Rotation; SpiralSink.Speed = CommonSink.Speed; SpiralWay = note_Spiral_Left; bIsSpiral = true; break; case note_Spiral_Right: SpiralSink.Rotation = CommonSink.Rotation; SpiralSink.Speed = CommonSink.Speed; SpiralWay = note_Spiral_Right; bIsSpiral = true; break; case note_NormalSpiral: SpiralSink.Rotation = CommonSink.Rotation; SpiralSink.Speed = CommonSink.Speed; SpiralWay = note_NormalSpiral; bIsSpiral = true; break; case note_FourWaySpiral: SpiralSink.Rotation = CommonSink.Rotation; SpiralSink.Speed = CommonSink.Speed; SpiralWay = note_FourWaySpiral; bIsSpiral = true; break; case note_EightWaySpiral: SpiralSink.Rotation = CommonSink.Rotation; SpiralSink.Speed = CommonSink.Speed; SpiralWay = note_EightWaySpiral; bIsSpiral = true; break; default: break; } SinkFile >> SinkTime >> NoteType >> CommonSink.Rotation >> CommonSink.Speed; } if (bIsSpiral) //달팽이노트 { if (CurTime - IntervalTime > 10) { switch (SpiralWay) { case note_Spiral_Left: vNote.push_back(new CSprite_Note(note_Spiral_Left, SpiralSink.Rotation, 0.f, SpiralSink.Speed, 0.f)); SpiralSink.Rotation -= CommonSink.Rotation_Rate; SpiralSink.Speed += CommonSink.Speed_Rate; break; case note_Spiral_Right: vNote.push_back(new CSprite_Note(note_Spiral_Right, SpiralSink.Rotation, 0.f, SpiralSink.Speed, 0.f)); SpiralSink.Rotation += CommonSink.Rotation_Rate; SpiralSink.Speed += CommonSink.Speed_Rate; break; case note_NormalSpiral: vNote.push_back(new CSprite_Note(note_Normal, SpiralSink.Rotation, 0.f, SpiralSink.Speed, 0.f)); SpiralSink.Rotation = GetMouseRotation(); SpiralSink.Speed += CommonSink.Speed_Rate; break; case note_FourWaySpiral: vNote.push_back(new CSprite_Note(note_FourWayNormal, SpiralSink.Rotation, 0.f, SpiralSink.Speed, 0.f)); vNote.push_back(new CSprite_Note(note_FourWayNormal, SpiralSink.Rotation + 90, 0.f, SpiralSink.Speed, 0.f)); vNote.push_back(new CSprite_Note(note_FourWayNormal, SpiralSink.Rotation + 180, 0.f, SpiralSink.Speed, 0.f)); vNote.push_back(new CSprite_Note(note_FourWayNormal, SpiralSink.Rotation + 270, 0.f, SpiralSink.Speed, 0.f)); SpiralSink.Speed += CommonSink.Speed_Rate; break; case note_EightWaySpiral: vNote.push_back(new CSprite_Note(note_FourWayNormal, SpiralSink.Rotation, 0.f, SpiralSink.Speed, 0.f)); vNote.push_back(new CSprite_Note(note_FourWayNormal, SpiralSink.Rotation + 90, 0.f, SpiralSink.Speed, 0.f)); vNote.push_back(new CSprite_Note(note_FourWayNormal, SpiralSink.Rotation + 180, 0.f, SpiralSink.Speed, 0.f)); vNote.push_back(new CSprite_Note(note_FourWayNormal, SpiralSink.Rotation + 270, 0.f, SpiralSink.Speed, 0.f)); vNote.push_back(new CSprite_Note(note_FourWayNormal, SpiralSink.Rotation + 45, 0.f, SpiralSink.Speed, 0.f)); vNote.push_back(new CSprite_Note(note_FourWayNormal, SpiralSink.Rotation + 135, 0.f, SpiralSink.Speed, 0.f)); vNote.push_back(new CSprite_Note(note_FourWayNormal, SpiralSink.Rotation + 225, 0.f, SpiralSink.Speed, 0.f)); vNote.push_back(new CSprite_Note(note_FourWayNormal, SpiralSink.Rotation + 315, 0.f, SpiralSink.Speed, 0.f)); SpiralSink.Speed += CommonSink.Speed_Rate; break; default: break; } IntervalTime = CurTime; } bIsRandomNote = false; } if (bIsRandomNote) { if (CurTime - IntervalTime > 5) { RandomSink.Rotation = rand() % 360; RandomSink.Speed = 7; vNote.push_back(new CSprite_Note(note_Random, RandomSink.Rotation, 0.f, RandomSink.Speed, 0.f)); } } if (CurTime >= ScoreTime) { ScoreTime += 100; Score += 100 * xScore; sprintf(strScore[0], "점수 %d", Score); ScoreBox[0].w = (strlen(strScore[0]) - 1) * 25; g_TextManager->ModifyText(strScore[0], 0); } if (CurTime >= xScoreTime) { if (xScore < 4.9f) { xScore += 0.1f; sprintf(strScore[1], "x%.1f", xScore); g_TextManager->ModifyText(strScore[1], 1); } xScoreTime += 1000; } if (CurTime >= GameEndTime) { bIsGameEnd = true; } if (vNote.size() == 0 && bIsGameEnd) { ScoreFile.open("./Data/Score.txt",ios::app); ScoreFile << " " << Score; g_SceneManager->SetScene(sGameEnd); } } void CScene_Game::Render() { SDL_Rect temprt; int x1, x2, x3, x4; int y1, y2, y3, y4; SDL_RenderCopy(g_DrawManager->pRenderer, SceneBGTexture, NULL, &SceneBGRect); for (int i = 0; i < vNote.size(); i++) //노트들 업데이트 { if (vNote[i] != nullptr) { SDL_RenderCopyEx(g_DrawManager->pRenderer, vNote[i]->GetSpriteTexture(), NULL, vNote[i]->GetSpriteRect(), vNote[i]->GetSpriteRotation(), vNote[i]->GetSpriteCenter(), *vNote[i]->GetSpriteFlip()); #ifdef _DEBUG SDL_SetRenderDrawColor(g_DrawManager->pRenderer, 255, 0, 0, 255); temprt = *vNote[i]->GetSpriteRect(); x1 = temprt.x, x2 = temprt.w + temprt.x, x3 = temprt.x, x4 = temprt.w + temprt.x; y1 = temprt.y, y2 = temprt.y, y3 = temprt.h + temprt.y, y4 = temprt.h + temprt.y; SDL_RenderDrawLine(g_DrawManager->pRenderer, x1, y1, x2, y2); SDL_RenderDrawLine(g_DrawManager->pRenderer, x1, y1, x3, y3); SDL_RenderDrawLine(g_DrawManager->pRenderer, x2, y2, x4, y4); SDL_RenderDrawLine(g_DrawManager->pRenderer, x3, y3, x4, y4); SDL_SetRenderDrawColor(g_DrawManager->pRenderer, 0, 0, 255, 255); g_EventManager->CheckCollition_by_Circle(vSprite[ePlayer], vNote[i]); #endif } } for (int i = 0; i != nSprite; i++) { if (vSprite[i] != nullptr) { SDL_RenderCopyEx(g_DrawManager->pRenderer, vSprite[i]->GetSpriteTexture(), NULL, vSprite[i]->GetSpriteRect(), vSprite[i]->GetSpriteRotation(), vSprite[i]->GetSpriteCenter(), *vSprite[i]->GetSpriteFlip()); #ifdef _DEBUG temprt = *vSprite[ePlayer]->GetSpriteMask(); x1 = temprt.x, x2 = temprt.w + temprt.x, x3 = temprt.x, x4 = temprt.w + temprt.x; y1 = temprt.y, y2 = temprt.y, y3 = temprt.h + temprt.y, y4 = temprt.h + temprt.y; SDL_RenderDrawLine(g_DrawManager->pRenderer, x1, y1, x2, y2); SDL_RenderDrawLine(g_DrawManager->pRenderer, x1, y1, x3, y3); SDL_RenderDrawLine(g_DrawManager->pRenderer, x2, y2, x4, y4); SDL_RenderDrawLine(g_DrawManager->pRenderer, x3, y3, x4, y4); #endif } } vSprite[eBar]->Update(); } void CScene_Game::Release() { g_TextManager->SetColor(0, 0, 0); g_SoundManager->StopSound(eChannel1); g_SoundManager->DestroySound(eGameTheme); g_TextManager->DestroyTextAll(); ScoreFile.close(); SinkFile.close(); /*for (int i = 0; i < vSprite.size(); i++) { delete vSprite[i]; }*/ SDL_ShowCursor(1); } void CScene_Game::addNote(CSprite_Note *newNote) { vNote.push_back(newNote); } float CScene_Game::GetMouseRotation() { float offset_x = g_EventManager->g_Event.motion.x - (WINDOW_DEFAULT_W / 2 - 14); float offset_y = g_EventManager->g_Event.motion.y - (WINDOW_DEFAULT_H / 2 - 14); float radian = atan2(offset_y, offset_x); //Shark.x += cos(radian) * 5.0f; // * -sinf(radian) * 5.0f; //Shark.y += -sin(radian) * 5.0f; // * cosf(radian) * 5.0f; return (180.0f * radian) / M_PI; }<file_sep>/han2unicode.h /* KSC5601 -> Unicode 2.0 mapping table, compressed for the 94*94 codeset. */ /* Generated based on KSC5601.txt at ftp://ftp.unicode.org/Public/MAPPINGS/EASTASIA/KSC */ /* * Unlike kuten-table, needed offset is 33 (0x21) instead of * 32 for 7-bit portion of each byte. i.e., a Unicode * codepoint for KSC's codepoint (n, m) would be found at * index (n-33)*94+m-33. */ extern "C" long tabksc5601[] = { /* KSC 5601 -> Unicode mapping table; max codepoint = 0x7d7e */ 0x3000, 0x3001, 0x3002, 0x00B7, 0x2025, 0x2026, 0x00A8, 0x3003, 0x00AD, 0x2015, 0x2225, 0xFF3C, 0x223C, 0x2018, 0x2019, 0x201C, 0x201D, 0x3014, 0x3015, 0x3008, 0x3009, 0x300A, 0x300B, 0x300C, 0x300D, 0x300E, 0x300F, 0x3010, 0x3011, 0x00B1, 0x00D7, 0x00F7, 0x2260, 0x2264, 0x2265, 0x221E, 0x2234, 0x00B0, 0x2032, 0x2033, 0x2103, 0x212B, 0xFFE0, 0xFFE1, 0xFFE5, 0x2642, 0x2640, 0x2220, 0x22A5, 0x2312, 0x2202, 0x2207, 0x2261, 0x2252, 0x00A7, 0x203B, 0x2606, 0x2605, 0x25CB, 0x25CF, 0x25CE, 0x25C7, 0x25C6, 0x25A1, 0x25A0, 0x25B3, 0x25B2, 0x25BD, 0x25BC, 0x2192, 0x2190, 0x2191, 0x2193, 0x2194, 0x3013, 0x226A, 0x226B, 0x221A, 0x223D, 0x221D, 0x2235, 0x222B, 0x222C, 0x2208, 0x220B, 0x2286, 0x2287, 0x2282, 0x2283, 0x222A, 0x2229, 0x2227, 0x2228, 0xFFE2, 0x21D2, 0x21D4, 0x2200, 0x2203, 0x00B4, 0xFF5E, 0x02C7, 0x02D8, 0x02DD, 0x02DA, 0x02D9, 0x00B8, 0x02DB, 0x00A1, 0x00BF, 0x02D0, 0x222E, 0x2211, 0x220F, 0x00A4, 0x2109, 0x2030, 0x25C1, 0x25C0, 0x25B7, 0x25B6, 0x2664, 0x2660, 0x2661, 0x2665, 0x2667, 0x2663, 0x2299, 0x25C8, 0x25A3, 0x25D0, 0x25D1, 0x2592, 0x25A4, 0x25A5, 0x25A8, 0x25A7, 0x25A6, 0x25A9, 0x2668, 0x260F, 0x260E, 0x261C, 0x261E, 0x00B6, 0x2020, 0x2021, 0x2195, 0x2197, 0x2199, 0x2196, 0x2198, 0x266D, 0x2669, 0x266A, 0x266C, 0x327F, 0x321C, 0x2116, 0x33C7, 0x2122, 0x33C2, 0x33D8, 0x2121, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0xFF01, 0xFF02, 0xFF03, 0xFF04, 0xFF05, 0xFF06, 0xFF07, 0xFF08, 0xFF09, 0xFF0A, 0xFF0B, 0xFF0C, 0xFF0D, 0xFF0E, 0xFF0F, 0xFF10, 0xFF11, 0xFF12, 0xFF13, 0xFF14, 0xFF15, 0xFF16, 0xFF17, 0xFF18, 0xFF19, 0xFF1A, 0xFF1B, 0xFF1C, 0xFF1D, 0xFF1E, 0xFF1F, 0xFF20, 0xFF21, 0xFF22, 0xFF23, 0xFF24, 0xFF25, 0xFF26, 0xFF27, 0xFF28, 0xFF29, 0xFF2A, 0xFF2B, 0xFF2C, 0xFF2D, 0xFF2E, 0xFF2F, 0xFF30, 0xFF31, 0xFF32, 0xFF33, 0xFF34, 0xFF35, 0xFF36, 0xFF37, 0xFF38, 0xFF39, 0xFF3A, 0xFF3B, 0xFFE6, 0xFF3D, 0xFF3E, 0xFF3F, 0xFF40, 0xFF41, 0xFF42, 0xFF43, 0xFF44, 0xFF45, 0xFF46, 0xFF47, 0xFF48, 0xFF49, 0xFF4A, 0xFF4B, 0xFF4C, 0xFF4D, 0xFF4E, 0xFF4F, 0xFF50, 0xFF51, 0xFF52, 0xFF53, 0xFF54, 0xFF55, 0xFF56, 0xFF57, 0xFF58, 0xFF59, 0xFF5A, 0xFF5B, 0xFF5C, 0xFF5D, 0xFFE3, 0x3131, 0x3132, 0x3133, 0x3134, 0x3135, 0x3136, 0x3137, 0x3138, 0x3139, 0x313A, 0x313B, 0x313C, 0x313D, 0x313E, 0x313F, 0x3140, 0x3141, 0x3142, 0x3143, 0x3144, 0x3145, 0x3146, 0x3147, 0x3148, 0x3149, 0x314A, 0x314B, 0x314C, 0x314D, 0x314E, 0x314F, 0x3150, 0x3151, 0x3152, 0x3153, 0x3154, 0x3155, 0x3156, 0x3157, 0x3158, 0x3159, 0x315A, 0x315B, 0x315C, 0x315D, 0x315E, 0x315F, 0x3160, 0x3161, 0x3162, 0x3163, 0x3164, 0x3165, 0x3166, 0x3167, 0x3168, 0x3169, 0x316A, 0x316B, 0x316C, 0x316D, 0x316E, 0x316F, 0x3170, 0x3171, 0x3172, 0x3173, 0x3174, 0x3175, 0x3176, 0x3177, 0x3178, 0x3179, 0x317A, 0x317B, 0x317C, 0x317D, 0x317E, 0x317F, 0x3180, 0x3181, 0x3182, 0x3183, 0x3184, 0x3185, 0x3186, 0x3187, 0x3188, 0x3189, 0x318A, 0x318B, 0x318C, 0x318D, 0x318E, 0x2170, 0x2171, 0x2172, 0x2173, 0x2174, 0x2175, 0x2176, 0x2177, 0x2178, 0x2179, -1, -1, -1, -1, -1, 0x2160, 0x2161, 0x2162, 0x2163, 0x2164, 0x2165, 0x2166, 0x2167, 0x2168, 0x2169, -1, -1, -1, -1, -1, -1, -1, 0x0391, 0x0392, 0x0393, 0x0394, 0x0395, 0x0396, 0x0397, 0x0398, 0x0399, 0x039A, 0x039B, 0x039C, 0x039D, 0x039E, 0x039F, 0x03A0, 0x03A1, 0x03A3, 0x03A4, 0x03A5, 0x03A6, 0x03A7, 0x03A8, 0x03A9, -1, -1, -1, -1, -1, -1, -1, -1, 0x03B1, 0x03B2, 0x03B3, 0x03B4, 0x03B5, 0x03B6, 0x03B7, 0x03B8, 0x03B9, 0x03BA, 0x03BB, 0x03BC, 0x03BD, 0x03BE, 0x03BF, 0x03C0, 0x03C1, 0x03C3, 0x03C4, 0x03C5, 0x03C6, 0x03C7, 0x03C8, 0x03C9, -1, -1, -1, -1, -1, -1, 0x2500, 0x2502, 0x250C, 0x2510, 0x2518, 0x2514, 0x251C, 0x252C, 0x2524, 0x2534, 0x253C, 0x2501, 0x2503, 0x250F, 0x2513, 0x251B, 0x2517, 0x2523, 0x2533, 0x252B, 0x253B, 0x254B, 0x2520, 0x252F, 0x2528, 0x2537, 0x253F, 0x251D, 0x2530, 0x2525, 0x2538, 0x2542, 0x2512, 0x2511, 0x251A, 0x2519, 0x2516, 0x2515, 0x250E, 0x250D, 0x251E, 0x251F, 0x2521, 0x2522, 0x2526, 0x2527, 0x2529, 0x252A, 0x252D, 0x252E, 0x2531, 0x2532, 0x2535, 0x2536, 0x2539, 0x253A, 0x253D, 0x253E, 0x2540, 0x2541, 0x2543, 0x2544, 0x2545, 0x2546, 0x2547, 0x2548, 0x2549, 0x254A, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0x3395, 0x3396, 0x3397, 0x2113, 0x3398, 0x33C4, 0x33A3, 0x33A4, 0x33A5, 0x33A6, 0x3399, 0x339A, 0x339B, 0x339C, 0x339D, 0x339E, 0x339F, 0x33A0, 0x33A1, 0x33A2, 0x33CA, 0x338D, 0x338E, 0x338F, 0x33CF, 0x3388, 0x3389, 0x33C8, 0x33A7, 0x33A8, 0x33B0, 0x33B1, 0x33B2, 0x33B3, 0x33B4, 0x33B5, 0x33B6, 0x33B7, 0x33B8, 0x33B9, 0x3380, 0x3381, 0x3382, 0x3383, 0x3384, 0x33BA, 0x33BB, 0x33BC, 0x33BD, 0x33BE, 0x33BF, 0x3390, 0x3391, 0x3392, 0x3393, 0x3394, 0x2126, 0x33C0, 0x33C1, 0x338A, 0x338B, 0x338C, 0x33D6, 0x33C5, 0x33AD, 0x33AE, 0x33AF, 0x33DB, 0x33A9, 0x33AA, 0x33AB, 0x33AC, 0x33DD, 0x33D0, 0x33D3, 0x33C3, 0x33C9, 0x33DC, 0x33C6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0x00C6, 0x00D0, 0x00AA, 0x0126, -1, 0x0132, -1, 0x013F, 0x0141, 0x00D8, 0x0152, 0x00BA, 0x00DE, 0x0166, 0x014A, -1, 0x3260, 0x3261, 0x3262, 0x3263, 0x3264, 0x3265, 0x3266, 0x3267, 0x3268, 0x3269, 0x326A, 0x326B, 0x326C, 0x326D, 0x326E, 0x326F, 0x3270, 0x3271, 0x3272, 0x3273, 0x3274, 0x3275, 0x3276, 0x3277, 0x3278, 0x3279, 0x327A, 0x327B, 0x24D0, 0x24D1, 0x24D2, 0x24D3, 0x24D4, 0x24D5, 0x24D6, 0x24D7, 0x24D8, 0x24D9, 0x24DA, 0x24DB, 0x24DC, 0x24DD, 0x24DE, 0x24DF, 0x24E0, 0x24E1, 0x24E2, 0x24E3, 0x24E4, 0x24E5, 0x24E6, 0x24E7, 0x24E8, 0x24E9, 0x2460, 0x2461, 0x2462, 0x2463, 0x2464, 0x2465, 0x2466, 0x2467, 0x2468, 0x2469, 0x246A, 0x246B, 0x246C, 0x246D, 0x246E, 0x00BD, 0x2153, 0x2154, 0x00BC, 0x00BE, 0x215B, 0x215C, 0x215D, 0x215E, 0x00E6, 0x0111, 0x00F0, 0x0127, 0x0131, 0x0133, 0x0138, 0x0140, 0x0142, 0x00F8, 0x0153, 0x00DF, 0x00FE, 0x0167, 0x014B, 0x0149, 0x3200, 0x3201, 0x3202, 0x3203, 0x3204, 0x3205, 0x3206, 0x3207, 0x3208, 0x3209, 0x320A, 0x320B, 0x320C, 0x320D, 0x320E, 0x320F, 0x3210, 0x3211, 0x3212, 0x3213, 0x3214, 0x3215, 0x3216, 0x3217, 0x3218, 0x3219, 0x321A, 0x321B, 0x249C, 0x249D, 0x249E, 0x249F, 0x24A0, 0x24A1, 0x24A2, 0x24A3, 0x24A4, 0x24A5, 0x24A6, 0x24A7, 0x24A8, 0x24A9, 0x24AA, 0x24AB, 0x24AC, 0x24AD, 0x24AE, 0x24AF, 0x24B0, 0x24B1, 0x24B2, 0x24B3, 0x24B4, 0x24B5, 0x2474, 0x2475, 0x2476, 0x2477, 0x2478, 0x2479, 0x247A, 0x247B, 0x247C, 0x247D, 0x247E, 0x247F, 0x2480, 0x2481, 0x2482, 0x00B9, 0x00B2, 0x00B3, 0x2074, 0x207F, 0x2081, 0x2082, 0x2083, 0x2084, 0x3041, 0x3042, 0x3043, 0x3044, 0x3045, 0x3046, 0x3047, 0x3048, 0x3049, 0x304A, 0x304B, 0x304C, 0x304D, 0x304E, 0x304F, 0x3050, 0x3051, 0x3052, 0x3053, 0x3054, 0x3055, 0x3056, 0x3057, 0x3058, 0x3059, 0x305A, 0x305B, 0x305C, 0x305D, 0x305E, 0x305F, 0x3060, 0x3061, 0x3062, 0x3063, 0x3064, 0x3065, 0x3066, 0x3067, 0x3068, 0x3069, 0x306A, 0x306B, 0x306C, 0x306D, 0x306E, 0x306F, 0x3070, 0x3071, 0x3072, 0x3073, 0x3074, 0x3075, 0x3076, 0x3077, 0x3078, 0x3079, 0x307A, 0x307B, 0x307C, 0x307D, 0x307E, 0x307F, 0x3080, 0x3081, 0x3082, 0x3083, 0x3084, 0x3085, 0x3086, 0x3087, 0x3088, 0x3089, 0x308A, 0x308B, 0x308C, 0x308D, 0x308E, 0x308F, 0x3090, 0x3091, 0x3092, 0x3093, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0x30A1, 0x30A2, 0x30A3, 0x30A4, 0x30A5, 0x30A6, 0x30A7, 0x30A8, 0x30A9, 0x30AA, 0x30AB, 0x30AC, 0x30AD, 0x30AE, 0x30AF, 0x30B0, 0x30B1, 0x30B2, 0x30B3, 0x30B4, 0x30B5, 0x30B6, 0x30B7, 0x30B8, 0x30B9, 0x30BA, 0x30BB, 0x30BC, 0x30BD, 0x30BE, 0x30BF, 0x30C0, 0x30C1, 0x30C2, 0x30C3, 0x30C4, 0x30C5, 0x30C6, 0x30C7, 0x30C8, 0x30C9, 0x30CA, 0x30CB, 0x30CC, 0x30CD, 0x30CE, 0x30CF, 0x30D0, 0x30D1, 0x30D2, 0x30D3, 0x30D4, 0x30D5, 0x30D6, 0x30D7, 0x30D8, 0x30D9, 0x30DA, 0x30DB, 0x30DC, 0x30DD, 0x30DE, 0x30DF, 0x30E0, 0x30E1, 0x30E2, 0x30E3, 0x30E4, 0x30E5, 0x30E6, 0x30E7, 0x30E8, 0x30E9, 0x30EA, 0x30EB, 0x30EC, 0x30ED, 0x30EE, 0x30EF, 0x30F0, 0x30F1, 0x30F2, 0x30F3, 0x30F4, 0x30F5, 0x30F6, -1, -1, -1, -1, -1, -1, -1, -1, 0x0410, 0x0411, 0x0412, 0x0413, 0x0414, 0x0415, 0x0401, 0x0416, 0x0417, 0x0418, 0x0419, 0x041A, 0x041B, 0x041C, 0x041D, 0x041E, 0x041F, 0x0420, 0x0421, 0x0422, 0x0423, 0x0424, 0x0425, 0x0426, 0x0427, 0x0428, 0x0429, 0x042A, 0x042B, 0x042C, 0x042D, 0x042E, 0x042F, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0x0430, 0x0431, 0x0432, 0x0433, 0x0434, 0x0435, 0x0451, 0x0436, 0x0437, 0x0438, 0x0439, 0x043A, 0x043B, 0x043C, 0x043D, 0x043E, 0x043F, 0x0440, 0x0441, 0x0442, 0x0443, 0x0444, 0x0445, 0x0446, 0x0447, 0x0448, 0x0449, 0x044A, 0x044B, 0x044C, 0x044D, 0x044E, 0x044F, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0xAC00, 0xAC01, 0xAC04, 0xAC07, 0xAC08, 0xAC09, 0xAC0A, 0xAC10, 0xAC11, 0xAC12, 0xAC13, 0xAC14, 0xAC15, 0xAC16, 0xAC17, 0xAC19, 0xAC1A, 0xAC1B, 0xAC1C, 0xAC1D, 0xAC20, 0xAC24, 0xAC2C, 0xAC2D, 0xAC2F, 0xAC30, 0xAC31, 0xAC38, 0xAC39, 0xAC3C, 0xAC40, 0xAC4B, 0xAC4D, 0xAC54, 0xAC58, 0xAC5C, 0xAC70, 0xAC71, 0xAC74, 0xAC77, 0xAC78, 0xAC7A, 0xAC80, 0xAC81, 0xAC83, 0xAC84, 0xAC85, 0xAC86, 0xAC89, 0xAC8A, 0xAC8B, 0xAC8C, 0xAC90, 0xAC94, 0xAC9C, 0xAC9D, 0xAC9F, 0xACA0, 0xACA1, 0xACA8, 0xACA9, 0xACAA, 0xACAC, 0xACAF, 0xACB0, 0xACB8, 0xACB9, 0xACBB, 0xACBC, 0xACBD, 0xACC1, 0xACC4, 0xACC8, 0xACCC, 0xACD5, 0xACD7, 0xACE0, 0xACE1, 0xACE4, 0xACE7, 0xACE8, 0xACEA, 0xACEC, 0xACEF, 0xACF0, 0xACF1, 0xACF3, 0xACF5, 0xACF6, 0xACFC, 0xACFD, 0xAD00, 0xAD04, 0xAD06, 0xAD0C, 0xAD0D, 0xAD0F, 0xAD11, 0xAD18, 0xAD1C, 0xAD20, 0xAD29, 0xAD2C, 0xAD2D, 0xAD34, 0xAD35, 0xAD38, 0xAD3C, 0xAD44, 0xAD45, 0xAD47, 0xAD49, 0xAD50, 0xAD54, 0xAD58, 0xAD61, 0xAD63, 0xAD6C, 0xAD6D, 0xAD70, 0xAD73, 0xAD74, 0xAD75, 0xAD76, 0xAD7B, 0xAD7C, 0xAD7D, 0xAD7F, 0xAD81, 0xAD82, 0xAD88, 0xAD89, 0xAD8C, 0xAD90, 0xAD9C, 0xAD9D, 0xADA4, 0xADB7, 0xADC0, 0xADC1, 0xADC4, 0xADC8, 0xADD0, 0xADD1, 0xADD3, 0xADDC, 0xADE0, 0xADE4, 0xADF8, 0xADF9, 0xADFC, 0xADFF, 0xAE00, 0xAE01, 0xAE08, 0xAE09, 0xAE0B, 0xAE0D, 0xAE14, 0xAE30, 0xAE31, 0xAE34, 0xAE37, 0xAE38, 0xAE3A, 0xAE40, 0xAE41, 0xAE43, 0xAE45, 0xAE46, 0xAE4A, 0xAE4C, 0xAE4D, 0xAE4E, 0xAE50, 0xAE54, 0xAE56, 0xAE5C, 0xAE5D, 0xAE5F, 0xAE60, 0xAE61, 0xAE65, 0xAE68, 0xAE69, 0xAE6C, 0xAE70, 0xAE78, 0xAE79, 0xAE7B, 0xAE7C, 0xAE7D, 0xAE84, 0xAE85, 0xAE8C, 0xAEBC, 0xAEBD, 0xAEBE, 0xAEC0, 0xAEC4, 0xAECC, 0xAECD, 0xAECF, 0xAED0, 0xAED1, 0xAED8, 0xAED9, 0xAEDC, 0xAEE8, 0xAEEB, 0xAEED, 0xAEF4, 0xAEF8, 0xAEFC, 0xAF07, 0xAF08, 0xAF0D, 0xAF10, 0xAF2C, 0xAF2D, 0xAF30, 0xAF32, 0xAF34, 0xAF3C, 0xAF3D, 0xAF3F, 0xAF41, 0xAF42, 0xAF43, 0xAF48, 0xAF49, 0xAF50, 0xAF5C, 0xAF5D, 0xAF64, 0xAF65, 0xAF79, 0xAF80, 0xAF84, 0xAF88, 0xAF90, 0xAF91, 0xAF95, 0xAF9C, 0xAFB8, 0xAFB9, 0xAFBC, 0xAFC0, 0xAFC7, 0xAFC8, 0xAFC9, 0xAFCB, 0xAFCD, 0xAFCE, 0xAFD4, 0xAFDC, 0xAFE8, 0xAFE9, 0xAFF0, 0xAFF1, 0xAFF4, 0xAFF8, 0xB000, 0xB001, 0xB004, 0xB00C, 0xB010, 0xB014, 0xB01C, 0xB01D, 0xB028, 0xB044, 0xB045, 0xB048, 0xB04A, 0xB04C, 0xB04E, 0xB053, 0xB054, 0xB055, 0xB057, 0xB059, 0xB05D, 0xB07C, 0xB07D, 0xB080, 0xB084, 0xB08C, 0xB08D, 0xB08F, 0xB091, 0xB098, 0xB099, 0xB09A, 0xB09C, 0xB09F, 0xB0A0, 0xB0A1, 0xB0A2, 0xB0A8, 0xB0A9, 0xB0AB, 0xB0AC, 0xB0AD, 0xB0AE, 0xB0AF, 0xB0B1, 0xB0B3, 0xB0B4, 0xB0B5, 0xB0B8, 0xB0BC, 0xB0C4, 0xB0C5, 0xB0C7, 0xB0C8, 0xB0C9, 0xB0D0, 0xB0D1, 0xB0D4, 0xB0D8, 0xB0E0, 0xB0E5, 0xB108, 0xB109, 0xB10B, 0xB10C, 0xB110, 0xB112, 0xB113, 0xB118, 0xB119, 0xB11B, 0xB11C, 0xB11D, 0xB123, 0xB124, 0xB125, 0xB128, 0xB12C, 0xB134, 0xB135, 0xB137, 0xB138, 0xB139, 0xB140, 0xB141, 0xB144, 0xB148, 0xB150, 0xB151, 0xB154, 0xB155, 0xB158, 0xB15C, 0xB160, 0xB178, 0xB179, 0xB17C, 0xB180, 0xB182, 0xB188, 0xB189, 0xB18B, 0xB18D, 0xB192, 0xB193, 0xB194, 0xB198, 0xB19C, 0xB1A8, 0xB1CC, 0xB1D0, 0xB1D4, 0xB1DC, 0xB1DD, 0xB1DF, 0xB1E8, 0xB1E9, 0xB1EC, 0xB1F0, 0xB1F9, 0xB1FB, 0xB1FD, 0xB204, 0xB205, 0xB208, 0xB20B, 0xB20C, 0xB214, 0xB215, 0xB217, 0xB219, 0xB220, 0xB234, 0xB23C, 0xB258, 0xB25C, 0xB260, 0xB268, 0xB269, 0xB274, 0xB275, 0xB27C, 0xB284, 0xB285, 0xB289, 0xB290, 0xB291, 0xB294, 0xB298, 0xB299, 0xB29A, 0xB2A0, 0xB2A1, 0xB2A3, 0xB2A5, 0xB2A6, 0xB2AA, 0xB2AC, 0xB2B0, 0xB2B4, 0xB2C8, 0xB2C9, 0xB2CC, 0xB2D0, 0xB2D2, 0xB2D8, 0xB2D9, 0xB2DB, 0xB2DD, 0xB2E2, 0xB2E4, 0xB2E5, 0xB2E6, 0xB2E8, 0xB2EB, 0xB2EC, 0xB2ED, 0xB2EE, 0xB2EF, 0xB2F3, 0xB2F4, 0xB2F5, 0xB2F7, 0xB2F8, 0xB2F9, 0xB2FA, 0xB2FB, 0xB2FF, 0xB300, 0xB301, 0xB304, 0xB308, 0xB310, 0xB311, 0xB313, 0xB314, 0xB315, 0xB31C, 0xB354, 0xB355, 0xB356, 0xB358, 0xB35B, 0xB35C, 0xB35E, 0xB35F, 0xB364, 0xB365, 0xB367, 0xB369, 0xB36B, 0xB36E, 0xB370, 0xB371, 0xB374, 0xB378, 0xB380, 0xB381, 0xB383, 0xB384, 0xB385, 0xB38C, 0xB390, 0xB394, 0xB3A0, 0xB3A1, 0xB3A8, 0xB3AC, 0xB3C4, 0xB3C5, 0xB3C8, 0xB3CB, 0xB3CC, 0xB3CE, 0xB3D0, 0xB3D4, 0xB3D5, 0xB3D7, 0xB3D9, 0xB3DB, 0xB3DD, 0xB3E0, 0xB3E4, 0xB3E8, 0xB3FC, 0xB410, 0xB418, 0xB41C, 0xB420, 0xB428, 0xB429, 0xB42B, 0xB434, 0xB450, 0xB451, 0xB454, 0xB458, 0xB460, 0xB461, 0xB463, 0xB465, 0xB46C, 0xB480, 0xB488, 0xB49D, 0xB4A4, 0xB4A8, 0xB4AC, 0xB4B5, 0xB4B7, 0xB4B9, 0xB4C0, 0xB4C4, 0xB4C8, 0xB4D0, 0xB4D5, 0xB4DC, 0xB4DD, 0xB4E0, 0xB4E3, 0xB4E4, 0xB4E6, 0xB4EC, 0xB4ED, 0xB4EF, 0xB4F1, 0xB4F8, 0xB514, 0xB515, 0xB518, 0xB51B, 0xB51C, 0xB524, 0xB525, 0xB527, 0xB528, 0xB529, 0xB52A, 0xB530, 0xB531, 0xB534, 0xB538, 0xB540, 0xB541, 0xB543, 0xB544, 0xB545, 0xB54B, 0xB54C, 0xB54D, 0xB550, 0xB554, 0xB55C, 0xB55D, 0xB55F, 0xB560, 0xB561, 0xB5A0, 0xB5A1, 0xB5A4, 0xB5A8, 0xB5AA, 0xB5AB, 0xB5B0, 0xB5B1, 0xB5B3, 0xB5B4, 0xB5B5, 0xB5BB, 0xB5BC, 0xB5BD, 0xB5C0, 0xB5C4, 0xB5CC, 0xB5CD, 0xB5CF, 0xB5D0, 0xB5D1, 0xB5D8, 0xB5EC, 0xB610, 0xB611, 0xB614, 0xB618, 0xB625, 0xB62C, 0xB634, 0xB648, 0xB664, 0xB668, 0xB69C, 0xB69D, 0xB6A0, 0xB6A4, 0xB6AB, 0xB6AC, 0xB6B1, 0xB6D4, 0xB6F0, 0xB6F4, 0xB6F8, 0xB700, 0xB701, 0xB705, 0xB728, 0xB729, 0xB72C, 0xB72F, 0xB730, 0xB738, 0xB739, 0xB73B, 0xB744, 0xB748, 0xB74C, 0xB754, 0xB755, 0xB760, 0xB764, 0xB768, 0xB770, 0xB771, 0xB773, 0xB775, 0xB77C, 0xB77D, 0xB780, 0xB784, 0xB78C, 0xB78D, 0xB78F, 0xB790, 0xB791, 0xB792, 0xB796, 0xB797, 0xB798, 0xB799, 0xB79C, 0xB7A0, 0xB7A8, 0xB7A9, 0xB7AB, 0xB7AC, 0xB7AD, 0xB7B4, 0xB7B5, 0xB7B8, 0xB7C7, 0xB7C9, 0xB7EC, 0xB7ED, 0xB7F0, 0xB7F4, 0xB7FC, 0xB7FD, 0xB7FF, 0xB800, 0xB801, 0xB807, 0xB808, 0xB809, 0xB80C, 0xB810, 0xB818, 0xB819, 0xB81B, 0xB81D, 0xB824, 0xB825, 0xB828, 0xB82C, 0xB834, 0xB835, 0xB837, 0xB838, 0xB839, 0xB840, 0xB844, 0xB851, 0xB853, 0xB85C, 0xB85D, 0xB860, 0xB864, 0xB86C, 0xB86D, 0xB86F, 0xB871, 0xB878, 0xB87C, 0xB88D, 0xB8A8, 0xB8B0, 0xB8B4, 0xB8B8, 0xB8C0, 0xB8C1, 0xB8C3, 0xB8C5, 0xB8CC, 0xB8D0, 0xB8D4, 0xB8DD, 0xB8DF, 0xB8E1, 0xB8E8, 0xB8E9, 0xB8EC, 0xB8F0, 0xB8F8, 0xB8F9, 0xB8FB, 0xB8FD, 0xB904, 0xB918, 0xB920, 0xB93C, 0xB93D, 0xB940, 0xB944, 0xB94C, 0xB94F, 0xB951, 0xB958, 0xB959, 0xB95C, 0xB960, 0xB968, 0xB969, 0xB96B, 0xB96D, 0xB974, 0xB975, 0xB978, 0xB97C, 0xB984, 0xB985, 0xB987, 0xB989, 0xB98A, 0xB98D, 0xB98E, 0xB9AC, 0xB9AD, 0xB9B0, 0xB9B4, 0xB9BC, 0xB9BD, 0xB9BF, 0xB9C1, 0xB9C8, 0xB9C9, 0xB9CC, 0xB9CE, 0xB9CF, 0xB9D0, 0xB9D1, 0xB9D2, 0xB9D8, 0xB9D9, 0xB9DB, 0xB9DD, 0xB9DE, 0xB9E1, 0xB9E3, 0xB9E4, 0xB9E5, 0xB9E8, 0xB9EC, 0xB9F4, 0xB9F5, 0xB9F7, 0xB9F8, 0xB9F9, 0xB9FA, 0xBA00, 0xBA01, 0xBA08, 0xBA15, 0xBA38, 0xBA39, 0xBA3C, 0xBA40, 0xBA42, 0xBA48, 0xBA49, 0xBA4B, 0xBA4D, 0xBA4E, 0xBA53, 0xBA54, 0xBA55, 0xBA58, 0xBA5C, 0xBA64, 0xBA65, 0xBA67, 0xBA68, 0xBA69, 0xBA70, 0xBA71, 0xBA74, 0xBA78, 0xBA83, 0xBA84, 0xBA85, 0xBA87, 0xBA8C, 0xBAA8, 0xBAA9, 0xBAAB, 0xBAAC, 0xBAB0, 0xBAB2, 0xBAB8, 0xBAB9, 0xBABB, 0xBABD, 0xBAC4, 0xBAC8, 0xBAD8, 0xBAD9, 0xBAFC, 0xBB00, 0xBB04, 0xBB0D, 0xBB0F, 0xBB11, 0xBB18, 0xBB1C, 0xBB20, 0xBB29, 0xBB2B, 0xBB34, 0xBB35, 0xBB36, 0xBB38, 0xBB3B, 0xBB3C, 0xBB3D, 0xBB3E, 0xBB44, 0xBB45, 0xBB47, 0xBB49, 0xBB4D, 0xBB4F, 0xBB50, 0xBB54, 0xBB58, 0xBB61, 0xBB63, 0xBB6C, 0xBB88, 0xBB8C, 0xBB90, 0xBBA4, 0xBBA8, 0xBBAC, 0xBBB4, 0xBBB7, 0xBBC0, 0xBBC4, 0xBBC8, 0xBBD0, 0xBBD3, 0xBBF8, 0xBBF9, 0xBBFC, 0xBBFF, 0xBC00, 0xBC02, 0xBC08, 0xBC09, 0xBC0B, 0xBC0C, 0xBC0D, 0xBC0F, 0xBC11, 0xBC14, 0xBC15, 0xBC16, 0xBC17, 0xBC18, 0xBC1B, 0xBC1C, 0xBC1D, 0xBC1E, 0xBC1F, 0xBC24, 0xBC25, 0xBC27, 0xBC29, 0xBC2D, 0xBC30, 0xBC31, 0xBC34, 0xBC38, 0xBC40, 0xBC41, 0xBC43, 0xBC44, 0xBC45, 0xBC49, 0xBC4C, 0xBC4D, 0xBC50, 0xBC5D, 0xBC84, 0xBC85, 0xBC88, 0xBC8B, 0xBC8C, 0xBC8E, 0xBC94, 0xBC95, 0xBC97, 0xBC99, 0xBC9A, 0xBCA0, 0xBCA1, 0xBCA4, 0xBCA7, 0xBCA8, 0xBCB0, 0xBCB1, 0xBCB3, 0xBCB4, 0xBCB5, 0xBCBC, 0xBCBD, 0xBCC0, 0xBCC4, 0xBCCD, 0xBCCF, 0xBCD0, 0xBCD1, 0xBCD5, 0xBCD8, 0xBCDC, 0xBCF4, 0xBCF5, 0xBCF6, 0xBCF8, 0xBCFC, 0xBD04, 0xBD05, 0xBD07, 0xBD09, 0xBD10, 0xBD14, 0xBD24, 0xBD2C, 0xBD40, 0xBD48, 0xBD49, 0xBD4C, 0xBD50, 0xBD58, 0xBD59, 0xBD64, 0xBD68, 0xBD80, 0xBD81, 0xBD84, 0xBD87, 0xBD88, 0xBD89, 0xBD8A, 0xBD90, 0xBD91, 0xBD93, 0xBD95, 0xBD99, 0xBD9A, 0xBD9C, 0xBDA4, 0xBDB0, 0xBDB8, 0xBDD4, 0xBDD5, 0xBDD8, 0xBDDC, 0xBDE9, 0xBDF0, 0xBDF4, 0xBDF8, 0xBE00, 0xBE03, 0xBE05, 0xBE0C, 0xBE0D, 0xBE10, 0xBE14, 0xBE1C, 0xBE1D, 0xBE1F, 0xBE44, 0xBE45, 0xBE48, 0xBE4C, 0xBE4E, 0xBE54, 0xBE55, 0xBE57, 0xBE59, 0xBE5A, 0xBE5B, 0xBE60, 0xBE61, 0xBE64, 0xBE68, 0xBE6A, 0xBE70, 0xBE71, 0xBE73, 0xBE74, 0xBE75, 0xBE7B, 0xBE7C, 0xBE7D, 0xBE80, 0xBE84, 0xBE8C, 0xBE8D, 0xBE8F, 0xBE90, 0xBE91, 0xBE98, 0xBE99, 0xBEA8, 0xBED0, 0xBED1, 0xBED4, 0xBED7, 0xBED8, 0xBEE0, 0xBEE3, 0xBEE4, 0xBEE5, 0xBEEC, 0xBF01, 0xBF08, 0xBF09, 0xBF18, 0xBF19, 0xBF1B, 0xBF1C, 0xBF1D, 0xBF40, 0xBF41, 0xBF44, 0xBF48, 0xBF50, 0xBF51, 0xBF55, 0xBF94, 0xBFB0, 0xBFC5, 0xBFCC, 0xBFCD, 0xBFD0, 0xBFD4, 0xBFDC, 0xBFDF, 0xBFE1, 0xC03C, 0xC051, 0xC058, 0xC05C, 0xC060, 0xC068, 0xC069, 0xC090, 0xC091, 0xC094, 0xC098, 0xC0A0, 0xC0A1, 0xC0A3, 0xC0A5, 0xC0AC, 0xC0AD, 0xC0AF, 0xC0B0, 0xC0B3, 0xC0B4, 0xC0B5, 0xC0B6, 0xC0BC, 0xC0BD, 0xC0BF, 0xC0C0, 0xC0C1, 0xC0C5, 0xC0C8, 0xC0C9, 0xC0CC, 0xC0D0, 0xC0D8, 0xC0D9, 0xC0DB, 0xC0DC, 0xC0DD, 0xC0E4, 0xC0E5, 0xC0E8, 0xC0EC, 0xC0F4, 0xC0F5, 0xC0F7, 0xC0F9, 0xC100, 0xC104, 0xC108, 0xC110, 0xC115, 0xC11C, 0xC11D, 0xC11E, 0xC11F, 0xC120, 0xC123, 0xC124, 0xC126, 0xC127, 0xC12C, 0xC12D, 0xC12F, 0xC130, 0xC131, 0xC136, 0xC138, 0xC139, 0xC13C, 0xC140, 0xC148, 0xC149, 0xC14B, 0xC14C, 0xC14D, 0xC154, 0xC155, 0xC158, 0xC15C, 0xC164, 0xC165, 0xC167, 0xC168, 0xC169, 0xC170, 0xC174, 0xC178, 0xC185, 0xC18C, 0xC18D, 0xC18E, 0xC190, 0xC194, 0xC196, 0xC19C, 0xC19D, 0xC19F, 0xC1A1, 0xC1A5, 0xC1A8, 0xC1A9, 0xC1AC, 0xC1B0, 0xC1BD, 0xC1C4, 0xC1C8, 0xC1CC, 0xC1D4, 0xC1D7, 0xC1D8, 0xC1E0, 0xC1E4, 0xC1E8, 0xC1F0, 0xC1F1, 0xC1F3, 0xC1FC, 0xC1FD, 0xC200, 0xC204, 0xC20C, 0xC20D, 0xC20F, 0xC211, 0xC218, 0xC219, 0xC21C, 0xC21F, 0xC220, 0xC228, 0xC229, 0xC22B, 0xC22D, 0xC22F, 0xC231, 0xC232, 0xC234, 0xC248, 0xC250, 0xC251, 0xC254, 0xC258, 0xC260, 0xC265, 0xC26C, 0xC26D, 0xC270, 0xC274, 0xC27C, 0xC27D, 0xC27F, 0xC281, 0xC288, 0xC289, 0xC290, 0xC298, 0xC29B, 0xC29D, 0xC2A4, 0xC2A5, 0xC2A8, 0xC2AC, 0xC2AD, 0xC2B4, 0xC2B5, 0xC2B7, 0xC2B9, 0xC2DC, 0xC2DD, 0xC2E0, 0xC2E3, 0xC2E4, 0xC2EB, 0xC2EC, 0xC2ED, 0xC2EF, 0xC2F1, 0xC2F6, 0xC2F8, 0xC2F9, 0xC2FB, 0xC2FC, 0xC300, 0xC308, 0xC309, 0xC30C, 0xC30D, 0xC313, 0xC314, 0xC315, 0xC318, 0xC31C, 0xC324, 0xC325, 0xC328, 0xC329, 0xC345, 0xC368, 0xC369, 0xC36C, 0xC370, 0xC372, 0xC378, 0xC379, 0xC37C, 0xC37D, 0xC384, 0xC388, 0xC38C, 0xC3C0, 0xC3D8, 0xC3D9, 0xC3DC, 0xC3DF, 0xC3E0, 0xC3E2, 0xC3E8, 0xC3E9, 0xC3ED, 0xC3F4, 0xC3F5, 0xC3F8, 0xC408, 0xC410, 0xC424, 0xC42C, 0xC430, 0xC434, 0xC43C, 0xC43D, 0xC448, 0xC464, 0xC465, 0xC468, 0xC46C, 0xC474, 0xC475, 0xC479, 0xC480, 0xC494, 0xC49C, 0xC4B8, 0xC4BC, 0xC4E9, 0xC4F0, 0xC4F1, 0xC4F4, 0xC4F8, 0xC4FA, 0xC4FF, 0xC500, 0xC501, 0xC50C, 0xC510, 0xC514, 0xC51C, 0xC528, 0xC529, 0xC52C, 0xC530, 0xC538, 0xC539, 0xC53B, 0xC53D, 0xC544, 0xC545, 0xC548, 0xC549, 0xC54A, 0xC54C, 0xC54D, 0xC54E, 0xC553, 0xC554, 0xC555, 0xC557, 0xC558, 0xC559, 0xC55D, 0xC55E, 0xC560, 0xC561, 0xC564, 0xC568, 0xC570, 0xC571, 0xC573, 0xC574, 0xC575, 0xC57C, 0xC57D, 0xC580, 0xC584, 0xC587, 0xC58C, 0xC58D, 0xC58F, 0xC591, 0xC595, 0xC597, 0xC598, 0xC59C, 0xC5A0, 0xC5A9, 0xC5B4, 0xC5B5, 0xC5B8, 0xC5B9, 0xC5BB, 0xC5BC, 0xC5BD, 0xC5BE, 0xC5C4, 0xC5C5, 0xC5C6, 0xC5C7, 0xC5C8, 0xC5C9, 0xC5CA, 0xC5CC, 0xC5CE, 0xC5D0, 0xC5D1, 0xC5D4, 0xC5D8, 0xC5E0, 0xC5E1, 0xC5E3, 0xC5E5, 0xC5EC, 0xC5ED, 0xC5EE, 0xC5F0, 0xC5F4, 0xC5F6, 0xC5F7, 0xC5FC, 0xC5FD, 0xC5FE, 0xC5FF, 0xC600, 0xC601, 0xC605, 0xC606, 0xC607, 0xC608, 0xC60C, 0xC610, 0xC618, 0xC619, 0xC61B, 0xC61C, 0xC624, 0xC625, 0xC628, 0xC62C, 0xC62D, 0xC62E, 0xC630, 0xC633, 0xC634, 0xC635, 0xC637, 0xC639, 0xC63B, 0xC640, 0xC641, 0xC644, 0xC648, 0xC650, 0xC651, 0xC653, 0xC654, 0xC655, 0xC65C, 0xC65D, 0xC660, 0xC66C, 0xC66F, 0xC671, 0xC678, 0xC679, 0xC67C, 0xC680, 0xC688, 0xC689, 0xC68B, 0xC68D, 0xC694, 0xC695, 0xC698, 0xC69C, 0xC6A4, 0xC6A5, 0xC6A7, 0xC6A9, 0xC6B0, 0xC6B1, 0xC6B4, 0xC6B8, 0xC6B9, 0xC6BA, 0xC6C0, 0xC6C1, 0xC6C3, 0xC6C5, 0xC6CC, 0xC6CD, 0xC6D0, 0xC6D4, 0xC6DC, 0xC6DD, 0xC6E0, 0xC6E1, 0xC6E8, 0xC6E9, 0xC6EC, 0xC6F0, 0xC6F8, 0xC6F9, 0xC6FD, 0xC704, 0xC705, 0xC708, 0xC70C, 0xC714, 0xC715, 0xC717, 0xC719, 0xC720, 0xC721, 0xC724, 0xC728, 0xC730, 0xC731, 0xC733, 0xC735, 0xC737, 0xC73C, 0xC73D, 0xC740, 0xC744, 0xC74A, 0xC74C, 0xC74D, 0xC74F, 0xC751, 0xC752, 0xC753, 0xC754, 0xC755, 0xC756, 0xC757, 0xC758, 0xC75C, 0xC760, 0xC768, 0xC76B, 0xC774, 0xC775, 0xC778, 0xC77C, 0xC77D, 0xC77E, 0xC783, 0xC784, 0xC785, 0xC787, 0xC788, 0xC789, 0xC78A, 0xC78E, 0xC790, 0xC791, 0xC794, 0xC796, 0xC797, 0xC798, 0xC79A, 0xC7A0, 0xC7A1, 0xC7A3, 0xC7A4, 0xC7A5, 0xC7A6, 0xC7AC, 0xC7AD, 0xC7B0, 0xC7B4, 0xC7BC, 0xC7BD, 0xC7BF, 0xC7C0, 0xC7C1, 0xC7C8, 0xC7C9, 0xC7CC, 0xC7CE, 0xC7D0, 0xC7D8, 0xC7DD, 0xC7E4, 0xC7E8, 0xC7EC, 0xC800, 0xC801, 0xC804, 0xC808, 0xC80A, 0xC810, 0xC811, 0xC813, 0xC815, 0xC816, 0xC81C, 0xC81D, 0xC820, 0xC824, 0xC82C, 0xC82D, 0xC82F, 0xC831, 0xC838, 0xC83C, 0xC840, 0xC848, 0xC849, 0xC84C, 0xC84D, 0xC854, 0xC870, 0xC871, 0xC874, 0xC878, 0xC87A, 0xC880, 0xC881, 0xC883, 0xC885, 0xC886, 0xC887, 0xC88B, 0xC88C, 0xC88D, 0xC894, 0xC89D, 0xC89F, 0xC8A1, 0xC8A8, 0xC8BC, 0xC8BD, 0xC8C4, 0xC8C8, 0xC8CC, 0xC8D4, 0xC8D5, 0xC8D7, 0xC8D9, 0xC8E0, 0xC8E1, 0xC8E4, 0xC8F5, 0xC8FC, 0xC8FD, 0xC900, 0xC904, 0xC905, 0xC906, 0xC90C, 0xC90D, 0xC90F, 0xC911, 0xC918, 0xC92C, 0xC934, 0xC950, 0xC951, 0xC954, 0xC958, 0xC960, 0xC961, 0xC963, 0xC96C, 0xC970, 0xC974, 0xC97C, 0xC988, 0xC989, 0xC98C, 0xC990, 0xC998, 0xC999, 0xC99B, 0xC99D, 0xC9C0, 0xC9C1, 0xC9C4, 0xC9C7, 0xC9C8, 0xC9CA, 0xC9D0, 0xC9D1, 0xC9D3, 0xC9D5, 0xC9D6, 0xC9D9, 0xC9DA, 0xC9DC, 0xC9DD, 0xC9E0, 0xC9E2, 0xC9E4, 0xC9E7, 0xC9EC, 0xC9ED, 0xC9EF, 0xC9F0, 0xC9F1, 0xC9F8, 0xC9F9, 0xC9FC, 0xCA00, 0xCA08, 0xCA09, 0xCA0B, 0xCA0C, 0xCA0D, 0xCA14, 0xCA18, 0xCA29, 0xCA4C, 0xCA4D, 0xCA50, 0xCA54, 0xCA5C, 0xCA5D, 0xCA5F, 0xCA60, 0xCA61, 0xCA68, 0xCA7D, 0xCA84, 0xCA98, 0xCABC, 0xCABD, 0xCAC0, 0xCAC4, 0xCACC, 0xCACD, 0xCACF, 0xCAD1, 0xCAD3, 0xCAD8, 0xCAD9, 0xCAE0, 0xCAEC, 0xCAF4, 0xCB08, 0xCB10, 0xCB14, 0xCB18, 0xCB20, 0xCB21, 0xCB41, 0xCB48, 0xCB49, 0xCB4C, 0xCB50, 0xCB58, 0xCB59, 0xCB5D, 0xCB64, 0xCB78, 0xCB79, 0xCB9C, 0xCBB8, 0xCBD4, 0xCBE4, 0xCBE7, 0xCBE9, 0xCC0C, 0xCC0D, 0xCC10, 0xCC14, 0xCC1C, 0xCC1D, 0xCC21, 0xCC22, 0xCC27, 0xCC28, 0xCC29, 0xCC2C, 0xCC2E, 0xCC30, 0xCC38, 0xCC39, 0xCC3B, 0xCC3C, 0xCC3D, 0xCC3E, 0xCC44, 0xCC45, 0xCC48, 0xCC4C, 0xCC54, 0xCC55, 0xCC57, 0xCC58, 0xCC59, 0xCC60, 0xCC64, 0xCC66, 0xCC68, 0xCC70, 0xCC75, 0xCC98, 0xCC99, 0xCC9C, 0xCCA0, 0xCCA8, 0xCCA9, 0xCCAB, 0xCCAC, 0xCCAD, 0xCCB4, 0xCCB5, 0xCCB8, 0xCCBC, 0xCCC4, 0xCCC5, 0xCCC7, 0xCCC9, 0xCCD0, 0xCCD4, 0xCCE4, 0xCCEC, 0xCCF0, 0xCD01, 0xCD08, 0xCD09, 0xCD0C, 0xCD10, 0xCD18, 0xCD19, 0xCD1B, 0xCD1D, 0xCD24, 0xCD28, 0xCD2C, 0xCD39, 0xCD5C, 0xCD60, 0xCD64, 0xCD6C, 0xCD6D, 0xCD6F, 0xCD71, 0xCD78, 0xCD88, 0xCD94, 0xCD95, 0xCD98, 0xCD9C, 0xCDA4, 0xCDA5, 0xCDA7, 0xCDA9, 0xCDB0, 0xCDC4, 0xCDCC, 0xCDD0, 0xCDE8, 0xCDEC, 0xCDF0, 0xCDF8, 0xCDF9, 0xCDFB, 0xCDFD, 0xCE04, 0xCE08, 0xCE0C, 0xCE14, 0xCE19, 0xCE20, 0xCE21, 0xCE24, 0xCE28, 0xCE30, 0xCE31, 0xCE33, 0xCE35, 0xCE58, 0xCE59, 0xCE5C, 0xCE5F, 0xCE60, 0xCE61, 0xCE68, 0xCE69, 0xCE6B, 0xCE6D, 0xCE74, 0xCE75, 0xCE78, 0xCE7C, 0xCE84, 0xCE85, 0xCE87, 0xCE89, 0xCE90, 0xCE91, 0xCE94, 0xCE98, 0xCEA0, 0xCEA1, 0xCEA3, 0xCEA4, 0xCEA5, 0xCEAC, 0xCEAD, 0xCEC1, 0xCEE4, 0xCEE5, 0xCEE8, 0xCEEB, 0xCEEC, 0xCEF4, 0xCEF5, 0xCEF7, 0xCEF8, 0xCEF9, 0xCF00, 0xCF01, 0xCF04, 0xCF08, 0xCF10, 0xCF11, 0xCF13, 0xCF15, 0xCF1C, 0xCF20, 0xCF24, 0xCF2C, 0xCF2D, 0xCF2F, 0xCF30, 0xCF31, 0xCF38, 0xCF54, 0xCF55, 0xCF58, 0xCF5C, 0xCF64, 0xCF65, 0xCF67, 0xCF69, 0xCF70, 0xCF71, 0xCF74, 0xCF78, 0xCF80, 0xCF85, 0xCF8C, 0xCFA1, 0xCFA8, 0xCFB0, 0xCFC4, 0xCFE0, 0xCFE1, 0xCFE4, 0xCFE8, 0xCFF0, 0xCFF1, 0xCFF3, 0xCFF5, 0xCFFC, 0xD000, 0xD004, 0xD011, 0xD018, 0xD02D, 0xD034, 0xD035, 0xD038, 0xD03C, 0xD044, 0xD045, 0xD047, 0xD049, 0xD050, 0xD054, 0xD058, 0xD060, 0xD06C, 0xD06D, 0xD070, 0xD074, 0xD07C, 0xD07D, 0xD081, 0xD0A4, 0xD0A5, 0xD0A8, 0xD0AC, 0xD0B4, 0xD0B5, 0xD0B7, 0xD0B9, 0xD0C0, 0xD0C1, 0xD0C4, 0xD0C8, 0xD0C9, 0xD0D0, 0xD0D1, 0xD0D3, 0xD0D4, 0xD0D5, 0xD0DC, 0xD0DD, 0xD0E0, 0xD0E4, 0xD0EC, 0xD0ED, 0xD0EF, 0xD0F0, 0xD0F1, 0xD0F8, 0xD10D, 0xD130, 0xD131, 0xD134, 0xD138, 0xD13A, 0xD140, 0xD141, 0xD143, 0xD144, 0xD145, 0xD14C, 0xD14D, 0xD150, 0xD154, 0xD15C, 0xD15D, 0xD15F, 0xD161, 0xD168, 0xD16C, 0xD17C, 0xD184, 0xD188, 0xD1A0, 0xD1A1, 0xD1A4, 0xD1A8, 0xD1B0, 0xD1B1, 0xD1B3, 0xD1B5, 0xD1BA, 0xD1BC, 0xD1C0, 0xD1D8, 0xD1F4, 0xD1F8, 0xD207, 0xD209, 0xD210, 0xD22C, 0xD22D, 0xD230, 0xD234, 0xD23C, 0xD23D, 0xD23F, 0xD241, 0xD248, 0xD25C, 0xD264, 0xD280, 0xD281, 0xD284, 0xD288, 0xD290, 0xD291, 0xD295, 0xD29C, 0xD2A0, 0xD2A4, 0xD2AC, 0xD2B1, 0xD2B8, 0xD2B9, 0xD2BC, 0xD2BF, 0xD2C0, 0xD2C2, 0xD2C8, 0xD2C9, 0xD2CB, 0xD2D4, 0xD2D8, 0xD2DC, 0xD2E4, 0xD2E5, 0xD2F0, 0xD2F1, 0xD2F4, 0xD2F8, 0xD300, 0xD301, 0xD303, 0xD305, 0xD30C, 0xD30D, 0xD30E, 0xD310, 0xD314, 0xD316, 0xD31C, 0xD31D, 0xD31F, 0xD320, 0xD321, 0xD325, 0xD328, 0xD329, 0xD32C, 0xD330, 0xD338, 0xD339, 0xD33B, 0xD33C, 0xD33D, 0xD344, 0xD345, 0xD37C, 0xD37D, 0xD380, 0xD384, 0xD38C, 0xD38D, 0xD38F, 0xD390, 0xD391, 0xD398, 0xD399, 0xD39C, 0xD3A0, 0xD3A8, 0xD3A9, 0xD3AB, 0xD3AD, 0xD3B4, 0xD3B8, 0xD3BC, 0xD3C4, 0xD3C5, 0xD3C8, 0xD3C9, 0xD3D0, 0xD3D8, 0xD3E1, 0xD3E3, 0xD3EC, 0xD3ED, 0xD3F0, 0xD3F4, 0xD3FC, 0xD3FD, 0xD3FF, 0xD401, 0xD408, 0xD41D, 0xD440, 0xD444, 0xD45C, 0xD460, 0xD464, 0xD46D, 0xD46F, 0xD478, 0xD479, 0xD47C, 0xD47F, 0xD480, 0xD482, 0xD488, 0xD489, 0xD48B, 0xD48D, 0xD494, 0xD4A9, 0xD4CC, 0xD4D0, 0xD4D4, 0xD4DC, 0xD4DF, 0xD4E8, 0xD4EC, 0xD4F0, 0xD4F8, 0xD4FB, 0xD4FD, 0xD504, 0xD508, 0xD50C, 0xD514, 0xD515, 0xD517, 0xD53C, 0xD53D, 0xD540, 0xD544, 0xD54C, 0xD54D, 0xD54F, 0xD551, 0xD558, 0xD559, 0xD55C, 0xD560, 0xD565, 0xD568, 0xD569, 0xD56B, 0xD56D, 0xD574, 0xD575, 0xD578, 0xD57C, 0xD584, 0xD585, 0xD587, 0xD588, 0xD589, 0xD590, 0xD5A5, 0xD5C8, 0xD5C9, 0xD5CC, 0xD5D0, 0xD5D2, 0xD5D8, 0xD5D9, 0xD5DB, 0xD5DD, 0xD5E4, 0xD5E5, 0xD5E8, 0xD5EC, 0xD5F4, 0xD5F5, 0xD5F7, 0xD5F9, 0xD600, 0xD601, 0xD604, 0xD608, 0xD610, 0xD611, 0xD613, 0xD614, 0xD615, 0xD61C, 0xD620, 0xD624, 0xD62D, 0xD638, 0xD639, 0xD63C, 0xD640, 0xD645, 0xD648, 0xD649, 0xD64B, 0xD64D, 0xD651, 0xD654, 0xD655, 0xD658, 0xD65C, 0xD667, 0xD669, 0xD670, 0xD671, 0xD674, 0xD683, 0xD685, 0xD68C, 0xD68D, 0xD690, 0xD694, 0xD69D, 0xD69F, 0xD6A1, 0xD6A8, 0xD6AC, 0xD6B0, 0xD6B9, 0xD6BB, 0xD6C4, 0xD6C5, 0xD6C8, 0xD6CC, 0xD6D1, 0xD6D4, 0xD6D7, 0xD6D9, 0xD6E0, 0xD6E4, 0xD6E8, 0xD6F0, 0xD6F5, 0xD6FC, 0xD6FD, 0xD700, 0xD704, 0xD711, 0xD718, 0xD719, 0xD71C, 0xD720, 0xD728, 0xD729, 0xD72B, 0xD72D, 0xD734, 0xD735, 0xD738, 0xD73C, 0xD744, 0xD747, 0xD749, 0xD750, 0xD751, 0xD754, 0xD756, 0xD757, 0xD758, 0xD759, 0xD760, 0xD761, 0xD763, 0xD765, 0xD769, 0xD76C, 0xD770, 0xD774, 0xD77C, 0xD77D, 0xD781, 0xD788, 0xD789, 0xD78C, 0xD790, 0xD798, 0xD799, 0xD79B, 0xD79D, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0x4F3D, 0x4F73, 0x5047, 0x50F9, 0x52A0, 0x53EF, 0x5475, 0x54E5, 0x5609, 0x5AC1, 0x5BB6, 0x6687, 0x67B6, 0x67B7, 0x67EF, 0x6B4C, 0x73C2, 0x75C2, 0x7A3C, 0x82DB, 0x8304, 0x8857, 0x8888, 0x8A36, 0x8CC8, 0x8DCF, 0x8EFB, 0x8FE6, 0x99D5, 0x523B, 0x5374, 0x5404, 0x606A, 0x6164, 0x6BBC, 0x73CF, 0x811A, 0x89BA, 0x89D2, 0x95A3, 0x4F83, 0x520A, 0x58BE, 0x5978, 0x59E6, 0x5E72, 0x5E79, 0x61C7, 0x63C0, 0x6746, 0x67EC, 0x687F, 0x6F97, 0x764E, 0x770B, 0x78F5, 0x7A08, 0x7AFF, 0x7C21, 0x809D, 0x826E, 0x8271, 0x8AEB, 0x9593, 0x4E6B, 0x559D, 0x66F7, 0x6E34, 0x78A3, 0x7AED, 0x845B, 0x8910, 0x874E, 0x97A8, 0x52D8, 0x574E, 0x582A, 0x5D4C, 0x611F, 0x61BE, 0x6221, 0x6562, 0x67D1, 0x6A44, 0x6E1B, 0x7518, 0x75B3, 0x76E3, 0x77B0, 0x7D3A, 0x90AF, 0x9451, 0x9452, 0x9F95, 0x5323, 0x5CAC, 0x7532, 0x80DB, 0x9240, 0x9598, 0x525B, 0x5808, 0x59DC, 0x5CA1, 0x5D17, 0x5EB7, 0x5F3A, 0x5F4A, 0x6177, 0x6C5F, 0x757A, 0x7586, 0x7CE0, 0x7D73, 0x7DB1, 0x7F8C, 0x8154, 0x8221, 0x8591, 0x8941, 0x8B1B, 0x92FC, 0x964D, 0x9C47, 0x4ECB, 0x4EF7, 0x500B, 0x51F1, 0x584F, 0x6137, 0x613E, 0x6168, 0x6539, 0x69EA, 0x6F11, 0x75A5, 0x7686, 0x76D6, 0x7B87, 0x82A5, 0x84CB, 0xF900, 0x93A7, 0x958B, 0x5580, 0x5BA2, 0x5751, 0xF901, 0x7CB3, 0x7FB9, 0x91B5, 0x5028, 0x53BB, 0x5C45, 0x5DE8, 0x62D2, 0x636E, 0x64DA, 0x64E7, 0x6E20, 0x70AC, 0x795B, 0x8DDD, 0x8E1E, 0xF902, 0x907D, 0x9245, 0x92F8, 0x4E7E, 0x4EF6, 0x5065, 0x5DFE, 0x5EFA, 0x6106, 0x6957, 0x8171, 0x8654, 0x8E47, 0x9375, 0x9A2B, 0x4E5E, 0x5091, 0x6770, 0x6840, 0x5109, 0x528D, 0x5292, 0x6AA2, 0x77BC, 0x9210, 0x9ED4, 0x52AB, 0x602F, 0x8FF2, 0x5048, 0x61A9, 0x63ED, 0x64CA, 0x683C, 0x6A84, 0x6FC0, 0x8188, 0x89A1, 0x9694, 0x5805, 0x727D, 0x72AC, 0x7504, 0x7D79, 0x7E6D, 0x80A9, 0x898B, 0x8B74, 0x9063, 0x9D51, 0x6289, 0x6C7A, 0x6F54, 0x7D50, 0x7F3A, 0x8A23, 0x517C, 0x614A, 0x7B9D, 0x8B19, 0x9257, 0x938C, 0x4EAC, 0x4FD3, 0x501E, 0x50BE, 0x5106, 0x52C1, 0x52CD, 0x537F, 0x5770, 0x5883, 0x5E9A, 0x5F91, 0x6176, 0x61AC, 0x64CE, 0x656C, 0x666F, 0x66BB, 0x66F4, 0x6897, 0x6D87, 0x7085, 0x70F1, 0x749F, 0x74A5, 0x74CA, 0x75D9, 0x786C, 0x78EC, 0x7ADF, 0x7AF6, 0x7D45, 0x7D93, 0x8015, 0x803F, 0x811B, 0x8396, 0x8B66, 0x8F15, 0x9015, 0x93E1, 0x9803, 0x9838, 0x9A5A, 0x9BE8, 0x4FC2, 0x5553, 0x583A, 0x5951, 0x5B63, 0x5C46, 0x60B8, 0x6212, 0x6842, 0x68B0, 0x68E8, 0x6EAA, 0x754C, 0x7678, 0x78CE, 0x7A3D, 0x7CFB, 0x7E6B, 0x7E7C, 0x8A08, 0x8AA1, 0x8C3F, 0x968E, 0x9DC4, 0x53E4, 0x53E9, 0x544A, 0x5471, 0x56FA, 0x59D1, 0x5B64, 0x5C3B, 0x5EAB, 0x62F7, 0x6537, 0x6545, 0x6572, 0x66A0, 0x67AF, 0x69C1, 0x6CBD, 0x75FC, 0x7690, 0x777E, 0x7A3F, 0x7F94, 0x8003, 0x80A1, 0x818F, 0x82E6, 0x82FD, 0x83F0, 0x85C1, 0x8831, 0x88B4, 0x8AA5, 0xF903, 0x8F9C, 0x932E, 0x96C7, 0x9867, 0x9AD8, 0x9F13, 0x54ED, 0x659B, 0x66F2, 0x688F, 0x7A40, 0x8C37, 0x9D60, 0x56F0, 0x5764, 0x5D11, 0x6606, 0x68B1, 0x68CD, 0x6EFE, 0x7428, 0x889E, 0x9BE4, 0x6C68, 0xF904, 0x9AA8, 0x4F9B, 0x516C, 0x5171, 0x529F, 0x5B54, 0x5DE5, 0x6050, 0x606D, 0x62F1, 0x63A7, 0x653B, 0x73D9, 0x7A7A, 0x86A3, 0x8CA2, 0x978F, 0x4E32, 0x5BE1, 0x6208, 0x679C, 0x74DC, 0x79D1, 0x83D3, 0x8A87, 0x8AB2, 0x8DE8, 0x904E, 0x934B, 0x9846, 0x5ED3, 0x69E8, 0x85FF, 0x90ED, 0xF905, 0x51A0, 0x5B98, 0x5BEC, 0x6163, 0x68FA, 0x6B3E, 0x704C, 0x742F, 0x74D8, 0x7BA1, 0x7F50, 0x83C5, 0x89C0, 0x8CAB, 0x95DC, 0x9928, 0x522E, 0x605D, 0x62EC, 0x9002, 0x4F8A, 0x5149, 0x5321, 0x58D9, 0x5EE3, 0x66E0, 0x6D38, 0x709A, 0x72C2, 0x73D6, 0x7B50, 0x80F1, 0x945B, 0x5366, 0x639B, 0x7F6B, 0x4E56, 0x5080, 0x584A, 0x58DE, 0x602A, 0x6127, 0x62D0, 0x69D0, 0x9B41, 0x5B8F, 0x7D18, 0x80B1, 0x8F5F, 0x4EA4, 0x50D1, 0x54AC, 0x55AC, 0x5B0C, 0x5DA0, 0x5DE7, 0x652A, 0x654E, 0x6821, 0x6A4B, 0x72E1, 0x768E, 0x77EF, 0x7D5E, 0x7FF9, 0x81A0, 0x854E, 0x86DF, 0x8F03, 0x8F4E, 0x90CA, 0x9903, 0x9A55, 0x9BAB, 0x4E18, 0x4E45, 0x4E5D, 0x4EC7, 0x4FF1, 0x5177, 0x52FE, 0x5340, 0x53E3, 0x53E5, 0x548E, 0x5614, 0x5775, 0x57A2, 0x5BC7, 0x5D87, 0x5ED0, 0x61FC, 0x62D8, 0x6551, 0x67B8, 0x67E9, 0x69CB, 0x6B50, 0x6BC6, 0x6BEC, 0x6C42, 0x6E9D, 0x7078, 0x72D7, 0x7396, 0x7403, 0x77BF, 0x77E9, 0x7A76, 0x7D7F, 0x8009, 0x81FC, 0x8205, 0x820A, 0x82DF, 0x8862, 0x8B33, 0x8CFC, 0x8EC0, 0x9011, 0x90B1, 0x9264, 0x92B6, 0x99D2, 0x9A45, 0x9CE9, 0x9DD7, 0x9F9C, 0x570B, 0x5C40, 0x83CA, 0x97A0, 0x97AB, 0x9EB4, 0x541B, 0x7A98, 0x7FA4, 0x88D9, 0x8ECD, 0x90E1, 0x5800, 0x5C48, 0x6398, 0x7A9F, 0x5BAE, 0x5F13, 0x7A79, 0x7AAE, 0x828E, 0x8EAC, 0x5026, 0x5238, 0x52F8, 0x5377, 0x5708, 0x62F3, 0x6372, 0x6B0A, 0x6DC3, 0x7737, 0x53A5, 0x7357, 0x8568, 0x8E76, 0x95D5, 0x673A, 0x6AC3, 0x6F70, 0x8A6D, 0x8ECC, 0x994B, 0xF906, 0x6677, 0x6B78, 0x8CB4, 0x9B3C, 0xF907, 0x53EB, 0x572D, 0x594E, 0x63C6, 0x69FB, 0x73EA, 0x7845, 0x7ABA, 0x7AC5, 0x7CFE, 0x8475, 0x898F, 0x8D73, 0x9035, 0x95A8, 0x52FB, 0x5747, 0x7547, 0x7B60, 0x83CC, 0x921E, 0xF908, 0x6A58, 0x514B, 0x524B, 0x5287, 0x621F, 0x68D8, 0x6975, 0x9699, 0x50C5, 0x52A4, 0x52E4, 0x61C3, 0x65A4, 0x6839, 0x69FF, 0x747E, 0x7B4B, 0x82B9, 0x83EB, 0x89B2, 0x8B39, 0x8FD1, 0x9949, 0xF909, 0x4ECA, 0x5997, 0x64D2, 0x6611, 0x6A8E, 0x7434, 0x7981, 0x79BD, 0x82A9, 0x887E, 0x887F, 0x895F, 0xF90A, 0x9326, 0x4F0B, 0x53CA, 0x6025, 0x6271, 0x6C72, 0x7D1A, 0x7D66, 0x4E98, 0x5162, 0x77DC, 0x80AF, 0x4F01, 0x4F0E, 0x5176, 0x5180, 0x55DC, 0x5668, 0x573B, 0x57FA, 0x57FC, 0x5914, 0x5947, 0x5993, 0x5BC4, 0x5C90, 0x5D0E, 0x5DF1, 0x5E7E, 0x5FCC, 0x6280, 0x65D7, 0x65E3, 0x671E, 0x671F, 0x675E, 0x68CB, 0x68C4, 0x6A5F, 0x6B3A, 0x6C23, 0x6C7D, 0x6C82, 0x6DC7, 0x7398, 0x7426, 0x742A, 0x7482, 0x74A3, 0x7578, 0x757F, 0x7881, 0x78EF, 0x7941, 0x7947, 0x7948, 0x797A, 0x7B95, 0x7D00, 0x7DBA, 0x7F88, 0x8006, 0x802D, 0x808C, 0x8A18, 0x8B4F, 0x8C48, 0x8D77, 0x9321, 0x9324, 0x98E2, 0x9951, 0x9A0E, 0x9A0F, 0x9A65, 0x9E92, 0x7DCA, 0x4F76, 0x5409, 0x62EE, 0x6854, 0x91D1, 0x55AB, 0x513A, 0xF90B, 0xF90C, 0x5A1C, 0x61E6, 0xF90D, 0x62CF, 0x62FF, 0xF90E, 0xF90F, 0xF910, 0xF911, 0xF912, 0xF913, 0x90A3, 0xF914, 0xF915, 0xF916, 0xF917, 0xF918, 0x8AFE, 0xF919, 0xF91A, 0xF91B, 0xF91C, 0x6696, 0xF91D, 0x7156, 0xF91E, 0xF91F, 0x96E3, 0xF920, 0x634F, 0x637A, 0x5357, 0xF921, 0x678F, 0x6960, 0x6E73, 0xF922, 0x7537, 0xF923, 0xF924, 0xF925, 0x7D0D, 0xF926, 0xF927, 0x8872, 0x56CA, 0x5A18, 0xF928, 0xF929, 0xF92A, 0xF92B, 0xF92C, 0x4E43, 0xF92D, 0x5167, 0x5948, 0x67F0, 0x8010, 0xF92E, 0x5973, 0x5E74, 0x649A, 0x79CA, 0x5FF5, 0x606C, 0x62C8, 0x637B, 0x5BE7, 0x5BD7, 0x52AA, 0xF92F, 0x5974, 0x5F29, 0x6012, 0xF930, 0xF931, 0xF932, 0x7459, 0xF933, 0xF934, 0xF935, 0xF936, 0xF937, 0xF938, 0x99D1, 0xF939, 0xF93A, 0xF93B, 0xF93C, 0xF93D, 0xF93E, 0xF93F, 0xF940, 0xF941, 0xF942, 0xF943, 0x6FC3, 0xF944, 0xF945, 0x81BF, 0x8FB2, 0x60F1, 0xF946, 0xF947, 0x8166, 0xF948, 0xF949, 0x5C3F, 0xF94A, 0xF94B, 0xF94C, 0xF94D, 0xF94E, 0xF94F, 0xF950, 0xF951, 0x5AE9, 0x8A25, 0x677B, 0x7D10, 0xF952, 0xF953, 0xF954, 0xF955, 0xF956, 0xF957, 0x80FD, 0xF958, 0xF959, 0x5C3C, 0x6CE5, 0x533F, 0x6EBA, 0x591A, 0x8336, 0x4E39, 0x4EB6, 0x4F46, 0x55AE, 0x5718, 0x58C7, 0x5F56, 0x65B7, 0x65E6, 0x6A80, 0x6BB5, 0x6E4D, 0x77ED, 0x7AEF, 0x7C1E, 0x7DDE, 0x86CB, 0x8892, 0x9132, 0x935B, 0x64BB, 0x6FBE, 0x737A, 0x75B8, 0x9054, 0x5556, 0x574D, 0x61BA, 0x64D4, 0x66C7, 0x6DE1, 0x6E5B, 0x6F6D, 0x6FB9, 0x75F0, 0x8043, 0x81BD, 0x8541, 0x8983, 0x8AC7, 0x8B5A, 0x931F, 0x6C93, 0x7553, 0x7B54, 0x8E0F, 0x905D, 0x5510, 0x5802, 0x5858, 0x5E62, 0x6207, 0x649E, 0x68E0, 0x7576, 0x7CD6, 0x87B3, 0x9EE8, 0x4EE3, 0x5788, 0x576E, 0x5927, 0x5C0D, 0x5CB1, 0x5E36, 0x5F85, 0x6234, 0x64E1, 0x73B3, 0x81FA, 0x888B, 0x8CB8, 0x968A, 0x9EDB, 0x5B85, 0x5FB7, 0x60B3, 0x5012, 0x5200, 0x5230, 0x5716, 0x5835, 0x5857, 0x5C0E, 0x5C60, 0x5CF6, 0x5D8B, 0x5EA6, 0x5F92, 0x60BC, 0x6311, 0x6389, 0x6417, 0x6843, 0x68F9, 0x6AC2, 0x6DD8, 0x6E21, 0x6ED4, 0x6FE4, 0x71FE, 0x76DC, 0x7779, 0x79B1, 0x7A3B, 0x8404, 0x89A9, 0x8CED, 0x8DF3, 0x8E48, 0x9003, 0x9014, 0x9053, 0x90FD, 0x934D, 0x9676, 0x97DC, 0x6BD2, 0x7006, 0x7258, 0x72A2, 0x7368, 0x7763, 0x79BF, 0x7BE4, 0x7E9B, 0x8B80, 0x58A9, 0x60C7, 0x6566, 0x65FD, 0x66BE, 0x6C8C, 0x711E, 0x71C9, 0x8C5A, 0x9813, 0x4E6D, 0x7A81, 0x4EDD, 0x51AC, 0x51CD, 0x52D5, 0x540C, 0x61A7, 0x6771, 0x6850, 0x68DF, 0x6D1E, 0x6F7C, 0x75BC, 0x77B3, 0x7AE5, 0x80F4, 0x8463, 0x9285, 0x515C, 0x6597, 0x675C, 0x6793, 0x75D8, 0x7AC7, 0x8373, 0xF95A, 0x8C46, 0x9017, 0x982D, 0x5C6F, 0x81C0, 0x829A, 0x9041, 0x906F, 0x920D, 0x5F97, 0x5D9D, 0x6A59, 0x71C8, 0x767B, 0x7B49, 0x85E4, 0x8B04, 0x9127, 0x9A30, 0x5587, 0x61F6, 0xF95B, 0x7669, 0x7F85, 0x863F, 0x87BA, 0x88F8, 0x908F, 0xF95C, 0x6D1B, 0x70D9, 0x73DE, 0x7D61, 0x843D, 0xF95D, 0x916A, 0x99F1, 0xF95E, 0x4E82, 0x5375, 0x6B04, 0x6B12, 0x703E, 0x721B, 0x862D, 0x9E1E, 0x524C, 0x8FA3, 0x5D50, 0x64E5, 0x652C, 0x6B16, 0x6FEB, 0x7C43, 0x7E9C, 0x85CD, 0x8964, 0x89BD, 0x62C9, 0x81D8, 0x881F, 0x5ECA, 0x6717, 0x6D6A, 0x72FC, 0x7405, 0x746F, 0x8782, 0x90DE, 0x4F86, 0x5D0D, 0x5FA0, 0x840A, 0x51B7, 0x63A0, 0x7565, 0x4EAE, 0x5006, 0x5169, 0x51C9, 0x6881, 0x6A11, 0x7CAE, 0x7CB1, 0x7CE7, 0x826F, 0x8AD2, 0x8F1B, 0x91CF, 0x4FB6, 0x5137, 0x52F5, 0x5442, 0x5EEC, 0x616E, 0x623E, 0x65C5, 0x6ADA, 0x6FFE, 0x792A, 0x85DC, 0x8823, 0x95AD, 0x9A62, 0x9A6A, 0x9E97, 0x9ECE, 0x529B, 0x66C6, 0x6B77, 0x701D, 0x792B, 0x8F62, 0x9742, 0x6190, 0x6200, 0x6523, 0x6F23, 0x7149, 0x7489, 0x7DF4, 0x806F, 0x84EE, 0x8F26, 0x9023, 0x934A, 0x51BD, 0x5217, 0x52A3, 0x6D0C, 0x70C8, 0x88C2, 0x5EC9, 0x6582, 0x6BAE, 0x6FC2, 0x7C3E, 0x7375, 0x4EE4, 0x4F36, 0x56F9, 0xF95F, 0x5CBA, 0x5DBA, 0x601C, 0x73B2, 0x7B2D, 0x7F9A, 0x7FCE, 0x8046, 0x901E, 0x9234, 0x96F6, 0x9748, 0x9818, 0x9F61, 0x4F8B, 0x6FA7, 0x79AE, 0x91B4, 0x96B7, 0x52DE, 0xF960, 0x6488, 0x64C4, 0x6AD3, 0x6F5E, 0x7018, 0x7210, 0x76E7, 0x8001, 0x8606, 0x865C, 0x8DEF, 0x8F05, 0x9732, 0x9B6F, 0x9DFA, 0x9E75, 0x788C, 0x797F, 0x7DA0, 0x83C9, 0x9304, 0x9E7F, 0x9E93, 0x8AD6, 0x58DF, 0x5F04, 0x6727, 0x7027, 0x74CF, 0x7C60, 0x807E, 0x5121, 0x7028, 0x7262, 0x78CA, 0x8CC2, 0x8CDA, 0x8CF4, 0x96F7, 0x4E86, 0x50DA, 0x5BEE, 0x5ED6, 0x6599, 0x71CE, 0x7642, 0x77AD, 0x804A, 0x84FC, 0x907C, 0x9B27, 0x9F8D, 0x58D8, 0x5A41, 0x5C62, 0x6A13, 0x6DDA, 0x6F0F, 0x763B, 0x7D2F, 0x7E37, 0x851E, 0x8938, 0x93E4, 0x964B, 0x5289, 0x65D2, 0x67F3, 0x69B4, 0x6D41, 0x6E9C, 0x700F, 0x7409, 0x7460, 0x7559, 0x7624, 0x786B, 0x8B2C, 0x985E, 0x516D, 0x622E, 0x9678, 0x4F96, 0x502B, 0x5D19, 0x6DEA, 0x7DB8, 0x8F2A, 0x5F8B, 0x6144, 0x6817, 0xF961, 0x9686, 0x52D2, 0x808B, 0x51DC, 0x51CC, 0x695E, 0x7A1C, 0x7DBE, 0x83F1, 0x9675, 0x4FDA, 0x5229, 0x5398, 0x540F, 0x550E, 0x5C65, 0x60A7, 0x674E, 0x68A8, 0x6D6C, 0x7281, 0x72F8, 0x7406, 0x7483, 0xF962, 0x75E2, 0x7C6C, 0x7F79, 0x7FB8, 0x8389, 0x88CF, 0x88E1, 0x91CC, 0x91D0, 0x96E2, 0x9BC9, 0x541D, 0x6F7E, 0x71D0, 0x7498, 0x85FA, 0x8EAA, 0x96A3, 0x9C57, 0x9E9F, 0x6797, 0x6DCB, 0x7433, 0x81E8, 0x9716, 0x782C, 0x7ACB, 0x7B20, 0x7C92, 0x6469, 0x746A, 0x75F2, 0x78BC, 0x78E8, 0x99AC, 0x9B54, 0x9EBB, 0x5BDE, 0x5E55, 0x6F20, 0x819C, 0x83AB, 0x9088, 0x4E07, 0x534D, 0x5A29, 0x5DD2, 0x5F4E, 0x6162, 0x633D, 0x6669, 0x66FC, 0x6EFF, 0x6F2B, 0x7063, 0x779E, 0x842C, 0x8513, 0x883B, 0x8F13, 0x9945, 0x9C3B, 0x551C, 0x62B9, 0x672B, 0x6CAB, 0x8309, 0x896A, 0x977A, 0x4EA1, 0x5984, 0x5FD8, 0x5FD9, 0x671B, 0x7DB2, 0x7F54, 0x8292, 0x832B, 0x83BD, 0x8F1E, 0x9099, 0x57CB, 0x59B9, 0x5A92, 0x5BD0, 0x6627, 0x679A, 0x6885, 0x6BCF, 0x7164, 0x7F75, 0x8CB7, 0x8CE3, 0x9081, 0x9B45, 0x8108, 0x8C8A, 0x964C, 0x9A40, 0x9EA5, 0x5B5F, 0x6C13, 0x731B, 0x76F2, 0x76DF, 0x840C, 0x51AA, 0x8993, 0x514D, 0x5195, 0x52C9, 0x68C9, 0x6C94, 0x7704, 0x7720, 0x7DBF, 0x7DEC, 0x9762, 0x9EB5, 0x6EC5, 0x8511, 0x51A5, 0x540D, 0x547D, 0x660E, 0x669D, 0x6927, 0x6E9F, 0x76BF, 0x7791, 0x8317, 0x84C2, 0x879F, 0x9169, 0x9298, 0x9CF4, 0x8882, 0x4FAE, 0x5192, 0x52DF, 0x59C6, 0x5E3D, 0x6155, 0x6478, 0x6479, 0x66AE, 0x67D0, 0x6A21, 0x6BCD, 0x6BDB, 0x725F, 0x7261, 0x7441, 0x7738, 0x77DB, 0x8017, 0x82BC, 0x8305, 0x8B00, 0x8B28, 0x8C8C, 0x6728, 0x6C90, 0x7267, 0x76EE, 0x7766, 0x7A46, 0x9DA9, 0x6B7F, 0x6C92, 0x5922, 0x6726, 0x8499, 0x536F, 0x5893, 0x5999, 0x5EDF, 0x63CF, 0x6634, 0x6773, 0x6E3A, 0x732B, 0x7AD7, 0x82D7, 0x9328, 0x52D9, 0x5DEB, 0x61AE, 0x61CB, 0x620A, 0x62C7, 0x64AB, 0x65E0, 0x6959, 0x6B66, 0x6BCB, 0x7121, 0x73F7, 0x755D, 0x7E46, 0x821E, 0x8302, 0x856A, 0x8AA3, 0x8CBF, 0x9727, 0x9D61, 0x58A8, 0x9ED8, 0x5011, 0x520E, 0x543B, 0x554F, 0x6587, 0x6C76, 0x7D0A, 0x7D0B, 0x805E, 0x868A, 0x9580, 0x96EF, 0x52FF, 0x6C95, 0x7269, 0x5473, 0x5A9A, 0x5C3E, 0x5D4B, 0x5F4C, 0x5FAE, 0x672A, 0x68B6, 0x6963, 0x6E3C, 0x6E44, 0x7709, 0x7C73, 0x7F8E, 0x8587, 0x8B0E, 0x8FF7, 0x9761, 0x9EF4, 0x5CB7, 0x60B6, 0x610D, 0x61AB, 0x654F, 0x65FB, 0x65FC, 0x6C11, 0x6CEF, 0x739F, 0x73C9, 0x7DE1, 0x9594, 0x5BC6, 0x871C, 0x8B10, 0x525D, 0x535A, 0x62CD, 0x640F, 0x64B2, 0x6734, 0x6A38, 0x6CCA, 0x73C0, 0x749E, 0x7B94, 0x7C95, 0x7E1B, 0x818A, 0x8236, 0x8584, 0x8FEB, 0x96F9, 0x99C1, 0x4F34, 0x534A, 0x53CD, 0x53DB, 0x62CC, 0x642C, 0x6500, 0x6591, 0x69C3, 0x6CEE, 0x6F58, 0x73ED, 0x7554, 0x7622, 0x76E4, 0x76FC, 0x78D0, 0x78FB, 0x792C, 0x7D46, 0x822C, 0x87E0, 0x8FD4, 0x9812, 0x98EF, 0x52C3, 0x62D4, 0x64A5, 0x6E24, 0x6F51, 0x767C, 0x8DCB, 0x91B1, 0x9262, 0x9AEE, 0x9B43, 0x5023, 0x508D, 0x574A, 0x59A8, 0x5C28, 0x5E47, 0x5F77, 0x623F, 0x653E, 0x65B9, 0x65C1, 0x6609, 0x678B, 0x699C, 0x6EC2, 0x78C5, 0x7D21, 0x80AA, 0x8180, 0x822B, 0x82B3, 0x84A1, 0x868C, 0x8A2A, 0x8B17, 0x90A6, 0x9632, 0x9F90, 0x500D, 0x4FF3, 0xF963, 0x57F9, 0x5F98, 0x62DC, 0x6392, 0x676F, 0x6E43, 0x7119, 0x76C3, 0x80CC, 0x80DA, 0x88F4, 0x88F5, 0x8919, 0x8CE0, 0x8F29, 0x914D, 0x966A, 0x4F2F, 0x4F70, 0x5E1B, 0x67CF, 0x6822, 0x767D, 0x767E, 0x9B44, 0x5E61, 0x6A0A, 0x7169, 0x71D4, 0x756A, 0xF964, 0x7E41, 0x8543, 0x85E9, 0x98DC, 0x4F10, 0x7B4F, 0x7F70, 0x95A5, 0x51E1, 0x5E06, 0x68B5, 0x6C3E, 0x6C4E, 0x6CDB, 0x72AF, 0x7BC4, 0x8303, 0x6CD5, 0x743A, 0x50FB, 0x5288, 0x58C1, 0x64D8, 0x6A97, 0x74A7, 0x7656, 0x78A7, 0x8617, 0x95E2, 0x9739, 0xF965, 0x535E, 0x5F01, 0x8B8A, 0x8FA8, 0x8FAF, 0x908A, 0x5225, 0x77A5, 0x9C49, 0x9F08, 0x4E19, 0x5002, 0x5175, 0x5C5B, 0x5E77, 0x661E, 0x663A, 0x67C4, 0x68C5, 0x70B3, 0x7501, 0x75C5, 0x79C9, 0x7ADD, 0x8F27, 0x9920, 0x9A08, 0x4FDD, 0x5821, 0x5831, 0x5BF6, 0x666E, 0x6B65, 0x6D11, 0x6E7A, 0x6F7D, 0x73E4, 0x752B, 0x83E9, 0x88DC, 0x8913, 0x8B5C, 0x8F14, 0x4F0F, 0x50D5, 0x5310, 0x535C, 0x5B93, 0x5FA9, 0x670D, 0x798F, 0x8179, 0x832F, 0x8514, 0x8907, 0x8986, 0x8F39, 0x8F3B, 0x99A5, 0x9C12, 0x672C, 0x4E76, 0x4FF8, 0x5949, 0x5C01, 0x5CEF, 0x5CF0, 0x6367, 0x68D2, 0x70FD, 0x71A2, 0x742B, 0x7E2B, 0x84EC, 0x8702, 0x9022, 0x92D2, 0x9CF3, 0x4E0D, 0x4ED8, 0x4FEF, 0x5085, 0x5256, 0x526F, 0x5426, 0x5490, 0x57E0, 0x592B, 0x5A66, 0x5B5A, 0x5B75, 0x5BCC, 0x5E9C, 0xF966, 0x6276, 0x6577, 0x65A7, 0x6D6E, 0x6EA5, 0x7236, 0x7B26, 0x7C3F, 0x7F36, 0x8150, 0x8151, 0x819A, 0x8240, 0x8299, 0x83A9, 0x8A03, 0x8CA0, 0x8CE6, 0x8CFB, 0x8D74, 0x8DBA, 0x90E8, 0x91DC, 0x961C, 0x9644, 0x99D9, 0x9CE7, 0x5317, 0x5206, 0x5429, 0x5674, 0x58B3, 0x5954, 0x596E, 0x5FFF, 0x61A4, 0x626E, 0x6610, 0x6C7E, 0x711A, 0x76C6, 0x7C89, 0x7CDE, 0x7D1B, 0x82AC, 0x8CC1, 0x96F0, 0xF967, 0x4F5B, 0x5F17, 0x5F7F, 0x62C2, 0x5D29, 0x670B, 0x68DA, 0x787C, 0x7E43, 0x9D6C, 0x4E15, 0x5099, 0x5315, 0x532A, 0x5351, 0x5983, 0x5A62, 0x5E87, 0x60B2, 0x618A, 0x6249, 0x6279, 0x6590, 0x6787, 0x69A7, 0x6BD4, 0x6BD6, 0x6BD7, 0x6BD8, 0x6CB8, 0xF968, 0x7435, 0x75FA, 0x7812, 0x7891, 0x79D5, 0x79D8, 0x7C83, 0x7DCB, 0x7FE1, 0x80A5, 0x813E, 0x81C2, 0x83F2, 0x871A, 0x88E8, 0x8AB9, 0x8B6C, 0x8CBB, 0x9119, 0x975E, 0x98DB, 0x9F3B, 0x56AC, 0x5B2A, 0x5F6C, 0x658C, 0x6AB3, 0x6BAF, 0x6D5C, 0x6FF1, 0x7015, 0x725D, 0x73AD, 0x8CA7, 0x8CD3, 0x983B, 0x6191, 0x6C37, 0x8058, 0x9A01, 0x4E4D, 0x4E8B, 0x4E9B, 0x4ED5, 0x4F3A, 0x4F3C, 0x4F7F, 0x4FDF, 0x50FF, 0x53F2, 0x53F8, 0x5506, 0x55E3, 0x56DB, 0x58EB, 0x5962, 0x5A11, 0x5BEB, 0x5BFA, 0x5C04, 0x5DF3, 0x5E2B, 0x5F99, 0x601D, 0x6368, 0x659C, 0x65AF, 0x67F6, 0x67FB, 0x68AD, 0x6B7B, 0x6C99, 0x6CD7, 0x6E23, 0x7009, 0x7345, 0x7802, 0x793E, 0x7940, 0x7960, 0x79C1, 0x7BE9, 0x7D17, 0x7D72, 0x8086, 0x820D, 0x838E, 0x84D1, 0x86C7, 0x88DF, 0x8A50, 0x8A5E, 0x8B1D, 0x8CDC, 0x8D66, 0x8FAD, 0x90AA, 0x98FC, 0x99DF, 0x9E9D, 0x524A, 0xF969, 0x6714, 0xF96A, 0x5098, 0x522A, 0x5C71, 0x6563, 0x6C55, 0x73CA, 0x7523, 0x759D, 0x7B97, 0x849C, 0x9178, 0x9730, 0x4E77, 0x6492, 0x6BBA, 0x715E, 0x85A9, 0x4E09, 0xF96B, 0x6749, 0x68EE, 0x6E17, 0x829F, 0x8518, 0x886B, 0x63F7, 0x6F81, 0x9212, 0x98AF, 0x4E0A, 0x50B7, 0x50CF, 0x511F, 0x5546, 0x55AA, 0x5617, 0x5B40, 0x5C19, 0x5CE0, 0x5E38, 0x5E8A, 0x5EA0, 0x5EC2, 0x60F3, 0x6851, 0x6A61, 0x6E58, 0x723D, 0x7240, 0x72C0, 0x76F8, 0x7965, 0x7BB1, 0x7FD4, 0x88F3, 0x89F4, 0x8A73, 0x8C61, 0x8CDE, 0x971C, 0x585E, 0x74BD, 0x8CFD, 0x55C7, 0xF96C, 0x7A61, 0x7D22, 0x8272, 0x7272, 0x751F, 0x7525, 0xF96D, 0x7B19, 0x5885, 0x58FB, 0x5DBC, 0x5E8F, 0x5EB6, 0x5F90, 0x6055, 0x6292, 0x637F, 0x654D, 0x6691, 0x66D9, 0x66F8, 0x6816, 0x68F2, 0x7280, 0x745E, 0x7B6E, 0x7D6E, 0x7DD6, 0x7F72, 0x80E5, 0x8212, 0x85AF, 0x897F, 0x8A93, 0x901D, 0x92E4, 0x9ECD, 0x9F20, 0x5915, 0x596D, 0x5E2D, 0x60DC, 0x6614, 0x6673, 0x6790, 0x6C50, 0x6DC5, 0x6F5F, 0x77F3, 0x78A9, 0x84C6, 0x91CB, 0x932B, 0x4ED9, 0x50CA, 0x5148, 0x5584, 0x5B0B, 0x5BA3, 0x6247, 0x657E, 0x65CB, 0x6E32, 0x717D, 0x7401, 0x7444, 0x7487, 0x74BF, 0x766C, 0x79AA, 0x7DDA, 0x7E55, 0x7FA8, 0x817A, 0x81B3, 0x8239, 0x861A, 0x87EC, 0x8A75, 0x8DE3, 0x9078, 0x9291, 0x9425, 0x994D, 0x9BAE, 0x5368, 0x5C51, 0x6954, 0x6CC4, 0x6D29, 0x6E2B, 0x820C, 0x859B, 0x893B, 0x8A2D, 0x8AAA, 0x96EA, 0x9F67, 0x5261, 0x66B9, 0x6BB2, 0x7E96, 0x87FE, 0x8D0D, 0x9583, 0x965D, 0x651D, 0x6D89, 0x71EE, 0xF96E, 0x57CE, 0x59D3, 0x5BAC, 0x6027, 0x60FA, 0x6210, 0x661F, 0x665F, 0x7329, 0x73F9, 0x76DB, 0x7701, 0x7B6C, 0x8056, 0x8072, 0x8165, 0x8AA0, 0x9192, 0x4E16, 0x52E2, 0x6B72, 0x6D17, 0x7A05, 0x7B39, 0x7D30, 0xF96F, 0x8CB0, 0x53EC, 0x562F, 0x5851, 0x5BB5, 0x5C0F, 0x5C11, 0x5DE2, 0x6240, 0x6383, 0x6414, 0x662D, 0x68B3, 0x6CBC, 0x6D88, 0x6EAF, 0x701F, 0x70A4, 0x71D2, 0x7526, 0x758F, 0x758E, 0x7619, 0x7B11, 0x7BE0, 0x7C2B, 0x7D20, 0x7D39, 0x852C, 0x856D, 0x8607, 0x8A34, 0x900D, 0x9061, 0x90B5, 0x92B7, 0x97F6, 0x9A37, 0x4FD7, 0x5C6C, 0x675F, 0x6D91, 0x7C9F, 0x7E8C, 0x8B16, 0x8D16, 0x901F, 0x5B6B, 0x5DFD, 0x640D, 0x84C0, 0x905C, 0x98E1, 0x7387, 0x5B8B, 0x609A, 0x677E, 0x6DDE, 0x8A1F, 0x8AA6, 0x9001, 0x980C, 0x5237, 0xF970, 0x7051, 0x788E, 0x9396, 0x8870, 0x91D7, 0x4FEE, 0x53D7, 0x55FD, 0x56DA, 0x5782, 0x58FD, 0x5AC2, 0x5B88, 0x5CAB, 0x5CC0, 0x5E25, 0x6101, 0x620D, 0x624B, 0x6388, 0x641C, 0x6536, 0x6578, 0x6A39, 0x6B8A, 0x6C34, 0x6D19, 0x6F31, 0x71E7, 0x72E9, 0x7378, 0x7407, 0x74B2, 0x7626, 0x7761, 0x79C0, 0x7A57, 0x7AEA, 0x7CB9, 0x7D8F, 0x7DAC, 0x7E61, 0x7F9E, 0x8129, 0x8331, 0x8490, 0x84DA, 0x85EA, 0x8896, 0x8AB0, 0x8B90, 0x8F38, 0x9042, 0x9083, 0x916C, 0x9296, 0x92B9, 0x968B, 0x96A7, 0x96A8, 0x96D6, 0x9700, 0x9808, 0x9996, 0x9AD3, 0x9B1A, 0x53D4, 0x587E, 0x5919, 0x5B70, 0x5BBF, 0x6DD1, 0x6F5A, 0x719F, 0x7421, 0x74B9, 0x8085, 0x83FD, 0x5DE1, 0x5F87, 0x5FAA, 0x6042, 0x65EC, 0x6812, 0x696F, 0x6A53, 0x6B89, 0x6D35, 0x6DF3, 0x73E3, 0x76FE, 0x77AC, 0x7B4D, 0x7D14, 0x8123, 0x821C, 0x8340, 0x84F4, 0x8563, 0x8A62, 0x8AC4, 0x9187, 0x931E, 0x9806, 0x99B4, 0x620C, 0x8853, 0x8FF0, 0x9265, 0x5D07, 0x5D27, 0x5D69, 0x745F, 0x819D, 0x8768, 0x6FD5, 0x62FE, 0x7FD2, 0x8936, 0x8972, 0x4E1E, 0x4E58, 0x50E7, 0x52DD, 0x5347, 0x627F, 0x6607, 0x7E69, 0x8805, 0x965E, 0x4F8D, 0x5319, 0x5636, 0x59CB, 0x5AA4, 0x5C38, 0x5C4E, 0x5C4D, 0x5E02, 0x5F11, 0x6043, 0x65BD, 0x662F, 0x6642, 0x67BE, 0x67F4, 0x731C, 0x77E2, 0x793A, 0x7FC5, 0x8494, 0x84CD, 0x8996, 0x8A66, 0x8A69, 0x8AE1, 0x8C55, 0x8C7A, 0x57F4, 0x5BD4, 0x5F0F, 0x606F, 0x62ED, 0x690D, 0x6B96, 0x6E5C, 0x7184, 0x7BD2, 0x8755, 0x8B58, 0x8EFE, 0x98DF, 0x98FE, 0x4F38, 0x4F81, 0x4FE1, 0x547B, 0x5A20, 0x5BB8, 0x613C, 0x65B0, 0x6668, 0x71FC, 0x7533, 0x795E, 0x7D33, 0x814E, 0x81E3, 0x8398, 0x85AA, 0x85CE, 0x8703, 0x8A0A, 0x8EAB, 0x8F9B, 0xF971, 0x8FC5, 0x5931, 0x5BA4, 0x5BE6, 0x6089, 0x5BE9, 0x5C0B, 0x5FC3, 0x6C81, 0xF972, 0x6DF1, 0x700B, 0x751A, 0x82AF, 0x8AF6, 0x4EC0, 0x5341, 0xF973, 0x96D9, 0x6C0F, 0x4E9E, 0x4FC4, 0x5152, 0x555E, 0x5A25, 0x5CE8, 0x6211, 0x7259, 0x82BD, 0x83AA, 0x86FE, 0x8859, 0x8A1D, 0x963F, 0x96C5, 0x9913, 0x9D09, 0x9D5D, 0x580A, 0x5CB3, 0x5DBD, 0x5E44, 0x60E1, 0x6115, 0x63E1, 0x6A02, 0x6E25, 0x9102, 0x9354, 0x984E, 0x9C10, 0x9F77, 0x5B89, 0x5CB8, 0x6309, 0x664F, 0x6848, 0x773C, 0x96C1, 0x978D, 0x9854, 0x9B9F, 0x65A1, 0x8B01, 0x8ECB, 0x95BC, 0x5535, 0x5CA9, 0x5DD6, 0x5EB5, 0x6697, 0x764C, 0x83F4, 0x95C7, 0x58D3, 0x62BC, 0x72CE, 0x9D28, 0x4EF0, 0x592E, 0x600F, 0x663B, 0x6B83, 0x79E7, 0x9D26, 0x5393, 0x54C0, 0x57C3, 0x5D16, 0x611B, 0x66D6, 0x6DAF, 0x788D, 0x827E, 0x9698, 0x9744, 0x5384, 0x627C, 0x6396, 0x6DB2, 0x7E0A, 0x814B, 0x984D, 0x6AFB, 0x7F4C, 0x9DAF, 0x9E1A, 0x4E5F, 0x503B, 0x51B6, 0x591C, 0x60F9, 0x63F6, 0x6930, 0x723A, 0x8036, 0xF974, 0x91CE, 0x5F31, 0xF975, 0xF976, 0x7D04, 0x82E5, 0x846F, 0x84BB, 0x85E5, 0x8E8D, 0xF977, 0x4F6F, 0xF978, 0xF979, 0x58E4, 0x5B43, 0x6059, 0x63DA, 0x6518, 0x656D, 0x6698, 0xF97A, 0x694A, 0x6A23, 0x6D0B, 0x7001, 0x716C, 0x75D2, 0x760D, 0x79B3, 0x7A70, 0xF97B, 0x7F8A, 0xF97C, 0x8944, 0xF97D, 0x8B93, 0x91C0, 0x967D, 0xF97E, 0x990A, 0x5704, 0x5FA1, 0x65BC, 0x6F01, 0x7600, 0x79A6, 0x8A9E, 0x99AD, 0x9B5A, 0x9F6C, 0x5104, 0x61B6, 0x6291, 0x6A8D, 0x81C6, 0x5043, 0x5830, 0x5F66, 0x7109, 0x8A00, 0x8AFA, 0x5B7C, 0x8616, 0x4FFA, 0x513C, 0x56B4, 0x5944, 0x63A9, 0x6DF9, 0x5DAA, 0x696D, 0x5186, 0x4E88, 0x4F59, 0xF97F, 0xF980, 0xF981, 0x5982, 0xF982, 0xF983, 0x6B5F, 0x6C5D, 0xF984, 0x74B5, 0x7916, 0xF985, 0x8207, 0x8245, 0x8339, 0x8F3F, 0x8F5D, 0xF986, 0x9918, 0xF987, 0xF988, 0xF989, 0x4EA6, 0xF98A, 0x57DF, 0x5F79, 0x6613, 0xF98B, 0xF98C, 0x75AB, 0x7E79, 0x8B6F, 0xF98D, 0x9006, 0x9A5B, 0x56A5, 0x5827, 0x59F8, 0x5A1F, 0x5BB4, 0xF98E, 0x5EF6, 0xF98F, 0xF990, 0x6350, 0x633B, 0xF991, 0x693D, 0x6C87, 0x6CBF, 0x6D8E, 0x6D93, 0x6DF5, 0x6F14, 0xF992, 0x70DF, 0x7136, 0x7159, 0xF993, 0x71C3, 0x71D5, 0xF994, 0x784F, 0x786F, 0xF995, 0x7B75, 0x7DE3, 0xF996, 0x7E2F, 0xF997, 0x884D, 0x8EDF, 0xF998, 0xF999, 0xF99A, 0x925B, 0xF99B, 0x9CF6, 0xF99C, 0xF99D, 0xF99E, 0x6085, 0x6D85, 0xF99F, 0x71B1, 0xF9A0, 0xF9A1, 0x95B1, 0x53AD, 0xF9A2, 0xF9A3, 0xF9A4, 0x67D3, 0xF9A5, 0x708E, 0x7130, 0x7430, 0x8276, 0x82D2, 0xF9A6, 0x95BB, 0x9AE5, 0x9E7D, 0x66C4, 0xF9A7, 0x71C1, 0x8449, 0xF9A8, 0xF9A9, 0x584B, 0xF9AA, 0xF9AB, 0x5DB8, 0x5F71, 0xF9AC, 0x6620, 0x668E, 0x6979, 0x69AE, 0x6C38, 0x6CF3, 0x6E36, 0x6F41, 0x6FDA, 0x701B, 0x702F, 0x7150, 0x71DF, 0x7370, 0xF9AD, 0x745B, 0xF9AE, 0x74D4, 0x76C8, 0x7A4E, 0x7E93, 0xF9AF, 0xF9B0, 0x82F1, 0x8A60, 0x8FCE, 0xF9B1, 0x9348, 0xF9B2, 0x9719, 0xF9B3, 0xF9B4, 0x4E42, 0x502A, 0xF9B5, 0x5208, 0x53E1, 0x66F3, 0x6C6D, 0x6FCA, 0x730A, 0x777F, 0x7A62, 0x82AE, 0x85DD, 0x8602, 0xF9B6, 0x88D4, 0x8A63, 0x8B7D, 0x8C6B, 0xF9B7, 0x92B3, 0xF9B8, 0x9713, 0x9810, 0x4E94, 0x4F0D, 0x4FC9, 0x50B2, 0x5348, 0x543E, 0x5433, 0x55DA, 0x5862, 0x58BA, 0x5967, 0x5A1B, 0x5BE4, 0x609F, 0xF9B9, 0x61CA, 0x6556, 0x65FF, 0x6664, 0x68A7, 0x6C5A, 0x6FB3, 0x70CF, 0x71AC, 0x7352, 0x7B7D, 0x8708, 0x8AA4, 0x9C32, 0x9F07, 0x5C4B, 0x6C83, 0x7344, 0x7389, 0x923A, 0x6EAB, 0x7465, 0x761F, 0x7A69, 0x7E15, 0x860A, 0x5140, 0x58C5, 0x64C1, 0x74EE, 0x7515, 0x7670, 0x7FC1, 0x9095, 0x96CD, 0x9954, 0x6E26, 0x74E6, 0x7AA9, 0x7AAA, 0x81E5, 0x86D9, 0x8778, 0x8A1B, 0x5A49, 0x5B8C, 0x5B9B, 0x68A1, 0x6900, 0x6D63, 0x73A9, 0x7413, 0x742C, 0x7897, 0x7DE9, 0x7FEB, 0x8118, 0x8155, 0x839E, 0x8C4C, 0x962E, 0x9811, 0x66F0, 0x5F80, 0x65FA, 0x6789, 0x6C6A, 0x738B, 0x502D, 0x5A03, 0x6B6A, 0x77EE, 0x5916, 0x5D6C, 0x5DCD, 0x7325, 0x754F, 0xF9BA, 0xF9BB, 0x50E5, 0x51F9, 0x582F, 0x592D, 0x5996, 0x59DA, 0x5BE5, 0xF9BC, 0xF9BD, 0x5DA2, 0x62D7, 0x6416, 0x6493, 0x64FE, 0xF9BE, 0x66DC, 0xF9BF, 0x6A48, 0xF9C0, 0x71FF, 0x7464, 0xF9C1, 0x7A88, 0x7AAF, 0x7E47, 0x7E5E, 0x8000, 0x8170, 0xF9C2, 0x87EF, 0x8981, 0x8B20, 0x9059, 0xF9C3, 0x9080, 0x9952, 0x617E, 0x6B32, 0x6D74, 0x7E1F, 0x8925, 0x8FB1, 0x4FD1, 0x50AD, 0x5197, 0x52C7, 0x57C7, 0x5889, 0x5BB9, 0x5EB8, 0x6142, 0x6995, 0x6D8C, 0x6E67, 0x6EB6, 0x7194, 0x7462, 0x7528, 0x752C, 0x8073, 0x8338, 0x84C9, 0x8E0A, 0x9394, 0x93DE, 0xF9C4, 0x4E8E, 0x4F51, 0x5076, 0x512A, 0x53C8, 0x53CB, 0x53F3, 0x5B87, 0x5BD3, 0x5C24, 0x611A, 0x6182, 0x65F4, 0x725B, 0x7397, 0x7440, 0x76C2, 0x7950, 0x7991, 0x79B9, 0x7D06, 0x7FBD, 0x828B, 0x85D5, 0x865E, 0x8FC2, 0x9047, 0x90F5, 0x91EA, 0x9685, 0x96E8, 0x96E9, 0x52D6, 0x5F67, 0x65ED, 0x6631, 0x682F, 0x715C, 0x7A36, 0x90C1, 0x980A, 0x4E91, 0xF9C5, 0x6A52, 0x6B9E, 0x6F90, 0x7189, 0x8018, 0x82B8, 0x8553, 0x904B, 0x9695, 0x96F2, 0x97FB, 0x851A, 0x9B31, 0x4E90, 0x718A, 0x96C4, 0x5143, 0x539F, 0x54E1, 0x5713, 0x5712, 0x57A3, 0x5A9B, 0x5AC4, 0x5BC3, 0x6028, 0x613F, 0x63F4, 0x6C85, 0x6D39, 0x6E72, 0x6E90, 0x7230, 0x733F, 0x7457, 0x82D1, 0x8881, 0x8F45, 0x9060, 0xF9C6, 0x9662, 0x9858, 0x9D1B, 0x6708, 0x8D8A, 0x925E, 0x4F4D, 0x5049, 0x50DE, 0x5371, 0x570D, 0x59D4, 0x5A01, 0x5C09, 0x6170, 0x6690, 0x6E2D, 0x7232, 0x744B, 0x7DEF, 0x80C3, 0x840E, 0x8466, 0x853F, 0x875F, 0x885B, 0x8918, 0x8B02, 0x9055, 0x97CB, 0x9B4F, 0x4E73, 0x4F91, 0x5112, 0x516A, 0xF9C7, 0x552F, 0x55A9, 0x5B7A, 0x5BA5, 0x5E7C, 0x5E7D, 0x5EBE, 0x60A0, 0x60DF, 0x6108, 0x6109, 0x63C4, 0x6538, 0x6709, 0xF9C8, 0x67D4, 0x67DA, 0xF9C9, 0x6961, 0x6962, 0x6CB9, 0x6D27, 0xF9CA, 0x6E38, 0xF9CB, 0x6FE1, 0x7336, 0x7337, 0xF9CC, 0x745C, 0x7531, 0xF9CD, 0x7652, 0xF9CE, 0xF9CF, 0x7DAD, 0x81FE, 0x8438, 0x88D5, 0x8A98, 0x8ADB, 0x8AED, 0x8E30, 0x8E42, 0x904A, 0x903E, 0x907A, 0x9149, 0x91C9, 0x936E, 0xF9D0, 0xF9D1, 0x5809, 0xF9D2, 0x6BD3, 0x8089, 0x80B2, 0xF9D3, 0xF9D4, 0x5141, 0x596B, 0x5C39, 0xF9D5, 0xF9D6, 0x6F64, 0x73A7, 0x80E4, 0x8D07, 0xF9D7, 0x9217, 0x958F, 0xF9D8, 0xF9D9, 0xF9DA, 0xF9DB, 0x807F, 0x620E, 0x701C, 0x7D68, 0x878D, 0xF9DC, 0x57A0, 0x6069, 0x6147, 0x6BB7, 0x8ABE, 0x9280, 0x96B1, 0x4E59, 0x541F, 0x6DEB, 0x852D, 0x9670, 0x97F3, 0x98EE, 0x63D6, 0x6CE3, 0x9091, 0x51DD, 0x61C9, 0x81BA, 0x9DF9, 0x4F9D, 0x501A, 0x5100, 0x5B9C, 0x610F, 0x61FF, 0x64EC, 0x6905, 0x6BC5, 0x7591, 0x77E3, 0x7FA9, 0x8264, 0x858F, 0x87FB, 0x8863, 0x8ABC, 0x8B70, 0x91AB, 0x4E8C, 0x4EE5, 0x4F0A, 0xF9DD, 0xF9DE, 0x5937, 0x59E8, 0xF9DF, 0x5DF2, 0x5F1B, 0x5F5B, 0x6021, 0xF9E0, 0xF9E1, 0xF9E2, 0xF9E3, 0x723E, 0x73E5, 0xF9E4, 0x7570, 0x75CD, 0xF9E5, 0x79FB, 0xF9E6, 0x800C, 0x8033, 0x8084, 0x82E1, 0x8351, 0xF9E7, 0xF9E8, 0x8CBD, 0x8CB3, 0x9087, 0xF9E9, 0xF9EA, 0x98F4, 0x990C, 0xF9EB, 0xF9EC, 0x7037, 0x76CA, 0x7FCA, 0x7FCC, 0x7FFC, 0x8B1A, 0x4EBA, 0x4EC1, 0x5203, 0x5370, 0xF9ED, 0x54BD, 0x56E0, 0x59FB, 0x5BC5, 0x5F15, 0x5FCD, 0x6E6E, 0xF9EE, 0xF9EF, 0x7D6A, 0x8335, 0xF9F0, 0x8693, 0x8A8D, 0xF9F1, 0x976D, 0x9777, 0xF9F2, 0xF9F3, 0x4E00, 0x4F5A, 0x4F7E, 0x58F9, 0x65E5, 0x6EA2, 0x9038, 0x93B0, 0x99B9, 0x4EFB, 0x58EC, 0x598A, 0x59D9, 0x6041, 0xF9F4, 0xF9F5, 0x7A14, 0xF9F6, 0x834F, 0x8CC3, 0x5165, 0x5344, 0xF9F7, 0xF9F8, 0xF9F9, 0x4ECD, 0x5269, 0x5B55, 0x82BF, 0x4ED4, 0x523A, 0x54A8, 0x59C9, 0x59FF, 0x5B50, 0x5B57, 0x5B5C, 0x6063, 0x6148, 0x6ECB, 0x7099, 0x716E, 0x7386, 0x74F7, 0x75B5, 0x78C1, 0x7D2B, 0x8005, 0x81EA, 0x8328, 0x8517, 0x85C9, 0x8AEE, 0x8CC7, 0x96CC, 0x4F5C, 0x52FA, 0x56BC, 0x65AB, 0x6628, 0x707C, 0x70B8, 0x7235, 0x7DBD, 0x828D, 0x914C, 0x96C0, 0x9D72, 0x5B71, 0x68E7, 0x6B98, 0x6F7A, 0x76DE, 0x5C91, 0x66AB, 0x6F5B, 0x7BB4, 0x7C2A, 0x8836, 0x96DC, 0x4E08, 0x4ED7, 0x5320, 0x5834, 0x58BB, 0x58EF, 0x596C, 0x5C07, 0x5E33, 0x5E84, 0x5F35, 0x638C, 0x66B2, 0x6756, 0x6A1F, 0x6AA3, 0x6B0C, 0x6F3F, 0x7246, 0xF9FA, 0x7350, 0x748B, 0x7AE0, 0x7CA7, 0x8178, 0x81DF, 0x81E7, 0x838A, 0x846C, 0x8523, 0x8594, 0x85CF, 0x88DD, 0x8D13, 0x91AC, 0x9577, 0x969C, 0x518D, 0x54C9, 0x5728, 0x5BB0, 0x624D, 0x6750, 0x683D, 0x6893, 0x6E3D, 0x6ED3, 0x707D, 0x7E21, 0x88C1, 0x8CA1, 0x8F09, 0x9F4B, 0x9F4E, 0x722D, 0x7B8F, 0x8ACD, 0x931A, 0x4F47, 0x4F4E, 0x5132, 0x5480, 0x59D0, 0x5E95, 0x62B5, 0x6775, 0x696E, 0x6A17, 0x6CAE, 0x6E1A, 0x72D9, 0x732A, 0x75BD, 0x7BB8, 0x7D35, 0x82E7, 0x83F9, 0x8457, 0x85F7, 0x8A5B, 0x8CAF, 0x8E87, 0x9019, 0x90B8, 0x96CE, 0x9F5F, 0x52E3, 0x540A, 0x5AE1, 0x5BC2, 0x6458, 0x6575, 0x6EF4, 0x72C4, 0xF9FB, 0x7684, 0x7A4D, 0x7B1B, 0x7C4D, 0x7E3E, 0x7FDF, 0x837B, 0x8B2B, 0x8CCA, 0x8D64, 0x8DE1, 0x8E5F, 0x8FEA, 0x8FF9, 0x9069, 0x93D1, 0x4F43, 0x4F7A, 0x50B3, 0x5168, 0x5178, 0x524D, 0x526A, 0x5861, 0x587C, 0x5960, 0x5C08, 0x5C55, 0x5EDB, 0x609B, 0x6230, 0x6813, 0x6BBF, 0x6C08, 0x6FB1, 0x714E, 0x7420, 0x7530, 0x7538, 0x7551, 0x7672, 0x7B4C, 0x7B8B, 0x7BAD, 0x7BC6, 0x7E8F, 0x8A6E, 0x8F3E, 0x8F49, 0x923F, 0x9293, 0x9322, 0x942B, 0x96FB, 0x985A, 0x986B, 0x991E, 0x5207, 0x622A, 0x6298, 0x6D59, 0x7664, 0x7ACA, 0x7BC0, 0x7D76, 0x5360, 0x5CBE, 0x5E97, 0x6F38, 0x70B9, 0x7C98, 0x9711, 0x9B8E, 0x9EDE, 0x63A5, 0x647A, 0x8776, 0x4E01, 0x4E95, 0x4EAD, 0x505C, 0x5075, 0x5448, 0x59C3, 0x5B9A, 0x5E40, 0x5EAD, 0x5EF7, 0x5F81, 0x60C5, 0x633A, 0x653F, 0x6574, 0x65CC, 0x6676, 0x6678, 0x67FE, 0x6968, 0x6A89, 0x6B63, 0x6C40, 0x6DC0, 0x6DE8, 0x6E1F, 0x6E5E, 0x701E, 0x70A1, 0x738E, 0x73FD, 0x753A, 0x775B, 0x7887, 0x798E, 0x7A0B, 0x7A7D, 0x7CBE, 0x7D8E, 0x8247, 0x8A02, 0x8AEA, 0x8C9E, 0x912D, 0x914A, 0x91D8, 0x9266, 0x92CC, 0x9320, 0x9706, 0x9756, 0x975C, 0x9802, 0x9F0E, 0x5236, 0x5291, 0x557C, 0x5824, 0x5E1D, 0x5F1F, 0x608C, 0x63D0, 0x68AF, 0x6FDF, 0x796D, 0x7B2C, 0x81CD, 0x85BA, 0x88FD, 0x8AF8, 0x8E44, 0x918D, 0x9664, 0x969B, 0x973D, 0x984C, 0x9F4A, 0x4FCE, 0x5146, 0x51CB, 0x52A9, 0x5632, 0x5F14, 0x5F6B, 0x63AA, 0x64CD, 0x65E9, 0x6641, 0x66FA, 0x66F9, 0x671D, 0x689D, 0x68D7, 0x69FD, 0x6F15, 0x6F6E, 0x7167, 0x71E5, 0x722A, 0x74AA, 0x773A, 0x7956, 0x795A, 0x79DF, 0x7A20, 0x7A95, 0x7C97, 0x7CDF, 0x7D44, 0x7E70, 0x8087, 0x85FB, 0x86A4, 0x8A54, 0x8ABF, 0x8D99, 0x8E81, 0x9020, 0x906D, 0x91E3, 0x963B, 0x96D5, 0x9CE5, 0x65CF, 0x7C07, 0x8DB3, 0x93C3, 0x5B58, 0x5C0A, 0x5352, 0x62D9, 0x731D, 0x5027, 0x5B97, 0x5F9E, 0x60B0, 0x616B, 0x68D5, 0x6DD9, 0x742E, 0x7A2E, 0x7D42, 0x7D9C, 0x7E31, 0x816B, 0x8E2A, 0x8E35, 0x937E, 0x9418, 0x4F50, 0x5750, 0x5DE6, 0x5EA7, 0x632B, 0x7F6A, 0x4E3B, 0x4F4F, 0x4F8F, 0x505A, 0x59DD, 0x80C4, 0x546A, 0x5468, 0x55FE, 0x594F, 0x5B99, 0x5DDE, 0x5EDA, 0x665D, 0x6731, 0x67F1, 0x682A, 0x6CE8, 0x6D32, 0x6E4A, 0x6F8D, 0x70B7, 0x73E0, 0x7587, 0x7C4C, 0x7D02, 0x7D2C, 0x7DA2, 0x821F, 0x86DB, 0x8A3B, 0x8A85, 0x8D70, 0x8E8A, 0x8F33, 0x9031, 0x914E, 0x9152, 0x9444, 0x99D0, 0x7AF9, 0x7CA5, 0x4FCA, 0x5101, 0x51C6, 0x57C8, 0x5BEF, 0x5CFB, 0x6659, 0x6A3D, 0x6D5A, 0x6E96, 0x6FEC, 0x710C, 0x756F, 0x7AE3, 0x8822, 0x9021, 0x9075, 0x96CB, 0x99FF, 0x8301, 0x4E2D, 0x4EF2, 0x8846, 0x91CD, 0x537D, 0x6ADB, 0x696B, 0x6C41, 0x847A, 0x589E, 0x618E, 0x66FE, 0x62EF, 0x70DD, 0x7511, 0x75C7, 0x7E52, 0x84B8, 0x8B49, 0x8D08, 0x4E4B, 0x53EA, 0x54AB, 0x5730, 0x5740, 0x5FD7, 0x6301, 0x6307, 0x646F, 0x652F, 0x65E8, 0x667A, 0x679D, 0x67B3, 0x6B62, 0x6C60, 0x6C9A, 0x6F2C, 0x77E5, 0x7825, 0x7949, 0x7957, 0x7D19, 0x80A2, 0x8102, 0x81F3, 0x829D, 0x82B7, 0x8718, 0x8A8C, 0xF9FC, 0x8D04, 0x8DBE, 0x9072, 0x76F4, 0x7A19, 0x7A37, 0x7E54, 0x8077, 0x5507, 0x55D4, 0x5875, 0x632F, 0x6422, 0x6649, 0x664B, 0x686D, 0x699B, 0x6B84, 0x6D25, 0x6EB1, 0x73CD, 0x7468, 0x74A1, 0x755B, 0x75B9, 0x76E1, 0x771E, 0x778B, 0x79E6, 0x7E09, 0x7E1D, 0x81FB, 0x852F, 0x8897, 0x8A3A, 0x8CD1, 0x8EEB, 0x8FB0, 0x9032, 0x93AD, 0x9663, 0x9673, 0x9707, 0x4F84, 0x53F1, 0x59EA, 0x5AC9, 0x5E19, 0x684E, 0x74C6, 0x75BE, 0x79E9, 0x7A92, 0x81A3, 0x86ED, 0x8CEA, 0x8DCC, 0x8FED, 0x659F, 0x6715, 0xF9FD, 0x57F7, 0x6F57, 0x7DDD, 0x8F2F, 0x93F6, 0x96C6, 0x5FB5, 0x61F2, 0x6F84, 0x4E14, 0x4F98, 0x501F, 0x53C9, 0x55DF, 0x5D6F, 0x5DEE, 0x6B21, 0x6B64, 0x78CB, 0x7B9A, 0xF9FE, 0x8E49, 0x8ECA, 0x906E, 0x6349, 0x643E, 0x7740, 0x7A84, 0x932F, 0x947F, 0x9F6A, 0x64B0, 0x6FAF, 0x71E6, 0x74A8, 0x74DA, 0x7AC4, 0x7C12, 0x7E82, 0x7CB2, 0x7E98, 0x8B9A, 0x8D0A, 0x947D, 0x9910, 0x994C, 0x5239, 0x5BDF, 0x64E6, 0x672D, 0x7D2E, 0x50ED, 0x53C3, 0x5879, 0x6158, 0x6159, 0x61FA, 0x65AC, 0x7AD9, 0x8B92, 0x8B96, 0x5009, 0x5021, 0x5275, 0x5531, 0x5A3C, 0x5EE0, 0x5F70, 0x6134, 0x655E, 0x660C, 0x6636, 0x66A2, 0x69CD, 0x6EC4, 0x6F32, 0x7316, 0x7621, 0x7A93, 0x8139, 0x8259, 0x83D6, 0x84BC, 0x50B5, 0x57F0, 0x5BC0, 0x5BE8, 0x5F69, 0x63A1, 0x7826, 0x7DB5, 0x83DC, 0x8521, 0x91C7, 0x91F5, 0x518A, 0x67F5, 0x7B56, 0x8CAC, 0x51C4, 0x59BB, 0x60BD, 0x8655, 0x501C, 0xF9FF, 0x5254, 0x5C3A, 0x617D, 0x621A, 0x62D3, 0x64F2, 0x65A5, 0x6ECC, 0x7620, 0x810A, 0x8E60, 0x965F, 0x96BB, 0x4EDF, 0x5343, 0x5598, 0x5929, 0x5DDD, 0x64C5, 0x6CC9, 0x6DFA, 0x7394, 0x7A7F, 0x821B, 0x85A6, 0x8CE4, 0x8E10, 0x9077, 0x91E7, 0x95E1, 0x9621, 0x97C6, 0x51F8, 0x54F2, 0x5586, 0x5FB9, 0x64A4, 0x6F88, 0x7DB4, 0x8F1F, 0x8F4D, 0x9435, 0x50C9, 0x5C16, 0x6CBE, 0x6DFB, 0x751B, 0x77BB, 0x7C3D, 0x7C64, 0x8A79, 0x8AC2, 0x581E, 0x59BE, 0x5E16, 0x6377, 0x7252, 0x758A, 0x776B, 0x8ADC, 0x8CBC, 0x8F12, 0x5EF3, 0x6674, 0x6DF8, 0x807D, 0x83C1, 0x8ACB, 0x9751, 0x9BD6, 0xFA00, 0x5243, 0x66FF, 0x6D95, 0x6EEF, 0x7DE0, 0x8AE6, 0x902E, 0x905E, 0x9AD4, 0x521D, 0x527F, 0x54E8, 0x6194, 0x6284, 0x62DB, 0x68A2, 0x6912, 0x695A, 0x6A35, 0x7092, 0x7126, 0x785D, 0x7901, 0x790E, 0x79D2, 0x7A0D, 0x8096, 0x8278, 0x82D5, 0x8349, 0x8549, 0x8C82, 0x8D85, 0x9162, 0x918B, 0x91AE, 0x4FC3, 0x56D1, 0x71ED, 0x77D7, 0x8700, 0x89F8, 0x5BF8, 0x5FD6, 0x6751, 0x90A8, 0x53E2, 0x585A, 0x5BF5, 0x60A4, 0x6181, 0x6460, 0x7E3D, 0x8070, 0x8525, 0x9283, 0x64AE, 0x50AC, 0x5D14, 0x6700, 0x589C, 0x62BD, 0x63A8, 0x690E, 0x6978, 0x6A1E, 0x6E6B, 0x76BA, 0x79CB, 0x82BB, 0x8429, 0x8ACF, 0x8DA8, 0x8FFD, 0x9112, 0x914B, 0x919C, 0x9310, 0x9318, 0x939A, 0x96DB, 0x9A36, 0x9C0D, 0x4E11, 0x755C, 0x795D, 0x7AFA, 0x7B51, 0x7BC9, 0x7E2E, 0x84C4, 0x8E59, 0x8E74, 0x8EF8, 0x9010, 0x6625, 0x693F, 0x7443, 0x51FA, 0x672E, 0x9EDC, 0x5145, 0x5FE0, 0x6C96, 0x87F2, 0x885D, 0x8877, 0x60B4, 0x81B5, 0x8403, 0x8D05, 0x53D6, 0x5439, 0x5634, 0x5A36, 0x5C31, 0x708A, 0x7FE0, 0x805A, 0x8106, 0x81ED, 0x8DA3, 0x9189, 0x9A5F, 0x9DF2, 0x5074, 0x4EC4, 0x53A0, 0x60FB, 0x6E2C, 0x5C64, 0x4F88, 0x5024, 0x55E4, 0x5CD9, 0x5E5F, 0x6065, 0x6894, 0x6CBB, 0x6DC4, 0x71BE, 0x75D4, 0x75F4, 0x7661, 0x7A1A, 0x7A49, 0x7DC7, 0x7DFB, 0x7F6E, 0x81F4, 0x86A9, 0x8F1C, 0x96C9, 0x99B3, 0x9F52, 0x5247, 0x52C5, 0x98ED, 0x89AA, 0x4E03, 0x67D2, 0x6F06, 0x4FB5, 0x5BE2, 0x6795, 0x6C88, 0x6D78, 0x741B, 0x7827, 0x91DD, 0x937C, 0x87C4, 0x79E4, 0x7A31, 0x5FEB, 0x4ED6, 0x54A4, 0x553E, 0x58AE, 0x59A5, 0x60F0, 0x6253, 0x62D6, 0x6736, 0x6955, 0x8235, 0x9640, 0x99B1, 0x99DD, 0x502C, 0x5353, 0x5544, 0x577C, 0xFA01, 0x6258, 0xFA02, 0x64E2, 0x666B, 0x67DD, 0x6FC1, 0x6FEF, 0x7422, 0x7438, 0x8A17, 0x9438, 0x5451, 0x5606, 0x5766, 0x5F48, 0x619A, 0x6B4E, 0x7058, 0x70AD, 0x7DBB, 0x8A95, 0x596A, 0x812B, 0x63A2, 0x7708, 0x803D, 0x8CAA, 0x5854, 0x642D, 0x69BB, 0x5B95, 0x5E11, 0x6E6F, 0xFA03, 0x8569, 0x514C, 0x53F0, 0x592A, 0x6020, 0x614B, 0x6B86, 0x6C70, 0x6CF0, 0x7B1E, 0x80CE, 0x82D4, 0x8DC6, 0x90B0, 0x98B1, 0xFA04, 0x64C7, 0x6FA4, 0x6491, 0x6504, 0x514E, 0x5410, 0x571F, 0x8A0E, 0x615F, 0x6876, 0xFA05, 0x75DB, 0x7B52, 0x7D71, 0x901A, 0x5806, 0x69CC, 0x817F, 0x892A, 0x9000, 0x9839, 0x5078, 0x5957, 0x59AC, 0x6295, 0x900F, 0x9B2A, 0x615D, 0x7279, 0x95D6, 0x5761, 0x5A46, 0x5DF4, 0x628A, 0x64AD, 0x64FA, 0x6777, 0x6CE2, 0x6D3E, 0x722C, 0x7436, 0x7834, 0x7F77, 0x82AD, 0x8DDB, 0x9817, 0x5224, 0x5742, 0x677F, 0x7248, 0x74E3, 0x8CA9, 0x8FA6, 0x9211, 0x962A, 0x516B, 0x53ED, 0x634C, 0x4F69, 0x5504, 0x6096, 0x6557, 0x6C9B, 0x6D7F, 0x724C, 0x72FD, 0x7A17, 0x8987, 0x8C9D, 0x5F6D, 0x6F8E, 0x70F9, 0x81A8, 0x610E, 0x4FBF, 0x504F, 0x6241, 0x7247, 0x7BC7, 0x7DE8, 0x7FE9, 0x904D, 0x97AD, 0x9A19, 0x8CB6, 0x576A, 0x5E73, 0x67B0, 0x840D, 0x8A55, 0x5420, 0x5B16, 0x5E63, 0x5EE2, 0x5F0A, 0x6583, 0x80BA, 0x853D, 0x9589, 0x965B, 0x4F48, 0x5305, 0x530D, 0x530F, 0x5486, 0x54FA, 0x5703, 0x5E03, 0x6016, 0x629B, 0x62B1, 0x6355, 0xFA06, 0x6CE1, 0x6D66, 0x75B1, 0x7832, 0x80DE, 0x812F, 0x82DE, 0x8461, 0x84B2, 0x888D, 0x8912, 0x900B, 0x92EA, 0x98FD, 0x9B91, 0x5E45, 0x66B4, 0x66DD, 0x7011, 0x7206, 0xFA07, 0x4FF5, 0x527D, 0x5F6A, 0x6153, 0x6753, 0x6A19, 0x6F02, 0x74E2, 0x7968, 0x8868, 0x8C79, 0x98C7, 0x98C4, 0x9A43, 0x54C1, 0x7A1F, 0x6953, 0x8AF7, 0x8C4A, 0x98A8, 0x99AE, 0x5F7C, 0x62AB, 0x75B2, 0x76AE, 0x88AB, 0x907F, 0x9642, 0x5339, 0x5F3C, 0x5FC5, 0x6CCC, 0x73CC, 0x7562, 0x758B, 0x7B46, 0x82FE, 0x999D, 0x4E4F, 0x903C, 0x4E0B, 0x4F55, 0x53A6, 0x590F, 0x5EC8, 0x6630, 0x6CB3, 0x7455, 0x8377, 0x8766, 0x8CC0, 0x9050, 0x971E, 0x9C15, 0x58D1, 0x5B78, 0x8650, 0x8B14, 0x9DB4, 0x5BD2, 0x6068, 0x608D, 0x65F1, 0x6C57, 0x6F22, 0x6FA3, 0x701A, 0x7F55, 0x7FF0, 0x9591, 0x9592, 0x9650, 0x97D3, 0x5272, 0x8F44, 0x51FD, 0x542B, 0x54B8, 0x5563, 0x558A, 0x6ABB, 0x6DB5, 0x7DD8, 0x8266, 0x929C, 0x9677, 0x9E79, 0x5408, 0x54C8, 0x76D2, 0x86E4, 0x95A4, 0x95D4, 0x965C, 0x4EA2, 0x4F09, 0x59EE, 0x5AE6, 0x5DF7, 0x6052, 0x6297, 0x676D, 0x6841, 0x6C86, 0x6E2F, 0x7F38, 0x809B, 0x822A, 0xFA08, 0xFA09, 0x9805, 0x4EA5, 0x5055, 0x54B3, 0x5793, 0x595A, 0x5B69, 0x5BB3, 0x61C8, 0x6977, 0x6D77, 0x7023, 0x87F9, 0x89E3, 0x8A72, 0x8AE7, 0x9082, 0x99ED, 0x9AB8, 0x52BE, 0x6838, 0x5016, 0x5E78, 0x674F, 0x8347, 0x884C, 0x4EAB, 0x5411, 0x56AE, 0x73E6, 0x9115, 0x97FF, 0x9909, 0x9957, 0x9999, 0x5653, 0x589F, 0x865B, 0x8A31, 0x61B2, 0x6AF6, 0x737B, 0x8ED2, 0x6B47, 0x96AA, 0x9A57, 0x5955, 0x7200, 0x8D6B, 0x9769, 0x4FD4, 0x5CF4, 0x5F26, 0x61F8, 0x665B, 0x6CEB, 0x70AB, 0x7384, 0x73B9, 0x73FE, 0x7729, 0x774D, 0x7D43, 0x7D62, 0x7E23, 0x8237, 0x8852, 0xFA0A, 0x8CE2, 0x9249, 0x986F, 0x5B51, 0x7A74, 0x8840, 0x9801, 0x5ACC, 0x4FE0, 0x5354, 0x593E, 0x5CFD, 0x633E, 0x6D79, 0x72F9, 0x8105, 0x8107, 0x83A2, 0x92CF, 0x9830, 0x4EA8, 0x5144, 0x5211, 0x578B, 0x5F62, 0x6CC2, 0x6ECE, 0x7005, 0x7050, 0x70AF, 0x7192, 0x73E9, 0x7469, 0x834A, 0x87A2, 0x8861, 0x9008, 0x90A2, 0x93A3, 0x99A8, 0x516E, 0x5F57, 0x60E0, 0x6167, 0x66B3, 0x8559, 0x8E4A, 0x91AF, 0x978B, 0x4E4E, 0x4E92, 0x547C, 0x58D5, 0x58FA, 0x597D, 0x5CB5, 0x5F27, 0x6236, 0x6248, 0x660A, 0x6667, 0x6BEB, 0x6D69, 0x6DCF, 0x6E56, 0x6EF8, 0x6F94, 0x6FE0, 0x6FE9, 0x705D, 0x72D0, 0x7425, 0x745A, 0x74E0, 0x7693, 0x795C, 0x7CCA, 0x7E1E, 0x80E1, 0x82A6, 0x846B, 0x84BF, 0x864E, 0x865F, 0x8774, 0x8B77, 0x8C6A, 0x93AC, 0x9800, 0x9865, 0x60D1, 0x6216, 0x9177, 0x5A5A, 0x660F, 0x6DF7, 0x6E3E, 0x743F, 0x9B42, 0x5FFD, 0x60DA, 0x7B0F, 0x54C4, 0x5F18, 0x6C5E, 0x6CD3, 0x6D2A, 0x70D8, 0x7D05, 0x8679, 0x8A0C, 0x9D3B, 0x5316, 0x548C, 0x5B05, 0x6A3A, 0x706B, 0x7575, 0x798D, 0x79BE, 0x82B1, 0x83EF, 0x8A71, 0x8B41, 0x8CA8, 0x9774, 0xFA0B, 0x64F4, 0x652B, 0x78BA, 0x78BB, 0x7A6B, 0x4E38, 0x559A, 0x5950, 0x5BA6, 0x5E7B, 0x60A3, 0x63DB, 0x6B61, 0x6665, 0x6853, 0x6E19, 0x7165, 0x74B0, 0x7D08, 0x9084, 0x9A69, 0x9C25, 0x6D3B, 0x6ED1, 0x733E, 0x8C41, 0x95CA, 0x51F0, 0x5E4C, 0x5FA8, 0x604D, 0x60F6, 0x6130, 0x614C, 0x6643, 0x6644, 0x69A5, 0x6CC1, 0x6E5F, 0x6EC9, 0x6F62, 0x714C, 0x749C, 0x7687, 0x7BC1, 0x7C27, 0x8352, 0x8757, 0x9051, 0x968D, 0x9EC3, 0x532F, 0x56DE, 0x5EFB, 0x5F8A, 0x6062, 0x6094, 0x61F7, 0x6666, 0x6703, 0x6A9C, 0x6DEE, 0x6FAE, 0x7070, 0x736A, 0x7E6A, 0x81BE, 0x8334, 0x86D4, 0x8AA8, 0x8CC4, 0x5283, 0x7372, 0x5B96, 0x6A6B, 0x9404, 0x54EE, 0x5686, 0x5B5D, 0x6548, 0x6585, 0x66C9, 0x689F, 0x6D8D, 0x6DC6, 0x723B, 0x80B4, 0x9175, 0x9A4D, 0x4FAF, 0x5019, 0x539A, 0x540E, 0x543C, 0x5589, 0x55C5, 0x5E3F, 0x5F8C, 0x673D, 0x7166, 0x73DD, 0x9005, 0x52DB, 0x52F3, 0x5864, 0x58CE, 0x7104, 0x718F, 0x71FB, 0x85B0, 0x8A13, 0x6688, 0x85A8, 0x55A7, 0x6684, 0x714A, 0x8431, 0x5349, 0x5599, 0x6BC1, 0x5F59, 0x5FBD, 0x63EE, 0x6689, 0x7147, 0x8AF1, 0x8F1D, 0x9EBE, 0x4F11, 0x643A, 0x70CB, 0x7566, 0x8667, 0x6064, 0x8B4E, 0x9DF8, 0x5147, 0x51F6, 0x5308, 0x6D36, 0x80F8, 0x9ED1, 0x6615, 0x6B23, 0x7098, 0x75D5, 0x5403, 0x5C79, 0x7D07, 0x8A16, 0x6B20, 0x6B3D, 0x6B46, 0x5438, 0x6070, 0x6D3D, 0x7FD5, 0x8208, 0x50D6, 0x51DE, 0x559C, 0x566B, 0x56CD, 0x59EC, 0x5B09, 0x5E0C, 0x6199, 0x6198, 0x6231, 0x665E, 0x66E6, 0x7199, 0x71B9, 0x71BA, 0x72A7, 0x79A7, 0x7A00, 0x7FB2, 0x8A70, 0/* End of table; # of entries=8741(0x2225)+1 */ }; int ksc5601max = sizeof(tabksc5601) / sizeof(tabksc5601[0]) - 1; /* # of entries in the table. */ static unsigned short convert_char_ksc5601_to_ucs2(unsigned char byte1, unsigned char byte2) { int tab_idx = ((int)byte1 - 0x00a1) * 94 + (int)byte2 - 0x00a1; long code_ucs2; if (tab_idx >= 0 && tab_idx < ksc5601max) { code_ucs2 = tabksc5601[tab_idx]; if (code_ucs2 != -1) return code_ucs2; } return 0; } void han2unicode(char *src, Uint16 *dest) { while (*src) { if (*src > 0 && *src < 128) { *dest++ = *src++; } else { *dest++ = convert_char_ksc5601_to_ucs2(src[0], src[1]); src += 2; } } *dest = 0; } <file_sep>/Scene_Credit.cpp #include "stdafx.h" #include "Scene_Credit.h" #include "TextManager.h" #include "EventManager.h" #include "SceneManager.h" CScene_Credit::CScene_Credit() : CScene(sCredit) { CreditBox[0] = { 100, 200, 0, 40 }; CreditBox[1] = { 100, 270, 0, 40 }; CreditBox[2] = { 100, 320, 0, 40 }; CreditBox[3] = { 100, 370, 0, 40 }; CreditBox[4] = { 100, 420, 0, 40 }; strcpy(CreditString[0], "앱동 ACM 제작진, 1.0 version"); strcpy(CreditString[1], "기획 : 차혁진"); strcpy(CreditString[2], "프로그래밍 : 장은준"); strcpy(CreditString[3], "그래픽 : 장호익"); strcpy(CreditString[4], "아무키나 눌러 주세요!"); CreditBox[0].w = (strlen(CreditString[0]) - 1) * 15; CreditBox[1].w = (strlen(CreditString[1]) - 1) * 15; CreditBox[2].w = (strlen(CreditString[2]) - 1) * 15; CreditBox[3].w = (strlen(CreditString[3]) - 1) * 15; CreditBox[4].w = (strlen(CreditString[4]) - 1) * 15; } CScene_Credit::~CScene_Credit() { Release(); } void CScene_Credit::Init() { for (int i = 0; i < 5; i++) { g_TextManager->CreateText(CreditString[i], &CreditBox[i]); } } void CScene_Credit::Update() { if (g_EventManager->g_Event.type == SDL_KEYDOWN) { g_SceneManager->SetScene(sMainMenu); } } void CScene_Credit::Release() { g_TextManager->DestroyTextAll(); } <file_sep>/Scene_Rule.h #pragma once #include "Scene.h" class CScene_Rule : public CScene { public: CScene_Rule(); ~CScene_Rule(); virtual void Init() override; virtual void Update() override; virtual void Release() override; private: char strRule[6][50]; SDL_Rect RuleBox[6]; fstream ScoreFile; }; <file_sep>/Scene_Score.h #pragma once #include "Scene.h" class CScene_Score : public CScene { public: CScene_Score(); ~CScene_Score(); virtual void Init() override; virtual void Update() override; virtual void Release() override; private: int BestScore; char strScore[4][50]; SDL_Rect ScoreBox[4]; fstream ScoreFile; }; <file_sep>/Sprite_Note.cpp #include "stdafx.h" #include "DrawManager.h" #include "EventManager.h" #include "ResourceManager.h" #include "Sprite.h" #include "Sprite_Note.h" CSprite_Note::CSprite_Note() : CSprite("Note", 20, 20, 0, 0, 20, 20) { //SetSpriteImage("Note.png"); } CSprite_Note::CSprite_Note(eNote type, float Rotation, float Rotation_Rate, int Speed, int Speed_Rate) : CSprite("Note", 20, 20, 0, 0, 20, 20) { NoteType = type; int NoteColor = rand() % 8; switch (type) { case note_Normal: case note_FourWayNormal: SpriteTexture = SDL_CreateTextureFromSurface(g_DrawManager->pRenderer, g_ResourceManager->NormalNoteSurface); SetSpriteCenter(39, 39); SpriteRect = { 0, 0, 39, 39 }; break; case note_Spiral_Left: case note_Spiral_Right: SpriteTexture = SDL_CreateTextureFromSurface(g_DrawManager->pRenderer, g_ResourceManager->SpiralNoteSurface); SetSpriteCenter(44, 44); SpriteRect = { 0, 0, 44, 44 }; break; case note_Random: SpriteTexture = SDL_CreateTextureFromSurface(g_DrawManager->pRenderer, g_ResourceManager->Note[NoteColor]); SetSpriteCenter(20, 20); SpriteRect = { 0, 0, 20, 20 }; break; default: break; } SetSpriteRect((WINDOW_DEFAULT_W / 2 - center.x), (WINDOW_DEFAULT_H / 2 - center.y)); SetSpriteRotation(Rotation); this->Speed = Speed; this->Speed_Rate = Speed_Rate; this->Rotation_Rate = Rotation_Rate; radian = rotation * (M_PI / 180); } CSprite_Note::~CSprite_Note() { } void CSprite_Note::Update() { SpriteRect.x += Speed * cosf(radian); SpriteRect.y += Speed * sinf(radian); //rotation += Rotation_Rate; //Speed += Speed_Rate; } eNote CSprite_Note::GetNoteType() { return NoteType; } <file_sep>/Sprite_Note.h #pragma once class CSprite_Note : public CSprite { public: CSprite_Note(); CSprite_Note(eNote type, float Rotation, float Rotation_Rate, int Speed, int Speed_Rate); ~CSprite_Note(); virtual void Update() override; eNote GetNoteType(); private: float Rotation_Rate; int Speed; int Speed_Rate; //SDL_Point pos[4]; float radian; eNote NoteType; }; <file_sep>/Sprite_SpawnNote.h #pragma once #include "Sprite.h" class CSprite_SpawnNote : public CSprite { public: CSprite_SpawnNote(); ~CSprite_SpawnNote(); virtual void Update() override; }; <file_sep>/ResourceManager.cpp #include "stdafx.h" #include "ResourceManager.h" CResourceManager::CResourceManager() { key = "ACM00"; } CResourceManager::~CResourceManager() { Release(); } void CResourceManager::Init() { // Zip 파일을 로드한다. hz = OpenZip("Resource.zip", key); mem = nullptr; rw = nullptr; NormalNoteSurface = IMG_Load_RW(LoadItem("NormalNote.png"), 0); RandomNoteSurface = IMG_Load_RW(LoadItem("RandomNote.png"), 0); SpiralNoteSurface = IMG_Load_RW(LoadItem("SpiralNote.png"), 0); Note[0] = IMG_Load_RW(LoadItem("note__1.png"), 0); Note[1] = IMG_Load_RW(LoadItem("note__2.png"), 0); Note[2] = IMG_Load_RW(LoadItem("note__3.png"), 0); Note[3] = IMG_Load_RW(LoadItem("note__4.png"), 0); Note[4] = IMG_Load_RW(LoadItem("note__5.png"), 0); Note[5] = IMG_Load_RW(LoadItem("note__6.png"), 0); Note[6] = IMG_Load_RW(LoadItem("note__7.png"), 0); Note[7] = IMG_Load_RW(LoadItem("note__8.png"), 0); } void CResourceManager::Release() { for (int i = 0; i < 8; i++) { SDL_FreeSurface(Note[i]); } SDL_FreeSurface(SpiralNoteSurface); SDL_FreeSurface(RandomNoteSurface); SDL_FreeSurface(NormalNoteSurface); for (int i = vRememberSurface.size() - 1; i >= 0; i--) { SDL_FreeSurface(vRememberSurface[i]); vRememberSurface.pop_back(); } CloseZip(hz); } SDL_RWops *CResourceManager::LoadItem(char *name) { // Zip에서 찾고자 하는 파일을 검색한다. ZRESULT z; z = FindZipItem(hz, name, false, &index, &ze); // 압축울 풀 메모리 공간을 할당한다. //if (mem != nullptr) //{ // free(mem); //} mem = malloc(ze.unc_size); // 메모리 공간상에 압축을 푼다. UnzipItem(hz, index, mem, ze.unc_size); // 압축푼곳으로부터 SDL_RWops를 생성한다 //if (rw != nullptr) //{ // SDL_FreeRW(rw); //} rw = SDL_RWFromMem(mem, ze.unc_size); return rw; //// RWops로 이미지를 로드한다 //return IMG_Load_RW(rw, 0); } int CResourceManager::addRememberSurface(SDL_Surface *s) { vRememberSurface.push_back(s); return vRememberSurface.size() - 1; } //hitomi <file_sep>/ResourceManager.h #pragma once #include "Singleton.h" #include "unzip.h" class CResourceManager : public Singleton<CResourceManager> { private: SDL_RWops *rw; HZIP hz; ZIPENTRY ze; int index; void *mem; char *key; vector<SDL_Surface *>vRememberSurface; public: CResourceManager(); ~CResourceManager(); void Init(); void Release(); SDL_RWops *LoadItem(char *name); int addRememberSurface(SDL_Surface *s); SDL_Surface *GetRememberSurface(int idx); SDL_Surface *NormalNoteSurface; SDL_Surface *RandomNoteSurface; SDL_Surface *SpiralNoteSurface; SDL_Surface *Note[8]; }; #define g_ResourceManager CResourceManager::GetInstance()<file_sep>/Singleton.h //#pragma once //template <typename T> //class Singleton //{ //private: // static auto_ptr<T> pSingleton; //static 맴버함수에서 참조가능하도록 정적선언 // //public: // static GetInstance(); //반환값을 객체의 주소로 하여 인터페이스 함수를 통해 외부에서 데이터 조작을 가능하게함. // static void Destroy(); //}; // //template <typename T> //Singleton<T>::GetInstance() //{ // if (pSingleton == nullptr) //싱글턴이므로 단 하나만 존재해야함 // { // pSingleton = new Singleton<T>; // std::cout << "싱글턴 동적할당" << std::endl; // } // return pSingleton.get(); //} // //template <typename T> //void Singleton<T>::Destroy() //사용을 다 한 뒤 해제를 해주는 함수 필요 //{ // if (pSingleton != nullptr) // { // delete pSingleton; // pSingleton = nullptr; // } //} #pragma once template <typename T> class Singleton { public: static T* GetInstance() { call_once(m_onceFlag, [] { m_pInstance.reset(new T); } ); return m_pInstance.get(); } private: static std::shared_ptr<T> Singleton<T>::m_pInstance; static std::once_flag m_onceFlag; }; template <typename T> std::shared_ptr<T> Singleton<T>::m_pInstance = nullptr; template <typename T> std::once_flag Singleton<T>::m_onceFlag; //#pragma once //template <class T> //class Singleton //{ //public: // static T *ms_pSingleton; // //public: // Singleton() // { // unsigned __int64 ulOffset = (unsigned __int64)((T*)(1)) - (unsigned __int64)((Singleton<T>*)(T*)1); // // ms_pSingleton = (T*)((unsigned __int64)this + ulOffset); // } // // virtual ~Singleton() // { // ms_pSingleton = 0; // } // // static T* GetSingleton() // { // return(ms_pSingleton); // } //}; // //template <class T> T* Singleton<T>::ms_pSingleton = 0; <file_sep>/Scene_Game.h #pragma once #include "Scene.h" #include "Sprite_Note.h" typedef struct _NoteData { float Rotation, Rotation_Rate; int Speed, Speed_Rate; int interval; }NoteData; class CScene_Game : public CScene { public: CScene_Game(); ~CScene_Game(); void addNote(CSprite_Note *); virtual void Init() override; virtual void Update() override; virtual void Render() override; virtual void Release() override; float GetMouseRotation(); void SetSong(eSong Song); private: int Score; vector<CSprite_Note *> vNote; clock_t SinkTime, GameEndTime, CurTime, IntervalTime, ScoreTime, xScoreTime; float xScore; //스코어 배율. 1~2까지. 5초간 0.1씩 올라감, 피격시 -0.2 int NoteType; int SpiralWay; //======SinkData=========== NoteData CommonSink; NoteData NormalSink; NoteData FourWaySink; NoteData SpiralSink; NoteData RandomSink; //========================= bool bIsSpiral; bool bIsRandomNote; bool bIsGameEnd; fstream SinkFile, ScoreFile; char strScore[2][128]; SDL_Rect ScoreBox[2]; eSong ThisSong; };
f6673735b52436683ffb6917e2b2f520c5752706
[ "C", "C++" ]
27
C++
SilverJun/ACM
1d96bfd1a5b4fde310d834249fd25ba02b993b3d
b313e7c1fa6120290e9cb5725e697a21bd9369db
refs/heads/master
<file_sep>package backtracking; import java.io.File; import java.io.FileNotFoundException; import java.util.*; public class Permutations { // turn on the DEBUG flag to see a bunch of helpful println statements // to watch the recursion trace private static HashMap<String,Node> graph; private static int bandwidth = Integer.MAX_VALUE; private static int vertex; private static int edge; public static void main(String[] args) throws FileNotFoundException { System.out.println("Enter file to be processed:"); String filename = "/Users/Bagel/Documents/CSE373/test_files/"; Scanner stdin = new Scanner(System.in); filename += stdin.nextLine() +".txt"; File file = new File(filename); stdin = new Scanner(file); vertex = Integer.valueOf(stdin.nextLine()); edge = Integer.valueOf(stdin.nextLine()); //vertex = Integer.valueOf(stdin.nextLine()); String nextLine; graph = new HashMap(); int[] vertices = new int[vertex]; for(int i = 0;i<vertices.length;i++) { vertices[i] = -1; } while(stdin.hasNextLine()) { nextLine = stdin.nextLine(); String[] nodePair = nextLine.split(" "); vertices[Integer.valueOf(nodePair[0])-1] = Integer.valueOf(nodePair[0]); vertices[Integer.valueOf(nodePair[1])-1] = Integer.valueOf(nodePair[1]); Node A = new Node(nodePair[0]); Node B = new Node(nodePair[1]); if(!graph.containsKey(nodePair[0])) { graph.put(nodePair[0],A); } if(!graph.containsKey(nodePair[1])) { graph.put(nodePair[1],B); } //initialize a list of all vertices Edge A1 = new Edge(graph.get(nodePair[0]),graph.get(nodePair[1])); Edge B1 = new Edge(graph.get(nodePair[1]),graph.get(nodePair[0])); graph.get(nodePair[0]).getEdges().add(A1); //make graph directed graph.get(nodePair[1]).getEdges().add(B1); } stdin.close(); List<Integer> list = checkComplete(graph.get(vertices[0]+"")); if(list!=null) { for(int i = 0;i<list.size();i++ ) { System.out.print(list.get(i)+" "); } System.out.println("minimum bandwidth:"+(vertex-1)); } else { permute(vertices); } } public static List<Integer> checkComplete(Node root)//it's complete if every node is connect to every other node { List<Integer> list = new ArrayList(); int size = root.getEdges().size(); if(size==vertex-1) { list.add(root.name()); for(Object child: root.getEdges()) { if( ((Edge)child).getB().getEdges().size()==vertex-1 ) { list.add(((Edge)child).getB().name()); } else return null; } } else { return null; } return list; } public static int findWidth(List<Integer> list,int print) { int width = 0; for(int i = 0 ; i<list.size();i++) { Node nodeToInspect = graph.get(list.get(i)+""); if(!nodeToInspect.isVisted()) { Object[] j = nodeToInspect.getEdges().toArray(); for(Object edges: nodeToInspect.getEdges().toArray()) { if(((Edge)edges).getBandWidth()>width) width = ((Edge)edges).getBandWidth(); if(width>=bandwidth) { //clearVisitStatus(); return -1;//not better than current bandwidth - disregard } //if current width is not optimal, return prematurely //find maximum width } nodeToInspect.visit(); } } return width; } public static void clearVisitStatus() { for(Object s:graph.values()) { ((Node)s).unvisit(); //unvisit all the nodes } } public static List<List<Integer>> permute(int[] nums) { List<List<Integer>> list = new ArrayList<>(); backtrack(list, new ArrayList<>(), nums); for(int i = 0;i<list.size();i++ ) { System.out.print(list.get(i)+"\n"); } System.out.println("minimum bandwidth:"+bandwidth); return list; } public static void backtrack(List<List<Integer>> list, List<Integer> tempList, int[] nums)// { if(tempList.size() == nums.length) { int possibleMin = findWidth(tempList,0); clearVisitStatus(); //System.out.printf("currentMin \n"+possibleMin); if(bandwidth>possibleMin && possibleMin!=-1) { bandwidth = possibleMin; list.clear(); list.add(new ArrayList<>(tempList)); } if(bandwidth==1) return; //bandwidth can't get better than 1 } else{ for(int i = 0; i < nums.length; i++){ if(tempList.contains(nums[i])) continue; // element already exists, skip if(!tempList.isEmpty()) if(nums[i]<tempList.get(0) && i==(vertex-1)) break; int add = check(tempList.size()+1,graph.get(nums[i]+"")); if(add==1) { tempList.add(nums[i]); graph.get(nums[i]+"").setIndex(tempList.size()); } else { //if current placement -> greater bandwidth //-> disregard all permutations that are like this break;//don't consider } backtrack(list, tempList, nums); int n = tempList.remove(tempList.size() - 1); graph.get(n+"").setIndex(-1); } } } public static int check(int currentIndex, Node node) { //check if the current index will result in a longer distance int edge = 0; for(Object edges:node.getEdges()) { Node b = ((Edge)edges).getB(); if(b.getIndex()<currentIndex && b.getIndex()!=-1) {//b has already been placed int newBand = Math.abs(b.getIndex()-currentIndex); if(bandwidth<=newBand) { //if there's already a better placement for this value return 0; //creates an even greater bandwidth } } else { if(currentIndex+(edge++)>=bandwidth) { return 0; } } } return 1; } }<file_sep> #for <NAME> #find two decimal average of 7 elements starting from beginning of index #could be more efficient - rn i'm summing redundant values.. def stringFormattedWeeklyPrices(dailyPrice): result = [] elements_now = dailyPrice[:7] #first 7 elements for index in range(6,len(dailyPrice)): result.append(findAverage(elements_now)) if(index>=len(dailyPrice)-1): break elements_now= elements_now[1:]+[dailyPrice[index+1]] return result def findAverage(elements): total = 0 for i in elements: total+=i return '{:0.2f}'.format(total/7) print(stringFormattedWeeklyPrices([1,1,1,1,1,1,1,1])) <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 tf; /** * * @author Bagel */ import java.util.*; public class ticketsToFans { public static void main(String args[] ) throws Exception { /* Enter your code here. Read input from STDIN. Print output to STDOUT */ Scanner scan = new Scanner(System.in); int sizeOfWorld = Integer.parseInt(scan.nextLine()); int numberOfEvents = Integer.parseInt(scan.nextLine()); int currentNumEvent = 0; int[] eventCoords = new int[2*numberOfEvents]; int[][] pricesPerEvent = new int[2*numberOfEvents][2*numberOfEvents]; while(numberOfEvents > 0){ String eventLine = scan.nextLine(); String[] split = eventLine.split(" "); int ticketNum = Integer.valueOf(split[0]);//ticket number for(int i = 1;i<=2;i++) { eventCoords[2*currentNumEvent+i] = Integer.valueOf(split[i]); } int k = 0; for(int i = 3;i<split.length;i++) { pricesPerEvent[currentNumEvent][k++] = Integer.valueOf(split[i]); //parse the prices into a 2d array } currentNumEvent++; // TODO: you will need to parse and store the events numberOfEvents--; } int numberOfBuyers = Integer.parseInt(scan.nextLine()); int[]buyerCoords = new int[2*numberOfBuyers]; int currentBuyer = 0; while(numberOfBuyers > 0){ String buyerLine = scan.nextLine(); // TODO: you will need to parse and store the buyers String[]split = buyerLine.split(" "); buyerCoords[2*currentBuyer] = Integer.valueOf(split[0]); buyerCoords[2*currentBuyer+1] = Integer.valueOf(split[1]); currentBuyer++; numberOfBuyers--; } for(int i = 0;i<currentBuyer;i++) { int eventNum = 0; int distance = 1000; for(int k = 0;k<currentNumEvent;k++) { int currentDistance = calculateManhattanDistance(buyerCoords[2*i],eventCoords[2*k], buyerCoords[2*i+1],eventCoords[2*k+1]); if(currentDistance <distance) { distance = currentDistance; eventNum = k; } } for(int j = 0;j<pricesPerEvent.length;j++) { if(j==0) break; } } // The solution to the first sample above would be to output the following to console: // (Obviously, your solution will need to figure out the output and not just hard code it) System.out.println("2 50"); } // The following method get the manhatten distance betwen two points (x1,y1) and (x2,y2) public static int calculateManhattanDistance(int x1, int y1, int x2, int y2) { return Math.abs(x1 - x2) + Math.abs(y1 - y2); } }<file_sep>def favoriteVideoGenre(numUsers, userBooksListenedTo, numGenres, bookGenres): #userGenresListened={} favorites = {} for entry in userBooksListenedTo: books = userBooksListenedTo[entry] #returns list of books #userGenresListened[entry]=[] CountGenres = {} for book in books: Max = 0 for genre in bookGenres: CountGenres.setdefault(genre,0) if book in bookGenres[genre]: print(entry,book,genre) CountGenres[genre]+=1 #increment book count if CountGenres[genre]>Max: Max = CountGenres[genre] #keep count of the mode break #print(CountGenres,Max) favorites[entry] = [x for x in CountGenres if CountGenres[x]==Max] #userGenresListened[entry].append(genre) return favorites userBooksListenedTo={ 'Fred':['m','w','s'], 'Jenie':['h','p'], 'Rone':['a'] } bookGenres ={ 'Horror':['m','s'], 'Comedy':['h'], 'Romance':['w','a','p'] } print(favoriteVideoGenre(3,userBooksListenedTo,3,bookGenres)) <file_sep> # # Complete the 'funWithAnagrams' function below. # # The function is expected to return a STRING_ARRAY. # The function accepts STRING_ARRAY s as parameter. # def funWithAnagrams(s): # Write your code here sorted_chars = [] result = [] ret = [] for word in s: sorted_chars.append("".join(sorted(word))) #sorted_chars=set(sorted_chars) sorted_chars = list(set(sorted_chars)) print(sorted_chars) if(len(sorted_chars)==1): print(s) return s[0] for i in range(len(sorted_chars)-1): for j in range(i+1,len(sorted_chars)): if(sorted_chars[i]==sorted_chars[j]): #if(s[i]<s[j]): result.append(i) #elif(s[i]>s[j]): # result.append(j) # found =1 print("result",result) for w in result: ret.append(s[w]) return sorted(ret) r = funWithAnagrams(['code','aaagmnrs','anagrams','doce']) #p = funWithAnagrams(['poke','pkoe','okpe','ekop']) #print(p) print(r) <file_sep>''' was given as an interview question at atlassian Given a string pattern of integers mixed with ? (if unknown) day = max hours to work per day hour = desired hours to work for the week return a list of possible work assignments problem(8hours/day,56/week,"???8???") would return 88888888 as the only element in array ''' #My solution uses backtracking and is not optimal answer = [] def construct_candidates(pos,partial,day,tot): candidates = [] min_val = 0 if partial[pos]=='?': current_sum = 0 for i in range(pos): current_sum = current_sum + int(partial[i]) if i== pos-1: min_val = int(partial[i]) if tot-current_sum>day: n = day else: n = tot-current_sum for i in range(min_val,n+1): candidates.append(i) return candidates def is_solution(a,total): cur_sum = 0 if '?' in a: return False for i in a: cur_sum = cur_sum + int(i) #print(cur_sum) if cur_sum == total: return True else: return False def sum_good(a,pos,day,total): tot = 0 for i in range(pos+1): tot+= int(a[i]) if tot > total: return False elif (total-tot)/(len(a)-pos+1)>day: return False return True def backtrack(a,pos,day,total): print(a) if(is_solution(a,total)): answer.append(a) elif not pos==len(a): candidates = construct_candidates(pos,a,day,total) ncand = len(candidates) if(ncand==0): #kth position letter was not ? backtrack(a,pos+1,day,total) for i in range(ncand): m = sum_good(a,pos-1,day,total) if m: s = list(a) s[pos] = str(candidates[i]) a = "".join(s) #print(a) if sum_good(a,pos,day,total): backtrack(a,pos+1,day,total) def problem(total,day,pattern): backtrack(pattern,0,day,total) print(answer) problem(12,5,"???") <file_sep># interview_Q hackerrank interview practice questions <file_sep>def criticalConnection(numOfWarehouses, numOfRoads, roads): if numOfWarehouses==0 or numOfRoads ==0: return [] matrix = [[0]*numOfWarehouses for _ in range(numOfWarehouses)] #initialize the graph for i in range(numOfRoads): start = roads[i][0]-1 end = roads[i][1]-1 matrix[start][end]=1 matrix[end][start]=1 out = [] for i in range(numOfRoads): count = 1 start=roads[i][0]-1 end=roads[i][1]-1 matrix[start][end]=0 matrix[end][start]=0 start=numOfWarehouses//2 visited = [False]*numOfWarehouses queue= [] queue.append(start) visited[start] = True #if breadth first search doesn't find all the warehouses while queue: start = queue.pop(0) for i in matrix[start]: if visited[i]==False: queue.append(i) visited[i] = True count+=1 if count<numOfWarehouses: out.append([start+1,end+1]) matrix[start][end]=1 matrix[end][start]=1 return out <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 backtracking; /** * * @author Bagel */ class Edge { private Node A;//The starting node private Node B;//The connected node public Edge(Node A,Node B) { this.A = A; this.B = B; } public int getBandWidth() { if(A.getIndex()<0 || B.getIndex()<0) return Integer.MIN_VALUE; return Math.abs(A.getIndex()-B.getIndex()); } public Node getB() { return B; } } <file_sep>#Find sum of unique values in the list, if a value is not unique, increment until it is def getUniqueUserIdSum(arr): sum_ = 0 count = {} newarr = [] for num in arr: temp = num while temp in count: # temp = temp+1 count[temp]=1 newarr.append(temp) for num in newarr: sum_+=num return sum_ print(getUniqueUserIdSum([1,2,2])) <file_sep>#find if a subset of the set adds up to a certain number def subs(l): if len(l) == 1: return [l] res = [] subsets = subs(l[0:-1]) res = res+subsets res.append([l[-1]]) for sub in subsets: res.append(sub+[l[-1]]) return res def isPossible(calCounts,requiredCals): subsets = subs(calCounts) for a_set in subsets: temp_sum = 0 for cal in a_set: if temp_sum < requiredCals: temp_sum+=cal else: break if temp_sum==requiredCals: return True return False print(subs([1,2,3])) print(isPossible([1,2,3],3)) <file_sep>email_dict = {} def getEmailThreads(emails): thread_num = 1 result = [] for comma in emails: first = comma.find(",")+1 second = comma[first:].find(",")+1 text=comma[first+second:].strip() print(text) #text = email[2] index = text.rfind("---") #find last index print(index) if index>-1: text = text[index+3:] print("key: ") print(text) email_dict[text][1]+=1 #increment thread count else: #start a new thread #increment thread num email_dict[text]=[thread_num,1] thread_num += 1 x =[] x.append(email_dict[text][0]) x.append(email_dict[text][1]) result.append(x) return result r = getEmailThreads(['<EMAIL>, <EMAIL>, hello x, how are you?', '<EMAIL>, <EMAIL>, did you take a look at the event?', '<EMAIL>, <EMAIL>, i am great. how are you?---hello x, how are you?']) print(r) <file_sep>#!/bin/python3 import math import os import random import re import sys # # Complete the 'maxStreak' function below. # # The function is expected to return an INTEGER. # The function accepts following parameters: # 1. INTEGER m # 2. STRING_ARRAY data # def maxStreak(m, data): max_conse = 0 current_conse = 0 for attendance in data: #iterate through each day's record if 'N' in attendance: if(current_conse>max_conse): max_conse = current_conse current_conse = 0 else: current_conse +=1 if(current_conse>max_conse): max_conse = current_conse return max_conse print(maxStreak(4,['NNNN','YNYY','YYYY','YNYN','YYYY','YYYY','YYYY','YYNY','YYYY','NYYN'])) <file_sep> def solution(A, B): if(len(A)==0 or len(B)==0): return 0 # write your code in Python 3.6 try: x = min(findSwaps(A[0],B[0],A[1:],B[1:]),1+findSwaps(B[0],A[0],A[1:],B[1:])) except: x = -1 return x def findSwaps(headA,headB,tailA,tailB): if(len(tailA)==0 or len(tailB)==0): return 0 else: if(headA==tailA[0] or headB==tailB[0]): #print(headA,tailA[0],"no swap necessary",headB,tailB[0]) return min(0+findSwaps(tailA[0],tailB[0],tailA[1:],tailB[1:]), 1+findSwaps(tailB[0],tailA[0],tailA[1:],tailB[1:])) elif(headA==tailB[0] or headB==tailA[0]): #print("swap needed",headA,tailB[0]," ",headB,tailA[0]) return 1+findSwaps(tailB[0],tailA[0],tailA[1:],tailB[1:]) else: raise Exception print(solution([1, 2, 1, 2], [2, 6, 1, 2])) print(solution([2,1,2,4,2,2],[5,2,6,2,3,2])) print(solution([5,2,6,2,3,2],[2,1,2,4,2,2])) <file_sep># # Complete the 'gridGame' function below. # # The function is expected to return a 2D_INTEGER_ARRAY. # The function accepts following parameters: # 1. 2D_INTEGER_ARRAY grid # 2. INTEGER k # 3. STRING_ARRAY rules # # For <NAME> #check neighbors and find value of alive def gridGame(grid, k, rules): new_grid = [] for iterations in range(k): for i in range(len(grid)): new_grid.append([]) for j in range(len(grid[i])): temp_val = getAliveNeighbors(grid,i,j) #new_grid[i].append(getAliveNeighbors(grid,i,j)) if(rules[temp_val]=='alive'): new_grid[i].append(1) else: new_grid[i].append(0) grid = new_grid new_grid=[] return grid def getAliveNeighbors(grid,x,y): #at most 8 neighbors #[x-1,y-1],[x-1,y],[x-1,y+1],[x,y-1],[x,y+1],[x+1,y],[x+1,y+1],[x+1,y-1] #find sum of all alive neighbors, out of bound neighbors return 0 neighbors = isAlive(grid,x-1,y-1)+isAlive(grid,x-1,y)+isAlive(grid,x-1,y+1)+isAlive(grid,x,y-1)+isAlive(grid,x,y+1)+isAlive(grid,x+1,y)+isAlive(grid,x+1,y+1)+isAlive(grid,x+1,y-1) return neighbors def isAlive(grid,i,j): if(i<0 or i>=(len(grid)) or j<0 or j>=(len(grid[i]))): #out of bounds return 0 else: print(i,j) return grid[i][j] print(gridGame([[0,1,0,0],[0,0,0,0]],2,['dead','alive','dead','dead','dead','alive','dead','dead','dead'])) <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 tf; /** * * @author Bagel */ import java.util.Arrays; class AppearsK { public static void main(String[]args) { int[] n = {6,2,3,2,3,6,4,5,6}; System.out.println(appearsKTimes(9,n,3)); } public static int appearsKTimes(int size, int inputArray[], int k) { Arrays.sort(inputArray); int i=1, count = 1; int element = inputArray[0]; int res = -1; while(i < size) { if(element == inputArray[i]) { count++; } else { if(count == k && element>res) { res = element; } element = inputArray[i]; count = 1; } i++; // System.out.println(count); } if(count == k && element>res) { res = element; } return res; } }
7b7f59ce0541e0c070e542dfacd574a8cc60cb24
[ "Markdown", "Java", "Python" ]
16
Java
yingz1985/interview_Q
7787e5e214b654b5e12dd449eaa77f46b7cead2e
de0e4a829a5bf2c4c1ba6839cee21f2675a2f91c
refs/heads/master
<file_sep>package gowbem import ( "errors" "net/url" "strings" ) var ( messageNotExists = errors.New("CIM.MESSAGE isn't exists.") simpleReqNotExists = errors.New("CIM.MESSAGE.SIMPLERSP isn't exists.") imethodResponseNotExists = errors.New("CIM.MESSAGE.SIMPLERSP.IMETHODRESPONSE isn't exists.") ireturnValueNotExists = errors.New("CIM.MESSAGE.SIMPLERSP.IMETHODRESPONSE.RETURNVALUE isn't exists.") instancePathNotExists = errors.New("CIM.MESSAGE.SIMPLERSP.IMETHODRESPONSE.RETURNVALUE.INSTANCEPATH isn't exists.") instanceNamesNotExists = errors.New("CIM.MESSAGE.SIMPLERSP.IMETHODRESPONSE.RETURNVALUE.INSTANCENAME isn't exists.") classNamesNotExists = errors.New("CIM.MESSAGE.SIMPLERSP.IMETHODRESPONSE.RETURNVALUE.CLASSNAME isn't exists.") instancesNotExists = errors.New("CIM.MESSAGE.SIMPLERSP.IMETHODRESPONSE.RETURNVALUE.INSTANCE isn't exists.") instancesMutiChioce = errors.New("CIM.MESSAGE.SIMPLERSP.IMETHODRESPONSE.RETURNVALUE.INSTANCE is greate one.") valueNamedInstancesNotExists = errors.New("CIM.MESSAGE.SIMPLERSP.IMETHODRESPONSE.RETURNVALUE.VALUE.NAMEDINSTANCE isn't exists.") classesNotExists = errors.New("CIM.MESSAGE.SIMPLERSP.IMETHODRESPONSE.RETURNVALUE.CLASS isn't exists.") classesMutiChioce = errors.New("CIM.MESSAGE.SIMPLERSP.IMETHODRESPONSE.RETURNVALUE.CLASS is greate one.") ) func booleanString(b bool) string { if b { return "true" } return "false" } type ClientCIMXML struct { Client CimVersion string DtdVersion string ProtocolVersion string } func (c *ClientCIMXML) init(u *url.URL, insecure bool) { c.Client.init(u, insecure) c.CimVersion = "2.0" c.DtdVersion = "2.0" c.ProtocolVersion = "1.0" //fmt.Println(c.Client.u.User) } func (c *ClientCIMXML) EnumerateClassNames(namespaceName, className string, deep bool) ([]string, error) { // obtain data if "" == namespaceName { return nil, WBEMException(CIM_ERR_INVALID_PARAMETER, "namespace name is empty.") } names := strings.Split(namespaceName, "/") namespaces := make([]CimNamespace, len(names)) for idx, name := range names { namespaces[idx].Name = name } var paramValues []CimIParamValue if deep { paramValues = []CimIParamValue{ CimIParamValue{Name: "DeepInheritance", Value: &CimValue{Value: "true"}}, } } if "" != className { paramValues = append(paramValues, CimIParamValue{ Name: "ClassName", ClassName: &CimClassName{Name: className}, }) } simpleReq := &CimSimpleReq{IMethodCall: &CimIMethodCall{ Name: "EnumerateClassNames", LocalNamespacePath: CimLocalNamespacePath{Namespaces: namespaces}, ParamValues: paramValues, }} req := &CIM{ CimVersion: c.CimVersion, DtdVersion: c.DtdVersion, Message: &CimMessage{ Id: c.generateId(), ProtocolVersion: c.ProtocolVersion, SimpleReq: simpleReq, }, //Declaration: &CimDeclaration, } resp := &CIM{hasFault: func(cim *CIM) error { if nil == cim.Message { return messageNotExists } if nil == cim.Message.SimpleRsp { return simpleReqNotExists } if nil == cim.Message.SimpleRsp.IMethodResponse { return imethodResponseNotExists } if nil != cim.Message.SimpleRsp.IMethodResponse.Error { e := cim.Message.SimpleRsp.IMethodResponse.Error return WBEMException(CIMStatusCode(e.Code), e.Description) } if nil == cim.Message.SimpleRsp.IMethodResponse.ReturnValue { return ireturnValueNotExists } if nil == cim.Message.SimpleRsp.IMethodResponse.ReturnValue.ClassNames { return classNamesNotExists } return nil }} if err := c.RoundTrip("POST", map[string]string{"CIMProtocolVersion": c.ProtocolVersion, "CIMOperation": "MethodCall", "CIMMethod": "EnumerateClassNames", "CIMObject": url.QueryEscape(namespaceName)}, req, resp); nil != err { return nil, err } results := make([]string, len(resp.Message.SimpleRsp.IMethodResponse.ReturnValue.ClassNames)) for idx, name := range resp.Message.SimpleRsp.IMethodResponse.ReturnValue.ClassNames { results[idx] = name.Name } return results, nil } func (c *ClientCIMXML) EnumerateInstanceNames(namespaceName, className string) ([]CIMInstanceName, error) { if "" == namespaceName { return nil, WBEMException(CIM_ERR_INVALID_PARAMETER, "namespace name is empty.") } if "" == className { return nil, WBEMException(CIM_ERR_INVALID_PARAMETER, "class name is empty.") } names := strings.Split(namespaceName, "/") namespaces := make([]CimNamespace, len(names)) for idx, name := range names { namespaces[idx].Name = name } paramValues := []CimIParamValue{ CimIParamValue{ Name: "ClassName", ClassName: &CimClassName{Name: className}, }, } simpleReq := &CimSimpleReq{IMethodCall: &CimIMethodCall{ Name: "EnumerateInstanceNames", LocalNamespacePath: CimLocalNamespacePath{Namespaces: namespaces}, ParamValues: paramValues, }} req := &CIM{ CimVersion: c.CimVersion, DtdVersion: c.DtdVersion, Message: &CimMessage{ Id: c.generateId(), ProtocolVersion: c.ProtocolVersion, SimpleReq: simpleReq, }, //Declaration: &CimDeclaration, } resp := &CIM{hasFault: func(cim *CIM) error { if nil == cim.Message { return messageNotExists } if nil == cim.Message.SimpleRsp { return simpleReqNotExists } if nil == cim.Message.SimpleRsp.IMethodResponse { return imethodResponseNotExists } if nil != cim.Message.SimpleRsp.IMethodResponse.Error { e := cim.Message.SimpleRsp.IMethodResponse.Error return WBEMException(CIMStatusCode(e.Code), e.Description) } if nil == cim.Message.SimpleRsp.IMethodResponse.ReturnValue { return ireturnValueNotExists } if nil == cim.Message.SimpleRsp.IMethodResponse.ReturnValue.InstanceNames { return instanceNamesNotExists } return nil }} // CIMProtocolVersion: 1.0 // CIMOperation: MethodCall // CIMMethod: EnumerateClassNames // CIMObject: root%2Fcimv2 if err := c.RoundTrip("POST", map[string]string{"CIMProtocolVersion": c.ProtocolVersion, "CIMOperation": "MethodCall", "CIMMethod": "EnumerateInstanceNames", "CIMObject": url.QueryEscape(namespaceName)}, req, resp); nil != err { return nil, err } results := make([]CIMInstanceName, len(resp.Message.SimpleRsp.IMethodResponse.ReturnValue.InstanceNames)) for idx, name := range resp.Message.SimpleRsp.IMethodResponse.ReturnValue.InstanceNames { results[idx] = name } return results, nil } func (c *ClientCIMXML) GetInstance(namespaceName, className string, keyBindings CIMKeyBindings, localOnly bool, includeQualifiers bool, includeClassOrigin bool, propertyList []string) (CIMInstance, error) { instanceName := &CimInstanceName{ ClassName: className, } switch keyBindings.Len() { case 0: return nil, errors.New("keyBindings is empty.") case 1: kb := keyBindings.Get(0) if "_" == kb.GetName() { instanceName.KeyValue = kb.(*CimKeyBinding).KeyValue instanceName.ValueReference = kb.(*CimKeyBinding).ValueReference break } fallthrough default: instanceName.KeyBindings = keyBindings.(CimKeyBindings) } return c.GetInstanceByInstanceName(namespaceName, instanceName, localOnly, includeQualifiers, includeClassOrigin, propertyList) } func (c *ClientCIMXML) GetInstanceByInstanceName(namespaceName string, instanceName CIMInstanceName, localOnly bool, includeQualifiers bool, includeClassOrigin bool, propertyList []string) (CIMInstance, error) { if "" == namespaceName { return nil, WBEMException(CIM_ERR_INVALID_PARAMETER, "namespace name is empty.") } if "" == instanceName.GetClassName() { return nil, WBEMException(CIM_ERR_INVALID_PARAMETER, "class name is empty.") } names := strings.Split(namespaceName, "/") namespaces := make([]CimNamespace, len(names)) for idx, name := range names { namespaces[idx].Name = name } paramValues := []CimIParamValue{ CimIParamValue{ Name: "InstanceName", InstanceName: instanceName.(*CimInstanceName), }, CimIParamValue{ Name: "LocalOnly", Value: &CimValue{Value: booleanString(localOnly)}, }, CimIParamValue{ Name: "IncludeQualifiers", Value: &CimValue{Value: booleanString(includeQualifiers)}, }, CimIParamValue{ Name: "IncludeClassOrigin", Value: &CimValue{Value: booleanString(includeClassOrigin)}, }, } if 0 != len(propertyList) { properties := CimValueArray{Values: make([]string, len(propertyList))} for idx, s := range propertyList { properties.Values[idx] = string(s) } paramValues = append(paramValues, CimIParamValue{ Name: "PropertyList", ValueArray: properties, }) } simpleReq := &CimSimpleReq{IMethodCall: &CimIMethodCall{ Name: "GetInstance", LocalNamespacePath: CimLocalNamespacePath{Namespaces: namespaces}, ParamValues: paramValues, }} req := &CIM{ CimVersion: c.CimVersion, DtdVersion: c.DtdVersion, Message: &CimMessage{ Id: c.generateId(), ProtocolVersion: c.ProtocolVersion, SimpleReq: simpleReq, }, //Declaration: &CimDeclaration, } resp := &CIM{hasFault: func(cim *CIM) error { if nil == cim.Message { return messageNotExists } if nil == cim.Message.SimpleRsp { return simpleReqNotExists } if nil == cim.Message.SimpleRsp.IMethodResponse { return imethodResponseNotExists } if nil != cim.Message.SimpleRsp.IMethodResponse.Error { e := cim.Message.SimpleRsp.IMethodResponse.Error return WBEMException(CIMStatusCode(e.Code), e.Description) } if nil == cim.Message.SimpleRsp.IMethodResponse.ReturnValue { return ireturnValueNotExists } if 0 == len(cim.Message.SimpleRsp.IMethodResponse.ReturnValue.Instances) { return instancesNotExists } if 1 < len(cim.Message.SimpleRsp.IMethodResponse.ReturnValue.Instances) { return instancesMutiChioce } return nil }} // CIMProtocolVersion: 1.0 // CIMOperation: MethodCall // CIMMethod: EnumerateClassNames // CIMObject: root%2Fcimv2 if err := c.RoundTrip("POST", map[string]string{"CIMProtocolVersion": c.ProtocolVersion, "CIMOperation": "MethodCall", "CIMMethod": "GetInstance", "CIMObject": url.QueryEscape(namespaceName)}, req, resp); nil != err { return nil, err } if 0 == len(resp.Message.SimpleRsp.IMethodResponse.ReturnValue.Instances) { return nil, nil } return &resp.Message.SimpleRsp.IMethodResponse.ReturnValue.Instances[0], nil } func (c *ClientCIMXML) EnumerateInstances(namespaceName, className string, deepInheritance bool, localOnly bool, includeQualifiers bool, includeClassOrigin bool, propertyList []string) ([]CIMInstanceWithName, error) { if "" == namespaceName { return nil, WBEMException(CIM_ERR_INVALID_PARAMETER, "namespace name is empty.") } if "" == className { return nil, WBEMException(CIM_ERR_INVALID_PARAMETER, "class name is empty.") } names := strings.Split(namespaceName, "/") namespaces := make([]CimNamespace, len(names)) for idx, name := range names { namespaces[idx].Name = name } paramValues := []CimIParamValue{ CimIParamValue{ Name: "ClassName", ClassName: &CimClassName{Name: className}, }, CimIParamValue{ Name: "LocalOnly", Value: &CimValue{Value: booleanString(localOnly)}, }, CimIParamValue{ Name: "DeepInheritance", Value: &CimValue{Value: booleanString(deepInheritance)}, }, CimIParamValue{ Name: "IncludeQualifiers", Value: &CimValue{Value: booleanString(includeQualifiers)}, }, CimIParamValue{ Name: "IncludeClassOrigin", Value: &CimValue{Value: booleanString(includeClassOrigin)}, }, } if 0 != len(propertyList) { properties := CimValueArray{Values: make([]string, len(propertyList))} for idx, s := range propertyList { properties.Values[idx] = string(s) } paramValues = append(paramValues, CimIParamValue{ Name: "PropertyList", ValueArray: properties, }) } simpleReq := &CimSimpleReq{IMethodCall: &CimIMethodCall{ Name: "EnumerateInstances", LocalNamespacePath: CimLocalNamespacePath{Namespaces: namespaces}, ParamValues: paramValues, }} req := &CIM{ CimVersion: c.CimVersion, DtdVersion: c.DtdVersion, Message: &CimMessage{ Id: c.generateId(), ProtocolVersion: c.ProtocolVersion, SimpleReq: simpleReq, }, //Declaration: &CimDeclaration, } resp := &CIM{hasFault: func(cim *CIM) error { if nil == cim.Message { return messageNotExists } if nil == cim.Message.SimpleRsp { return simpleReqNotExists } if nil == cim.Message.SimpleRsp.IMethodResponse { return imethodResponseNotExists } if nil != cim.Message.SimpleRsp.IMethodResponse.Error { e := cim.Message.SimpleRsp.IMethodResponse.Error return WBEMException(CIMStatusCode(e.Code), e.Description) } if nil == cim.Message.SimpleRsp.IMethodResponse.ReturnValue { return ireturnValueNotExists } if nil == cim.Message.SimpleRsp.IMethodResponse.ReturnValue.ValueNamedInstances { return valueNamedInstancesNotExists } return nil }} // CIMProtocolVersion: 1.0 // CIMOperation: MethodCall // CIMMethod: EnumerateClassNames // CIMObject: root%2Fcimv2 if err := c.RoundTrip("POST", map[string]string{"CIMProtocolVersion": c.ProtocolVersion, "CIMOperation": "MethodCall", "CIMMethod": "EnumerateInstances", "CIMObject": url.QueryEscape(namespaceName)}, req, resp); nil != err { return nil, err } results := make([]CIMInstanceWithName, len(resp.Message.SimpleRsp.IMethodResponse.ReturnValue.ValueNamedInstances)) for idx, _ := range resp.Message.SimpleRsp.IMethodResponse.ReturnValue.ValueNamedInstances { results[idx] = &resp.Message.SimpleRsp.IMethodResponse.ReturnValue.ValueNamedInstances[idx] } return results, nil } func (c *ClientCIMXML) GetClass(namespaceName string, className string, localOnly bool, includeQualifiers bool, includeClassOrigin bool, propertyList []string) (string, error) { if "" == namespaceName { return "", WBEMException(CIM_ERR_INVALID_PARAMETER, "namespace name is empty.") } if "" == className { return "", WBEMException(CIM_ERR_INVALID_PARAMETER, "class name is empty.") } names := strings.Split(namespaceName, "/") namespaces := make([]CimNamespace, len(names)) for idx, name := range names { namespaces[idx].Name = name } paramValues := []CimIParamValue{ CimIParamValue{ Name: "ClassName", ClassName: &CimClassName{Name: className}, }, CimIParamValue{ Name: "LocalOnly", Value: &CimValue{Value: booleanString(localOnly)}, }, CimIParamValue{ Name: "IncludeQualifiers", Value: &CimValue{Value: booleanString(includeQualifiers)}, }, CimIParamValue{ Name: "IncludeClassOrigin", Value: &CimValue{Value: booleanString(includeClassOrigin)}, }, } if 0 != len(propertyList) { properties := CimValueArray{Values: make([]string, len(propertyList))} for idx, s := range propertyList { properties.Values[idx] = string(s) } paramValues = append(paramValues, CimIParamValue{ Name: "PropertyList", ValueArray: properties, }) } simpleReq := &CimSimpleReq{IMethodCall: &CimIMethodCall{ Name: "GetClass", LocalNamespacePath: CimLocalNamespacePath{Namespaces: namespaces}, ParamValues: paramValues, }} req := &CIM{ CimVersion: c.CimVersion, DtdVersion: c.DtdVersion, Message: &CimMessage{ Id: c.generateId(), ProtocolVersion: c.ProtocolVersion, SimpleReq: simpleReq, }, //Declaration: &CimDeclaration, } resp := &CIM{hasFault: func(cim *CIM) error { if nil == cim.Message { return messageNotExists } if nil == cim.Message.SimpleRsp { return simpleReqNotExists } if nil == cim.Message.SimpleRsp.IMethodResponse { return imethodResponseNotExists } if nil != cim.Message.SimpleRsp.IMethodResponse.Error { e := cim.Message.SimpleRsp.IMethodResponse.Error return WBEMException(CIMStatusCode(e.Code), e.Description) } if nil == cim.Message.SimpleRsp.IMethodResponse.ReturnValue { return ireturnValueNotExists } if 0 == len(cim.Message.SimpleRsp.IMethodResponse.ReturnValue.Classes) { return classesNotExists } if 1 < len(cim.Message.SimpleRsp.IMethodResponse.ReturnValue.Classes) { return classesMutiChioce } return nil }} // CIMProtocolVersion: 1.0 // CIMOperation: MethodCall // CIMMethod: EnumerateClassNames // CIMObject: root%2Fcimv2 if err := c.RoundTrip("POST", map[string]string{"CIMProtocolVersion": c.ProtocolVersion, "CIMOperation": "MethodCall", "CIMMethod": "GetClass", "CIMObject": url.QueryEscape(namespaceName)}, req, resp); nil != err { return "", err } return resp.Message.SimpleRsp.IMethodResponse.ReturnValue.Classes[0].String(), nil } func (c *ClientCIMXML) EnumerateClasses(namespaceName string, className string, deepInheritance bool, localOnly bool, includeQualifiers bool, includeClassOrigin bool) ([]string, error) { if "" == namespaceName { return nil, WBEMException(CIM_ERR_INVALID_PARAMETER, "namespace name is empty.") } names := strings.Split(namespaceName, "/") namespaces := make([]CimNamespace, len(names)) for idx, name := range names { namespaces[idx].Name = name } paramValues := []CimIParamValue{ CimIParamValue{ Name: "LocalOnly", Value: &CimValue{Value: booleanString(localOnly)}, }, CimIParamValue{ Name: "DeepInheritance", Value: &CimValue{Value: booleanString(deepInheritance)}, }, CimIParamValue{ Name: "IncludeQualifiers", Value: &CimValue{Value: booleanString(includeQualifiers)}, }, CimIParamValue{ Name: "IncludeClassOrigin", Value: &CimValue{Value: booleanString(includeClassOrigin)}, }, } if "" != className { paramValues = append(paramValues, CimIParamValue{ Name: "ClassName", ClassName: &CimClassName{Name: className}, }) } simpleReq := &CimSimpleReq{IMethodCall: &CimIMethodCall{ Name: "EnumerateClasses", LocalNamespacePath: CimLocalNamespacePath{Namespaces: namespaces}, ParamValues: paramValues, }} req := &CIM{ CimVersion: c.CimVersion, DtdVersion: c.DtdVersion, Message: &CimMessage{ Id: c.generateId(), ProtocolVersion: c.ProtocolVersion, SimpleReq: simpleReq, }, //Declaration: &CimDeclaration, } resp := &CIM{hasFault: func(cim *CIM) error { if nil == cim.Message { return messageNotExists } if nil == cim.Message.SimpleRsp { return simpleReqNotExists } if nil == cim.Message.SimpleRsp.IMethodResponse { return imethodResponseNotExists } if nil != cim.Message.SimpleRsp.IMethodResponse.Error { e := cim.Message.SimpleRsp.IMethodResponse.Error return WBEMException(CIMStatusCode(e.Code), e.Description) } if nil == cim.Message.SimpleRsp.IMethodResponse.ReturnValue { return ireturnValueNotExists } // if 0 == len(cim.Message.SimpleRsp.IMethodResponse.ReturnValue.Classes) && // 0 == len(resp.Message.SimpleRsp.IMethodResponse.ReturnValue.ClassNames) { // return classesNotExists // } return nil }} // CIMProtocolVersion: 1.0 // CIMOperation: MethodCall // CIMMethod: EnumerateClassNames // CIMObject: root%2Fcimv2 if err := c.RoundTrip("POST", map[string]string{"CIMProtocolVersion": c.ProtocolVersion, "CIMOperation": "MethodCall", "CIMMethod": "EnumerateClasses", "CIMObject": url.QueryEscape(namespaceName)}, req, resp); nil != err { return nil, err } results := make([]string, len(resp.Message.SimpleRsp.IMethodResponse.ReturnValue.Classes)) for idx, class := range resp.Message.SimpleRsp.IMethodResponse.ReturnValue.Classes { results[idx] = class.String() } for _, name := range resp.Message.SimpleRsp.IMethodResponse.ReturnValue.ClassNames { results = append(results, name.Name) } return results, nil } func (c *ClientCIMXML) AssociatorNames(namespaceName string, instanceName CIMInstanceName, assocClass, resultClass, role, resultRole string) ([]CIMInstanceName, error) { if "" == namespaceName { return nil, WBEMException(CIM_ERR_INVALID_PARAMETER, "namespace name is empty.") } if "" == instanceName.GetClassName() { return nil, WBEMException(CIM_ERR_INVALID_PARAMETER, "class name is empty.") } names := strings.Split(namespaceName, "/") namespaces := make([]CimNamespace, len(names)) for idx, name := range names { namespaces[idx].Name = name } paramValues := []CimIParamValue{ CimIParamValue{ Name: "ObjectName", InstanceName: instanceName.(*CimInstanceName), }, } if "" != assocClass { paramValues = append(paramValues, CimIParamValue{ Name: "AssocClass", ClassName: &CimClassName{Name: assocClass}, }) } if "" != resultClass { paramValues = append(paramValues, CimIParamValue{ Name: "ResultClass", ClassName: &CimClassName{Name: resultClass}, }) } if "" != role { paramValues = append(paramValues, CimIParamValue{ Name: "Role", Value: &CimValue{Value: role}, }) } if "" != resultRole { paramValues = append(paramValues, CimIParamValue{ Name: "ResultRole", Value: &CimValue{Value: resultRole}, }) } simpleReq := &CimSimpleReq{IMethodCall: &CimIMethodCall{ Name: "AssociatorNames", LocalNamespacePath: CimLocalNamespacePath{Namespaces: namespaces}, ParamValues: paramValues, }} req := &CIM{ CimVersion: c.CimVersion, DtdVersion: c.DtdVersion, Message: &CimMessage{ Id: c.generateId(), ProtocolVersion: c.ProtocolVersion, SimpleReq: simpleReq, }, //Declaration: &CimDeclaration, } resp := &CIM{hasFault: func(cim *CIM) error { if nil == cim.Message { return messageNotExists } if nil == cim.Message.SimpleRsp { return simpleReqNotExists } if nil == cim.Message.SimpleRsp.IMethodResponse { return imethodResponseNotExists } if nil != cim.Message.SimpleRsp.IMethodResponse.Error { e := cim.Message.SimpleRsp.IMethodResponse.Error return WBEMException(CIMStatusCode(e.Code), e.Description) } if nil == cim.Message.SimpleRsp.IMethodResponse.ReturnValue { return ireturnValueNotExists } // if 0 == len(cim.Message.SimpleRsp.IMethodResponse.ReturnValue.InstanceNames) { // return InstanceNamesNotExists // } return nil }} // CIMProtocolVersion: 1.0 // CIMOperation: MethodCall // CIMMethod: EnumerateClassNames // CIMObject: root%2Fcimv2 if err := c.RoundTrip("POST", map[string]string{"CIMProtocolVersion": c.ProtocolVersion, "CIMOperation": "MethodCall", "CIMMethod": "AssociatorNames", "CIMObject": url.QueryEscape(namespaceName)}, req, resp); nil != err { return nil, err } results := make([]CIMInstanceName, len(resp.Message.SimpleRsp.IMethodResponse.ReturnValue.ObjectPaths)) for idx, _ := range resp.Message.SimpleRsp.IMethodResponse.ReturnValue.ObjectPaths { results[idx] = &resp.Message.SimpleRsp.IMethodResponse.ReturnValue.ObjectPaths[idx].InstancePath.InstanceName } return results, nil } func (c *ClientCIMXML) AssociatorInstances(namespaceName string, instanceName CIMInstanceName, assocClass, resultClass, role, resultRole string, includeClassOrigin bool, propertyList []string) ([]CIMInstance, error) { if "" == namespaceName { return nil, WBEMException(CIM_ERR_INVALID_PARAMETER, "namespace name is empty.") } if "" == instanceName.GetClassName() { return nil, WBEMException(CIM_ERR_INVALID_PARAMETER, "class name is empty.") } names := strings.Split(namespaceName, "/") namespaces := make([]CimNamespace, len(names)) for idx, name := range names { namespaces[idx].Name = name } paramValues := []CimIParamValue{ CimIParamValue{ Name: "ObjectName", InstanceName: instanceName.(*CimInstanceName), }, CimIParamValue{ Name: "IncludeClassOrigin", Value: &CimValue{Value: booleanString(includeClassOrigin)}, }, } if "" != assocClass { paramValues = append(paramValues, CimIParamValue{ Name: "AssocClass", ClassName: &CimClassName{Name: assocClass}, }) } if "" != resultClass { paramValues = append(paramValues, CimIParamValue{ Name: "ResultClass", ClassName: &CimClassName{Name: resultClass}, }) } if "" != role { paramValues = append(paramValues, CimIParamValue{ Name: "Role", Value: &CimValue{Value: role}, }) } if "" != resultRole { paramValues = append(paramValues, CimIParamValue{ Name: "ResultRole", Value: &CimValue{Value: resultRole}, }) } if 0 != len(propertyList) { properties := CimValueArray{Values: make([]string, len(propertyList))} for idx, s := range propertyList { properties.Values[idx] = string(s) } paramValues = append(paramValues, CimIParamValue{ Name: "PropertyList", ValueArray: properties, }) } simpleReq := &CimSimpleReq{IMethodCall: &CimIMethodCall{ Name: "Associators", LocalNamespacePath: CimLocalNamespacePath{Namespaces: namespaces}, ParamValues: paramValues, }} req := &CIM{ CimVersion: c.CimVersion, DtdVersion: c.DtdVersion, Message: &CimMessage{ Id: c.generateId(), ProtocolVersion: c.ProtocolVersion, SimpleReq: simpleReq, }, //Declaration: &CimDeclaration, } resp := &CIM{hasFault: func(cim *CIM) error { if nil == cim.Message { return messageNotExists } if nil == cim.Message.SimpleRsp { return simpleReqNotExists } if nil == cim.Message.SimpleRsp.IMethodResponse { return imethodResponseNotExists } if nil != cim.Message.SimpleRsp.IMethodResponse.Error { e := cim.Message.SimpleRsp.IMethodResponse.Error return WBEMException(CIMStatusCode(e.Code), e.Description) } if nil == cim.Message.SimpleRsp.IMethodResponse.ReturnValue { return ireturnValueNotExists } // if 0 == len(cim.Message.SimpleRsp.IMethodResponse.ReturnValue.Instances) { // return classesNotExists // } return nil }} // CIMProtocolVersion: 1.0 // CIMOperation: MethodCall // CIMMethod: EnumerateClassNames // CIMObject: root%2Fcimv2 if err := c.RoundTrip("POST", map[string]string{"CIMProtocolVersion": c.ProtocolVersion, "CIMOperation": "MethodCall", "CIMMethod": "Associators", "CIMObject": url.QueryEscape(namespaceName)}, req, resp); nil != err { return nil, err } results := make([]CIMInstance, len(resp.Message.SimpleRsp.IMethodResponse.ReturnValue.ValueObjectWithPaths)) if count := len(resp.Message.SimpleRsp.IMethodResponse.ReturnValue.ValueObjectWithPaths); count > 0 { for idx, _ := range resp.Message.SimpleRsp.IMethodResponse.ReturnValue.ValueObjectWithPaths { results[idx] = resp.Message.SimpleRsp.IMethodResponse.ReturnValue.ValueObjectWithPaths[idx].Instance } } if count := len(resp.Message.SimpleRsp.IMethodResponse.ReturnValue.ValueObjectWithLocalPaths); count > 0 { for idx, _ := range resp.Message.SimpleRsp.IMethodResponse.ReturnValue.ValueObjectWithLocalPaths { results = append(results, resp.Message.SimpleRsp.IMethodResponse.ReturnValue.ValueObjectWithLocalPaths[idx].Instance) } } return results, nil } func (c *ClientCIMXML) AssociatorClasses(namespaceName, className, assocClass, resultClass, role, resultRole string, includeQualifiers, includeClassOrigin bool, propertyList []string) ([]string, error) { if "" == namespaceName { return nil, WBEMException(CIM_ERR_INVALID_PARAMETER, "namespace name is empty.") } if "" == className { return nil, WBEMException(CIM_ERR_INVALID_PARAMETER, "class name is empty.") } names := strings.Split(namespaceName, "/") namespaces := make([]CimNamespace, len(names)) for idx, name := range names { namespaces[idx].Name = name } paramValues := []CimIParamValue{ CimIParamValue{ Name: "ObjectName", InstanceName: &CimInstanceName{ClassName: className}, }, CimIParamValue{ Name: "IncludeQualifiers", Value: &CimValue{Value: booleanString(includeQualifiers)}, }, CimIParamValue{ Name: "IncludeClassOrigin", Value: &CimValue{Value: booleanString(includeClassOrigin)}, }, } if "" != assocClass { paramValues = append(paramValues, CimIParamValue{ Name: "AssocClass", ClassName: &CimClassName{Name: assocClass}, }) } if "" != resultClass { paramValues = append(paramValues, CimIParamValue{ Name: "ResultClass", ClassName: &CimClassName{Name: resultClass}, }) } if "" != role { paramValues = append(paramValues, CimIParamValue{ Name: "Role", Value: &CimValue{Value: role}, }) } if "" != resultRole { paramValues = append(paramValues, CimIParamValue{ Name: "ResultRole", Value: &CimValue{Value: resultRole}, }) } if 0 != len(propertyList) { properties := CimValueArray{Values: make([]string, len(propertyList))} for idx, s := range propertyList { properties.Values[idx] = string(s) } paramValues = append(paramValues, CimIParamValue{ Name: "PropertyList", ValueArray: properties, }) } simpleReq := &CimSimpleReq{IMethodCall: &CimIMethodCall{ Name: "Associators", LocalNamespacePath: CimLocalNamespacePath{Namespaces: namespaces}, ParamValues: paramValues, }} req := &CIM{ CimVersion: c.CimVersion, DtdVersion: c.DtdVersion, Message: &CimMessage{ Id: c.generateId(), ProtocolVersion: c.ProtocolVersion, SimpleReq: simpleReq, }, //Declaration: &CimDeclaration, } resp := &CIM{hasFault: func(cim *CIM) error { if nil == cim.Message { return messageNotExists } if nil == cim.Message.SimpleRsp { return simpleReqNotExists } if nil == cim.Message.SimpleRsp.IMethodResponse { return imethodResponseNotExists } if nil != cim.Message.SimpleRsp.IMethodResponse.Error { e := cim.Message.SimpleRsp.IMethodResponse.Error return WBEMException(CIMStatusCode(e.Code), e.Description) } if nil == cim.Message.SimpleRsp.IMethodResponse.ReturnValue { return ireturnValueNotExists } // if 0 == len(cim.Message.SimpleRsp.IMethodResponse.ReturnValue.Classes) { // return classesNotExists // } return nil }} // CIMProtocolVersion: 1.0 // CIMOperation: MethodCall // CIMMethod: Associators // CIMObject: root%2Fcimv2 if err := c.RoundTrip("POST", map[string]string{"CIMProtocolVersion": c.ProtocolVersion, "CIMOperation": "MethodCall", "CIMMethod": "Associators", "CIMObject": url.QueryEscape(namespaceName)}, req, resp); nil != err { return nil, err } results := make([]string, len(resp.Message.SimpleRsp.IMethodResponse.ReturnValue.Classes)) for idx, class := range resp.Message.SimpleRsp.IMethodResponse.ReturnValue.Classes { results[idx] = class.String() } for _, name := range resp.Message.SimpleRsp.IMethodResponse.ReturnValue.ClassNames { results = append(results, name.Name) } for _, objectWithPath := range resp.Message.SimpleRsp.IMethodResponse.ReturnValue.ValueObjectWithPaths { if nil != objectWithPath.Class { results = append(results, objectWithPath.Class.Name) } } for _, objectWithLocalPath := range resp.Message.SimpleRsp.IMethodResponse.ReturnValue.ValueObjectWithLocalPaths { if nil != objectWithLocalPath.Class { results = append(results, objectWithLocalPath.Class.Name) } } return results, nil } func (c *ClientCIMXML) ReferenceNames(namespaceName string, instanceName CIMInstanceName, resultClass, role string) ([]CIMInstanceName, error) { if "" == namespaceName { return nil, WBEMException(CIM_ERR_INVALID_PARAMETER, "namespace name is empty.") } if "" == instanceName.GetClassName() { return nil, WBEMException(CIM_ERR_INVALID_PARAMETER, "class name is empty.") } if 0 == instanceName.GetKeyBindings().Len() { return nil, WBEMException(CIM_ERR_INVALID_PARAMETER, "key bindings is empty.") } names := strings.Split(namespaceName, "/") namespaces := make([]CimNamespace, len(names)) for idx, name := range names { namespaces[idx].Name = name } paramValues := []CimIParamValue{ CimIParamValue{ Name: "ObjectName", InstanceName: instanceName.(*CimInstanceName), }, } if "" != resultClass { paramValues = append(paramValues, CimIParamValue{ Name: "ResultClass", ClassName: &CimClassName{Name: resultClass}, }) } if "" != role { paramValues = append(paramValues, CimIParamValue{ Name: "Role", Value: &CimValue{Value: role}, }) } simpleReq := &CimSimpleReq{IMethodCall: &CimIMethodCall{ Name: "ReferenceNames", LocalNamespacePath: CimLocalNamespacePath{Namespaces: namespaces}, ParamValues: paramValues, }} req := &CIM{ CimVersion: c.CimVersion, DtdVersion: c.DtdVersion, Message: &CimMessage{ Id: c.generateId(), ProtocolVersion: c.ProtocolVersion, SimpleReq: simpleReq, }, //Declaration: &CimDeclaration, } resp := &CIM{hasFault: func(cim *CIM) error { if nil == cim.Message { return messageNotExists } if nil == cim.Message.SimpleRsp { return simpleReqNotExists } if nil == cim.Message.SimpleRsp.IMethodResponse { return imethodResponseNotExists } if nil != cim.Message.SimpleRsp.IMethodResponse.Error { e := cim.Message.SimpleRsp.IMethodResponse.Error return WBEMException(CIMStatusCode(e.Code), e.Description) } if nil == cim.Message.SimpleRsp.IMethodResponse.ReturnValue { return ireturnValueNotExists } // if 0 == len(cim.Message.SimpleRsp.IMethodResponse.ReturnValue.ObjectPaths) { // return InstanceNamesNotExists // } return nil }} // CIMProtocolVersion: 1.0 // CIMOperation: MethodCall // CIMMethod: ReferenceNames // CIMObject: root%2Fcimv2 if err := c.RoundTrip("POST", map[string]string{"CIMProtocolVersion": c.ProtocolVersion, "CIMOperation": "MethodCall", "CIMMethod": "ReferenceNames", "CIMObject": url.QueryEscape(namespaceName)}, req, resp); nil != err { return nil, err } results := make([]CIMInstanceName, len(resp.Message.SimpleRsp.IMethodResponse.ReturnValue.ObjectPaths)) for idx, _ := range resp.Message.SimpleRsp.IMethodResponse.ReturnValue.ObjectPaths { results[idx] = &resp.Message.SimpleRsp.IMethodResponse.ReturnValue.ObjectPaths[idx].InstancePath.InstanceName } return results, nil } func (c *ClientCIMXML) ReferenceInstances(namespaceName string, instanceName CIMInstanceName, resultClass, role string, includeClassOrigin bool, propertyList []string) ([]CIMInstance, error) { if "" == namespaceName { return nil, WBEMException(CIM_ERR_INVALID_PARAMETER, "namespace name is empty.") } if "" == instanceName.GetClassName() { return nil, WBEMException(CIM_ERR_INVALID_PARAMETER, "class name is empty.") } names := strings.Split(namespaceName, "/") namespaces := make([]CimNamespace, len(names)) for idx, name := range names { namespaces[idx].Name = name } paramValues := []CimIParamValue{ CimIParamValue{ Name: "ObjectName", InstanceName: instanceName.(*CimInstanceName), }, CimIParamValue{ Name: "IncludeClassOrigin", Value: &CimValue{Value: booleanString(includeClassOrigin)}, }, } if "" != resultClass { paramValues = append(paramValues, CimIParamValue{ Name: "ResultClass", ClassName: &CimClassName{Name: resultClass}, }) } if "" != role { paramValues = append(paramValues, CimIParamValue{ Name: "Role", Value: &CimValue{Value: role}, }) } if 0 != len(propertyList) { properties := CimValueArray{Values: make([]string, len(propertyList))} for idx, s := range propertyList { properties.Values[idx] = string(s) } paramValues = append(paramValues, CimIParamValue{ Name: "PropertyList", ValueArray: properties, }) } simpleReq := &CimSimpleReq{IMethodCall: &CimIMethodCall{ Name: "References", LocalNamespacePath: CimLocalNamespacePath{Namespaces: namespaces}, ParamValues: paramValues, }} req := &CIM{ CimVersion: c.CimVersion, DtdVersion: c.DtdVersion, Message: &CimMessage{ Id: c.generateId(), ProtocolVersion: c.ProtocolVersion, SimpleReq: simpleReq, }, //Declaration: &CimDeclaration, } resp := &CIM{hasFault: func(cim *CIM) error { if nil == cim.Message { return messageNotExists } if nil == cim.Message.SimpleRsp { return simpleReqNotExists } if nil == cim.Message.SimpleRsp.IMethodResponse { return imethodResponseNotExists } if nil != cim.Message.SimpleRsp.IMethodResponse.Error { e := cim.Message.SimpleRsp.IMethodResponse.Error return WBEMException(CIMStatusCode(e.Code), e.Description) } if nil == cim.Message.SimpleRsp.IMethodResponse.ReturnValue { return ireturnValueNotExists } // if 0 == len(cim.Message.SimpleRsp.IMethodResponse.ReturnValue.Instances) { // return classesNotExists // } return nil }} // CIMProtocolVersion: 1.0 // CIMOperation: MethodCall // CIMMethod: EnumerateClassNames // CIMObject: root%2Fcimv2 if err := c.RoundTrip("POST", map[string]string{"CIMProtocolVersion": c.ProtocolVersion, "CIMOperation": "MethodCall", "CIMMethod": "References", "CIMObject": url.QueryEscape(namespaceName)}, req, resp); nil != err { return nil, err } var results []CIMInstance if count := len(resp.Message.SimpleRsp.IMethodResponse.ReturnValue.ValueObjectWithPaths); count > 0 { results = make([]CIMInstance, count) for idx, _ := range resp.Message.SimpleRsp.IMethodResponse.ReturnValue.ValueObjectWithPaths { results[idx] = resp.Message.SimpleRsp.IMethodResponse.ReturnValue.ValueObjectWithPaths[idx].Instance } } else if count = len(resp.Message.SimpleRsp.IMethodResponse.ReturnValue.ValueObjectWithLocalPaths); count > 0 { results = make([]CIMInstance, count) for idx, _ := range resp.Message.SimpleRsp.IMethodResponse.ReturnValue.ValueObjectWithLocalPaths { results[idx] = resp.Message.SimpleRsp.IMethodResponse.ReturnValue.ValueObjectWithLocalPaths[idx].Instance } } return results, nil } func (c *ClientCIMXML) ReferenceClasses(namespaceName, className, resultClass, role string, includeQualifiers, includeClassOrigin bool, propertyList []string) ([]string, error) { if "" == namespaceName { return nil, WBEMException(CIM_ERR_INVALID_PARAMETER, "namespace name is empty.") } if "" == className { return nil, WBEMException(CIM_ERR_INVALID_PARAMETER, "class name is empty.") } names := strings.Split(namespaceName, "/") namespaces := make([]CimNamespace, len(names)) for idx, name := range names { namespaces[idx].Name = name } paramValues := []CimIParamValue{ CimIParamValue{ Name: "ObjectName", ClassName: &CimClassName{Name: className}, }, CimIParamValue{ Name: "IncludeQualifiers", Value: &CimValue{Value: booleanString(includeQualifiers)}, }, CimIParamValue{ Name: "IncludeClassOrigin", Value: &CimValue{Value: booleanString(includeClassOrigin)}, }, } if "" != resultClass { paramValues = append(paramValues, CimIParamValue{ Name: "ResultClass", ClassName: &CimClassName{Name: resultClass}, }) } if "" != role { paramValues = append(paramValues, CimIParamValue{ Name: "Role", Value: &CimValue{Value: role}, }) } if 0 != len(propertyList) { properties := CimValueArray{Values: make([]string, len(propertyList))} for idx, s := range propertyList { properties.Values[idx] = string(s) } paramValues = append(paramValues, CimIParamValue{ Name: "PropertyList", ValueArray: properties, }) } simpleReq := &CimSimpleReq{IMethodCall: &CimIMethodCall{ Name: "References", LocalNamespacePath: CimLocalNamespacePath{Namespaces: namespaces}, ParamValues: paramValues, }} req := &CIM{ CimVersion: c.CimVersion, DtdVersion: c.DtdVersion, Message: &CimMessage{ Id: c.generateId(), ProtocolVersion: c.ProtocolVersion, SimpleReq: simpleReq, }, //Declaration: &CimDeclaration, } resp := &CIM{hasFault: func(cim *CIM) error { if nil == cim.Message { return messageNotExists } if nil == cim.Message.SimpleRsp { return simpleReqNotExists } if nil == cim.Message.SimpleRsp.IMethodResponse { return imethodResponseNotExists } if nil != cim.Message.SimpleRsp.IMethodResponse.Error { e := cim.Message.SimpleRsp.IMethodResponse.Error return WBEMException(CIMStatusCode(e.Code), e.Description) } if nil == cim.Message.SimpleRsp.IMethodResponse.ReturnValue { return ireturnValueNotExists } // if 0 == len(cim.Message.SimpleRsp.IMethodResponse.ReturnValue.Classes) // 0 == len(cim.Message.SimpleRsp.IMethodResponse.ReturnValue.ClassNames) { // return classesNotExists // } return nil }} // CIMProtocolVersion: 1.0 // CIMOperation: MethodCall // CIMMethod: References // CIMObject: root%2Fcimv2 if err := c.RoundTrip("POST", map[string]string{"CIMProtocolVersion": c.ProtocolVersion, "CIMOperation": "MethodCall", "CIMMethod": "References", "CIMObject": url.QueryEscape(namespaceName)}, req, resp); nil != err { return nil, err } results := make([]string, len(resp.Message.SimpleRsp.IMethodResponse.ReturnValue.Classes)) for idx, class := range resp.Message.SimpleRsp.IMethodResponse.ReturnValue.Classes { results[idx] = class.String() } for _, name := range resp.Message.SimpleRsp.IMethodResponse.ReturnValue.ClassNames { results = append(results, name.Name) } for _, objectWithPath := range resp.Message.SimpleRsp.IMethodResponse.ReturnValue.ValueObjectWithPaths { if nil != objectWithPath.Class { results = append(results, objectWithPath.Class.Name) } } for _, objectWithLocalPath := range resp.Message.SimpleRsp.IMethodResponse.ReturnValue.ValueObjectWithLocalPaths { if nil != objectWithLocalPath.Class { results = append(results, objectWithLocalPath.Class.Name) } } return results, nil } func NewClientCIMXML(u *url.URL, insecure bool) (*ClientCIMXML, error) { c := &ClientCIMXML{} c.init(u, insecure) return c, nil }
c4983c59a2fae0b3215009d45c2ddde93ab8d17e
[ "Go" ]
1
Go
raysdata/gowbem
88ae45419d19314027413b954d64a7483f322d86
0371142bbdce9ae08bc75d6a51e648cf66956f39
refs/heads/master
<file_sep>// // Created by jmarierr on 2019-12-09. // #ifndef BATTLEARENA_SETUP_H #define BATTLEARENA_SETUP_H #include "../utils/includes.h" class setup { private: SDL_Window *win = nullptr; SDL_GLContext context; std::string terrainfile; public: int width = 0, height = 0; setup(); ~setup(); void initialize(int width, int height); void clear(); const std::string &getTerrainfile() const; void setTerrainfile(const std::string &terrainfile); SDL_Window* getWin(); }; #endif //BATTLEARENA_SETUP_H <file_sep>// // Created by jmarierr on 2019-12-09. // #include "bulletManager.h" bulletManager::bulletManager() { } bulletManager::~bulletManager() { } void bulletManager::update(terrainManager *terrain) { for (int i = 0; i < bullets.size(); i++) { int nbCollision=0; for(wall* w : *terrain->walls) { if(!((bullets[i].position.x-10>=w->x-550)|| (bullets[i].position.x+10<=w->x-650)|| bullets[i].position.y-5>=w->y-200|| bullets[i].position.y+5<=w->y-300)) { nbCollision++; } } if (bullets[i].estExpire()||nbCollision!=0|| !bullets[i].isAlive) { gluDeleteQuadric(bullets[i].params); bullets.erase(bullets.begin()+i); } else { bullets[i].update(); } } } void bulletManager::initialiser() { } <file_sep>// // Created by jmarierr on 2019-12-11. // #ifndef BATTLEARENA_FLOW_H #define BATTLEARENA_FLOW_H #include "../utils/includes.h" class flow { protected: bool isRunning; SDL_Event event; const Uint8 *state; setup* settings; public: flow(); ~flow(); virtual void initialize(setup* _settings); virtual void updateFlow(); virtual void clearWindow(); virtual void manageEvents(); virtual void draw(); virtual void pauseFrame(); virtual void updateWindow(); virtual void clearFlow(); virtual bool getIsRunning() const; }; #endif //BATTLEARENA_FLOW_H <file_sep>// // Created by jmarierr on 2019-12-10. // #include "wall.h" wall::wall(int x, int y, int width, int length, GLuint texture) : x(x), y(y), width(width), length(length), idTexture(texture){ height = 20; } wall::~wall(){ glDeleteTextures(1, &idTexture); glDeleteLists(idList, 1); } void wall::createWall(){ idList = glGenLists(1); width *= 2; length *= 2; glNewList(idList, GL_COMPILE); glPushMatrix(); glBindTexture(GL_TEXTURE_2D, idTexture); glTranslated(x, 0, y); glBegin(GL_QUADS); glTexCoord2f(0, 0);glVertex3d(0, 0, 0); glTexCoord2f(1, 0);glVertex3d(0, 0, length); glTexCoord2f(1, 1);glVertex3d(width, 0, length); glTexCoord2f(0, 1);glVertex3d(width, 0, 0); glTexCoord2f(0, 0);glVertex3d(0, 0, 0); glTexCoord2f(1, 0);glVertex3d(0, 0, length); glTexCoord2f(1, 1);glVertex3d(0, height, length); glTexCoord2f(0, 1);glVertex3d(0, height, 0); glTexCoord2f(0, 0);glVertex3d(0, 0, 0); glTexCoord2f(1, 0);glVertex3d(0, height, 0); glTexCoord2f(1, 1);glVertex3d(width, height, 0); glTexCoord2f(0, 1);glVertex3d(width, 0, 0); glTexCoord2f(0, 0);glVertex3d(width, 0, 0); glTexCoord2f(1, 0);glVertex3d(width, height, 0); glTexCoord2f(1, 1);glVertex3d(width, height, length); glTexCoord2f(0, 1);glVertex3d(width, 0, length); glTexCoord2f(0, 0);glVertex3d(width, 0, length); glTexCoord2f(1, 0);glVertex3d(width, height, length); glTexCoord2f(1, 1);glVertex3d(0, height, length); glTexCoord2f(0, 1);glVertex3d(0, 0, length); glTexCoord2f(0, 0);glVertex3d(0, height, length); glTexCoord2f(1, 0);glVertex3d(width, height, length); glTexCoord2f(1, 1);glVertex3d(width, height, 0); glTexCoord2f(0, 1);glVertex3d(0, height, 0); glEnd(); glPopMatrix(); glEndList(); } <file_sep>// // Created by jmarierr on 2019-12-09. // #include "Bullet.h" Bullet::~Bullet() { } void Bullet::update() { if(tempsExpiration>0) { position.x += velociteX * cos((angleTir * M_PI) / 180.0); position.y -= velociteZ * sin((angleTir * M_PI) / 180.0); } } void Bullet::drawBullet() { glTranslatef(position.x,1,position.y); update(); glRotatef(angleTir+90,0,1,0); glScalef(10,10,10); gluCylinder(params,0.2f,0.2f,1,20,20); glTranslatef(0,0,1); gluCylinder(params,.5f,0.1f,1,20,20); glPopMatrix(); glPushMatrix(); tempsExpiration--; } void Bullet::initialiser(float angle){ params = gluNewQuadric(); velociteX=10; velociteZ=10; tempsExpiration=10; isAlive=true; angleTir=angle; } void Bullet::atteindreCible(IDestructive *destructive, int degat) { destructive->recevoirDommage(degat); } bool Bullet::estExpire() { if(tempsExpiration<0) return true; else return false; } <file_sep>// // Created by okotcham on 12/11/2019. // #ifndef BATTLEARENA_DIRECTION_H #define BATTLEARENA_DIRECTION_H enum Direction{AVANCE,RECULE,TOURNER_GAUCHE,TOURNER_DROITE,TOURNER_CANON_GAUCHE,TOURNER_CANON_DROITE,NONE}; #endif //BATTLEARENA_DIRECTION_H <file_sep>// // Created by jmarierr on 2019-12-10. // #include "terrain.h" #include "../gameflow/gamesetup.h" terrain::terrain(){ tileWidth = tileLength = 50; walls = new std::vector<wall*>(); idGroundTex = loadTexture("../assets/sand.jpg"); idWallTex = loadTexture("../assets/rock.jpg"); readFile(gamesetup::mapFile); createTerrain(); h = new hud(); } terrain::~terrain(){ delete h; for(wall* w: *walls){ delete w; } glDeleteTextures(1,&idGroundTex); glDeleteLists(idList, 1); } void terrain::readFile(const std::string path) { std::ifstream infile; infile.open(path); //compte le nombre de rangee se trouve dans le fichier pour pouvoir utiliser Length plus tard if (infile) { std::string line; int nbLine = 0; while (std::getline(infile, line)) { nbLine++; } length = nbLine * tileLength; infile.close(); } infile.open(path); if (!infile) { std::cout << "Unable to open file datafile.txt"; } //lire le fichier txt et creer un mur dependement de ce que contient le fichier else { std::string line; int nbLine = 0; while (std::getline(infile, line)) { width = tileWidth * line.size(); for(int i = 0; i < line.size(); i++){ if(line[i] == '1'){ walls->push_back(new wall(tileWidth * 2 * i, tileLength * 2 * nbLine, tileWidth, tileLength, idWallTex)); } } nbLine++; } infile.close(); } } void terrain::createTerrain(){ idList = glGenLists(1); glNewList(idList, GL_COMPILE); glPushMatrix(); glColor3f(1, 1, 1); glBindTexture(GL_TEXTURE_2D, idGroundTex); glBegin(GL_QUADS); glTexCoord2f(0, 0);glVertex3d(-width, 0, -length); glTexCoord2f(0, 50);glVertex3d(width, 0, -length); glTexCoord2f(50, 50);glVertex3d(width, 0, length); glTexCoord2f(50, 0);glVertex3d(-width, 0, length); glEnd(); glPopMatrix(); glEndList(); //glTranslatef(width - tileWidth/2, 0, -length + tileLength / 2); for(wall* w : *walls){ w->createWall(); } } GLuint terrain::getIdList() const { return idList; } std::vector<wall*> *terrain::getWalls() const { return walls; } int terrain::getWidth() const { return width; } int terrain::getLength() const { return length; } int terrain::getTileWidth() const { return tileWidth; } int terrain::getTileLength() const { return tileLength; } <file_sep>// // Created by jmarierr on 2019-12-12. // #ifndef BATTLEARENA_MENUFLOW_H #define BATTLEARENA_MENUFLOW_H #include "../utils/includes.h" #include "flow.h" class menuflow : public flow { private: }; #endif //BATTLEARENA_MENUFLOW_H <file_sep>// // Created by okotcham on 12/11/2019. // #ifndef BATTLEARENA_CAMERA_H #define BATTLEARENA_CAMERA_H #include <math.h> class Camera { private: public: float eyeX; float eyeY; float eyeZ; float cibleX; float cibleY; float cibleZ; void changerPosition(float angle); void initialiser(); }; #endif //BATTLEARENA_CAMERA_H <file_sep>// // Created by okotcham on 12/11/2019. // #include "IDestructive.h" void IDestructive::recevoirDommage(int bulletDommage) { } <file_sep>// // Created by jmarierr on 2019-12-10. // #ifndef BATTLEARENA_TERRAINMANAGER_H #define BATTLEARENA_TERRAINMANAGER_H #include "../utils/includes.h" #include "../entities/terrain.h" class terrainManager { private: terrain *arena; public: std::vector<wall*>* walls; terrainManager(); ~terrainManager(); void updateManager(); }; #endif //BATTLEARENA_TERRAINMANAGER_H <file_sep>// // Created by jmarierr on 2019-12-10. // #ifndef BATTLEARENA_TERRAIN_H #define BATTLEARENA_TERRAIN_H #include "../utils/includes.h" #include "wall.h" #include "ui/hud.h" class terrain { private: int width, length, tileWidth, tileLength; GLuint idList; GLuint idGroundTex, idWallTex; //int divisionsX, divisionsZ; //nombre de divisions pour les murs sur les axes x et z std::vector<wall*>* walls; public: hud* h; terrain(); ~terrain(); void readFile(std::string path); void createTerrain(); GLuint getIdList() const; std::vector<wall *> *getWalls() const; int getWidth() const; int getLength() const; int getTileWidth() const; int getTileLength() const; }; #endif //BATTLEARENA_TERRAIN_H <file_sep>// // Created by jmarierr on 2019-12-09. // #include "setup.h" setup::~setup()= default; setup::setup(){} void setup::initialize(int _width, int _height){ // terrainfile = "../../assets/terrain/1.txt"; width = _width; height = _height; SDL_Init(SDL_INIT_EVERYTHING); Mix_Init(MIX_INIT_MP3); SDL_Init(SDL_INIT_VIDEO|SDL_INIT_JOYSTICK); Mix_OpenAudio(22050, AUDIO_S16SYS, 2, 640); if(SDL_NumJoysticks()>=1){ std::cout<<"manette connectée"<<std::endl; SDL_Joystick *joystick=SDL_JoystickOpen(0); std::cout<<"joystick name: "<<SDL_JoystickName(0)<<std::endl; std::cout<<"num axe: "<<SDL_JoystickNumAxes(joystick)<<std::endl; std::cout<<"num button: "<<SDL_JoystickNumButtons(joystick)<<std::endl; std::cout<<"num balls: "<<SDL_JoystickNumBalls(joystick)<<std::endl; std::cout<<"num hats: "<<SDL_JoystickNumHats(joystick)<<std::endl; } //init fenetre en opengl win = SDL_CreateWindow("Battle Arena", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, width, height, SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1); context = SDL_GL_CreateContext(win); glEnable(GL_DEPTH_TEST); glEnable(GL_TEXTURE_2D); // SDL_GL_SetSwapInterval(10); glMatrixMode(GL_PROJECTION); glLoadIdentity( ); gluPerspective(70, (double) 800.0 / 600.0, 1, 1000); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); } void setup::clear(){ SDL_GL_DeleteContext(context); SDL_DestroyWindow(win); SDL_Quit(); } SDL_Window* setup::getWin(){ return win; } const std::string &setup::getTerrainfile() const { return terrainfile; } void setup::setTerrainfile(const std::string &terrainfile) { setup::terrainfile = terrainfile; } <file_sep>// // Created by jmarierr on 2019-12-09. // #ifndef BATTLEARENA_GAMEFLOW_H #define BATTLEARENA_GAMEFLOW_H #include "../utils/includes.h" #include "../managers/terrainManager.h" #include "../managers/tankManager.h" #include "flow.h" class gameflow : public flow { private: terrainManager* terrain; tankManager* tank; int nbPlayers, screenWidth, screenHeight; // std::vector<void (*)(GLint x, GLint y, GLsizei width, GLsizei height)> setViewport; //list of viewport to be used in the loop and draw each players view GLsizei vpWidth, vpHeight; // size of viewport width/height int x1, x2, y1, y2; //test int f = 0; public: gameflow(int nbPlayers, int screenWidth, int screenHeight); ~gameflow(); void initialize(setup* _settings) override; void manageEvents() override; void updateFlow() override; void draw() override; void clearFlow() override; bool getIsRunning() const override; }; #endif //BATTLEARENA_GAMEFLOW_H <file_sep>// // Created by okotcham on 12/11/2019. // #include "Camera.h" void Camera::changerPosition(float angle) { eyeX=-cos((angle*M_PI)/180.0)*300; eyeZ=sin((angle*M_PI)/180.0)*300; } void Camera::initialiser() { eyeX=300; eyeY=500; eyeZ=0; cibleX=0; cibleY=0; cibleZ=0; } <file_sep>// // Created by jmarierr on 2019-12-09. // #ifndef BATTLEARENA_TANK_H #define BATTLEARENA_TANK_H #include <SDL2/SDL.h> #include <GL/gl.h> #include <GL/glu.h> #include "Direction.h" #include "../managers/bulletManager.h" #include "../managers/CameraManager.h" #include "IDestructive.h" #include <vector> #include <math.h> #include <SDL2/SDL_mixer.h> class Tank:public IDestructive { private: GLUquadric* params; float velociteX; float velociteZ; float rotation; float rotationCanon; float vitesseRotationCanon; float vitesseRotation; SDL_Point position; SDL_Point dernierePosition; //SDL_Point possitionTir; int pointDeVie; Mix_Music *music = nullptr; int id; public: bool isAlive; Direction direction; CameraManager camera; bulletManager bullet; Tank(int id); const SDL_Point &getPosition() const; void drawCube(float x, float y, float z,int type); void drawTank(); ~Tank(); void deplacer(Direction direction); void initiliser(); void tirer(); void recevoirDommage(int bulletDommage) override; const SDL_Point &getDernierePosition() const; void setPosition(const SDL_Point &position); void setDernierePosition(const SDL_Point &dernierePosition); int getId() const; void setId(int id); }; #endif //BATTLEARENA_TANK_H <file_sep>// // Created by jmarierr on 2019-12-09. // #ifndef BATTLEARENA_BULLET_H #define BATTLEARENA_BULLET_H #include <SDL2/SDL.h> #include <GL/gl.h> #include <GL/glu.h> #include "IDestructive.h" class Bullet { private: float velociteX; float velociteZ; float tempsExpiration; public: bool isAlive; GLUquadric* params; SDL_Point position; float angleTir; ~Bullet(); void update(); void drawBullet(); void initialiser(float angle); void atteindreCible(IDestructive *destructive, int degat); bool estExpire(); }; #endif //BATTLEARENA_BULLET_H <file_sep>// // Created by jmarierr on 2019-12-12. // #ifndef BATTLEARENA_HUD_H #define BATTLEARENA_HUD_H #include "../../utils/includes.h" class hud { private: GLuint idHealthTex; GLuint idList; public: hud(); ~hud(); void draw(); void createHealthUI(); }; #endif //BATTLEARENA_HUD_H <file_sep>#include "../utils/includes.h" #include "gameflow.h" //attention il faudrait mettre des majuscule au nom des objet int main(int argc, char **args) { setup *settings = new setup(); gameflow *flow = new gameflow(2, 800, 600); settings->initialize(800, 600); flow->initialize(settings); while(flow->getIsRunning()){ flow->updateFlow(); } flow->clearFlow(); settings->clear(); return 0; }<file_sep>// // Created by jmarierr on 2019-12-12. // #include "hud.h" hud::hud(){ idHealthTex = loadTexture("../../assets/ui/healthbar.png"); createHealthUI(); } hud::~hud(){ glDeleteTextures(1, &idHealthTex); } void hud::draw(){ glCallList(idList); } void hud::createHealthUI(){ idList = glGenLists(1); glNewList(idList, GL_COMPILE); glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); gluOrtho2D(0, 1.0, 1.0, 0); glMatrixMode(GL_MODELVIEW); glPushMatrix(); glLoadIdentity(); glPushMatrix(); glBindTexture(idHealthTex, GL_TEXTURE_2D); glColor3f(1.0, 1.0, 1.0); glBegin(GL_QUADS); glTexCoord2f(0, 1.0); glVertex2f(0.05, 0.05); glTexCoord2f(1.0, 1.0); glVertex2f(0.03, 0.05); glTexCoord2f(1.0, 0); glVertex2f(0.3, 0.05); glTexCoord2f(0, 0); glVertex2f(0.05, 0.15); glEnd(); glPopMatrix(); glMatrixMode(GL_PROJECTION); glPopMatrix(); glMatrixMode(GL_MODELVIEW); glPopMatrix(); glEndList(); }<file_sep>// // Created by jmarierr on 2019-12-09. // #ifndef BATTLEARENA_INCLUDES_H #define BATTLEARENA_INCLUDES_H #endif //BATTLEARENA_INCLUDES_H #include <SDL2/SDL.h> #include <GL/gl.h> #include <GL/glu.h> #include <string> #include <fstream> #include <iostream> #include <vector> #include <map> #include "opengl_util.h" #include "../gameflow/setup.h" #include <SDL2/SDL_mixer.h><file_sep>// // Created by jmarierr on 2019-12-12. // #include "menuflow.h" <file_sep>// // Created by okotcham on 12/11/2019. // #ifndef BATTLEARENA_IDESTRUCTIVE_H #define BATTLEARENA_IDESTRUCTIVE_H class IDestructive { public: virtual void recevoirDommage(int bulletDommage); }; #endif //BATTLEARENA_IDESTRUCTIVE_H <file_sep>batle arena controle du premier tank -avancer: touche up -reculer: touche douwn -tourner tank gauche: touche LEFT -tourner tank droite: touche RIGHT -tourner canon tank à gauche: touche A -tourner canon tank à droite: touche D -tirer: touche espace controle du deuxieme tank -avancer: touche I -reculer: touche K -tourner tank gauche: touche J -tourner tank droite: touche L -tourner canon tank à gauche: touche end(clavier nimerique) -tourner canon tank à droite: touche home -tirer: touche enter(clavier numerique)<file_sep>// // Created by jmarierr on 2019-12-11. // #ifndef BATTLEARENA_GAMESETUP_H #define BATTLEARENA_GAMESETUP_H #include "../utils/includes.h" namespace gs{ } class gamesetup { public: static int nbPlayers; static int gameTimer; static std::string mapFile; gamesetup(); ~gamesetup(); static void setNbPlayers(int nbPlayers); static void setGameTimer(int gameTimer); static void setMapFile(const std::string &mapFile); static int getNbPlayers(); static int getGameTimer(); static const std::string &getMapFile(); }; #endif //BATTLEARENA_GAMESETUP_H <file_sep>// // Created by jmarierr on 2019-12-11. // #include "gamesetup.h" int gamesetup::nbPlayers = 2; int gamesetup::gameTimer; std::string gamesetup::mapFile = "../assets/terrain/1.txt"; gamesetup::gamesetup(){ } gamesetup::~gamesetup(){ } int gamesetup::getNbPlayers() { return nbPlayers; } int gamesetup::getGameTimer() { return gameTimer; } const std::string &gamesetup::getMapFile() { return mapFile; } void gamesetup::setNbPlayers(int nbPlayers) { gamesetup::nbPlayers = nbPlayers; } void gamesetup::setGameTimer(int gameTimer) { gamesetup::gameTimer = gameTimer; } void gamesetup::setMapFile(const std::string &mapFile) { gamesetup::mapFile = mapFile; } <file_sep>// // Created by jmarierr on 2019-12-10. // #ifndef BATTLEARENA_WALL_H #define BATTLEARENA_WALL_H #include "../utils/includes.h" class wall { private: int width, length, height; GLuint idTexture; GLuint idList; public: int x, y; wall(int x, int y, int width, int length, GLuint texture); ~wall(); void createWall(); //Trump made that function GLuint getIdTexture() const { return idTexture; } GLuint getIdList() const { return idList; } }; #endif //BATTLEARENA_WALL_H <file_sep>// // Created by jmarierr on 2019-12-09. // #ifndef BATTLEARENA_BULLETMANAGER_H #define BATTLEARENA_BULLETMANAGER_H #include "../utils/includes.h" #include "../entities/Bullet.h" #include <vector> #include "../managers/terrainManager.h" class bulletManager { private: public: std::vector<Bullet> bullets; bulletManager(); ~bulletManager(); void update(terrainManager *terrain); void initialiser(); }; #endif //BATTLEARENA_BULLETMANAGER_H <file_sep>// // Created by okotcham on 12/11/2019. // #include "CameraManager.h" CameraManager::CameraManager() { camera=new Camera(); } CameraManager::~CameraManager() { delete camera; } void CameraManager::update(float angle) { camera->changerPosition(angle); } void CameraManager::initialiser() { camera->initialiser(); } Camera *CameraManager::getCamera() const { return camera; } <file_sep>// // Created by jmarierr on 2019-12-09. // #include "tankManager.h" tankManager::tankManager(int nbPlayers) { for (int i = 0; i < nbPlayers; i++) { tankList.push_back(new Tank(i)); } } tankManager::~tankManager() { for(auto t : tankList){ delete t; } tankList.clear(); } void tankManager::update(Direction direction, int idTank) { tankList[idTank]->deplacer(direction); } void tankManager::update(int idTank) { tankList[idTank]->tirer(); } void tankManager::update() { for (Tank* t : tankList) { if(!t->isAlive) tankList.erase(tankList.begin()+t->getId()); } } void tankManager::initialiser() { for (Tank* t : tankList) { t->initiliser(); } } <file_sep>// // Created by jmarierr on 2019-12-10. // #ifndef BATTLEARENA_MANAGER_H #define BATTLEARENA_MANAGER_H class manager { }; #endif //BATTLEARENA_MANAGER_H <file_sep>// // Created by okotcham on 12/11/2019. // #ifndef BATTLEARENA_CAMERAMANAGER_H #define BATTLEARENA_CAMERAMANAGER_H #include "../utils/includes.h" #include "../entities/Camera.h" class CameraManager { private: Camera *camera; public: CameraManager(); ~CameraManager(); void update(float angle); void initialiser(); Camera *getCamera() const; }; #endif //BATTLEARENA_CAMERAMANAGER_H <file_sep>// // Created by jmarierr on 2019-12-09. // #ifndef BATTLEARENA_TANKMANAGER_H #define BATTLEARENA_TANKMANAGER_H #include "../utils/includes.h" #include "../entities/Tank.h" class tankManager { private: //Tank *tank; public: std::vector<Tank*> tankList; tankManager(int nbPlayers); ~tankManager(); void update(Direction direction,int idTank); void update(int idTank); void update(); void initialiser(); }; #endif //BATTLEARENA_TANKMANAGER_H <file_sep>// // Created by jmarierr on 2019-12-09. // #include "gameflow.h" gameflow::gameflow(int nbPlayers, int screenWidth, int screenHeight) : nbPlayers(nbPlayers), screenWidth(screenWidth), screenHeight(screenHeight){ x1 = 10; y1 = 0; x2 = 0; y2 = 0; switch(nbPlayers){ case 1: vpWidth = screenWidth; vpHeight = screenHeight; break; case 2: vpWidth = screenWidth; vpHeight = screenHeight / 2; break; } } gameflow::~gameflow(){ } void gameflow::initialize(setup* _settings){ isRunning = true; settings = _settings; terrain = new terrainManager(); tank=new tankManager(nbPlayers); tank->initialiser(); } void gameflow::manageEvents() { flow::manageEvents(); //controle 1er tank if (state[SDL_SCANCODE_A]) { tank->update(Direction::TOURNER_CANON_GAUCHE,0); } if (state[SDL_SCANCODE_D]) { tank->update(Direction::TOURNER_CANON_DROITE,0); } if (state[SDL_SCANCODE_RIGHT]) { tank->update(Direction::TOURNER_DROITE,0); } if (state[SDL_SCANCODE_LEFT]) { tank->update(Direction::TOURNER_GAUCHE,0); } if (state[SDL_SCANCODE_DOWN]) { tank->update(Direction::RECULE,0); //angle+5; } if (state[SDL_SCANCODE_UP]) { tank->update(Direction::AVANCE,0); } if (state[SDL_SCANCODE_SPACE]) { tank->update(0); } //controle 2eme tank if (state[SDL_SCANCODE_END]) { tank->update(Direction::TOURNER_CANON_GAUCHE,1); } if (state[SDL_SCANCODE_HOME]) { tank->update(Direction::TOURNER_CANON_DROITE,1); } if (state[SDL_SCANCODE_L]) { tank->update(Direction::TOURNER_DROITE,1); } if (state[SDL_SCANCODE_J]) { tank->update(Direction::TOURNER_GAUCHE,1); } if (state[SDL_SCANCODE_K]) { tank->update(Direction::RECULE,1); //angle+5; } if (state[SDL_SCANCODE_I]) { tank->update(Direction::AVANCE,1); } if (state[SDL_SCANCODE_KP_ENTER]) { tank->update(1); } if(tank->tankList.size()==1){ isRunning=false; } //SDL_WaitEvent(&event); SDL_JoystickEventState(SDL_ENABLE); SDL_JoystickUpdate(); if(event.type==SDL_JOYAXISMOTION){ if(event.jaxis.which==0) { if( event.jaxis.axis == 0 ) { //Left of dead zone if( event.jaxis.value < -0 ) { tank->update(Direction::TOURNER_GAUCHE,0); } //Right of dead zone else if( event.jaxis.value > 0 ) { tank->update(Direction::TOURNER_DROITE,0); } } else if( event.jaxis.axis == 1 ) { //Below of dead zone if( event.jaxis.value < -0 ) { tank->update(Direction::RECULE,0); } //Above of dead zone else if( event.jaxis.value > 0 ) { tank->update(Direction::AVANCE,0); } } } } if ( event.type == SDL_JOYHATMOTION ) { // Mouvement d'un chapeau // Nous devons donc utiliser le champ jhat if ( event.jhat.value == SDL_HAT_DOWN ) { tank->update(Direction::RECULE,0); } if ( event.jhat.value == SDL_HAT_LEFT ) { tank->update(Direction::TOURNER_GAUCHE,0); } if ( event.jhat.value == SDL_HAT_RIGHT ) { tank->update(Direction::TOURNER_DROITE,0); } if ( event.jhat.value == SDL_HAT_UP ) { tank->update(Direction::AVANCE,0); } } if(event.type==SDL_JOYBUTTONDOWN){ if(event.jbutton.button==0){ if(event.jbutton.which==0){ tank->update(0); } } printf("Appui sur le bouton %d du joystick %d\n", event.jbutton.button, event.jbutton.which); } } void gameflow::updateFlow(){ clearWindow(); manageEvents(); draw(); pauseFrame(); updateWindow(); } void gameflow::draw(){ for(int i = 0; i < nbPlayers; i++) { if (nbPlayers == 2) { glViewport(0, i * vpHeight, vpWidth, vpHeight); } if (i == 0) { //gluLookAt(x1, 10, y1, 0, 10, 0, 0, 1, 0); gluLookAt(tank->tankList[0]->camera.getCamera()->eyeX + tank->tankList[0]->getPosition().x, tank->tankList[0]->camera.getCamera()->eyeY, tank->tankList[0]->camera.getCamera()->eyeZ + tank->tankList[0]->getPosition().y, tank->tankList[0]->getPosition().x, 0, tank->tankList[0]->getPosition().y, 0, 1, 0 ); glPushMatrix(); terrain->updateManager(); for (int k = 0; k < nbPlayers; k++) { //verifier si le bullet a atteint la cible for (int j = 0; j < tank->tankList[k]->bullet.bullets.size(); j++) { int nbCibleTouche= 0; for (Tank* t: tank->tankList) { if(t->getId()!=k){ std::cout<<"bullet "<<j<<" player "<<k<<" x "<<tank->tankList[k]->bullet.bullets[j].position.x<<" y "<<tank->tankList[k]->bullet.bullets[j].position.y<<std::endl; std::cout<<"playerX "<<t->getPosition().x<<" playerY "<<t->getPosition().y<<std::endl; if(!((t->getPosition().x-15>=tank->tankList[k]->bullet.bullets[j].position.x+10)|| (t->getPosition().x+20<=tank->tankList[k]->bullet.bullets[j].position.x-10)|| t->getPosition().y-10>=tank->tankList[k]->bullet.bullets[j].position.y+5|| t->getPosition().y+10<=tank->tankList[k]->bullet.bullets[j].position.x-5)) { t->recevoirDommage(4); nbCibleTouche++; } } } if(nbCibleTouche!=0){ tank->tankList[k]->bullet.bullets[j].isAlive= false; } } //verifier collision tank avec murs int nbCollision= 0; for(wall* w : *terrain->walls) { if(!((tank->tankList[k]->getPosition().x-15>=w->x-550)|| (tank->tankList[k]->getPosition().x+20<=w->x-650)|| tank->tankList[k]->getPosition().y-10>=w->y-200|| tank->tankList[k]->getPosition().y+10<=w->y-300)) { nbCollision++; } } if(nbCollision!=0){ tank->tankList[k]->setPosition(tank->tankList[0]->getDernierePosition()); } tank->tankList[k]->drawTank(); tank->tankList[k]->bullet.update(terrain); for (int j = 0; j < tank->tankList[k]->bullet.bullets.size(); j++) { tank->tankList[k]->bullet.bullets[j].drawBullet(); } tank->tankList[k]->setDernierePosition(tank->tankList[k]->getPosition()); tank->update(); } glPopMatrix(); } else if (i == 1){ gluLookAt(x2, 10, y2, 10, 10, 5, 0, 1, 0); /*gluLookAt(tank->tankList[1]->camera.getCamera()->eyeX + tank->tankList[1]->getPosition().x, tank->tankList[1]->camera.getCamera()->eyeY, tank->tankList[1]->camera.getCamera()->eyeZ + tank->tankList[1]->getPosition().y, tank->tankList[1]->getPosition().x, 0, tank->tankList[1]->getPosition().y, 0, 1, 0 );*/ terrain->updateManager(); for (int k = 0; k < nbPlayers; k++) { //verifier si le bullet a atteint la cible for (int j = 0; j < tank->tankList[k]->bullet.bullets.size(); j++) { int nbCibleTouche= 0; for (Tank* t: tank->tankList) { if(t->getId()!=k){ if(!((t->getPosition().x-15>=tank->tankList[k]->bullet.bullets[j].position.x+5)|| (t->getPosition().x+20<=tank->tankList[k]->bullet.bullets[j].position.x-5)|| t->getPosition().y-10>=tank->tankList[k]->bullet.bullets[j].position.y+5|| t->getPosition().y+10<=tank->tankList[k]->bullet.bullets[j].position.x-5)){ t->recevoirDommage(4); nbCibleTouche++; } } } if(nbCibleTouche!=0){ tank->tankList[k]->bullet.bullets[j].isAlive= false; } } //verifier collision tank avec murs int nbCollision= 0; for(wall* w : *terrain->walls) { if(!((tank->tankList[k]->getPosition().x-15>=w->x-550)|| (tank->tankList[k]->getPosition().x+20<=w->x-650)|| tank->tankList[k]->getPosition().y-10>=w->y-200|| tank->tankList[k]->getPosition().y+10<=w->y-300)) { nbCollision++; } } if(nbCollision!=0){ tank->tankList[k]->setPosition(tank->tankList[0]->getDernierePosition()); } tank->tankList[k]->drawTank(); tank->tankList[k]->bullet.update(terrain); for (int j = 0; j < tank->tankList[k]->bullet.bullets.size(); j++) { tank->tankList[k]->bullet.bullets[j].drawBullet(); } tank->tankList[k]->setDernierePosition(tank->tankList[k]->getPosition()); } glPopMatrix(); } } } void gameflow::clearFlow(){ delete(settings); } bool gameflow::getIsRunning() const{ return isRunning; }<file_sep>// // Created by jmarierr on 2019-12-10. // #include "terrainManager.h" terrainManager::terrainManager(){ arena = new terrain(); walls=arena->getWalls(); } terrainManager::~terrainManager(){ delete (arena); } void terrainManager::updateManager(){ glCallList(arena->getIdList()); //drawAxis(50); glPushMatrix(); glTranslatef(-arena->getWidth(), 0, -arena->getLength()); //drawAxis(50); for(wall* w: *arena->getWalls()){ glCallList(w->getIdList()); } glPopMatrix(); arena->h->draw(); }<file_sep>// // Created by jmarierr on 2019-12-11. // #include "flow.h" flow::flow(){ } flow::~flow(){ } void flow::initialize(setup* _settings){ isRunning = true; settings = _settings; } void flow::updateFlow(){ } void flow::clearWindow(){ glClearColor(.0f, .0f, .0f, .0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glClearColor(1.f, 1.f, 1.f, 1.f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glLoadIdentity(); } void flow::manageEvents(){ SDL_PollEvent(&event); state = SDL_GetKeyboardState(NULL); if (event.type == SDL_QUIT || state[SDL_SCANCODE_ESCAPE]) { isRunning = false; } } void flow::draw(){ } void flow::pauseFrame() { SDL_Delay(100); } void flow::updateWindow(){ glFlush(); SDL_GL_SwapWindow(settings->getWin()); } void flow::clearFlow(){ } bool flow::getIsRunning() const { return isRunning; } <file_sep>// // Created by jmarierr on 2019-12-09. // #include "Tank.h" Tank::Tank(int id) { this->id=id; } Tank::~Tank() { gluDeleteQuadric(params); Mix_FreeMusic(music); } void Tank::drawCube(float x, float y, float z,int type){ glScalef(x,y,z); if(type==1){ glColor3f(1, 0, 0); } else if(type==2){ glColor3f(0.1, 0, 0.1); } glBegin(GL_QUADS); if (type==0) { glColor3f(1, 0, 0); } glVertex3f(1, -1, -1); glVertex3f(1, 1, -1); glVertex3f(-1, 1, -1); glVertex3f(-1, -1, -1); //cyan if (type==0) { glColor3f(0, 1, 1); } glVertex3f(1, -1, 1); glVertex3f(1, -1, -1); glVertex3f(1, 1, -1); glVertex3f(1, 1, 1); //vert if (type==0) { glColor3f(0, 1, 0); } glVertex3f(1, -1, 1); glVertex3f(1, -1, -1); glVertex3f(-1, -1, -1); glVertex3f(-1, -1, 1); //blue if (type==0) { glColor3f(0, 0, 1); } glVertex3f(-1, -1, 1); glVertex3f(-1, -1, -1); glVertex3f(-1, 1, -1); glVertex3f(-1, 1, 1); //violet if (type==0) { glColor3f(1, 0, 1); } glVertex3f(1, 1, -1); glVertex3f(-1, 1, -1); glVertex3f(-1, 1, 1); glVertex3f(1, 1, 1); //jaune if (type==0) { glColor3f(1, 1, 0); } glVertex3f(1, -1, 1); glVertex3f(1, 1, 1); glVertex3f(-1, 1, 1); glVertex3f(-1, -1, 1); glEnd(); } void Tank::drawTank(){ glPopMatrix(); glPushMatrix(); glTranslatef(position.x, 0, position.y); glRotatef(rotation,0,1,0); glScalef(10,10,10); glTranslatef(0,0.5f,0); drawCube(1.5f, 0.5f, 1, 2); glScalef(0.666666f,2,1); //roues glColor3f(1, 1, 0); glTranslatef(0,0,1); //roue1 glScalef(2,0.4f,0.5f); gluSphere(params, 1,20,20); //roue2 glTranslatef(0,0,-4); gluSphere(params, 1,20,20); glScalef(0.5f,2.5f,2); //#endRoues glTranslatef(0,0,1); glRotatef(-rotation,0,1,0); glTranslatef(0,0.5f,0); glRotatef(rotationCanon,0,1,0); drawCube(1, 0.5f, 0.5f, 1); glScalef(1,2,2); //canon glTranslatef(0,0.25f,0); glColor3f(1, 1, 0); glRotatef(90,0,1,0); gluCylinder(params,0.1f,0.1f,3,100,100); glRotatef(-90,0,1,0); glTranslatef(0,-0.75f,1); glRotatef(-rotationCanon,0,1,0); glPopMatrix(); glPushMatrix(); //roue1 //glScalef(2,0.4f,0.5f); //gluSphere(params, 1,20,20); //roue2 //glTranslatef(0,0,-4); //gluSphere(params, 1,20,20); } void Tank::deplacer(Direction direction) { switch (direction){ case Direction::AVANCE: position.x+=velociteX*cos((rotation*M_PI)/180.0); position.y-=velociteZ*sin((rotation*M_PI)/180.0); break; case Direction::RECULE: position.x-=velociteX*cos((rotation*M_PI)/180.0); position.y+=velociteZ*sin((rotation*M_PI)/180.0); break; case Direction::TOURNER_GAUCHE: rotation+=vitesseRotation; if(rotation>360.0) rotation-=360.0; //camera.update(rotationCanon); camera.update(rotation); break; case Direction::TOURNER_DROITE: rotation-=vitesseRotation; if(rotation<-360.0) rotation+=360.0; camera.update(rotation); break; case Direction::TOURNER_CANON_GAUCHE: rotationCanon+=vitesseRotationCanon; if(rotationCanon>360.0) rotationCanon-=360.0; break; case Direction::TOURNER_CANON_DROITE: rotationCanon-=vitesseRotationCanon; if(rotationCanon<-360.0) rotationCanon+=360.0; break; } this->direction=direction; } void Tank::initiliser() { position={25,30}; dernierePosition=position; params = gluNewQuadric(); velociteX=10; velociteZ=10; vitesseRotation=4; vitesseRotationCanon=4; camera.initialiser(); direction=Direction ::NONE; rotation=180; rotationCanon=180; pointDeVie=20; isAlive= true; music = Mix_LoadMUS("assets/fire.mp3"); } void Tank::tirer() { Bullet b; b.position.x=position.x+30*cos((rotationCanon*M_PI)/180.0);; b.position.y=position.y-30*sin((rotationCanon*M_PI)/180.0); b.initialiser(rotationCanon); std::cout<<"rotationCanon "<<rotationCanon<<std::endl; bullet.bullets.push_back(b); Mix_PlayMusic(music, 0); } const SDL_Point &Tank::getPosition() const { return position; } const SDL_Point &Tank::getDernierePosition() const { return dernierePosition; } void Tank::setPosition(const SDL_Point &position) { Tank::position = position; } void Tank::setDernierePosition(const SDL_Point &dernierePosition) { Tank::dernierePosition = dernierePosition; } void Tank::recevoirDommage(int bulletDommage){ pointDeVie-=bulletDommage; if (pointDeVie <= 0){ std::cout<<"player "<<id+1<<" est mort"<<std::endl; isAlive= false; } } int Tank::getId() const { return id; } void Tank::setId(int id) { Tank::id = id; } <file_sep>// // Created by jmarierr on 2019-12-10. // #include "manager.h"
7bedb76a4ae35a8a84c8f81bf2453080bbc68686
[ "C", "Text", "C++" ]
38
C++
Cpt-Leviathan/battlearena
81ad6f98c639bc4583a6aab4a251baba28569321
f495eb8b4242de7e204f3988fd11cb7bfb59e981
refs/heads/master
<file_sep>const express = require("express"); const ffmpeg = require("fluent-ffmpeg"); const config = require('config'); const router = express.Router(); router.get("/:filename", (req, res) => { const pathToMovie = `${config.get("streamConfig.host")+req.params.filename}`; ffmpeg(pathToMovie) // .videoCodec("libx264") .save(`assets/save/${req.params.filename}.flv`); console.log("video generated"); res.send("Video has been saved"); }); module.exports = router; <file_sep>const express = require("express"); const ffmpeg = require("fluent-ffmpeg"); const config = require("config"); const fs = require("fs"); const request = require("request"); const router = express.Router(); router.get("/", (req, res) => { // let queries = { // tableNo: req.query.tableNo, // gameSet: req.query.gameSet, // gameNo: req.query.gameNo // }; // let pathToMovie = `${config.get("streamConfig.host")}${queries.tableNo}_${ // queries.gameSet // }_${queries.gameNo}.flv`; // let pathToMovie = `${config.get("streamConfig.host")}1_1_3.flv`; let checkMovie = "rtmp://192.168.127.12/vod/1_1_3.flv"; // request(checkMovie, (err, res, body) => { // console.log("error : ", err); // console.log("response : ", res); // console.log("body : ", body); // }); /* let stats = fs.statSync(pathToMovie); let range = req.headers.range || ""; let total = stats.size; let parts = range.replace(/bytes=/, "").split("-"); let partialstart = parts[0]; let partialend = parts[1]; let start = parseInt(partialstart, 10); let end = partialend ? parseInt(partialend, 10) : total - 1; let chunksize = end - start + 1; console.log("stats : ", stats); headers = { "Content-Range": "bytes " + start + "-" + end + "/" + total, "Accept-Ranges": "bytes", "Content-Length": chunksize, "Content-Type": "video/mp4" }; res.writeHead(206, headers); */ res.contentType("mp4"); /* var stream = fs .createReadStream(pathToMovie, { start: start, end: end }) .on("open", () => { stream.pipe(res); }) .on("error", err => { res.end(err); }); res.on("close", () => { // close or destroy stream stream = null; }); */ let videoConverter = ffmpeg(checkMovie) // let videoConverter = ffmpeg(pathToMovie) .videoCodec("libx264") .format("mp4") .outputOptions("-movflags frag_keyframe"); let videoConverted = videoConverter .on("open", param => { console.log("open", param); }) .on("error", err => console.log(err)) // .output(res, { start: start, end: end, close: null }); .pipe( res, // { start: start, end: end } { end: true } ) .on("close", param => { // console.log("output closed", param); videoConverted = null; }); console.log(videoConverted); // videoConverted.output(res, { start: start, end: end, close: null }).run(); }); module.exports = router; <file_sep>const express = require("express"); const ffmpeg = require("fluent-ffmpeg"); const fs = require("fs"); const config = require("config"); // const contentRange = require("content-range"); const router = express.Router(); router.get("/", (req, res) => { // let pathToMovie = `${config.get("streamConfig.host")}1_9_1.flv`; let pathToMovie = `${"rtmp://172.16.17.32/vod/"}1_1_1.flv` //------------ Header Range Implementation start // let stat = fs.statSync(pathToMovie); // let header = contentRange.format({ // unit: "bytes", // first: 0, // limit: 20, // length: stat.size // }); // console.log("bytes " + 0 + "-" + (stat.size - 1) + "/" + stat.size); // console.log(req.headers.range); // console.log(header); // console.log(req.headers.range) //------------ Header Range Implementation end //------------ Coba Coba start // let stats = fs.statSync(pathToMovie); let stats = pathToMovie let range = req.headers.range || ""; let total = stats.size; console.log(total) //------------ Coba Coba end // res.contentType("mp4"); let parts = range.replace(/bytes=/, "").split("-"); let partialstart = parts[0]; let partialend = parts[1]; let start = parseInt(partialstart, 10); let end = partialend ? parseInt(partialend, 10) : total-1; let chunksize = (end-start) + 1; headers = { "Content-Range": "bytes " + start + "-" + end + "/" + total, "Accept-Ranges": "bytes", // "Content-Length": chunksize, "Content-Type": "video/mp4", Connection: "keep-alive" }; res.writeHead(206, headers); // console.log("start : ", start); // console.log("end : ", end); // console.log("range : " + range); ffmpeg(pathToMovie) .outputOption("-c:v libx264") .outputOption("-f mp4") // .outputOption("-movflags frag_keyframe+empty_moov+faststart") .outputOption("-movflags frag_keyframe") .on("error", (err, stdout, stderr) => { console.log(err); console.log(stdout); console.log(stderr); }) // .pipe(res, { end: true }) .output(res, { end: true }) .run(); // res.send("done"); }); module.exports = router; <file_sep>const express = require("express"); const ffmpeg = require("fluent-ffmpeg"); const config = require("config"); const fs = require("fs"); const http = require("http"); const router = express.Router(); router.get("/", (req, res) => { let queries = { tableNo: req.query.tableNo, gameSet: req.query.gameSet, gameNo: req.query.gameNo }; // let otherPath = `${config.get("streamConfig.host")}${queries.tableNo}_${ // queries.gameSet // }_${queries.gameNo}.flv`; // let pathToMovie = `${"rtmp://192.168.3.11/vod/"}4_1_3.flv`; let pathToMovie = `${"rtmp://192.168.3.11/vod/"}${queries.tableNo}_${ queries.gameSet }_${queries.gameNo}.flv`; res.contentType("mp4"); // ---------------------------------------------------- Range Header Implementation Start /* let stats = pathToMovie; // let stats = fs.statSync(pathToMovie); // let statscoba = fs.lstatSync(pathToMovieCoba); let range = req.headers.range || ""; let total = stats.size; let parts = range.replace(/bytes=/, "").split("-"); let partialstart = parts[0]; let partialend = parts[1]; let start = parseInt(partialstart, 10); let end = partialend ? parseInt(partialend, 10) : total - 1; let chunksize = end - start + 1; console.log("stats : ", stats); // console.log("statcoba : ", statscoba); headers = { "Content-Range": "bytes " + start + "-" + end + "/" + total, "Accept-Ranges": "bytes", "Content-Length": chunksize, "Content-Type": "video/mp4", Connection: "keep-alive" }; res.writeHead(206, headers); */ // ---------------------------------------------------- Range Header Implementation End /* let videoConverter = ffmpeg(pathToMovie) // .videoCodec("libx264") .outputOptions("-c:v libx264") // .outputOptions("-sameq") .outputOptions("-f mp4") // .outputOptions("-vcodec libx264") .outputOptions("-movflags frag_keyframe+faststart") // .outputOptions("-movflags frag_keyframe+empty_moov +faststart") .size("640x?") .on("end", () => { console.log("ready"); }) .on("error", (err, stdout, stderr) => { console.log("Somethings wrong : ", err); console.log("ffmpeg stdout: ", stdout); console.log("ffmpeg stderr: ", stderr); // res.render("notfound.html"); // alert("not found") }); */ let videoConverter = ffmpeg(pathToMovie) // .outputOptions("-c:v libx264") // .outputOptions("-f mp4") .videoCodec("libx264") .format("mp4") // .outputOptions("-movflags frag_keyframe+faststart") .outputOptions("-movflags frag_keyframe"); // .size("640x?") // ffmpeg.ffprobe(videoConverter, function(err, metadata) { // if (err) { // console.error(err); // } else { // // metadata should contain 'width', 'height' and 'display_aspect_ratio' // console.log(metadata); // } // }); let videoConverted = videoConverter .on("end", apapun => { console.log(apapun); }) .on("error", err => console.log(err)) .output(res, { end: true }); videoConverted.run(); }); module.exports = router; <file_sep>const express = require("express"); const router = express.Router(); const ffmpegPath = require('@ffmpeg-installer/ffmpeg').path; const ffmpeg = require("fluent-ffmpeg"); const config = require("config"); const path = require("path"); ffmpeg.setFfmpegPath(ffmpegPath); router.get("/", (req, res) => { let queries = { tableNo: req.query.tableNo, gameSet: req.query.gameSet, gameNo: req.query.gameNo }; let emptyQuery = []; if ( queries.tableNo !== undefined && queries.tableNo.length > 0 && (queries.gameSet !== undefined && queries.gameSet.length > 0) && (queries.gameNo !== undefined && queries.gameNo.length > 0) ) { res.contentType("mp4"); let pathToMovie = `${config.get("streamConfig.host")}${queries.tableNo}_${ queries.gameSet }_${queries.gameNo}.flv`; ffmpeg(pathToMovie) .outputOptions("-c:v libx264") // .outputOptions("-t 3") // .outputOptions("-pix_fmt yuv420p") .outputOptions("-f mp4") // .size("1024x?") .outputOptions("-movflags frag_keyframe+empty_moov") // .on("start", function(commandLine) { // console.log("Spawned Ffmpeg with command: " + commandLine); // }) .on("end", () => { console.log( `stream video ${queries.tableNo}_${queries.gameSet}_${ queries.gameNo }.flv is ready` ); }) .on("error", (err, stdout, stderr) => { console.log("Somethings wrong : ", err); console.log("ffmpeg stdout: ", stdout); console.log("ffmpeg stderr: ", stderr); // res.render("notfound.html"); // alert("not found") }) .output(res, { end: true }) .run(); } else { for (let index = 0; index < Object.entries(queries).length; index++) { if ( Object.values(queries)[index] === undefined || Object.values(queries)[index].length === 0 ) { emptyQuery.push(Object.keys(queries)[index]); } } console.log(`${emptyQuery} is not defined`); res.send(`${emptyQuery} is not defined`); } }); module.exports = router; <file_sep>// const express = require("express"); // const router = express.Router(); const ffmpeg = require("fluent-ffmpeg"); const videoArray = [ "4_21_13.flv", "42_28_43.flv", "38_26_52.flv", "20051210-w50s.flv.flv" ]; let videoCounter = 0; let totalVideo = 0; { /* <table_no>_<gameset>_<gameno>.flv */ } // router.get("/", (req, res) => { for (let tableNo = 0; tableNo < 9; tableNo++) { for (let gameSet = 0; gameSet < 9; gameSet++) { for (let gameNo = 0; gameNo < 9; gameNo++) { if (videoCounter === videoArray.length) { videoCounter = 0; } // generate video ffmpeg(`assets/video/${videoArray[videoCounter]}`).save( `assets/videos/${tableNo + 1}_${gameSet + 1}_${gameNo + 1}.flv` ); // log the result console.log( `${tableNo + 1}_${gameSet + 1}_${gameNo + 1}.flv = from video = ${ videoArray[videoCounter] } is generated & video Counter is ${videoCounter}` ); videoCounter++; totalVideo++; } } } console.log(`Total ${totalVideo} Video is generated`); // res.send("done"); // }); // module.exports = router;
9f33a6c6b5f1bf605e8e854ae3abd007e9f8350b
[ "JavaScript" ]
6
JavaScript
normanBPT/videoconverter
7749474a236f0f89bbf088127ff571d629e86efb
f34de5acb817067ae0c1b693e56fa7bb328141ab
refs/heads/master
<repo_name>rdhelms/asteroids<file_sep>/README.md # asteroids The beginnings of the Asteroids game for use in teaching JavaScript at The Iron Yard https://rdhelms.github.io/asteroids/ <file_sep>/game.js (function gameSetup() { 'use strict'; var shipElem = document.getElementById('ship'); // Create your "ship" object and any other variables you might need... var gameWidth = document.documentElement.clientWidth; var gameHeight = document.documentElement.clientHeight; //Game timer var timer = 0; //Initial display var state = "begin"; var main = document.querySelector("main"); var display = document.createElement('div'); shipElem.style.visibility = "hidden"; display.style.position = "absolute"; display.style.zIndex = "1"; display.style.opacity = "0.5"; display.style.top = "50%"; display.style.left = "50%"; display.style.transform = "translate(-50%, -50%)"; display.style.color = "white"; display.style.background = "black"; display.style.fontSize = "5em"; display.style.textAlign = "center"; display.innerHTML = "PRESS ENTER TO PLAY"; main.appendChild(display); var ship = { body: shipElem.style, velocity: 0, angle: 0, x: gameWidth/2, y: gameHeight/2, top: shipElem.getBoundingClientRect().top, left: shipElem.getBoundingClientRect().left, right: shipElem.getBoundingClientRect().right, bottom: shipElem.getBoundingClientRect().bottom, missileSpeed: 5, update: function () { this.top = shipElem.getBoundingClientRect().top; this.left = shipElem.getBoundingClientRect().left; this.right = shipElem.getBoundingClientRect().right; this.bottom = shipElem.getBoundingClientRect().bottom; }, }; function Asteroid(detail, top, left, right, bottom) { this.detail = detail; this.top = top; this.left = left; this.right = right; this.bottom = bottom; this.update = function () { this.top = this.detail.getBoundingClientRect().top; this.left = this.detail.getBoundingClientRect().left; this.right = this.detail.getBoundingClientRect().right; this.bottom = this.detail.getBoundingClientRect().bottom; }; } var allMissiles = []; function Missile(detail, x, y, dx, dy, id) { this.detail = detail; this.x = x; this.y = y; this.dx = dx; this.dy = dy; this.id = id; this.top = null; this.left = null; this.right = null; this.bottom = null; this.update = function () { this.x -= this.dx; this.y -= this.dy; this.detail.style.left = parseFloat(this.x) + "px"; this.detail.style.top = parseFloat(this.y) + "px"; this.top = this.detail.getBoundingClientRect().top; this.left = this.detail.getBoundingClientRect().left; this.right = this.detail.getBoundingClientRect().right; this.bottom = this.detail.getBoundingClientRect().bottom; }; } //Reset game conditions when player presses enter function resetShip() { ship.body.visibility = "visible"; ship.velocity = 0; ship.angle = 0; ship.x = gameWidth/2; ship.y = gameHeight/2; } var allAsteroids = []; shipElem.addEventListener('asteroidDetected', function (event) { // You can detect when a new asteroid appears with this event. // The new asteroid's HTML element will be in: event.detail // What might you need/want to do in here? var newAsteroid = event.detail; var topBorder = newAsteroid.getBoundingClientRect().top; var leftBorder = newAsteroid.getBoundingClientRect().left; var right = newAsteroid.getBoundingClientRect().right; var bottom = newAsteroid.getBoundingClientRect().height; var asteroidObject = new Asteroid(newAsteroid, topBorder, leftBorder, right, bottom); allAsteroids.push(asteroidObject); }); /** * Use this function to handle when a key is pressed. Which key? Use the * event.keyCode property to know: * * 13 = enter * 32 = space * 37 = left * 38 = up * 39 = right * 40 = down * * @param {Event} event The "keyup" event object with a bunch of data in it * @return {void} In other words, no need to return anything */ function handleKeys(event) { console.log(event.keyCode); var key = event.keyCode; // Implement me! switch (key) { case 13: if (state == "begin") { resetShip(); display.style.visibility = "hidden"; state = "play"; } break; case 32: if (state == "play") { //Create missile var shotHTML = document.createElement("div"); shotHTML.style.position = "absolute"; shotHTML.style.width = "4px"; shotHTML.style.height = "4px"; shotHTML.style.background = "white"; main.appendChild(shotHTML); var shotMove = getShipMovement(ship.missileSpeed, ship.angle); var shotX = (ship.left + ship.right)/2; var shotY = (ship.top + ship.bottom)/2; var id = allMissiles.length; var shot = new Missile(shotHTML, shotX, shotY, shotMove.left, shotMove.top, id); allMissiles.push(shot); } else if (state == "over") { location.reload(); } break; case 37: //Increase angle ship.angle+=20; break; case 38: //Decrease velocity variable, increase velocity in game ship.velocity--; break; case 39: //Decrease angle ship.angle-=20; break; case 40: //Increase velocity variable, decrease velocity in game. // Check to make sure ship can not go backwards if (ship.velocity >= 0) { ship.velocity = 0; } else { ship.velocity++; } break; } console.clear(); console.log("Ship velocity: " + ship.velocity); console.log("Ship angle: " + ship.angle); console.log("Ship x: " + ship.x); console.log("Ship y: " + ship.y); console.log("Left of ship: " + ship.body.left); console.log("Top of ship: " + ship.body.top); console.log("Left of ship box: " + ship.left); console.log("Right of ship box: " + ship.right); console.log("Top of ship box: " + ship.top); console.log("Bottom of ship box: " + ship.bottom); console.log("Game width: " + gameWidth); console.log("Game height: " + gameHeight); console.log("Asteroids: " + allAsteroids); console.log("Missiles: " + allMissiles); console.log("First asteroid's left side: " + allAsteroids[0].left); console.log("First asteroid's right side: " + allAsteroids[0].right); console.log("First asteroid's top: " + allAsteroids[0].top); console.log("First asteroid's bottom: " + allAsteroids[0].bottom); } document.querySelector('body').addEventListener('keyup', handleKeys); /** * This is the primary "game loop"... in traditional game development, things * happen in a loop like this. This function will execute every 20 milliseconds * in order to do various things. For example, this is when all game entities * (ships, etc) should be moved, and also when things like hit detection happen. * * @return {void} */ function gameLoop() { if (state == "begin") { } else if (state == "play") { // This function for getting ship movement is given to you (at the bottom). // NOTE: you will need to change these arguments to match your ship object! // What does this function return? What will be in the `move` variable? // Read the documentation! var move = getShipMovement(ship.velocity, ship.angle); //Refresh game dimensions in case browser window changes gameWidth = document.documentElement.clientWidth; gameHeight = document.documentElement.clientHeight; // Move the ship here! if (ship.x < -10) { ship.x = gameWidth; } else if (ship.x > gameWidth + 10) { ship.x = 0; } if (ship.y < -10) { ship.y = gameHeight; } else if (ship.y > gameHeight + 10) { ship.y = 0; } ship.x += move.left; ship.y += move.top; ship.body.left = parseFloat(ship.x) + "px"; ship.body.top = parseFloat(ship.y) + "px"; var rotateString = "rotate(" + -1*ship.angle + "deg)"; ship.body.transform = rotateString; // Time to check for any collisions (see below)... checkForCollisions(); //For scoring timer += 0.02; display.style.position = "absolute"; display.style.zIndex = "1"; display.style.top = "0"; display.style.left = "0"; display.style.width = "300px"; display.style.transform = "translate(0, 0)"; display.style.color = "white"; display.style.opacity = "0.5"; display.style.background = "gray"; display.style.fontSize = "3em"; display.style.textAlign = "left"; display.innerHTML = "Score = " + Math.round(timer) + " Level: " + allAsteroids.length; display.style.visibility = "visible"; } } /** * This function checks for any collisions between asteroids and the ship. * If a collision is detected, the crash method should be called with the * asteroid that was hit: * crash(someAsteroidElement); * * You can get the bounding box of an element using: * someElement.getBoundingClientRect(); * * A bounding box is an object with top, left, width, and height properties * that you can use to detect whether one box is on top of another. * * @return void */ function checkForCollisions() { // Implement me! for (var index = 0; index < allAsteroids.length; index++) { var current = allAsteroids[index]; for (var missileIndex = 0; missileIndex < allMissiles.length; missileIndex++) { var currentMissile = allMissiles[missileIndex]; currentMissile.update(); if (allMissiles.length > 5) { var old = allMissiles[0]; old.detail.style.display = "none"; allMissiles.splice(0,1); } if (current.right > currentMissile.left && current.top < currentMissile.bottom && current.bottom > currentMissile.top && current.left < currentMissile.right) { current.detail.style.display = "none"; currentMissile.detail.style.display = "none"; } } ship.update(); current.update(); if (current.right > ship.left && current.top < ship.bottom && current.bottom > ship.top && current.left < ship.right) { crash(current.detail); } } } /** * This event handler will execute when a crash occurs * * return {void} */ document.querySelector('main').addEventListener('crash', function () { console.log('A crash occurred!'); // What might you need/want to do in here? //Stop game from looping clearInterval(loopHandle); loopHandle = 0; //Restart keyup handler document.querySelector('body').addEventListener('keyup', handleKeys); //Change game state state = "over"; //Display "GAME OVER!" var final = document.createElement("div"); final.style.position = "absolute"; final.style.top = gameHeight/2+"px"; final.style.left = gameWidth/2+"px"; final.style.transform = "translate(-50%, -50%)"; final.style.opacity = "0.5"; final.style.background = "black"; final.style.fontSize = "5em"; final.style.color = "white"; final.style.textAlign = "center"; final.innerHTML = "GAME OVER!<br>Press space to play again"; main.appendChild(final); }); /** ************************************************************************ * These functions and code are given to you. * * !!! DO NOT EDIT BELOW HERE !!! ** ************************************************************************/ var loopHandle = setInterval(gameLoop, 20); /** * Executes the code required when a crash has occurred. You should call * this function when a collision has been detected with the asteroid that * was hit as the only argument. * * @param {HTMLElement} asteroidHit The HTML element of the hit asteroid * @return {void} */ function crash(asteroidHit) { document.querySelector('body').removeEventListener('keyup', handleKeys); asteroidHit.classList.add('hit'); document.querySelector('#ship').classList.add('crash'); var event = new CustomEvent('crash', { detail: asteroidHit }); document.querySelector('main').dispatchEvent(event); } /** * Get the change in ship position (movement) given the current velocity * and angle the ship is pointing. * * @param {Number} velocity The current speed of the ship (no units) * @param {Number} angle The angle the ship is pointing (no units) * @return {Object} The amount to move the ship by with regard to left and top position (object with two properties) */ function getShipMovement(velocity, angle) { return { left: (velocity * Math.sin(angle * Math.PI / 180)), top: (velocity * Math.cos(angle * Math.PI / 180)) }; } })();
66a5da63786136208092dc20af9802f24cafe344
[ "Markdown", "JavaScript" ]
2
Markdown
rdhelms/asteroids
4349e9db6c3284ed382a60605da500959a313db8
c3fd1d857537a5371ef92f87320db6504f7c0008
refs/heads/master
<repo_name>Adalewis/MEAN-stack<file_sep>/src/app/posts/posts.service.ts import { Injectable } from "@angular/core"; import { HttpClient } from "@angular/common/http"; import { Subject } from "rxjs";//Subject is event emitter import { map } from 'rxjs/operators'; import { Post } from "./post.model"; import { Router } from "@angular/router"; //instead of placing PostsService in providers of app.module @ngModule //use @Injectable so PostsService is available from the root @Injectable({ providedIn: "root" }) export class PostsService { private posts: Post[] = []; //Subject passess list of posts private postsUpdated = new Subject<Post[]>(); //injecting httpclient and binded as private property constructor(private http: HttpClient, private router: Router) {} getPosts() { this.http //get body of response .get<{ message: string; posts: any }>( "http://localhost:3000/api/posts" ) //actions to handle data before they get to subscribe, //add in a map() operator through pipe() to create _id, //wrap in observable and passed to subscription .pipe(map((postData) => { return postData.posts.map(post => { return { title: post.title, content: post.content, id: post._id }; }); })) //given by rxjs, when there is a change that is observed //subscribe method gets called .subscribe(convertedPosts => { this.posts = convertedPosts; //new array created with spread operator this.postsUpdated.next([...this.posts]); }); } getPostUpdateListener() { return this.postsUpdated.asObservable(); } getPost(id: string) { return this.http.get<{ _id: string; title: string; content: string }>( "http://localhost:3000/api/posts/" + id ); } addPost(title: string, content: string) { const post: Post = { id: null, title: title, content: content }; this.http .post<{ message: string, postId: string }>( "http://localhost:3000/api/posts", post) .subscribe(responseData => { const id = responseData.postId; //updates null value of Post id to the id sent so posts can be sent without error post.id = id; this.posts.push(post); //actively updates frontend when posts are added this.postsUpdated.next([...this.posts]); this.router.navigate(["/"]); }); } updatePost(id: string, title: string, content: string) { const post: Post = { id: id, title: title, content: content }; this.http .put("http://localhost:3000/api/posts/" + id, post) .subscribe(response => { const updatedPosts = [...this.posts]; const oldPostIndex = updatedPosts.findIndex(p => p.id === post.id); updatedPosts[oldPostIndex] = post; this.posts = updatedPosts; this.postsUpdated.next([...this.posts]); this.router.navigate(["/"]); }); } //post-list.component's onDelete method sends request to deletePost which updates angular frontend via filter deletePost(postId: string) { this.http.delete("http://localhost:3000/api/posts/" + postId) .subscribe(() => { //actively updates view of frontend after delete //filter() returns subset that is true where postId const updatedPosts = this.posts.filter(post => post.id !== postId); this.posts = updatedPosts; this.postsUpdated.next([...this.posts]); }); } } <file_sep>/src/app/posts/post-list/post-list.component.ts import { Component, OnInit, OnDestroy } from "@angular/core"; import { Subscription } from 'rxjs'; import { Post } from "../post.model"; import { PostsService } from "../posts.service"; @Component({ selector: "app-post-list", templateUrl: "./post-list.component.html", styleUrls: ["./post-list.component.css"] }) export class PostListComponent implements OnInit, OnDestroy { //Post from post.model posts: Post[] = []; isLoading = false; //store subscription to prevent memory leak private postsSub: Subscription; constructor(public postsService: PostsService) {} //initialization tasks ngOnInit() { this.isLoading = true; this.postsService.getPosts(); this.postsSub = this.postsService.getPostUpdateListener() //subscribe connects observer with observables to see items emitted by observable .subscribe((posts: Post[]) => { this.isLoading = false; this.posts = posts; }); } onDelete(postId: string) { //uses delete method from posts.service.ts this.postsService.deletePost(postId); } //when component is removed subscription unsubscribe/ prevents memory leak ngOnDestroy() { this.postsSub.unsubscribe(); } }
1fe7a76599e1b4d119c044b621608c19e35742ee
[ "TypeScript" ]
2
TypeScript
Adalewis/MEAN-stack
6b1456643e56d576f48d5d3a5ec878f0a45fea05
84998e1143e4ffe289337498771de7342ffeca14
refs/heads/master
<file_sep><?php namespace App\Action; use Doctrine\ORM\EntityManager; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Zend\Diactoros\Response\HtmlResponse; use Zend\Diactoros\Response\JsonResponse; use Zend\Expressive\Router; use Zend\Expressive\Template; use App\Entity\Foo; class HomePageAction { private $router; private $template; private $em; public function __construct( Router\RouterInterface $router, Template\TemplateRendererInterface $template = null, EntityManager $em) { $this->router = $router; $this->template = $template; $this->em = $em; } public function __invoke( ServerRequestInterface $request, ResponseInterface $response, callable $next = null) { $data = []; $data['routerName'] = 'FastRoute'; $data['routerDocs'] = 'https://github.com/nikic/FastRoute'; $data['templateName'] = 'Zend View'; $data['templateDocs'] = 'http://framework.zend.com/manual/current/en/modules/zend.view.quick-start.html'; $fooRepository = $this->em->getRepository(Foo::class); $foos = $fooRepository->findAll(); if (!$this->template) { return new JsonResponse([ 'welcome' => 'Congratulations! You have installed the zend-expressive skeleton application.', 'docsUrl' => 'zend-expressive.readthedocs.org', ]); } return new JsonResponse($foos); // return new HtmlResponse($this->template->render('app::home-page', $data)); } }
72534805cf0da5d35fc9b67c16adbe7e410a0120
[ "PHP" ]
1
PHP
marcusvy/mv-site-api
1918b5e20cbb0e55e892b136a07adc4798d35a94
1cbe30c13d71089814347baa2310d7164baa1fdd
refs/heads/master
<file_sep>mkdir /tmp/tweet /tmp/tweet2 <file_sep>dictionary = {} with open("dictionary.tsv", "r") as f: lines = f.readlines()[0].split("\r") for line in lines: elements = line.split("\t") power = elements[0] word = elements[2] ponderation = elements[5] if ponderation == "negative": ponderation = -1 elif ponderation == "positive": ponderation = -1 else: ponderation = 0 if power == "strongsubj": ponderation *= 2 dictionary[word] = ponderation with open('dictionary.csv', 'w') as f: content = "" for k in dictionary.keys(): content += k + ";" + str(dictionary[k]) + "\n" f.write(content) <file_sep># coding: utf-8 import json import urllib2 import time import os import sys from os import listdir from os.path import isfile, join import nltk reload(sys) sys.setdefaultencoding('utf8') nltk.download('punkt') pathSource = "/tmp/tweet/" pathDest = "/tmp/tweet2/" def send_result(idProxy, result, computationTime): data = {"idProxy": idProxy,"result": result, "time": computationTime} req = urllib2.Request("http://localhost:4242/answer") req.add_header('Content-Type', 'application/json') res = urllib2.urlopen(req, json.dumps(data)) def separate_words(tweet): tweet = unicode(tweet, errors='ignore') return nltk.word_tokenize(tweet) def ponderation_list_words(listWords): ponderation = 0 for word in listWords: if word in dictionary: ponderation += dictionary[word] return ponderation def evaluate_tweet(tweet): words = separate_words(tweet) ponderation = ponderation_list_words(words) return ponderation def load_dictionary(): dictionary = {} with open("dictionary.csv", "r") as f: lines = f.read().split("\n") for line in lines: elements = line.split(";") if len(elements) == 2: dictionary[elements[0]] = int(elements[1]) return dictionary def watch_and_move(): while True: files = [f for f in listdir(pathSource) if isfile(join(pathSource, f))] for nameFile in files: f = open(pathSource+nameFile, "r") content = f.read() elements = content.split("\n") tic = time.clock() ponderation = evaluate_tweet(elements[0]) timeComputation = time.clock() - tic try: send_result(nameFile.replace(".txt", ""), ponderation, timeComputation) except Exception as e: print(e) os.rename(pathSource+nameFile, pathDest+nameFile) time.sleep(0.01) dictionary = load_dictionary() watch_and_move() # below, test of evaluate_tweet """ tweet = "The woman stushgyal_yoly and I about to watch Iron Man 3 #ironman #marvel #geek #superhero #avengers http://t.co/CCHfImAVJuMane @CLowe_ is the guy who goes to see iron man 3 w/o me me....wtf bro" dictionary = load_dictionary() ponderation = evaluate_tweet(tweet) print(ponderation) """ # below, test of send_result """ try: send_result("aaaaccccrrrrllll", 10, 0.001) except Exception as e: print(e) """ <file_sep>mkdir /tmp/casi <file_sep>const express = require('express') const fs = require('fs'); var bodyParser = require('body-parser'); var path = require("path"); const app = express(); const pathFile = "/tmp/casi/" app.use( bodyParser.json() ); // to support JSON-encoded bodies app.use(bodyParser.urlencoded({ // to support URL-encoded bodies extended: true })); app.use(function(req, res, next) { res.header('Access-Control-Allow-Origin', req.headers.origin); res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); next(); }); // to test : curl -H "Conte-Type: application/json" -X POST -d '{"idProxy":"xxxBOBxxx","result":"2","time":"0.002"}' http://localhost:4242/answer app.post('/answer', function (req, res) { if (req.body){ if (req.body.idProxy && req.body.result && req.body.time) { fs.writeFile(pathFile + req.body.idProxy + ".txt", req.body.result + ";" + req.body.time, function(err) { if(err) { res.status(400).send("Error while writing in the file : "+err); } else { console.log(req.body); res.send('OK'); } }); } else { res.status(400).send("Field idProxy or/and result or/and time missing"); } } else { res.status(400).send('Problem with the body of your request : there is no body'); } }) app.listen(4242, function () { console.log('app listening on port 4242!') }) <file_sep># project_casi Projet de CASI (conception et architecture des systèmes d'information) de l'équipe CookiesChoco. Consiste à du sentiment analysis sur des tweets avec Hadoop (et un dico terme-pondération). <file_sep>This folder is used to get the file "tweets", which contains every tweet as a string without \n, and the file "dictionary.csv". <file_sep># coding: utf-8 import json import urllib2 import string import random randomAlphabet = string.letters + "0123456789" def createIdProxy(sizeId = 16): idProxy = "" for i in range(sizeId): idProxy += random.choice(string.letters) return idProxy def sendTweet(tweet): idProxy = createIdProxy() data = {"idProxy": idProxy,"tweet": tweet, "uri":"http://localhost:4242/answer"} req = urllib2.Request("http://10.0.2.15:10042/tweet") req.add_header('Content-Type', 'application/json') res = urllib2.urlopen(req, json.dumps(data)) return idProxy smartProxy = "" # will contain lines "num line in the file 'tweets';idProxy\n" with open("tweets", "r") as f: tweets = f.read().split("\n") for i in range(len(tweets)): if(len(tweets[i]) > 1): try: idProxy = sendTweet(tweets[i]) smartProxy += str(i) + ";" + str(idProxy) + "\n" except Exception as e: print("error with the tweet num "+str(i)) print(e) else: print("tweet num "+str(i)+" is empty") outputFile = open("smartProxy.csv", "w") outputFile.write(smartProxy) outputFile.close() <file_sep>from os import listdir from os.path import isfile, join import sys mypath = "tweets_raw/" onlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))] tweets = [] for myfile in onlyfiles: with open(mypath+myfile, "r") as f: content = f.read() elements = content.split("\n") for tweet_raw in elements: if len(tweet_raw) > 1: try: tweet = eval(tweet_raw.replace("null", "None").replace("false", "False").replace("true", "True")) tweet = tweet["text"] tweets.append(tweet) except: print("Unexpected error:", sys.exc_info()[0]) outputFile = open("tweets", "w") outputFile.write("\n".join(tweets)) outputFile.close()
0a2c1c6d69505d491114552f6dc0f0df6c52ef76
[ "JavaScript", "Python", "Markdown", "Shell" ]
9
Shell
jajoe/project_casi
d4cd00ea576e8a7bcf4bf55436bd62882928fd78
3c04c31c3de87cddc03847d32c24467f6400ee94
refs/heads/master
<repo_name>RamonOga/grabber<file_sep>/src/main/resources/app.properties url=jdbc:postgresql://localhost:5432/post_db login=postgres password=<PASSWORD> driver=org.postgresql.Driver time=1000 socketPort=8081 parseUrl=https://www.sql.ru/forum/job-offers/ href=.msgBody date=.msgFooter oldHref=.postslisttopic oldDate=.altCol <file_sep>/src/main/java/ru/db/scripts/rabbits.sql create table rabbit ( id serial primary key, name varchar(255), create_date text );<file_sep>/src/main/resources/parse.properties url=https://www.sql.ru/forum/job-offers/ href=.msgBody date=.msgFooter oldHref=.postslisttopic oldDate=.altCol<file_sep>/src/main/resources/rabbit.properties rabbit.interval=10 driver=org.postgresql.Driver url=jdbc:postgresql://localhost:5432/rabbit_db login=postgres password=<PASSWORD><file_sep>/README.md [![codecov](https://codecov.io/gh/RamonOga/grabber/branch/master/graph/badge.svg?token=<KEY>)](https://codecov.io/gh/RamonOga/grabber) [![Build Status](https://travis-ci.com/RamonOga/grabber.svg?branch=master)](https://travis-ci.com/RamonOga/grabber)<file_sep>/src/main/java/ru/db/scripts/scripts.sql drop table posts; create table posts ( id serial primary key, title text, href text unique, descr text, date timestamp );
b80b75d1dc5a5831db64a4d0b6ae2bd61483760d
[ "Markdown", "SQL", "INI" ]
6
INI
RamonOga/grabber
ba927059836c6c140f7b4d3f5a409668f41bae3c
dcd544432f5b2637e4f5530d9d61409faf628497
refs/heads/master
<file_sep># -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='contact', fields=[ ('contactid', models.AutoField(primary_key=True, serialize=False)), ('name', models.CharField(max_length=45)), ('email', models.EmailField(max_length=100)), ('address', models.CharField(max_length=50)), ('city', models.CharField(max_length=50)), ('state', models.CharField(max_length=30)), ('zip', models.CharField(max_length=5)), ('phone', models.CharField(max_length=13)), ('comments', models.TextField()), ('attendees', models.TextField()), ('guestnum', models.IntegerField()), ], ), ] <file_sep>from django import forms from django.contrib.auth.forms import AuthenticationForm from django.utils.translation import ugettext_lazy as _ from django.forms import ModelForm #import models from rsvp_app.models import * #bootstrap login form class BootstrapAuthenticationForm(AuthenticationForm): """Authentication form which uses boostrap CSS.""" username = forms.CharField(max_length=254, widget=forms.TextInput({ 'class': 'form-control', 'placeholder': 'User name'})) password = forms.CharField(label=_("Password"), widget=forms.PasswordInput({ 'class': 'form-control', 'placeholder':'Password'})) #all other forms class RSVP_CodeForm(forms.Form): code = forms.CharField(label = False, max_length=20) class RSVP_Form(forms.Form): name = forms.CharField(label = False, max_length=20, widget=forms.TextInput(attrs={'placeholder': 'Name'})) email = forms.EmailField(label = False, widget=forms.TextInput(attrs={'placeholder': 'Email'})) phone = forms.CharField(label = False, max_length=13, widget=forms.TextInput(attrs={'placeholder': 'Phone'})) address = forms.CharField(label = False, max_length=30, widget=forms.TextInput(attrs={'placeholder': 'Address'})) address2 = forms.CharField(required=False, label = False, max_length=30, widget=forms.TextInput(attrs={'placeholder': 'Address 2'})) city = forms.CharField(label = False, max_length=30, widget=forms.TextInput(attrs={'placeholder': 'City'})) state = forms.CharField(label = False, max_length=30, widget=forms.TextInput(attrs={'placeholder': 'State'})) zip = forms.CharField(label = False, max_length=5, widget=forms.TextInput(attrs={'placeholder': 'Zip'})) numguests = forms.IntegerField(label= False, widget=forms.TextInput(attrs={'placeholder': 'Number \'O Guests'})) guestnames = forms.CharField(required = False, label = False, widget=forms.Textarea(attrs={'placeholder': 'Guest Names'})) comments = forms.CharField(required = False, label= False, widget=forms.Textarea(attrs={'placeholder': 'Questions or Comments'})) class Advice_Form(forms.Form): name = forms.CharField(label = False, max_length=45, widget=forms.TextInput(attrs={'placeholder': 'Name'})) advice = forms.CharField(required = True, label= False, widget=forms.Textarea(attrs={'placeholder': 'Advice For the Newlyweds OR Travel Suggestions'})) <file_sep>from django.shortcuts import * from django.http import HttpRequest from django.template import RequestContext from django.views.generic import CreateView from django.views.generic import DeleteView from django.views.generic import ListView from datetime import datetime from rsvp_app.forms import * from rsvp_app.models import * from django.core.urlresolvers import reverse # Create your views here. def index(request): assert isinstance(request, HttpRequest) context = RequestContext(request, { 'navbar':'index', }) return render( request, 'rsvp_app/index.html', context ) def rsvp(request): assert isinstance(request, HttpRequest) finished = False flag = True wrong = False error = False if request.method == 'POST': if 'code' in request.POST: codeform = RSVP_CodeForm(request.POST) if codeform.is_valid(): if codeform.cleaned_data['code'] == 'celebrationstation': flag = False else: wrong = True rsvpform = RSVP_Form() elif 'rsvp' in request.POST: rsvpform = RSVP_Form(request.POST) if rsvpform.is_valid(): flag = True finished = True addressfull = rsvpform.cleaned_data['address'] + " " + rsvpform.cleaned_data['address2'] newcont = contact(name=rsvpform.cleaned_data['name'], email=rsvpform.cleaned_data['email'], phone=rsvpform.cleaned_data['phone'], address=addressfull, city=rsvpform.cleaned_data['city'], state=rsvpform.cleaned_data['state'], zip=rsvpform.cleaned_data['zip'], guestnum=rsvpform.cleaned_data['numguests']) if 'comments' in rsvpform.cleaned_data: newcont.comments=rsvpform.cleaned_data['comments'] if rsvpform.cleaned_data['numguests'] > 1: newcont.attendees=rsvpform.cleaned_data['guestnames'] newcont.save() codeform = RSVP_CodeForm() else: error = True codeform = RSVP_CodeForm() rsvpform = RSVP_Form() else: print('security') else: codeform = RSVP_CodeForm() rsvpform = RSVP_Form() context = RequestContext(request, { 'navbar':'rsvp', 'flag':flag, 'finished':finished, 'codeform':codeform, 'rsvpform':rsvpform, 'wrong':wrong, 'error':error, }) return render( request, 'rsvp_app/rsvp.html', context ) def details(request): assert isinstance(request, HttpRequest) context = RequestContext(request, { 'navbar':'details', }) return render( request, 'rsvp_app/details.html', context ) def about(request): assert isinstance(request, HttpRequest) if request.method == 'POST': form = Advice_Form(request.POST) if form.is_valid(): newadv = advice(name=form.cleaned_data['name'], advice=form.cleaned_data['advice']) newadv.save() form = Advice_Form() context = RequestContext(request, { 'navbar':'about', 'form':form, }) return render( request, 'rsvp_app/about.html', context ) <file_sep># -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('rsvp_app', '0001_initial'), ] operations = [ migrations.CreateModel( name='advice', fields=[ ('adviceid', models.AutoField(primary_key=True, serialize=False)), ('name', models.CharField(max_length=45)), ('advice', models.TextField()), ], ), migrations.AlterField( model_name='contact', name='address', field=models.CharField(null=True, max_length=50), ), migrations.AlterField( model_name='contact', name='attendees', field=models.TextField(null=True), ), migrations.AlterField( model_name='contact', name='city', field=models.CharField(null=True, max_length=50), ), migrations.AlterField( model_name='contact', name='comments', field=models.TextField(null=True), ), migrations.AlterField( model_name='contact', name='email', field=models.EmailField(null=True, max_length=100), ), migrations.AlterField( model_name='contact', name='guestnum', field=models.IntegerField(null=True), ), migrations.AlterField( model_name='contact', name='phone', field=models.CharField(null=True, max_length=13), ), migrations.AlterField( model_name='contact', name='state', field=models.CharField(null=True, max_length=30), ), migrations.AlterField( model_name='contact', name='zip', field=models.CharField(null=True, max_length=5), ), ] <file_sep>from django.db import models # Create your models here. class contact(models.Model): contactid = models.AutoField(primary_key=True) name = models.CharField(max_length=45, null=False) email = models.EmailField(max_length=100, null=True) address = models.CharField(max_length=50, null=True) city = models.CharField(max_length=50, null=True) state = models.CharField(max_length=30, null=True) zip = models.CharField(max_length=5, null=True) phone = models.CharField(max_length=13, null=True) comments = models.TextField(null=True) attendees = models.TextField(null=True) guestnum = models.IntegerField(null=True) class advice(models.Model): adviceid = models.AutoField(primary_key=True) name = models.CharField(max_length=45, null=False) advice = models.TextField(null=False) <file_sep>from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ # Examples: url(r'^$', 'rsvp_app.views.index', name='home'), url(r'^admin/', include(admin.site.urls)), url(r'^rsvp$', 'rsvp_app.views.rsvp', name='rsvp'), url(r'^details$', 'rsvp_app.views.details', name='details'), url(r'^about$', 'rsvp_app.views.about', name='about'), ] <file_sep>from django.contrib import admin # Register your models here. from .models import contact, advice admin.site.register(contact) admin.site.register(advice) <file_sep># WeddingSite This is the wedding website for Sarah and I
9f3a84918a89af30b6ba2edb202ed98e19688d3f
[ "Markdown", "Python" ]
8
Python
carterfawson/WeddingSite
3869c317042f21bdd4dd5e505fe1d21b94ef7b86
f41f33b362250f1165a59a927e1ab989f48547fc
refs/heads/master
<file_sep># Прохождение курса https://github.com/Avik-Jain/100-Days-Of-ML-Code <file_sep># linear regression это механизм, который позволяет создать линейную функцию # для предсказания значений зависимой переменной import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split from sklearn.linear_model import LinearRegression if __name__ == '__main__': dataset = pd.read_csv('studentscores.csv') X = dataset.iloc[:, : 1].values Y = dataset.iloc[:, 1].values X_train, X_test, Y_train, Y_test =\ train_test_split(X, Y, test_size=1 / 4, random_state=0) regressor = LinearRegression() regressor = regressor.fit(X_train, Y_train) Y_pred = regressor.predict(X_test) plt.scatter(X_test, Y_test, color = 'red') plt.plot(X_test, regressor.predict(X_test), color = 'green') plt.show() <file_sep>import pandas as pd import numpy as np from sklearn.cross_validation import train_test_split from sklearn.linear_model import LinearRegression from sklearn.preprocessing import LabelEncoder, OneHotEncoder if __name__ == '__main__': # pd.read_csv - мы вызываем функцию, которая берет наши данные # и создает объект типа dataframe read_csv = pd.read_csv('50_Startups.csv') # с помощью переменной iloc мы по индексам выбираем необходимую # нам часть данных и сохраняем их в переменную также типом dataframe # у нас dataframe, его хэшировать нельзя, # поэтому переводим в массив через .values X = read_csv.iloc[:, :-1].values Y = read_csv.iloc[:, -1].values label_encoder = LabelEncoder() X[:, 3] = label_encoder.fit_transform(X[:, 3]) one_hot_encoder = OneHotEncoder(categorical_features=[3]) X = one_hot_encoder.fit_transform(X).toarray() X = X[:, 1:] X_train, X_test, Y_train, Y_test =\ train_test_split(X, Y, test_size=0.2, random_state=0) linear_regression = LinearRegression() linear_regression = linear_regression.fit(X_train, Y_train) Y_pred = linear_regression.predict(X_test) print(Y_test) print(Y_test - Y_pred) <file_sep>import numpy as np import pandas as pd from sklearn.model_selection import train_test_split from sklearn.preprocessing import Imputer, StandardScaler from sklearn.preprocessing import LabelEncoder, OneHotEncoder class Durasha: def __init__(self, age=0, name="Masha"): # self. это обращение к коробочке с данными (текущему объекту, # с которым ты работаешь ---- self. росто показывает, # где хранится переменная) инит это конструктор, создатель объекта # и мы вызываем эту функцию, когда создаем новый объект в классе self.age = age self.name = name def get_name(self): return self.name def sum(self, a, b): return a + b # self то обязательный аргумент функции в классе def set_name(self, new_name): self.name = new_name def __str__(self): return "Object of Durasha class: name=" \ + self.name + ", age=" + str(self.age) # когда мы используем функцию, мы должны понять, будет ли # у нее возвращение данных, потому что есть два типа функций: # те, которые что-то делают и возвращают значение, и те, которые просто # что-то делают и его нам не возвращают # когда есть ретерн, мы можем потом написать # слева *название новой переменной* = # куда будет сохраняться то, что вернула функция # если ретерна нет, то будет None # в функции инит это встроено разработчиками # для других нужно смотреть в описании к функции def deniska(a): print(a) return a**2 if __name__ == '__main__': # здесь слева название объекта, справа название класса # в скобочках аргументы # мы обращаемся к функции инит через объект, который обозначаем как # названиекласса() durasha = Durasha(18, "masha") # dict = {} # # dict['A'] = 42 # # # # dict_of_dicts = {} # # dict_of_dicts[dict] = 1 # # # # print(dict_of_dicts) exit() print(durasha.get_name()) b = deniska(4) print(durasha) read_csv = pd.read_csv('Data.csv') X = read_csv.iloc[:, :-1].values Y = read_csv.iloc[:, 3].values # создали объект в классе imputer = Imputer(missing_values="NaN", strategy="mean", axis=0) # вызывали ф-ю фит, накормили ее инфой imputer = imputer.fit(X[:, 1:3]) # взяли данные из места, с ними поработали и туда же вернули X[:, 1:3] = imputer.transform(X[:, 1:3]) # создали объект в классе label_encoder = LabelEncoder() # заменили во всех строках первый столбец # с названием страны на цифру для этой страны X[ : , 0] = label_encoder.fit_transform(X[ : , 0]) onehotencoder = OneHotEncoder(categorical_features = [0]) X = onehotencoder.fit_transform(X).toarray() labelencoder_Y = LabelEncoder() Y = labelencoder_Y.fit_transform(Y) X_train, X_test, Y_train, Y_test = \ train_test_split( X , Y , test_size = 0.2, random_state = 0) sc_X = StandardScaler() X_train = sc_X.fit_transform(X_train) X_test = sc_X.fit_transform(X_test) print(X_train)
f74ef047d8bf078f1f444d31a398ad42e00ba5c8
[ "Markdown", "Python" ]
4
Markdown
pavlyuchenkomaria/100daysML
8d86010cdef9ef95b318506c584838828ac4a047
84d96f1bcce19f4fe8a243aeadb3575f7f1b636c
refs/heads/master
<repo_name>kokihonda/algorithms<file_sep>/depth_search.c #include <stdio.h> #include <stdlib.h> #define UNVISITED 0 #define TRUE 1 #define FALSE 0 void depth_first(); void visit(int v); struct edge_cell { int destination; struct edge_cell *next; }; typedef struct edge_cell *edge_list; struct edge_cell edge_strage[1024]; struct { edge_list adj_list; int seq; int searching; } vertex[1024]; int n, m; int counter; int main() { edge_strage[0].destination = 2; edge_strage[0].next = &edge_strage[1]; edge_strage[1].destination = 3; edge_strage[1].next = &edge_strage[2]; edge_strage[2].destination = 4; edge_strage[2].next = NULL; edge_strage[3].destination = 0; edge_strage[3].next = NULL; edge_strage[4].destination = 1; edge_strage[4].next = NULL; edge_strage[5].destination = 2; edge_strage[5].next = &edge_strage[6]; edge_strage[6].destination = 4; edge_strage[6].next = NULL; edge_strage[7].destination = 0; edge_strage[7].next = &edge_strage[8]; edge_strage[8].destination = 6; edge_strage[8].next = NULL; vertex[0].adj_list = &edge_strage[0]; vertex[1].adj_list = &edge_strage[3]; vertex[2].adj_list = &edge_strage[4]; vertex[3].adj_list = &edge_strage[5]; vertex[4].adj_list = NULL; vertex[5].adj_list = &edge_strage[7]; vertex[6].adj_list = NULL; n = 6; depth_first(); } void depth_first() { int i; for (i = 0; i < n; i++) { vertex[i].seq = UNVISITED; } counter = 0; for (i = 0; i < n; i++) { if (vertex[i].seq == UNVISITED) { visit(i); } } } void visit(int v) { int d; edge_list p; counter++; vertex[v].seq = counter; vertex[v].searching = TRUE; p = vertex[v].adj_list; while(p != 0) { d = p->destination; if (vertex[d].seq == UNVISITED) { printf("%d -> %d\n", v, d); visit(d); } else if (vertex[d].seq > vertex[v].seq) { // down_edge(v, d); printf("down: %d -> %d\n", v, d); } else if (vertex[d].searching) { //up_edge(v, d); printf("up: %d -> %d\n", v, d); } else { //closs_edge(v, d); printf("closs: %d -> %d\n", v, d); } p = p->next; } vertex[v].searching = FALSE; } <file_sep>/README.md # algorithms アルゴリズムの勉強 <file_sep>/dijkstra.c #include <stdio.h> #define UNVISITED 0 #define VISITED 1 #define INFINITY 10000 void dijkstra(); int min(int, int); struct edge_cell { int destination; int weight; struct edge_cell *next; }; typedef struct edge_cell *edge_list; struct edge_cell edge_strage[1024]; struct { edge_list adj_list; int distance; int state; } vertex[1024]; int n; int main() { int i; edge_strage[0].destination = 1; edge_strage[0].weight = 6; edge_strage[0].next = &edge_strage[1]; edge_strage[1].destination = 2; edge_strage[1].weight = 4; edge_strage[1].next = NULL; edge_strage[2].destination = 3; edge_strage[2].weight = 3; edge_strage[2].next = NULL; edge_strage[3].destination = 4; edge_strage[3].weight = 3; edge_strage[3].next = &edge_strage[4]; edge_strage[4].destination = 5; edge_strage[4].weight = 6; edge_strage[4].next = NULL; edge_strage[5].destination = 3; edge_strage[5].weight = 1; edge_strage[5].next = NULL; vertex[0].adj_list = &edge_strage[0]; vertex[1].adj_list = &edge_strage[2]; vertex[2].adj_list = &edge_strage[3]; vertex[3].adj_list = NULL; vertex[4].adj_list = &edge_strage[5]; vertex[5].adj_list = NULL; n = 6; dijkstra(); for (i = 0; i < n; i++) { printf("vertex[%d] = %d\n", i, vertex[i].distance); } } void dijkstra() { int i, p, x,minimum, step; edge_list t; for (i = 0; i < n; i++) { vertex[i].distance = INFINITY; vertex[i].state = UNVISITED; } vertex[0].distance = 0; for (step = 0; step < n; step++) { minimum = INFINITY; for (i = 0; i < n; i++) { if (vertex[i].state == UNVISITED && vertex[i].distance < minimum) { p = i; minimum = vertex[i].distance; } } if (minimum == INFINITY) { fprintf(stderr, "graph is disconnected\n"); } vertex[p].state = VISITED; for (t = vertex[p].adj_list; t != 0; t = t->next) { x = t->destination; vertex[x].distance = min(vertex[x].distance, vertex[p].distance+t->weight); } } } int min(int x1, int x2) { if (x1 < x2) return x1; else return x2; } <file_sep>/present/src/main.rs #[allow(unused_macros)] macro_rules! input { (source = $s:expr, $($r:tt)*) => { let mut iter = $s.split_whitespace(); let mut next = || { iter.next().unwrap() }; input_inner!{next, $($r)*} }; ($($r:tt)*) => { let stdin = std::io::stdin(); let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock())); let mut next = move || -> String{ bytes .by_ref() .map(|r|r.unwrap() as char) .skip_while(|c|c.is_whitespace()) .take_while(|c|!c.is_whitespace()) .collect() }; input_inner!{next, $($r)*} }; } #[allow(unused_macros)] macro_rules! input_inner { ($next:expr) => {}; ($next:expr, ) => {}; ($next:expr, $var:ident : $t:tt $($r:tt)*) => { let $var = read_value!($next, $t); input_inner!{$next $($r)*} }; ($next:expr, mut $var:ident : $t:tt $($r:tt)*) => { let mut $var = read_value!($next, $t); input_inner!{$next $($r)*} }; } #[allow(unused_macros)] macro_rules! read_value { ($next:expr, ( $($t:tt),* )) => { ( $(read_value!($next, $t)),* ) }; ($next:expr, [ $t:tt ; $len:expr ]) => { (0..$len).map(|_| read_value!($next, $t)).collect::<Vec<_>>() }; ($next:expr, chars) => { read_value!($next, String).chars().collect::<Vec<char>>() }; ($next:expr, bytes) => { read_value!($next, String).into_bytes() }; ($next:expr, usize1) => { read_value!($next, usize) - 1 }; ($next:expr, $t:ty) => { $next().parse::<$t>().expect("Parse error") }; } use std::cmp::Ordering; fn main() { input! { n: usize, mut p: [(usize, usize); n], } let mut dp = vec![0; n+1]; let mut arr = vec![0; 100010]; let mut bit = Bit::new(100001, &mut arr); let func = |pair: &(usize, usize), other: &(usize, usize)| { if pair.0.cmp(&other.0) == Ordering::Equal { return other.1.cmp(&pair.1); } else { return pair.0.cmp(&other.0) } }; //let mut pp = p.clone(); //pp.sort_by_key(|w| {(w.0, -w.1)}); p.sort_by(func); for i in 0..n { dp[i] = bit.query((p[i].1-1) as isize) + 1; bit.update(p[i].1 as isize, dp[i]); } println!("{}", dp.iter().max().unwrap()); } struct Bit<'a> { arr: &'a mut Vec<usize>, n: usize, } impl<'a> Bit<'a> { fn new(n: usize, v: &mut Vec<usize>) -> Bit { Bit { arr: v, n: n, } } fn update(&mut self, a: isize, w: usize) { let mut x = a; while x <= self.n as isize { if self.arr[x as usize] < w { self.arr[x as usize] = w } x = x + (x & -x); } } fn query(&self, a: isize) -> usize { let mut ret = 0; let mut x = a; while x > 0 { if ret < self.arr[x as usize] { ret = self.arr[x as usize]; } x = x - (x & -x); } ret } }
72dce3ffa1526a2aa892a14593943fdc104ca975
[ "Markdown", "C", "Rust" ]
4
C
kokihonda/algorithms
d71afce80b12aef3bfd73db7ecf984ee68c53e8d
6d7c73430fab25d52c8dbded9874a7409a9855a2
refs/heads/master
<repo_name>RunicGlympse/Revolt-Mod<file_sep>/Revolt_Radiation/MyPlayer.cs using Terraria; using Terraria.ModLoader; using Terraria.ID; using System; using System.Collections.Generic; using System.IO; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace Revolt_Radiation { public class MyPlayer : ModPlayer { public bool LightPet = false; public bool LunarPetProjectile = false; public bool LunarPetBuff = false; public int cameraShakeDur = 0; public float cameraShakeMagnitude = 0f; public Vector2 shakeO; public bool shakeReset = false; public override void ResetEffects() { LunarPetBuff = false; LightPet = false; if (cameraShakeDur > 0) { cameraShakeDur--; shakeReset = false; } else { cameraShakeMagnitude = 0; if (shakeReset == true) shakeO = player.position; else { player.position = shakeO; shakeReset = true; } } } public override void PreUpdate() { Random random = new Random(); if (cameraShakeDur > 0) { cameraShakeMagnitude += 1f / 5f; player.position.X = shakeO.X - cameraShakeMagnitude + (float)random.NextDouble() * cameraShakeMagnitude * 2; player.position.Y = shakeO.Y - cameraShakeMagnitude + (float)random.NextDouble() * cameraShakeMagnitude * 2; } } } }<file_sep>/Revolt_Radiation/Projectiles/BookTome.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Terraria; using Terraria.ModLoader; using Terraria.ID; namespace Revolt_Radiation.Projectiles { public class BookTome : ModProjectile { public override void SetStaticDefaults() { DisplayName.SetDefault("BookTome"); Main.projFrames[projectile.type] = 8; } public override void SetDefaults() { projectile.CloneDefaults(ProjectileID.BookStaffShot); aiType = ProjectileID.BookStaffShot; } public override void OnHitNPC(NPC target, int damage, float knockback, bool crit) { target.AddBuff(BuffID.Dazed, 3, false); } public void OnHitPvp(NPC target, int damage, float knockback, bool crit) { target.AddBuff(BuffID.Dazed, 3, false); } public override void Kill(int timeLeft) { Main.PlaySound(SoundID.Item32); } } }<file_sep>/Revolt_Radiation/Projectiles/Hostile/LancerionSpear.cs using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Terraria; using Terraria.ID; using Terraria.ModLoader; namespace Revolt_Radiation.Projectiles.Hostile { public class LancerionSpear : ModProjectile { public override void SetStaticDefaults() { DisplayName.SetDefault("Lancerion's Spear"); } public override void SetDefaults() { projectile.width = 18; projectile.height = 54; projectile.aiStyle = 1; projectile.friendly = false; projectile.hostile = true; projectile.timeLeft = 90; projectile.tileCollide = false; } public override void Kill(int timeLeft) { Main.PlaySound(25, (int)projectile.position.X, (int)projectile.position.Y); // Play a death sound Vector2 usePos = projectile.position; Vector2 rotVector = (projectile.rotation - MathHelper.ToRadians(90f)).ToRotationVector2(); usePos += rotVector * 16f; for (int i = 0; i < 20; i++) { Dust dust = Dust.NewDustDirect(usePos, projectile.width, projectile.height, 12); dust.position = (dust.position + projectile.Center) / 2f; dust.velocity += rotVector * 2f; dust.velocity *= 0.5f; dust.noGravity = true; usePos -= rotVector * 8f; } } } } <file_sep>/Revolt_Radiation/Projectiles/Hostile/LancerionStomp.cs using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Terraria; using Terraria.ID; using Terraria.ModLoader; namespace Revolt_Radiation.Projectiles.Hostile { public class LancerionStomp : ModProjectile { public int timer = 0; public override void SetStaticDefaults() { DisplayName.SetDefault("Lancerion's Stomp"); Main.projFrames[projectile.type] = 4; } public override void SetDefaults() { projectile.width = 60; projectile.height = 28; projectile.aiStyle = 1; projectile.friendly = false; projectile.hostile = true; projectile.timeLeft = 1000; } public override void AI() { projectile.rotation = projectile.velocity.ToRotation() + MathHelper.ToRadians(180f); if (++projectile.frameCounter >= 5) { projectile.frameCounter = 0; if (++projectile.frame >= 4) { projectile.frame = 0; } } timer++; if (timer == 10) { Dust dust = Main.dust[Dust.NewDust(projectile.position, projectile.width, projectile.height / 2, 6, 0f, -5f, 100, default(Color), 1.5f)]; Main.PlaySound(SoundID.Item68, projectile.Center); timer = 0; } } public override void Kill(int timeleft) { } } } <file_sep>/Revolt_Radiation/Projectiles/SolarBall.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Terraria; using Terraria.ModLoader; using Terraria.ID; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace Revolt_Radiation.Projectiles { public class SolarBall : ModProjectile { public override void SetStaticDefaults() { DisplayName.SetDefault("Solar Ball"); Main.projFrames[projectile.type] = 4; } public override void SetDefaults() { projectile.width = 40; projectile.height = 40; projectile.aiStyle = 1; projectile.alpha = 0; projectile.ignoreWater = true; projectile.friendly = true; } public override void AI() { if (++projectile.frameCounter >= 3) { projectile.frame++; projectile.frameCounter = 0; if (projectile.frame >= 4) { projectile.frame = 0; } } if (projectile.ai[1] == 0f) { projectile.ai[1] = 1f; Main.PlaySound(SoundID.Item34, projectile.position); } Lighting.AddLight(projectile.Center, 1.1f, 0.9f, 0.4f); if (projectile.localAI[0] == 12f) { projectile.localAI[0] = 0f; int num2; for (int num12 = 0; num12 < 12; num12 = num2 + 1) { Vector2 value2 = Vector2.UnitX * (0f - (float)projectile.width) / 2f; value2 += -Vector2.UnitY.RotatedBy((double)((float)num12 * 3.14159274f / 6f), default(Vector2)) * new Vector2(8f, 16f); value2 = value2.RotatedBy((double)(projectile.rotation - 1.57079637f), default(Vector2)); int num13 = Dust.NewDust(projectile.Center, 0, 0, 6, 0f, 0f, 160, default(Color), 1f); Main.dust[num13].scale = 1.1f; Main.dust[num13].noGravity = true; Main.dust[num13].position = projectile.Center + value2; Main.dust[num13].velocity = projectile.velocity * 0.1f; Main.dust[num13].velocity = Vector2.Normalize(projectile.Center - projectile.velocity * 3f - Main.dust[num13].position) * 1.25f; num2 = num12; } } if (Main.rand.Next(4) == 0) { int num2; for (int num14 = 0; num14 < 1; num14 = num2 + 1) { Vector2 value3 = -Vector2.UnitX.RotatedByRandom(0.19634954631328583).RotatedBy((double)projectile.velocity.ToRotation(), default(Vector2)); int num15 = Dust.NewDust(projectile.position, projectile.width, projectile.height, 31, 0f, 0f, 100, default(Color), 1f); Dust dust3 = Main.dust[num15]; dust3.velocity *= 0.1f; Main.dust[num15].position = projectile.Center + value3 * (float)projectile.width / 2f; Main.dust[num15].fadeIn = 0.9f; num2 = num14; } } if (Main.rand.Next(32) == 0) { int num2; for (int num16 = 0; num16 < 1; num16 = num2 + 1) { Vector2 value4 = -Vector2.UnitX.RotatedByRandom(0.39269909262657166).RotatedBy((double)projectile.velocity.ToRotation(), default(Vector2)); int num17 = Dust.NewDust(projectile.position, projectile.width, projectile.height, 31, 0f, 0f, 155, default(Color), 0.8f); Dust dust3 = Main.dust[num17]; dust3.velocity *= 0.3f; Main.dust[num17].position = projectile.Center + value4 * (float)projectile.width / 2f; if (Main.rand.Next(2) == 0) { Main.dust[num17].fadeIn = 1.4f; } num2 = num16; } } if (Main.rand.Next(2) == 0) { int num2; for (int num18 = 0; num18 < 2; num18 = num2 + 1) { Vector2 value5 = -Vector2.UnitX.RotatedByRandom(0.78539818525314331).RotatedBy((double)projectile.velocity.ToRotation(), default(Vector2)); int num19 = Dust.NewDust(projectile.position, projectile.width, projectile.height, 6, 0f, 0f, 0, default(Color), 1.2f); Dust dust3 = Main.dust[num19]; dust3.velocity *= 0.3f; Main.dust[num19].noGravity = true; Main.dust[num19].position = projectile.Center + value5 * (float)projectile.width / 2f; if (Main.rand.Next(2) == 0) { Main.dust[num19].fadeIn = 1.4f; } num2 = num18; } } } public override void OnHitNPC(NPC target, int damage, float knockback, bool crit) { target.AddBuff(BuffID.OnFire, 1, false); } public void OnHitPvp(NPC target, int damage, float knockback, bool crit) { target.AddBuff(BuffID.OnFire, 1, false); } public override void Kill(int timeleft) { Dust dust = Main.dust[Dust.NewDust(projectile.position, projectile.width, projectile.height, 6, 0f, 0, 50, default(Color), 5f)]; Main.PlaySound(SoundID.Item14, projectile.Center); } public void OnTileCollide() { projectile.timeLeft = 1; } } }<file_sep>/Revolt_Radiation/Projectiles/AtomicBall.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Terraria; using Terraria.ModLoader; using Terraria.ID; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace Revolt_Radiation.Projectiles { public class AtomicBall : ModProjectile { public int combineCount = 0; public int combineCap = 5; public override void SetStaticDefaults() { DisplayName.SetDefault("Atomic Ball"); Main.projFrames[projectile.type] = 4; } public override void SetDefaults() { projectile.width = 40; projectile.height = 40; projectile.aiStyle = 0; projectile.alpha = 0; projectile.ignoreWater = true; projectile.friendly = true; projectile.damage = 5; projectile.timeLeft = 200; projectile.light = 1f; projectile.tileCollide = false; } public override void AI() { if (++projectile.frameCounter >= 3) { projectile.frame++; projectile.frameCounter = 0; if (projectile.frame >= 4) { projectile.frame = 0; } } projectile.velocity *= 0.5f; if (projectile.ai[1] == 0f) { projectile.ai[1] = 1f; Main.PlaySound(SoundID.Item34, projectile.position); } Lighting.AddLight(projectile.Center, 1.1f, 0.9f, 0.4f); for (int i = 0; i < 1000; i++) { if (Main.projectile[i].Hitbox.Intersects(projectile.Hitbox)) { if (combineCount < combineCap) { projectile.width *= 2; projectile.height *= 2; projectile.scale += 2f; projectile.damage += 10; combineCount += 1; projectile.timeLeft += 25; } } } if (projectile.timeLeft == 1) { for (int i = 0; i < 1000; i++) { NPC target = Main.npc[i]; float distanceX = target.position.X - projectile.Center.X; float distanceY = target.position.Y - projectile.Center.Y; float distance = (float)System.Math.Sqrt((double)(distanceX * distanceX + distanceY * distanceY)); float growthVar = 0f; float rotation = MathHelper.ToRadians(25); if (!target.friendly && target.active && target.type != 488 && !target.dontTakeDamage && Collision.CanHitLine(projectile.Center, 1, 1, target.Center, 1, 1)) { if (combineCount == 1) { if (!target.friendly && target.active && target.type != 488 && !target.dontTakeDamage && Collision.CanHitLine(projectile.Center, 1, 1, target.Center, 1, 1)) { distance = 3f / distance; distanceX *= distance * 3; distanceY *= distance * 3; Vector2 perturbedSpeed = new Vector2(distanceX, distanceY).RotatedBy(MathHelper.Lerp(-rotation, rotation, i / (growthVar - 1))) * .2f; Projectile.NewProjectile(projectile.Center.X, projectile.Center.Y, perturbedSpeed.X, perturbedSpeed.Y, mod.ProjectileType("FriendlyLightning"), (int)(projectile.damage * 1f), 0, projectile.owner, 0f, 0f); } } if (combineCount == 2) { growthVar = 2f; distance = 3f / distance; distanceX *= distance * 3; distanceY *= distance * 3; for (int k = 0; k < growthVar; k++) { Vector2 perturbedSpeed = new Vector2(distanceX, distanceY).RotatedBy(MathHelper.Lerp(-rotation, rotation, i / (growthVar - 1))) * .2f; Projectile.NewProjectile(projectile.Center.X, projectile.Center.Y, perturbedSpeed.X, perturbedSpeed.Y, mod.ProjectileType("FriendlyLightning"), (int)(projectile.damage * 1f), 0, projectile.owner, 0f, 0f); } } if (combineCount == 3) { growthVar = 3f; distance = 3f / distance; distanceX *= distance * 3; distanceY *= distance * 3; for (int k = 0; k < growthVar; k++) { Vector2 perturbedSpeed = new Vector2(distanceX, distanceY).RotatedBy(MathHelper.Lerp(-rotation, rotation, i / (growthVar - 1))) * .2f; Projectile.NewProjectile(projectile.Center.X, projectile.Center.Y, perturbedSpeed.X, perturbedSpeed.Y, mod.ProjectileType("FriendlyLightning"), (int)(projectile.damage * 1f), 0, projectile.owner, 0f, 0f); } } if (combineCount == 4) { growthVar = 4f; distance = 3f / distance; distanceX *= distance * 3; distanceY *= distance * 3; for (int k = 0; k < growthVar; k++) { Vector2 perturbedSpeed = new Vector2(distanceX, distanceY).RotatedBy(MathHelper.Lerp(-rotation, rotation, i / (growthVar - 1))) * .2f; Projectile.NewProjectile(projectile.Center.X, projectile.Center.Y, perturbedSpeed.X, perturbedSpeed.Y, mod.ProjectileType("FriendlyLightning"), (int)(projectile.damage * 1f), 0, projectile.owner, 0f, 0f); } } if (combineCount == 5) { growthVar = 5f; distance = 3f / distance; distanceX *= distance * 3; distanceY *= distance * 3; for (int k = 0; k < growthVar; k++) { Vector2 perturbedSpeed = new Vector2(distanceX, distanceY).RotatedBy(MathHelper.Lerp(-rotation, rotation, i / (growthVar - 1))) * .2f; Projectile.NewProjectile(projectile.Center.X, projectile.Center.Y, perturbedSpeed.X, perturbedSpeed.Y, mod.ProjectileType("FriendlyLightning"), (int)(projectile.damage * 1f), 0, projectile.owner, 0f, 0f); } } } } } } } }<file_sep>/README.md # Terraria Revolt Mod Why. Meant for contributors and secondary programmers. Technically the mod is open source, but I don't want you to copy and paste the code like I do. Don't be me. <file_sep>/Revolt_Radiation/Revolt_Radiation.cs using Terraria.ModLoader; namespace Revolt_Radiation { class Revolt_Radiation : Mod { public Revolt_Radiation() { Properties = new ModProperties() { Autoload = true, AutoloadGores = true, AutoloadSounds = true }; } } } <file_sep>/Revolt_Radiation/NPCs/Cyber_Elemental.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Terraria; using Terraria.ModLoader; using Terraria.ID; using Terraria.Graphics.Effects; using Terraria.Graphics.Shaders; using Terraria.DataStructures; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace Revolt_Radiation.NPCs { public class Cyber_Elemental : ModNPC { public override void SetStaticDefaults() { DisplayName.SetDefault("Cyber Elemental"); Main.npcFrameCount[npc.type] = 15; } public override void SetDefaults() { npc.width = 28; npc.height = 42; npc.damage = 10; npc.defense = 5; npc.lifeMax = 100; npc.HitSound = SoundID.NPCHit53; npc.DeathSound = SoundID.NPCDeath44; npc.value = 60f; npc.knockBackResist = 1f; npc.aiStyle = 3; aiType = NPCID.Zombie; animationType = NPCID.ChaosElemental; } public override float SpawnChance(NPCSpawnInfo spawnInfo) { return SpawnCondition.OverworldNightMonster.Chance * 0.1f; } public override void OnHitByProjectile(Projectile projectile, int damage, float knockback, bool crit) { Projectile.NewProjectile(npc.Center.X, npc.Center.Y, Main.rand.Next(-5,6), Main.rand.Next(-5,6), mod.ProjectileType("Digital_Residue"), 20, 0); } } } <file_sep>/Revolt_Radiation/Projectiles/Hostile/Digital_Residue.cs using Terraria; using Terraria.ID; using Terraria.ModLoader; namespace Revolt_Radiation.Projectiles.Hostile { public class Digital_Residue : ModProjectile { public override void SetStaticDefaults() { DisplayName.SetDefault("Digital Residue"); } public override void SetDefaults() { projectile.width = 16; projectile.height = 16; projectile.aiStyle = 44; projectile.friendly = false; projectile.hostile = true; projectile.timeLeft = 20; } public override void PostAI() { if (Main.rand.Next(2) == 0) { Dust dust = Dust.NewDustDirect(projectile.position, projectile.width, projectile.height, 140); dust.scale = 0.5f; } } } } <file_sep>/Revolt_Radiation/Projectiles/FriendlyLightning.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Terraria; using Terraria.ModLoader; using Terraria.ID; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace Revolt_Radiation.Projectiles { public class FriendlyLightning : ModProjectile { public override void SetStaticDefaults() { DisplayName.SetDefault("Lightning"); Main.projFrames[projectile.type] = 7; } public override void SetDefaults() { projectile.width = 14; projectile.height = 14; projectile.aiStyle = 88; projectile.friendly = true; projectile.alpha = 255; projectile.ignoreWater = true; aiType = ProjectileID.CultistBossLightningOrbArc; } } }<file_sep>/Revolt_Radiation/Projectiles/Green_Flare_Projectile.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Terraria; using Terraria.ModLoader; using Terraria.ID; using Terraria.Graphics.Effects; using Terraria.Graphics.Shaders; using Terraria.DataStructures; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace Revolt_Radiation.Projectiles { public class Green_Flare_Projectile : ModProjectile { public override void SetStaticDefaults() { DisplayName.SetDefault("Green Flare"); Main.projFrames[projectile.type] = 1; } public override void SetDefaults() { projectile.width = 6; projectile.height = 6; projectile.friendly = true; projectile.penetrate = -1; projectile.alpha = 255; projectile.timeLeft = 36000; projectile.aiStyle = 1; } public override void AI() { if (projectile.alpha > 0) { projectile.alpha -= 50; if (projectile.alpha < 0) { projectile.alpha = 0; } } float num1 = 4f; float num2 = projectile.ai[0]; float num3 = projectile.ai[1]; if (num2 == 0f && num3 == 0f) { num2 = 1f; } float num4 = (float)Math.Sqrt((double)(num2 * num2 + num3 * num3)); num4 = num1 / num4; num2 *= num4; num3 *= num4; if (projectile.alpha < 70) { Vector2 position = new Vector2(projectile.position.X, projectile.position.Y - 2f); float x = -projectile.velocity.X; float y = -projectile.velocity.Y; int num7 = Dust.NewDust(position, projectile.width, projectile.height / 2, 163, x, y, 100, default(Color), 0.75f); Main.dust[num7].noGravity = true; Dust dust1 = Main.dust[num7]; dust1.position.X = dust1.position.X - num2 * 1f; Dust dust2 = Main.dust[num7]; dust2.position.Y = dust2.position.Y - num3 * 1f; Dust dust3 = Main.dust[num7]; dust3.velocity.X = dust3.velocity.X - num2; Dust dust4 = Main.dust[num7]; dust4.velocity.Y = dust4.velocity.Y - num3; } if (projectile.localAI[0] == 0f) { projectile.ai[0] = projectile.velocity.X; projectile.ai[1] = projectile.velocity.Y; if (projectile.localAI[1] >= 30f) { projectile.velocity.Y = projectile.velocity.Y + 0.09f; projectile.localAI[1] = 30f; } } else { if (!Collision.SolidCollision(projectile.position, projectile.width, projectile.height)) { projectile.localAI[0] = 0f; projectile.localAI[1] = 30f; } projectile.damage = 0; } if (projectile.velocity.Y > 16f) { projectile.velocity.Y = 16f; } projectile.rotation = (float)Math.Atan2((double)projectile.ai[1], (double)projectile.ai[0]) + 1.57f; } public override bool OnTileCollide(Vector2 oldVelocity) { if (projectile.localAI[0] == 0f) { if (projectile.wet) { projectile.position += oldVelocity / 2f; } else { projectile.position += oldVelocity; } projectile.velocity *= 0f; projectile.localAI[0] = 1f; } return false; } public override void OnHitNPC(NPC target, int damage, float knockback, bool crit) { if (Main.rand.Next(3) == 0) { target.AddBuff(24, 600, false); } else { target.AddBuff(24, 300, false); } } public override void OnHitPvp(Player target, int damage, bool crit) { if (Main.rand.Next(3) == 0) { target.AddBuff(24, 600, false); } else { target.AddBuff(24, 300, false); } } } }<file_sep>/Revolt_Radiation/Items/Infinispear.cs using Terraria; using Terraria.ID; using Terraria.ModLoader; namespace Revolt_Radiation.Items { public class InfiniSpear : ModItem { public override void SetStaticDefaults() { DisplayName.SetDefault("InfiniSpear"); Tooltip.SetDefault("Lo and behold, a solution to the Throwing Boycott!\nShoots apparations of Lancerion's weapon"); } public override void SetDefaults() { // Alter any of these values as you see fit, but you should probably keep useStyle on 1, as well as the noUseGraphic and noMelee bools item.shootSpeed = 10f; item.damage = 15; item.knockBack = 5f; item.useStyle = 1; item.useAnimation = 35; item.useTime = 35; item.width = 18; item.height = 54; item.maxStack = 1; item.rare = 5; item.consumable = false; item.noUseGraphic = true; item.noMelee = true; item.autoReuse = true; item.thrown = true; item.UseSound = SoundID.Item20; item.value = Item.sellPrice(gold: 1); item.shoot = mod.ProjectileType("LancerionSpearFriendly"); } } } <file_sep>/Revolt_Radiation/Projectiles/LunarPetProjectile.cs using System; using Microsoft.Xna.Framework; using Terraria; using Terraria.ID; using Terraria.ModLoader; namespace Revolt_Radiation.Projectiles { public class LunarPetProjectile : ModProjectile { public override void SetStaticDefaults() { ProjectileID.Sets.TrailingMode[projectile.type] = 2; ProjectileID.Sets.LightPet[projectile.type] = true; Main.projPet[projectile.type] = true; Main.projFrames[projectile.type] = 16; } public override void SetDefaults() { projectile.CloneDefaults(ProjectileID.SuspiciousTentacle); projectile.tileCollide = true; projectile.ignoreWater = false; projectile.alpha = 0; } const int fadeInTicks = 10; const int fullBrightTicks = 200; const int range = 50; int rangeHypoteneus = (int)Math.Sqrt(range * range + range * range); public override bool PreAI() { Player player = Main.player[projectile.owner]; player.lightOrb = false; return true; } public override bool CloneNewInstances { get { return true; } } int frame = 5; int frameCounter = 16; public override void AI() { Player player = Main.player[projectile.owner]; MyPlayer modPlayer = player.GetModPlayer<MyPlayer>(mod); if (player.dead) { modPlayer.LightPet = false; } if (modPlayer.LightPet) { projectile.timeLeft = 2; } if (++frameCounter >= 5) { frameCounter = 0; if (++frame >= 16) { frame = 0; } Vector2 vectorToPlayer = player.Center - projectile.Center; Lighting.AddLight(projectile.Center, ((255 - projectile.alpha) * 0.9f) / 255f, ((255 - projectile.alpha) * 0.1f) / 255f, ((255 - projectile.alpha) * 0.3f) / 255f); } } } }<file_sep>/Revolt_Radiation/Projectiles/SeekerVortex.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Terraria; using Terraria.ModLoader; using Terraria.ID; using Terraria.Graphics.Effects; using Terraria.Graphics.Shaders; using Terraria.DataStructures; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace Revolt_Radiation.Projectiles { public class SeekerVortex : ModProjectile { public override void SetStaticDefaults() { DisplayName.SetDefault("Seeker Vortex"); Main.projFrames[projectile.type] = 1; } public override void SetDefaults() { projectile.width = 1; projectile.height = 1; projectile.alpha = 255; projectile.timeLeft = 180; // 3 seconds projectile.hide = true; projectile.hostile = false; projectile.tileCollide = false; projectile.penetrate = 5; } public override void AI() { if (projectile.owner == Main.myPlayer) { if (projectile.timeLeft == 160) { projectile.ai[0] = Projectile.NewProjectile(projectile.Center.X, projectile.Center.Y, 0f, 0f, ProjectileID.MoonlordTurret, 34, 5, Main.myPlayer, projectile.ai[1]); } if (projectile.timeLeft == 1) { Projectile child = Main.projectile[(int)projectile.ai[0]]; if (child.active && child.type == ProjectileID.MoonlordTurret) { child.Kill(); } } } } public override void DrawBehind(int index, List<int> drawCacheProjsBehindNPCsAndTiles, List<int> drawCacheProjsBehindNPCs, List<int> drawCacheProjsBehindProjectiles, List<int> drawCacheProjsOverWiresUI) { drawCacheProjsBehindNPCsAndTiles.Add(index); } } }<file_sep>/Revolt_Radiation/Items/Green_Flare.cs using System; using Terraria; using Terraria.ID; using Terraria.Localization; using Terraria.ModLoader; namespace Revolt_Radiation.Items { public class Green_Flare : ModItem { public override void SetStaticDefaults() { ItemID.Sets.ItemNoGravity[item.type] = true; DisplayName.SetDefault("Green Flare"); } public override void SetDefaults() { item.shootSpeed = 6f; item.shoot = mod.ProjectileType("Green_Flare_Projectile"); item.damage = 1; item.width = 12; item.height = 12; item.maxStack = 999; item.consumable = true; item.ammo = AmmoID.Flare; item.knockBack = 1.5f; item.value = 7; item.ranged = true; } } }<file_sep>/Revolt_Radiation/Projectiles/Hostile/Rocket_0_Hostile.cs using Terraria; using Terraria.ID; using Terraria.ModLoader; namespace Revolt_Radiation.Projectiles.Hostile { public class Rocket_0_Hostile : ModProjectile { public override void SetStaticDefaults() { DisplayName.SetDefault("Snail Rocket"); Main.projFrames[projectile.type] = 4; } public override void SetDefaults() { projectile.width = 30; projectile.height = 25; projectile.aiStyle = 16; projectile.friendly = false; projectile.hostile = true; projectile.timeLeft = 900; projectile.penetrate = -1; projectile.tileCollide = false; } public override void AI() { Main.PlaySound(SoundID.Item14, projectile.position); } } } <file_sep>/Revolt_Radiation/Items/LancerionBag.cs using Terraria; using Terraria.ID; using Terraria.ModLoader; namespace Revolt_Radiation.Items { public class LancerionBag : ModItem { public override void SetStaticDefaults() { DisplayName.SetDefault("Treasure Bag"); Tooltip.SetDefault("{$CommonItemTooltip.RightClickToOpen}"); } public override void SetDefaults() { item.maxStack = 999; item.consumable = true; item.width = 24; item.height = 24; item.rare = 11; item.expert = true; bossBagNPC = mod.NPCType("Lancerion"); } public override bool CanRightClick() { return true; } public override void OpenBossBag(Player player) { if (Main.rand.Next(5)==1) { player.QuickSpawnItem(mod.ItemType("InfiniSpear")); } if (Main.rand.Next(7)==1) { player.QuickSpawnItem(mod.ItemType("LancerionMask")); } if (Main.rand.Next(2)==1) { player.QuickSpawnItem(ItemID.DaybloomSeeds, 1); } else if (Main.rand.Next(2)==1) { player.QuickSpawnItem(ItemID.MoonglowSeeds, 1); } else if (Main.rand.Next(2)==1) { player.QuickSpawnItem(ItemID.WaterleafSeeds, 1); } if (Main.rand.Next(2)==1) { player.QuickSpawnItem(ItemID.BlinkrootSeeds, 1); } else if (Main.rand.Next(2)==1) { player.QuickSpawnItem(ItemID.DeathweedSeeds, 1); } else if (Main.rand.Next(2)==1) { player.QuickSpawnItem(ItemID.FireblossomSeeds, 1); } } } }<file_sep>/Revolt_Radiation/Projectiles/LunarFlare.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Terraria; using Terraria.ModLoader; using Terraria.ID; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace Revolt_Radiation.Projectiles { public class LunarFlare : ModProjectile { public override void SetStaticDefaults() { DisplayName.SetDefault("Lunar Flare"); Main.projFrames[projectile.type] = 7; } public override void SetDefaults() { projectile.CloneDefaults(ProjectileID.LunarFlare); aiType = ProjectileID.LunarFlare; } public override void OnHitNPC(NPC target, int damage, float knockback, bool crit) { target.AddBuff(BuffID.Chilled, 10, false); } public void OnHitPvp(NPC target, int damage, float knockback, bool crit) { target.AddBuff(BuffID.Chilled, 10, false); } public override void Kill(int timeleft) { if (Main.rand.NextBool(5)) { Main.PlaySound(SoundID.Item122, projectile.position); Projectile.NewProjectile(projectile.Center.X, projectile.Center.Y, 0f, 0f, mod.ProjectileType("SeekerVortex"), 20, 3, Main.myPlayer); } else { Main.PlaySound(SoundID.Item34, projectile.position); } } public void OnTileCollide() { } } }<file_sep>/Revolt_Radiation/Items/AtomicFusion.cs using Terraria; using Terraria.ID; using Terraria.ModLoader; namespace Revolt_Radiation.Items { public class AtomicFusion : ModItem { public override void SetStaticDefaults() { DisplayName.SetDefault("Atomic Fusion"); Tooltip.SetDefault("Shoot atoms at each other and see what blows up"); } public override void SetDefaults() { item.shootSpeed = 5f; item.damage = 60; item.knockBack = 9f; item.useStyle = 5; item.useAnimation = 20; item.useTime = 20; item.width = 28; item.height = 32; item.maxStack = 1; item.rare = 8; item.noMelee = true; item.autoReuse = true; item.magic = true; item.UseSound = SoundID.Item66; item.value = Item.sellPrice(gold: 10); item.shoot = mod.ProjectileType("AtomicBall"); } } } <file_sep>/Revolt_Radiation/description.txt ______ _ _ | ___ \ | | | | |_/ /_____ _____ | | |_ | // _ \ \ / / _ \| | __| | |\ \ __/\ V / (_) | | |_ \_| \_\___| \_/ \___/|_|\__| ___ ___ ___ | \/ | | | | . . | ___ __| | | |\/| |/ _ \ / _` | | | | | (_) | (_| | \_| |_/\___/ \__,_| By RunicGlympse, with visuals by Cooper and ShockedHorizon5 This mod will be huge. Not in content, but in terms of features. The mod currently includes... 1 WIP Material 2 Weapons 1 Enemy 1 Boss The next version may include... 2 more WIP Materials 1 Boss 2 Enemies 3 Weapons Don't expect me to get this far. You can contact me more on Discord at RunicGlympse#3570<file_sep>/Revolt_Radiation/Items/LunarPet.cs using Terraria; using Terraria.ID; using Terraria.ModLoader; namespace Revolt_Radiation.Items { public class LunarPet : ModItem { public override void SetStaticDefaults() { DisplayName.SetDefault("<NAME>"); Tooltip.SetDefault("Exactly the same thing, but now it's your friend!"); } public override void SetDefaults() { item.CloneDefaults(ItemID.MagicLantern); item.shoot = mod.ProjectileType("LunarPetProjectile"); item.buffType = mod.BuffType("LunarPetBuff"); } public override void UseStyle(Player player) { if (player.whoAmI == Main.myPlayer && player.itemTime == 0) { player.AddBuff(item.buffType, 3600, true); } } } }<file_sep>/Revolt_Radiation/NPCs/Bosses/Lancerion.cs using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using ReLogic.Utilities; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Terraria; using Terraria.ModLoader; using Terraria.ID; using Terraria.DataStructures; using Terraria.World.Generation; using Terraria.Localization; using Terraria.GameContent.Generation; using Terraria.ModLoader.IO; using Terraria.GameContent.Tile_Entities; using Terraria.GameContent.UI; using Terraria.Graphics.Effects; using Terraria.Graphics.Shaders; using Terraria.Utilities; namespace Revolt_Radiation.NPCs.Bosses { enum LancerionState : byte { Following = 0, Stomping = 1, Teleporting = 2, Dashing = 3 } [AutoloadBossHead] public class Lancerion : ModNPC { // Determines the AI that is to be fired. Kind of like a state manager. // Using enums to determine AI states is very neat, since networking the 'LancerionState' will only need to send one byte. NEATO! :D internal LancerionState state; bool teleporting = false; Vector2 teleportationPosition = Vector2.Zero; public int dustPortal = 0; public int timer = 0; public double frametick = 0.0; public int frame = 0; public int frametick2 = 0; public double despawnTimer = 0; public int regenTimer = 0; public bool deadMeat = false; public bool collision = false; public bool attack1 = false; public bool attack2 = false; public bool jump = false; public bool throwingUp = false; public int wait = 0; public override void SetStaticDefaults() { DisplayName.SetDefault("Executioner Knight, Lancerion"); //spawn me like the eye of cthulhu! =D Main.npcFrameCount[npc.type] = 13; } public override void SetDefaults() { npc.width = 50; npc.height = 50; npc.damage = 25; npc.defense = 25; npc.lifeMax = 2000; npc.HitSound = SoundID.NPCHit4; npc.DeathSound = SoundID.NPCDeath44; npc.value = 60f; npc.knockBackResist = 0f; npc.aiStyle = 26; npc.boss = true; music = MusicID.OldOnesArmy; musicPriority = MusicPriority.BossLow; npc.netAlways = true; bossBag = mod.ItemType("LancerionBag"); state = LancerionState.Following; } public override void BossLoot(ref string name, ref int potionType) { potionType = 188; Revolt_Radiation_World.downedLancerion = true; } public override void NPCLoot() { if (Main.netMode != 1) { if (Main.expertMode) { npc.DropBossBags(); } else { if (Main.rand.Next(5) == 1) { Item.NewItem((int)npc.position.X, (int)npc.position.Y, npc.width, npc.height, mod.ItemType("InfiniSpear")); } if (Main.rand.Next(2) == 1) { Item.NewItem((int)npc.position.X, (int)npc.position.Y, npc.width, npc.height, ItemID.DaybloomSeeds, 1); } else if (Main.rand.Next(2) == 1) { Item.NewItem((int)npc.position.X, (int)npc.position.Y, npc.width, npc.height, ItemID.MoonglowSeeds, 1); } else if (Main.rand.Next(2) == 1) { Item.NewItem((int)npc.position.X, (int)npc.position.Y, npc.width, npc.height, ItemID.WaterleafSeeds, 1); } if (Main.rand.Next(2) == 1) { Item.NewItem((int)npc.position.X, (int)npc.position.Y, npc.width, npc.height, ItemID.BlinkrootSeeds, 1); } else if (Main.rand.Next(2) == 1) { Item.NewItem((int)npc.position.X, (int)npc.position.Y, npc.width, npc.height, ItemID.DeathweedSeeds, 1); } else if (Main.rand.Next(2) == 1) { Item.NewItem((int)npc.position.X, (int)npc.position.Y, npc.width, npc.height, ItemID.FireblossomSeeds, 1); } } } } public override void ScaleExpertStats(int numPlayers, float bossLifeScale) { if (numPlayers > 1) { npc.lifeMax = (int)(2500 * numPlayers * 0.20f); } } public override void PostAI() { npc.netUpdate = true; npc.TargetClosest(true); Player player = Main.player[npc.target]; if (!npc.HasValidTarget) { npc.velocity *= 0f; npc.alpha += 1; despawnTimer++; npc.spriteDirection = npc.direction; Main.PlaySound(SoundID.Item24, (int)npc.position.X, (int)npc.position.Y); Dust.NewDustDirect(npc.position, npc.width, npc.height / 2, 58, 0f, -5f, 100, default(Color), 1.5f); if (despawnTimer == 255) { npc.active = false; Main.PlaySound(SoundID.Item6, (int)npc.position.X, (int)npc.position.Y); Dust.NewDustDirect(npc.position, npc.width, npc.height, 58, 0f, 0f, 0, default(Color), 1.5f); } } npc.rotation = npc.velocity.X * 0.03F; npc.spriteDirection = npc.direction; if (npc.life >= npc.lifeMax) npc.life = npc.lifeMax; timer++; if (state == LancerionState.Following) { npc.width = 50; if (timer == 200) { state = LancerionState.Dashing; } if (timer >= 600) { if (Main.netMode != 1) { // First time entering this AI. Determines the attack type that is used. if (timer == 600) { if (Main.rand.Next(2) == 1) { attack1 = true; } else { attack2 = true; } } npc.velocity.X = 0; npc.velocity.Y = 0; if (attack1 == true) { Dust dust = Main.dust[Dust.NewDust(npc.position, npc.width, npc.height / 2, 12, 0f, -5f, 100, default(Color), 1.5f)]; dust.position = npc.Center + Vector2.UnitY.RotatedByRandom(4.1887903213500977) * new Vector2(npc.width * 1.5f, npc.height * 1.1f) * 0.8f * (0.8f + Main.rand.NextFloat() * 0.2f); if (timer < 700) { if ((timer - 600) % 20 == 0) { Main.PlaySound(SoundID.Item82, npc.Center); } } // No longer need for an extra timer. Just use the one we already have. else if ((timer - 700) % 20 == 0) { throwingUp = true; float perturbedSpeedX = player.Center.X - npc.Center.X; float perturbedSpeedY = player.Center.Y - npc.Center.Y; Projectile.NewProjectile(npc.Center.X, npc.Center.Y, perturbedSpeedX, perturbedSpeedY, mod.ProjectileType("LancerionSpear"), (int)(npc.damage * 0.50f), 2, Main.myPlayer); npc.netUpdate = true; Main.PlaySound(SoundID.Item19, npc.Center); } } else if (attack2 == true) { Dust dust = Main.dust[Dust.NewDust(npc.position, npc.width, npc.height / 2, 58, 0f, -5f, 100, default(Color), 1.5f)]; dust.position = npc.Center + Vector2.UnitY.RotatedByRandom(4.1887903213500977) * new Vector2(npc.width * 1.5f, npc.height * 1.1f) * 0.8f * (0.8f + Main.rand.NextFloat() * 0.2f); // No longer need for an extra timer. Just use the one we already have. if ((timer - 600) % 30 == 0) { float floatingY = 1; float acceleration = 1.3f; float SpeedY = floatingY * acceleration; Projectile.NewProjectile(player.Center.X, player.Center.Y - 125, 0, SpeedY, mod.ProjectileType("LancerionSpear"), (int)(npc.damage * 0.50f), 2, Main.myPlayer); npc.netUpdate = true; Main.PlaySound(SoundID.Item19, npc.Center); } } // If the timer reaches a certain point, start one of the other two AI states. if (timer >= 900) { if (Main.rand.Next(2) == 1) { state = LancerionState.Teleporting; } else { state = LancerionState.Stomping; } timer = 0; attack1 = attack2 = false; } } } } else if (state == LancerionState.Dashing) { if (timer < 250) { npc.velocity *= 0; } else if (timer == 250) { Main.PlaySound(SoundID.Item19, npc.Center); if (npc.direction == 1) { npc.velocity.X = 15; } if (npc.direction == -1) { npc.velocity.X = -15; } if (player.Center.Y - npc.Center.Y <= 0) { npc.velocity.Y = 1; } if (player.Center.Y - npc.Center.Y >= 0) { npc.velocity.Y = -1; } } else if (timer == 400) { state = LancerionState.Following; } } else if (state == LancerionState.Teleporting) //make this work { npc.velocity *= 0; if (++dustPortal >= 0) { Vector2 usePos = npc.position; Vector2 rotVector = (npc.rotation - MathHelper.ToRadians(90f)).ToRotationVector2(); usePos += rotVector * 16f; Dust.NewDustDirect(npc.position, npc.width, npc.height / 2, 58, 0f, -5f, 100, default(Color), 1.5f); } if (++regenTimer >= 5 && npc.life != 2000) { npc.life += 1; regenTimer = 0; } // We've already gained a new teleportation position, so we can begin processing it. if (teleporting) { if (teleportationPosition != Vector2.Zero && timer++ >= 100) { Vector2 usePos = npc.position; Vector2 rotVector = (npc.rotation - MathHelper.ToRadians(90f)).ToRotationVector2(); usePos += rotVector * 16f; npc.position = teleportationPosition; // Teleport to dust. Main.PlaySound(SoundID.Item6, (int)npc.position.X, (int)npc.position.Y); for (int i = 0; i < 50; ++i) { Dust.NewDustDirect(teleportationPosition, npc.width, npc.height, 58, 0f, 0f, 0, default(Color), 1.5f); } npc.netUpdate = true; // Reset NPC values and teleportation variables. timer = -50; teleporting = false; state = LancerionState.Following; if (timer == 0) { teleportationPosition = Vector2.Zero; } } else if (teleportationPosition == Vector2.Zero) // Teleportation did not succeed; reset everything to default. { timer = 0; teleporting = false; state = LancerionState.Following; } } else // We do not yet have a teleportation position for this teleport sequence. { bool tryTeleport = true; int teleportTries = 0; // We give the teleportation 50 tries to get a new, valid position. If this does not get a valid teleportation position before the tries are up, it won't teleport at all. while (tryTeleport && teleportTries <= 50) { // This position was done in pixel coordinates, not tile coordinate :s int randX = (int)(player.position.X / 16) + Main.rand.Next(16) - 8; int randY = (int)(player.position.Y / 16) + Main.rand.Next(16) - 8; int minTilePosX = randX; int maxTilePosX = randX + ((npc.width * 2) / 16); int minTilePosY = randY; int maxTilePosY = randY + ((npc.height * 2) / 16); for (int x = minTilePosX; x < maxTilePosX; x++) { for (int y = minTilePosY; y < maxTilePosY; y++) { if (WorldGen.InWorld(x, y)) { if (!Collision.SolidTiles(randX, randX + 2, randY, randY + 2)) { Vector2 vector2; vector2.X = (x * 16); vector2.Y = (y * 16); teleportationPosition = new Vector2(randX * 16, randY * 16); tryTeleport = false; } } } } teleportTries++; } teleporting = true; } } else if (state == LancerionState.Stomping) { int stompTry = 0; stompTry++; npc.velocity.X = 0; if (npc.velocity.Y == 0) { npc.ai[0] = 3; } if (npc.ai[0] > 0) { npc.velocity.Y -= 5f; npc.ai[0]--; } if (npc.collideY && npc.velocity.Y >= 0) { for (int k = 0; k < 8; k++) { if (Main.player[k].active) { MyPlayer modPlayer = Main.player[k].GetModPlayer<MyPlayer>(mod); modPlayer.cameraShakeDur = 20; modPlayer.cameraShakeMagnitude = 5f; } } if (Main.netMode != 1) { Projectile.NewProjectile(npc.Center.X, npc.Center.Y, 3f, -5f, mod.ProjectileType("LancerionStomp"), (int)(npc.damage * 0.50f), 2f, Main.myPlayer); Projectile.NewProjectile(npc.Center.X, npc.Center.Y, -3f, -5f, mod.ProjectileType("LancerionStomp"), (int)(npc.damage * 0.50f), 2f, Main.myPlayer); } Main.PlaySound(SoundID.Item66, npc.Center); timer = 0; state = LancerionState.Following; } else if (stompTry >= 1000) { stompTry = 0; npc.width = 50; timer = 0; state = LancerionState.Following; } } else { timer = 0; state = LancerionState.Following; } } public override void FindFrame(int frameHeight) { npc.frame.Y = frameHeight * frame; frametick++; if (npc.velocity.Y >= 0.5f) { frametick = 0; frame = 1; } else { npc.spriteDirection = npc.direction; if (attack1 == true) { frametick = 0; frametick2++; if (frametick2 < 10) { frame = 9; } else if (frametick2 < 20) { frame = 10; } else if (frametick2 < 30) { frame = 11; } else { frametick2 = 0; } } else if (npc.velocity.X == 0f) { frametick = 0.0; frame = 0; } else { frametick += (double)(Math.Abs(npc.velocity.X) * 1.5f); if (frametick > 10.0) { frame += 1; frametick = 0.0; } if (frame >= 9) { frame = 2; } } } if (Main.netMode != 1) { if (state == LancerionState.Teleporting) { frame = 12; } if (attack2 == true) { frame = 12; } if (despawnTimer > 0) { frame = 12; } } } public override bool PreDraw(SpriteBatch spriteBatch, Color drawColor) { if (teleporting) { if (Main.netMode != 1) { Texture2D texture = mod.GetTexture("NPCs/Bosses/AttackIndicator"); Vector2 drawPos = teleportationPosition + new Vector2(texture.Width / 2, texture.Height / 2) - Main.screenPosition; spriteBatch.Draw(texture, drawPos, Color.White); } } if (state == LancerionState.Dashing) { Vector2 drawOrigin = new Vector2(Main.npcTexture[npc.type].Width, npc.height); for (int k = 0; k < npc.oldPos.Length; k++) { Texture2D texture = mod.GetTexture("NPCs/Bosses/LancerionDash"); Vector2 afterPos = npc.oldPos[k] - Main.screenPosition + drawOrigin + new Vector2(0f, npc.gfxOffY); spriteBatch.Draw ( texture, afterPos, npc.frame, Color.White, npc.rotation, texture.Size(), 1f, SpriteEffects.None, 200f ); } return true; } return true; } public override void HitEffect(int hitDirection, double damage) { if (Main.rand.Next(2) == 1) { Dust.NewDust(npc.position, npc.width, npc.height, 94); } } public override void ModifyHitByItem(Player player, Item item, ref int damage, ref float knockback, ref bool crit) { damage *= 5; } public override void ModifyHitByProjectile(Projectile projectile, ref int damage, ref float knockback, ref bool crit, ref int hitDirection) { damage *= 2; } public override bool StrikeNPC(ref double damage, int defense, ref float knockback, int hitDirection, ref bool crit) { if (damage > 100) damage /= 2; return true; } } }
7e69c81b2d0b59eb36d26130cc760ed4092c6862
[ "Markdown", "C#", "Text" ]
23
C#
RunicGlympse/Revolt-Mod
b4698600e38decf8278b2f5fb5dddc86c95ab32e
c3c3ee3a7d078656a79ab1665a145458db01f406
refs/heads/master
<file_sep># DatePicker_Kivy A Kivy App that accepts user input date through a Date Picker. <file_sep> #!/usr/bin/python # -*- coding: utf-8 -*- ########################################################### # KivyCalendar ########################################################### from kivy.uix.popup import Popup from kivy.uix.gridlayout import GridLayout from kivy.uix.textinput import TextInput from kivy.uix.label import Label from kivy.core.window import Window from kivy.properties import NumericProperty, ReferenceListProperty from kivy.uix.popup import Popup from kivy.app import App from calendar_widget import * class LoginScreen(GridLayout): pHint_x = NumericProperty(0.7) pHint_y = NumericProperty(0.7) pHint = ReferenceListProperty(pHint_x ,pHint_y) def __init__(self, touch_switch=False, *args, **kwargs): super(LoginScreen, self).__init__(*args, **kwargs) self.touch_switch = touch_switch self.cols = 2 self.add_widget(Label(text='Select Date')) self.startdate = TextInput(multiline=False) self.add_widget(self.startdate) self.init_ui() def init_ui(self): self.startdate.text = today_date() # Calendar self.cal = CalendarWidget(as_popup=True, touch_switch=self.touch_switch) # Popup self.popup = Popup(content=self.cal, on_dismiss=self.update_value, title="") self.cal.parent_popup = self.popup self.startdate.bind(focus=self.show_popup) def show_popup(self, isnt, val): """ Open popup if textinput focused, and regardless update the popup size_hint """ self.popup.size_hint=self.pHint if val: # Automatically dismiss the keyboard # that results from the textInput Window.release_all_keyboards() self.popup.open() def update_value(self, inst): """ Update textinput value on popup close """ self.startdate.text = "%s-%s-%s" % tuple(self.cal.active_date) self.focus = False class MyApp(App): def build(self): return LoginScreen() if __name__ == '__main__': MyApp().run()
d8f1f9689a6e9aee477058a1695385b062986553
[ "Markdown", "Python" ]
2
Markdown
palakjadav/DatePicker_Kivy
92b95255869d405b02b443c8429d9a7ccf7edda5
eb4b3f1eb09f97c9d27d43679ffab4788bd4d933
refs/heads/master
<file_sep><?php namespace App\Http\Controllers\Api; use App\Models\Cms\Customer; use App\Models\Shop\Product; use App\Models\System\User; use App\Models\Tool\Supermarket; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use DB, Cache; use Spatie\Activitylog\Models\Activity; class VisualizationController extends Controller { //本周起止时间unix时间戳 private $week_start; private $week_end; //本月起止时间unix时间戳 private $month_start; private $month_end; function __construct() { $this->week_start = mktime(0, 0, 0, date("m"), date("d") - date("w") + 1, date("Y")); $this->week_end = mktime(23, 59, 59, date("m"), date("d") - date("w") + 7, date("Y")); $this->month_start = mktime(0, 0, 0, date("m"), 1, date("Y")); $this->month_end = mktime(23, 59, 59, date("m"), date("t"), date("Y")); } /** * 本周销售额 * @return array */ function sales_amount() { return Cache::remember('xApi_visualization_sales_amount', 60, function () { $amount = []; for ($i = 0; $i < 7; $i++) { $start = date('Y-m-d H:i:s', strtotime("+" . $i . " day", $this->week_start)); $end = date('Y-m-d H:i:s', strtotime("+" . ($i + 1) . " day", $this->week_start)); $amount['create'][] = Order::whereBetween('created_at', [$start, $end])->where('status', 1)->sum('total_price'); $amount['pay'][] = Order::whereBetween('pay_time', [$start, $end])->where('status', '>', 1)->sum('total_price'); } $data = [ 'week_start' => date("Y年m月d日", $this->week_start), 'week_end' => date("Y年m月d日", $this->week_end), 'amount' => $amount, ]; return $data; }); } /** * * /** * @return array */ function statistics_customer() { $year = date("Y", time()); $num = []; for ($i = 1; $i <= 12; $i++) { $month = strlen($i) == 1 ? '0' . $i : $i; $like = $year . '_' . $month . '%'; $num[] = Customer::where('created_at', 'like', $like)->count(); } $data = [ 'this_year' => $year, 'num' => $num ]; return $data; } /** * 贷超浏览情况 * @return array */ function statistics_supermarket() { Supermarket::clear(); $supermarkets = Supermarket::get_supermarkets(); if (!empty($supermarkets)) { foreach ($supermarkets as $key => $supermarket) { $supermarkets[$key]['num'] = Activity::where(array('log_name' => 'supermarket', 'subject_id' => $supermarket['id']))->count(); } } return $supermarkets; } function statistics_product() { $products = Product::all(); if (!empty($products)) { foreach ($products as $key => $product) { $products[$key]['num'] = Activity::where(array('log_name' => 'product', 'subject_id' => $product['id']))->count(); } } return $products; } /** * @param $user_id * @param $start_date * @param $end_date * @return mixed */ function product_pv($user_id, $start_date, $end_date) { $start = $start_date . ' 00:00:00'; $end = $end_date . ' 23:59:59'; if ($user_id == 1) { $product_pvs = Product::withCount(['pvs' => function ($query) use ($start, $end) { $query->whereBetween('created_at', [$start, $end]); }])->get(); } else { $user = User::find($user_id); $rate = $user->rate; $product_pvs = Product::withCount(['pvs' => function ($query) use ($user_id, $start, $end) { $query->where('user_id', $user_id); $query->whereBetween('created_at', [$start, $end]); }])->get(); foreach ($product_pvs as $key => $product_pv) { $product_pvs[$key]['pvs_count'] = intval($rate * $product_pv['pvs_count']); } } return $product_pvs; } function supermarket_pv($user_id, $start_date, $end_date) { $start = $start_date . ' 00:00:00'; $end = $end_date . ' 23:59:59'; if ($user_id == 1) { $product_pvs = Supermarket::withCount(['pvs' => function ($query) use ($start, $end) { $query->whereBetween('created_at', [$start, $end]); }])->get(); } else { $user = User::find($user_id); $rate = $user->rate; $product_pvs = Supermarket::withCount(['pvs' => function ($query) use ($user_id, $start, $end) { $query->where('user_id', $user_id); $query->whereBetween('created_at', [$start, $end]); }])->get(); foreach ($product_pvs as $key => $product_pv) { $product_pvs[$key]['pvs_count'] = intval($rate * $product_pv['pvs_count']); } } return $product_pvs; } } <file_sep><?php namespace CKSource\CKFinder\Command; use CKSource\CKFinder\Acl\Permission; use CKSource\CKFinder\Error; use CKSource\CKFinder\Config; use CKSource\CKFinder\Exception\CKFinderException; use CKSource\CKFinder\Exception\InvalidNameException; use CKSource\CKFinder\Exception\InvalidRequestException; use CKSource\CKFinder\Filesystem\File\File; use CKSource\CKFinder\Filesystem\Folder\WorkingFolder; use CKSource\CKFinder\Image; use CKSource\CKFinder\Thumbnail\ThumbnailRepository; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; class Thumbnail extends CommandAbstract { protected $requires = array(Permission::FILE_VIEW); public function execute(Request $request, WorkingFolder $workingFolder, Config $config, ThumbnailRepository $thumbnailRepository) { if (!$config->get('thumbnails.enabled')) { throw new CKFinderException('Thumbnails feature is disabled', Error::THUMBNAILS_DISABLED); } $fileName = $request->get('fileName'); $ext = strtolower(pathinfo($fileName, PATHINFO_EXTENSION)); if (!Image::isSupportedExtension($ext, $thumbnailRepository->isBitmapSupportEnabled())) { throw new InvalidNameException('Invalid source file name'); } if (null === $fileName || !File::isValidName($fileName, $config->get('disallowUnsafeCharacters'))) { throw new InvalidRequestException('Invalid file name'); } list($requestedWidth, $requestedHeight) = Image::parseSize($request->get('size')); $thumbnail = $thumbnailRepository->getThumbnail($workingFolder->getResourceType(), $workingFolder->getClientCurrentFolder(), $fileName, $requestedWidth, $requestedHeight); /** * This was added on purpose to reset any Cache-Control headers set * for example by session_start(). Symfony Session has a workaround, * but but we can't rely on this as application may not use Symfony * components to handle sessions. */ header('Cache-Control:'); $response = new Response(); $response->setPublic(); $response->setEtag(dechex($thumbnail->getTimestamp()) . "-" . dechex($thumbnail->getSize())); $lastModificationDate = new \DateTime(); $lastModificationDate->setTimestamp($thumbnail->getTimestamp()); $response->setLastModified($lastModificationDate); if ($response->isNotModified($request)) { return $response; } $thumbnailsCacheExpires = (int) $config->get('cache.thumbnails'); if ($thumbnailsCacheExpires > 0) { $response->setMaxAge($thumbnailsCacheExpires); $expireTime = new \DateTime(); $expireTime->modify('+' . $thumbnailsCacheExpires . 'seconds'); $response->setExpires($expireTime); } $response->headers->set('Content-Type', $thumbnail->getMimeType() . '; name="' . $thumbnail->getFileName() . '"'); $response->setContent($thumbnail->getImageData()); return $response; } } <file_sep><?php namespace App\Http\Controllers\Admin\Tool; use App\Models\Tool\Notice; use Illuminate\Http\Request; use App\Http\Controllers\Controller; class NoticeController extends Controller { /** * @param Request $request * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View */ public function index(Request $request) { $where = function ($query) use ($request) { if ($request->has('keyword') and $request->keyword != '') { $search = "%" . $request->keyword . "%"; $query->where('title', 'like', $search); } }; $notices = Notice::where($where)->paginate(config('admin.page_size')); //分页处理 $page = isset($page) ? $request['page'] : 1; $notices = $notices->appends(array( 'title' => $request->keyword, 'page' => $page )); return view('admin.tool.notice.index', compact('notices')); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { return view('admin.tool.notice.create'); } /** * @param Request $request * @return \Illuminate\Http\RedirectResponse * @throws \Illuminate\Validation\ValidationException */ public function store(Request $request) { $messages = [ 'title.unique' => '标题不能重复!' ]; if (!empty($request->title)){ $this->validate($request, [ 'title' => 'unique:tool_notice,title', ],$messages); } $notices = $request->all(); Notice::create($notices); return redirect(route('tool.notice.index'))->with('notice', '新增成功~'); } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { // } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { $notice = Notice::find($id); return view('admin.tool.notice.edit', compact('notice')); } /** * @param Request $request * @param Notice $notice * @return \Illuminate\Http\RedirectResponse * @throws \Illuminate\Validation\ValidationException */ public function update(Request $request, Notice $notice) { $messages = [ 'title.unique' => '标题不能重复!', ]; if (!empty($request->title)){ $this->validate($request, [ 'title' => 'unique:tool_notice,title,'.$notice->id, ],$messages); } $notice->update($request->all()); return redirect(route('tool.notice.index'))->with('notice', '编辑成功~'); } /** * @param Notice $notice * @return \Illuminate\Http\RedirectResponse * @throws \Exception */ public function destroy(Notice $notice) { $notice->delete(); return back()->with('notice', '删数成功~'); } } <file_sep><?php namespace App\Console\Commands; use Illuminate\Console\Command; use Goutte\Client as GoutteClient; use GuzzleHttp\Client as GuzzleClient; use GuzzleHttp\Exception\ConnectException; use Illuminate\Support\Facades\Redis; class Torrentkitty extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'command:torrentkitty'; /** * The console command description. * * @var string */ protected $description = '种子链接地址自动选择'; private $link; private $links = []; private $totalCount; /** * Create a new command instance. * * @return void */ public function __construct() { parent::__construct(); } /** * Execute the console command. * * @return mixed */ public function handle() { $url = "http://torrentkittyurl.com/tk/"; $goutte_client = new GoutteClient(); $crawler = $goutte_client->request('GET', $url); $crawler->filter('.text>h2>strong>a')->each(function ($node) { $this->links[] = $node->first()->attr('href'); $this->info($node->first()->attr('href')); // Redis::rpush('torrentkittyurls', $node->first()->attr('href')); }); $this->totalCount = count($this->links); $this->info("请求".$this->totalCount."条链接"); $client = new GuzzleClient([ // You can set any number of default request options. 'timeout' => 2.6, ]); foreach ($this->links as $key => $link) { try { //抛出错误的代码 $client->get($link); } catch (ConnectException $ex) { // return $ex->getMessage(); continue; } $this->link = $link; } $this->info($this->link); Redis::set('torrentkittyurl',$this->link); } } <file_sep><?php /* * CKFinder * ======== * http://cksource.com/ckfinder * Copyright (C) 2007-2015, CKSource - <NAME>. All rights reserved. * * The software, this file and its contents are subject to the CKFinder * License. Please read the license.txt file before using, installing, copying, * modifying or distribute this file or part of its contents. The contents of * this file is part of the Source Code of CKFinder. */ namespace CKSource\CKFinder\Backend; use CKSource\CKFinder\Acl\AclInterface; use CKSource\CKFinder\Acl\Permission; use CKSource\CKFinder\Config; use CKSource\CKFinder\Filesystem\Path; use CKSource\CKFinder\ResourceType\ResourceType; use CKSource\CKFinder\Utils; use League\Flysystem\Adapter\Ftp; use League\Flysystem\AdapterInterface; use League\Flysystem\Plugin\GetWithMetadata; use League\Flysystem\Filesystem; use League\Flysystem\AwsS3v2\AwsS3Adapter; /** * Backend filesystem class * * Wrapper class for League\Flysystem\Filesystem with * CKFinder customizations */ class Backend extends Filesystem { /** * Acl * * @var AclInterface $acl */ protected $acl; /** * Config * * @var Config $ckConfig */ protected $ckConfig; /** * Backend configuration array */ protected $backendConfig; /** * Constructor * * @param array $backendConfig backend configuration node * @param AclInterface $acl CKFinder ACL * @param Config $ckConfig CKFinder Config * @param AdapterInterface $adapter adapter * @param null $config config */ public function __construct(array $backendConfig, AclInterface $acl, Config $ckConfig, AdapterInterface $adapter, $config = null) { $this->backendConfig = $backendConfig; $this->acl = $acl; $this->ckConfig = $ckConfig; parent::__construct($adapter, $config); $this->addPlugin(new GetWithMetadata()); } /** * Returns a path based on resource type and resource type relative path * * @param ResourceType $resourceType resource type * @param string $path resource type relative path * * @return string path to be used with backend adapter */ public function buildPath(ResourceType $resourceType, $path) { return Path::combine($resourceType->getDirectory(), $path); } /** * Returns a filtered list of directories for given resource type and path * * @param ResourceType $resourceType * @param string $path * @param bool $recursive * * @return array */ public function directories(ResourceType $resourceType, $path = '', $recursive = false) { $directoryPath = $this->buildPath($resourceType, $path); $contents = $this->listContents($directoryPath, $recursive); // A temporary fix to disable folders renaming for AWS-S3 adapter $isAws3 = $this->adapter instanceof AwsS3Adapter; foreach ($contents as &$entry) { $entry['acl'] = $this->acl->getComputedMask($resourceType->getName(), Path::combine($path, $entry['basename'])); if ($isAws3) { $entry['acl'] &= ~Permission::FOLDER_RENAME; } } return array_filter($contents, function ($v) { return isset($v['type']) && $v['type'] === 'dir' && !$this->isHiddenFolder($v['basename']) && $v['acl'] & Permission::FOLDER_VIEW; }); } /** * Returns a filtered list of files for given resource type and path * * @param ResourceType $resourceType * @param string $path * @param bool $recursive * * @return array */ public function files(ResourceType $resourceType, $path = '', $recursive = false) { $directoryPath = $this->buildPath($resourceType, $path); $contents = $this->listContents($directoryPath, $recursive); return array_filter($contents, function($v) use ($resourceType) { return isset($v['type']) && $v['type'] === 'file' && !$this->isHiddenFile($v['basename']) && $resourceType->isAllowedExtension(isset($v['extension']) ? $v['extension'] : ''); }); } /** * Check if directory under given path contains subdirectories * * @param ResourceType $resourceType * @param string $path * * @return bool true if directory contains subdirectories */ public function containsDirectories(ResourceType $resourceType, $path = '') { if (method_exists($this->adapter, 'containsDirectories')) { return $this->adapter->containsDirectories($this, $resourceType, $path, $this->acl); } $directoryPath = $this->buildPath($resourceType, $path); $contents = $this->listContents($directoryPath); foreach ($contents as $entry) { if ($entry['type'] === 'dir' && !$this->isHiddenFolder($entry['basename']) && $this->acl->isAllowed($resourceType->getName(), Path::combine($path, $entry['basename']), Permission::FOLDER_VIEW) ) { return true; } } return false; } /** * Check if file with given name is hidden * * @param string $fileName * * @return bool true if file is hidden */ public function isHiddenFile($fileName) { $hideFilesRegex = $this->ckConfig->getHideFilesRegex(); if ($hideFilesRegex) { return (bool) preg_match($hideFilesRegex, $fileName); } return false; } /** * Check if directory with given name is hidden * * @param string $folderName * * @return bool true if directory is hidden */ public function isHiddenFolder($folderName) { $hideFoldersRegex = $this->ckConfig->getHideFoldersRegex(); if ($hideFoldersRegex) { return (bool) preg_match($hideFoldersRegex, $folderName); } return false; } /** * Check if path is hidden * * @param string $path * * @return bool true if path is hidden */ public function isHiddenPath($path) { $pathParts = explode('/', trim($path, '/')); if ($pathParts) { foreach ($pathParts as $part) { if ($this->isHiddenFolder($part)) { return true; } } } return false; } /** * Delete a directory * * @param string $dirname * * @return bool */ public function deleteDir($dirname) { // For FTP first remove recursively all directory contents if ($this->adapter instanceof Ftp) { $this->deleteContents($dirname); } return parent::deleteDir($dirname); } /** * Delete all contents in given directory * * @param string $dirname */ public function deleteContents($dirname) { $contents = $this->listContents($dirname); foreach ($contents as $entry) { if ($entry['type'] === 'dir') { $this->deleteContents($entry['path']); $this->deleteDir($entry['path']); } else { $this->delete($entry['path']); } } } /** * Checks if backend contains a directory * * The Backend::has() method is not always reliable and may * work differently for various adapters. Checking for directory * should be done with this method. * * @param string $directoryPath * * @return bool */ public function hasDirectory($directoryPath) { // Temp fix for #74 if ($this->adapter instanceof AwsS3Adapter) { $errorReporting = error_reporting(); error_reporting($errorReporting & ~E_NOTICE); } $pathParts = array_filter(explode('/', $directoryPath), 'strlen'); $dirName = array_pop($pathParts); $contents = $this->listContents(implode('/', $pathParts)); foreach ($contents as $c) { if (isset($c['type']) && isset($c['basename']) && $c['type'] === 'dir' && $c['basename'] === $dirName) { return true; } } } /** * Returns a direct url to a file * * @param string $path * * @return string|null direct url to a file or null if backend * doesn't support direct access */ public function getFileUrl($path) { if (method_exists($this->adapter, 'getFileUrl')) { return $this->adapter->getFileUrl($path); } if (isset($this->backendConfig['baseUrl'])) { return Path::combine($this->backendConfig['baseUrl'], Utils::encodeURLParts($path)); } return null; } /** * Returns the base url used to build direct url to files stored * in this backend * * @return string|null base url or null if base url for a backend * was not defined */ public function getBaseUrl() { if (isset($this->backendConfig['baseUrl'])) { return $this->backendConfig['baseUrl']; } return null; } /** * Returns the root directory defined for backend * * @return string|null root directory or null if root directory * was not defined */ public function getRootDirectory() { if (isset($this->backendConfig['root'])) { return $this->backendConfig['root']; } return null; } /** * Creates a stream for writing * * @param string $path file path * * @return resource|null a stream to a file or null if backend doesn't * support writing streams */ public function createWriteStream($path) { if (method_exists($this->adapter, 'createWriteStream')) { return $this->adapter->createWriteStream($path); } return null; } } <file_sep><?php use Illuminate\Http\Request; /* |-------------------------------------------------------------------------- | API Routes |-------------------------------------------------------------------------- | | Here is where you can register API routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | is assigned the "api" middleware group. Enjoy building your API! | */ Route::middleware('auth:api')->get('/customer', function (Request $request) { return success_data('成功', $request->user()); }); Route::group(['domain' => env('ADMIN_DOMAIN'), 'namespace' => 'Api', 'as' => 'api.'], function () { //用户统计 Route::get('statistics_customer', 'VisualizationController@statistics_customer'); //流量统计 Route::get('statistics_supermarket', 'VisualizationController@statistics_supermarket'); //流量统计 Route::get('statistics_product', 'VisualizationController@statistics_product'); //产品点击数统计 Route::get('supermarket_pv/{user_id}/{start_date}/{end_date}', 'VisualizationController@supermarket_pv'); Route::get('product_pv/{user_id}/{start_date}/{end_date}', 'VisualizationController@product_pv'); //会员管理 require 'api/customer.php'; //系统管理 require 'api/system.php'; //工具管理 require 'api/tool.php'; });<file_sep><?php // autoload_psr4.php @generated by Composer $vendorDir = dirname(dirname(__FILE__)); $baseDir = dirname($vendorDir); return array( 'Symfony\\Component\\Debug\\' => array($vendorDir . '/symfony/debug'), 'Psr\\Log\\' => array($vendorDir . '/psr/log/Psr/Log'), 'Monolog\\' => array($vendorDir . '/monolog/monolog/src/Monolog'), 'League\\Flysystem\\Dropbox\\' => array($vendorDir . '/league/flysystem-dropbox/src'), 'League\\Flysystem\\AwsS3v2\\' => array($vendorDir . '/league/flysystem-aws-s3-v2/src'), 'League\\Flysystem\\' => array($vendorDir . '/league/flysystem/src'), 'CKSource\\CKFinder\\Plugin\\' => array($vendorDir . '/cksource/ckfinder/plugins'), ); <file_sep><?php namespace App\Console\Commands; use Illuminate\Console\Command; use Goutte\Client as GoutteClient; use GuzzleHttp\Client as GuzzleClient; use GuzzleHttp\Pool; use GuzzleHttp\Psr7\Request; use GuzzleHttp\Exception\ClientException; use Illuminate\Support\Facades\Storage; class Spider extends Command { /** * The name and signature of the console command. * * @var string */ // protected $signature = 'command:spider {concurrency} {keyWords*}'; //concurrency为并发数 keyWords为查询关键词 protected $signature = 'command:spider'; private $totalPageCount; private $counter = 1; private $concurrency = 3; // 同时并发抓取 private $users = ['CycloneAxe', 'appleboy', 'Aufree', 'lifesign', 'overtrue', 'zhengjinghua', 'NauxLiu','grubby']; /** * The console command description. * * @var string */ protected $description = '爬虫'; /** * Create a new command instance. * * @return void */ public function __construct() { parent::__construct(); } /** * Execute the console command. * * @return mixed */ public function handle() { $this->totalPageCount = count($this->users); $client = new GuzzleClient(); $requests = function ($total) use ($client) { foreach ($this->users as $key => $user) { $uri = 'https://api.github.com/users/' . $user; yield function() use ($client, $uri) { return $client->getAsync($uri); }; } }; $pool = new Pool($client, $requests($this->totalPageCount), [ 'concurrency' => $this->concurrency, 'fulfilled' => function ($response, $index){ $res = json_decode($response->getBody()->getContents()); $this->info("请求第 $index 个请求,用户 " . $this->users[$index] . " 的 Github ID 为:" .$res->id); $this->countedAndCheckEnded(); }, 'rejected' => function ($reason, $index){ $this->error("rejected" ); $this->error("rejected reason: " . $reason ); $this->countedAndCheckEnded(); }, ]); // 开始发送请求 $promise = $pool->promise(); $promise->wait(); } public function countedAndCheckEnded() { if ($this->counter < $this->totalPageCount) { $this->counter++; return; } $this->info("请求结束!"); } } <file_sep><?php namespace App\Http\Controllers\Api\System; use App\Models\System\Config; use Illuminate\Http\Request; use App\Http\Controllers\Controller; class ConfigController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { $config = Config::first(); return success_data('成功', $config); } } <file_sep><?php namespace App\Models\Cms; use Illuminate\Database\Eloquent\Model; use Cache; class Category extends Model { protected $guarded = []; protected $table = 'article_categories'; public function children() { return $this->hasMany('App\Models\Cms\Category', 'parent_id', 'id'); } public function articles() { return $this->hasMany('App\Models\Cms\Article'); } //清除缓存 static function clear() { Cache::forget('cms_category_categories'); } /** * 前端导航条 * @return mixed */ static function get_navigation() { $navigation = Cache::rememberForever('cms_index_navigation', function () { return self::with(['children' => function ($query) { $query->where('is_show', true)->orderBy('sort_order')->orderBy('id'); }]) ->where('is_show', true)->where("parent_id", 0) ->orderBy('sort_order')->orderBy('id')->get(); }); return $navigation; } /** * 生成分类数据 * @return mixed */ static function get_categories() { $categories = Cache::rememberForever('cms_category_categories', function () { $categories = self::orderBy('parent_id')->orderBy('sort_order')->orderBy('id')->get(); return tree($categories); }); return $categories; } /** * 检查是否有子栏目 */ static function check_children($id) { $category = self::with('children')->find($id); if ($category->children->isEmpty()) { return true; } return false; } /** * 检查是否有文章 */ static function check_articles($id) { $category = self::with('articles')->find($id); if ($category->articles->isEmpty()) { return true; } return false; } } <file_sep>//使用ckfinder上传 $("#ck_thumb_upload").click(function () { CKFinder.modal({ chooseFiles: true, language: 'zh-cn', onInit: function (finder) { finder.on('files:choose', function (evt) { var url = evt.data.files.first().getUrl(); $("input[name='thumb']").val(url); $("#img_show").attr('src', url); }); finder.on('file:choose:resizedImage', function (evt) { var url = evt.data.resizedUrl; $("input[name='thumb']").val(url); $("#img_show").attr('src', url); }); } }); });<file_sep><?php // Copyright (c) 2003-2015, CKSource - <NAME>. All rights reserved. // For licensing, see LICENSE.html or http://ckfinder.com/license // Defines the object for the Polish language. return array ( 'ErrorUnknown' => 'Wykonanie operacji zakończyło się niepowodzeniem. (Błąd %1)', 'Errors' => array ( 10 => 'Nieprawidłowe polecenie (command).', 11 => 'Brak wymaganego parametru: typ danych (resource type).', 12 => 'Nieprawidłowy typ danych (resource type).', 13 => 'Plik konfiguracyjny connectora jest nieprawidłowy.', 14 => 'Nieprawidłowy plugin: %1.', 102 => 'Nieprawidłowa nazwa pliku lub folderu.', 103 => 'Wykonanie operacji nie jest możliwe: brak uprawnień.', 104 => 'Wykonanie operacji nie powiodło się z powodu niewystarczających uprawnień do systemu plików.', 105 => 'Nieprawidłowe rozszerzenie.', 109 => 'Nieprawiłowe żądanie.', 110 => 'Niezidentyfikowany błąd.', 111 => 'Wykonanie operacji nie powiodło się z powodu zbyt dużego rozmiaru pliku wynikowego.', 115 => 'Plik lub folder o podanej nazwie już istnieje.', 116 => 'Nie znaleziono folderu. Odśwież panel i spróbuj ponownie.', 117 => 'Nie znaleziono pliku. Odśwież listę plików i spróbuj ponownie.', 118 => 'Ścieżki źródłowa i docelowa są jednakowe.', 201 => 'Plik o podanej nazwie już istnieje. Nazwa przesłanego pliku została zmieniona na "%1".', 202 => 'Nieprawidłowy plik.', 203 => 'Nieprawidłowy plik. Plik przekracza dozwolony rozmiar.', 204 => 'Przesłany plik jest uszkodzony.', 205 => 'Brak folderu tymczasowego na serwerze do przesyłania plików.', 206 => 'Przesyłanie pliku zakończyło się niepowodzeniem z powodów bezpieczeństwa. Plik zawiera dane przypominające HTML.', 207 => 'Nazwa przesłanego pliku została zmieniona na "%1".', 300 => 'Przenoszenie nie powiodło się.', 301 => 'Kopiowanie nie powiodło się.', 302 => 'Usuwanie nie powiodło się.', 500 => 'Menedżer plików jest wyłączony z powodów bezpieczeństwa. Skontaktuj się z administratorem oraz sprawdź plik konfiguracyjny CKFindera.', 501 => 'Tworzenie miniatur jest wyłączone.' ) ); <file_sep><?php namespace App\Http\Controllers\Admin\System; use App\Http\Controllers\Controller; use Cache, Auth, Hash; class CacheController extends Controller { /** * 清除缓存 * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View */ function index() { return view('admin.system.cache.index'); } /** * 执行清除缓存 * @return \Illuminate\Http\RedirectResponse */ function destroy() { Cache::flush(); return back()->with('notice', '缓存清除成功~'); } } <file_sep><?php namespace App\Http\Controllers\Api\Customer; use App\Models\Cms\Customer; use App\Http\Controllers\Controller; use Illuminate\Http\Request; use Illuminate\Support\Facades\Validator; use App\Services\SMSService; class RegisterController extends Controller { protected $SMSService; public function __construct(SMSService $SMSService) { $this->send_sms = $SMSService; } public function change_password(Request $request) { $response = $this->send_sms->check($request); if ($response['status'] == 0) { return error_data($response['msg'], $response['datas']); } $customer = Customer::where(array('phone' => $request->phone))->first(); $customer->password = <PASSWORD>($request->password); $customer->save(); return success_data('修改成功', $customer); } public function phone_login(Request $request) { $response = $this->send_sms->check($request); if ($response['status'] == 0) { return error_data($response['msg'], $response['datas']); } $ip = $request->getClientIp(); $customer = Customer::where(array('phone' => $request->phone))->first(); $activity = activity()->inLog('customer_login') ->performedOn($customer) ->withProperties(['ip' => $ip]) ->causedBy($customer) ->log('登录成功'); $activity->ip = $ip; $activity->save(); return success_data('登陆成功', $customer); } public function register(Request $request) { $messages = [ 'phone.unique' => '不能重复注册!', 'password.required' => '密码不能为空!', 'password.min' => '密码最少为六位!', 'password.confirmed' => '两次密码不一样!', 'phone.required' => '手机号不能为空!', ]; $rules = [ 'phone' => 'required|unique:customers,phone', 'password' => 'required|min:6|confirmed', ]; $validator = Validator::make($request->all(), $rules, $messages); if ($validator->fails()) { $error = $validator->errors()->first(); return error_data($error); } $response = $this->send_sms->check($request); if ($response['status'] == 0) { return error_data($response['msg'], $response['datas']); } $customer = Customer::create([ 'phone' => $request->phone, 'password' => <PASSWORD>($request->password), 'api_token' => str_random(64) ]); if ($customer) { return success_data('注册成功', $customer); } else { return error_data('注册失败'); } } public function sms(Request $request) { $request_type = $request->request_type; // 请求类型: "send_sms"->发送短信验证码;"check_verify_code"->短信验证码校验 $send_phone = $request->phone; // 待接收短信验证码的手机号码,一般由用户在登录或注册时输入 $user_info = Customer::where(array('phone' => $send_phone))->exists(); if ($user_info && $request_type == "send_sms") { return ['status' => 0, 'msg' => '该手机号已经注册过']; } if (!$user_info && $request_type == "check_verify_code") { return ['status' => 0, 'msg' => '该用户不存在']; } if (!preg_match("/^1[0-9]{10}$/", $send_phone)) { return error_data('手机号格式错误'); } $response = $this->send_sms->code($send_phone, $request->ip()); return $response; } } <file_sep><?php namespace App\Models\Tool; use Illuminate\Database\Eloquent\Model; class Slide extends Model { //黑名单为空 protected $guarded = []; protected $table = 'tool_slide'; public $timestamps = false; } <file_sep># CKFinder 3 for PHP Thank you for choosing CKFinder. ## Feedback Use https://github.com/ckfinder/ckfinder/issues to report issues in CKFinder 3 (and its documentation) or submit feature requests. If you are unsure what information to provide when reporting a bug, check http://docs.cksource.com/ckfinder3/#!/guide/dev_issues_readme ## Translations In order to submit translations for CKFinder please visit https://github.com/ckfinder/ckfinder-translations ## Documentation CKFinder is made from two parts: the client side part and the server side connector(s). The client side part is common across all distributions (PHP and ASP.NET, Java in the future), while the server side parts are different for each language, that's why there are multiple documentation websites available. ### CKFinder 3 Documentation - http://docs.cksource.com/ckfinder3/ This website contains documentation about the client side part of CKFinder, common for all versions of CKFinder 3 and includes information about: * Integrating CKFinder with your website or with CKEditor. * Client side configuration options. * API documentation. * Tutorials about creating JavaScript plugins. * Tutorials about creating skins. ### CKFinder 3 for PHP Documentation - http://docs.cksource.com/ckfinder3-php/ This website contains documentation about the PHP connector for CKFinder 3 and includes information about: * Enabling the PHP connector. * Configuring the PHP connector. * Tutorials about creating PHP plugins. ## License Copyright (C) 2007-2015, CKSource - <NAME>. All rights reserved. To purchase a license for CKFinder visit http://cksource.com/ckfinder <file_sep><?php namespace CKSource\CKFinder\Command; use CKSource\CKFinder\Cache\CacheManager; use CKSource\CKFinder\Event\CKFinderEvent; use CKSource\CKFinder\Event\EditFileEvent; use CKSource\CKFinder\Exception\CKFinderException; use CKSource\CKFinder\Exception\InvalidExtensionException; use CKSource\CKFinder\Exception\InvalidUploadException; use CKSource\CKFinder\Filesystem\File\EditedFile; use CKSource\CKFinder\Filesystem\Path; use CKSource\CKFinder\Image; use CKSource\CKFinder\Filesystem\Folder\WorkingFolder; use CKSource\CKFinder\ResizedImage\ResizedImageRepository; use CKSource\CKFinder\Thumbnail\ThumbnailRepository; use CKSource\CKFinder\Utils; use Symfony\Component\EventDispatcher\EventDispatcher; use Symfony\Component\HttpFoundation\Request; class SaveImage extends CommandAbstract { public function execute(Request $request, WorkingFolder $workingFolder, EventDispatcher $dispatcher, CacheManager $cache, ResizedImageRepository $resizedImageRepository, ThumbnailRepository $thumbnailRepository) { $fileName = $request->query->get('fileName'); $editedFile = new EditedFile($fileName, $this->app); $saveAsNew = false; if (!$editedFile->exists()) { $saveAsNew = true; $editedFile->saveAsNew(true); } if (!$editedFile->isValid()) { throw new InvalidUploadException('Invalid file provided'); } if (!Image::isSupportedExtension($editedFile->getExtension())) { throw new InvalidExtensionException('Unsupported image type or not image file'); } $imageFormat = Image::mimeTypeFromExtension($editedFile->getExtension()); $uploadedData = $request->get('content'); if (null === $uploadedData || strpos($uploadedData, 'data:image/png;base64,') !== 0) { throw new InvalidUploadException('Invalid upload. Expected base64 encoded PNG image.'); } $data = explode(',', $uploadedData); $data = isset($data[1]) ? base64_decode($data[1]) : false; if (!$data) { throw new InvalidUploadException(); } $uploadedImage = Image::create($data); $newContents = $uploadedImage->getData($imageFormat); $editFileEvent = new EditFileEvent($this->app, $editedFile, $newContents); $cache->set( Path::combine( $workingFolder->getResourceType()->getName(), $workingFolder->getClientCurrentFolder(), $fileName), $uploadedImage->getInfo() ); $dispatcher->dispatch(CKFinderEvent::SAVE_IMAGE, $editFileEvent); $saved = false; if (!$editFileEvent->isPropagationStopped()) { $saved = $editedFile->setContents($editFileEvent->getNewContents()); //Remove thumbnails and resized images in case if file is overwritten if (!$saveAsNew && $saved) { $resourceType = $workingFolder->getResourceType(); $thumbnailRepository->deleteThumbnails($resourceType, $workingFolder->getClientCurrentFolder(), $fileName); $resizedImageRepository->deleteResizedImages($resourceType, $workingFolder->getClientCurrentFolder(), $fileName); } } return array( 'saved' => (int) $saved, 'date' => Utils::formatDate(time()) ); } } <file_sep><?php namespace App\Http\Controllers\Admin\System; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use App\Models\System\Config; class ConfigController extends Controller { /** * 显示系统设置 * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View */ function edit() { $config = Config::first(); return view('admin.system.config.edit', compact('config')); } /** * 更新系统设置 * @param Request $request * @return \Illuminate\Http\RedirectResponse */ function update(Request $request) { $config = Config::first(); $config->update($request->all()); return back()->with('notice', '修改成功~'); } } <file_sep><?php /* * CKFinder * ======== * http://cksource.com/ckfinder * Copyright (C) 2007-2015, CKSource - <NAME>. All rights reserved. * * The software, this file and its contents are subject to the CKFinder * License. Please read the license.txt file before using, installing, copying, * modifying or distribute this file or part of its contents. The contents of * this file is part of the Source Code of CKFinder. */ namespace CKSource\CKFinder\Acl\User; /** * Role context interface * * You can implement this interface to get current user role in your application. * By default Acl uses SessionRoleContext to get user role from defined $_SESSION field. * * @copyright 2015 CKSource - <NAME> */ interface RoleContextInterface { /** * Returns current user role name * * @return string|null current user role name or null */ public function getRole(); } <file_sep><?php Route::group(['prefix' => 'system', 'namespace' => 'System', 'as' => 'system.'], function () { // 清除缓存 Route::get('cache', 'CacheController@index')->name('cache.index'); Route::delete('cache', 'CacheController@destroy')->name('cache.destroy'); // 上传设置 Route::group(['prefix' => 'photo'], function () { Route::get('photo', 'PhotoController@index')->name('photo.index'); Route::get('/contents/{name}', 'PhotoController@get_contents')->name('photo.get_contents'); Route::post('/upload_public', 'PhotoController@upload_public')->name('photo.upload_public'); //自定义传入变量 Route::delete('/destroy_file/{name}', 'PhotoController@destroy_file')->name('photo.destroy_file'); Route::post('/update_file', 'PhotoController@update_file')->name('photo.update_file'); Route::post('upload_icon', 'PhotoController@upload_icon')->name('photo.upload_icon'); Route::post('upload', 'PhotoController@upload')->name('photo.upload'); Route::post('upload_img', 'PhotoController@upload_img')->name('photo.upload_img'); Route::post('upload_background_img', 'PhotoController@upload_background_img')->name('photo.upload_background_img'); }); // 系统设置 Route::group(['prefix' => 'config'], function () { Route::get('/', 'ConfigController@edit')->name('config.edit'); Route::put('/', 'ConfigController@update')->name('config.update'); }); // 用户权限 Route::patch('permission/sort_order', 'PermissionController@sort_order')->name('permission.sort_order'); Route::resource('permission', 'PermissionController'); Route::patch('user/is_something', 'UserController@is_something')->name('user.is_something'); Route::post('user/mail', 'UserController@mail')->name('user.mail'); Route::resource('user', 'UserController'); Route::resource('role', 'RoleController'); });<file_sep><?php /* * CKFinder * ======== * http://cksource.com/ckfinder * Copyright (C) 2007-2015, CKSource - <NAME>. All rights reserved. * * The software, this file and its contents are subject to the CKFinder * License. Please read the license.txt file before using, installing, copying, * modifying or distribute this file or part of its contents. The contents of * this file is part of the Source Code of CKFinder. */ namespace CKSource\CKFinder\Filesystem\File; use CKSource\CKFinder\Backend\Backend; use CKSource\CKFinder\CKFinder; use CKSource\CKFinder\Error; use CKSource\CKFinder\Exception\AccessDeniedException; use CKSource\CKFinder\Exception\InvalidUploadException; use CKSource\CKFinder\Filesystem\Folder\WorkingFolder; use Symfony\Component\HttpFoundation\File\UploadedFile as UploadedFileBase; /** * Class UploadedFile * * Represents uploaded file */ class UploadedFile extends File { /** * Symfony UploadedFile object * * @var UploadedFileBase $uploadedFile */ protected $uploadedFile; /** * WorkingFolder object pointing on folder where file is uploaded * * @var WorkingFolder $workingFolder */ protected $workingFolder; /** * Temporary path for uploaded file * * @var string $tempFilePath */ protected $tempFilePath; /** * Constructor * * @param UploadedFileBase $uploadedFile * @param CKFinder $app * * @throws \Exception if file upload failed */ public function __construct(UploadedFileBase $uploadedFile, CKFinder $app) { $this->uploadedFile = $uploadedFile; $this->workingFolder = $app['working_folder']; $this->tempFilePath = tempnam(sys_get_temp_dir(), 'ckf'); $pathinfo = pathinfo($this->tempFilePath); try { $uploadedFile->move($pathinfo['dirname'], $pathinfo['basename']); } catch (\Exception $e) { $errorMessage = $uploadedFile->getErrorMessage(); switch ($uploadedFile->getError()) { case UPLOAD_ERR_INI_SIZE: case UPLOAD_ERR_FORM_SIZE: throw new InvalidUploadException($errorMessage, Error::UPLOADED_TOO_BIG, array(), $e); case UPLOAD_ERR_PARTIAL: case UPLOAD_ERR_NO_FILE: throw new InvalidUploadException($errorMessage, Error::UPLOADED_CORRUPT, array(), $e); case UPLOAD_ERR_NO_TMP_DIR: throw new InvalidUploadException($errorMessage, Error::UPLOADED_NO_TMP_DIR, array(), $e); case UPLOAD_ERR_CANT_WRITE: case UPLOAD_ERR_EXTENSION: throw new AccessDeniedException($errorMessage, array(), $e); } } parent::__construct($uploadedFile->getClientOriginalName(), $app); } /** * Checks if file was uploaded properly * * @return bool true if upload is valid */ public function isValid() { return $this->uploadedFile && $this->tempFilePath && is_readable($this->tempFilePath) && is_writable($this->tempFilePath); } /** * Sanitizes current file name using options set in Config */ public function sanitizeFilename() { $this->fileName = static::secureName($this->fileName, $this->config->get('disallowUnsafeCharacters')); $resourceType = $this->workingFolder->getResourceType(); if ($this->config->get('checkDoubleExtension')) { $pieces = explode('.', $this->fileName); $basename = array_shift($pieces); $extension = array_pop($pieces); foreach ($pieces as $p) { $basename .= $resourceType->isAllowedExtension($p) ? '.' : '_'; $basename .= $p; } // Add the last extension to the final name. $this->fileName = $basename . '.' . $extension; } } /** * Checks if file extension is allowed in target folder * * @return bool true if extension is allowed in target folder */ public function hasAllowedExtension() { if (strpos($this->fileName, '.') === false) { return true; } return $this->workingFolder->getResourceType()->isAllowedExtension($this->getExtension()); } /** * @copydoc File::autorename() */ public function autorename(Backend $backend = null, $path = '') { return parent::autorename($this->workingFolder->getBackend(), $this->workingFolder->getPath()); } /** * Check if file was renamed * * @return bool true if file was renamed */ public function wasRenamed() { return $this->fileName != $this->uploadedFile->getClientOriginalName(); } /** * Check if current file name is defined as hidden in configuration settings * * @return bool true if filename is hidden */ public function isHiddenFile() { return $this->workingFolder->getBackend()->isHiddenFile($this->fileName); } /** * Returns the upload error. * * If the upload was successful, the constant UPLOAD_ERR_OK is returned. * Otherwise one of the other UPLOAD_ERR_XXX constants is returned. * * @return int upload error */ public function getError() { return $this->uploadedFile->getError(); } /** * Returns the upload error message. * * @return string upload error */ public function getErrorMessage() { return $this->uploadedFile->getErrorMessage(); } /** * Returns uploaded file contents * * @return string uploaded file data */ public function getContents() { return file_get_contents($this->tempFilePath); } /** * Returns contents stream for uploaded file * * @return resource */ public function getContentsStream() { return fopen($this->tempFilePath, 'r'); } /** * Returns uploaded file size in bytes * * @return int file size in bytes */ public function getSize() { clearstatcache(); return filesize($this->tempFilePath); } /** * Detect HTML in the first KB to prevent against potential security issue with * IE/Safari/Opera file type auto detection bug. * Returns true if file contain insecure HTML code at the beginning. * * @return boolean true if uploaded file contains html in first 1024 bytes */ public function containsHtml() { $fp = fopen($this->tempFilePath, 'rb'); $chunk = fread($fp, 1024); fclose($fp); $chunk = strtolower($chunk); if (!$chunk) { return false; } $chunk = trim($chunk); if (preg_match("/<!DOCTYPE\W*X?HTML/sim", $chunk)) { return true; } $tags = array('<body', '<head', '<html', '<img', '<pre', '<script', '<table', '<title'); foreach ($tags as $tag) { if (false !== strpos($chunk, $tag)) { return true ; } } //type = javascript if (preg_match('!type\s*=\s*[\'"]?\s*(?:\w*/)?(?:ecma|java)!sim', $chunk)) { return true ; } //href = javascript //src = javascript //data = javascript if (preg_match('!(?:href|src|data)\s*=\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk)) { return true ; } //url(javascript if (preg_match('!url\s*\(\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk)) { return true ; } return false ; } /** * Checks if file with current extension is allowed to contain any HTML/JS * * @return bool true if file is allowed to contain HTML chunks */ public function isAllowedHtmlFile() { return in_array(strtolower($this->getExtension()), $this->config->get('htmlExtensions')); } /** * Checks if file is a valid image * * Internally `getimagesize` is used for validation * * @return bool true if file is allowed to contain HTML chunks */ public function isValidImage() { if (@getimagesize($this->tempFilePath) === false) { return false ; } return true; } /** * Sets given data as new file contents * * @param string $data new file contents */ public function setContents($data) { file_put_contents($this->tempFilePath, $data); } } <file_sep><?php namespace App\Http\Requests\Admin\System; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Support\Facades\Auth; class ChildUpdate extends FormRequest { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return true; } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { $user_id = Auth::user()->id; return [ 'name' => 'required|unique:users,name,' . $user_id . '|max:255', // 'email' => 'required|email|unique:users,email,' . $user_id . '|max:255', 'phone' => 'required|unique:users,phone,' . $user_id . '|max:255', // 'old_password' => '<PASSWORD>', 'password' => '<PASSWORD>', ]; } // public function messages() // { // $user_id = Auth::user()->id; // return [ // 'name.unique' => $user_id, // 'email.unique' => $user_id, // ]; // // } } <file_sep><?php Route::group(['prefix' => 'system', 'namespace' => 'System', 'as' => 'system.'], function () { Route::get('config', 'ConfigController@index')->name('index'); });<file_sep><?php namespace App\Models\Tool; use Illuminate\Database\Eloquent\Model; class About extends Model { //黑名单为空 protected $guarded = []; protected $table = 'tool_about'; public $timestamps = false; } <file_sep><?php namespace App\Http\Controllers\Api\Customer; use App\Http\Controllers\Controller; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; class LoginController extends Controller { public function login(Request $request) { $phone = $request->phone; $password = $request->password; $ip = $request->getClientIp(); if (Auth::guard('customer')->attempt(['phone' => $phone, 'password' => $password])) { $customer = Auth::guard('customer')->user(); $activity = activity()->inLog('customer_login') ->performedOn($customer) ->withProperties(['ip' => $ip]) ->causedBy($customer) ->log('登录成功'); $activity->ip = $ip; $activity->save(); return success_data('登陆成功', $customer); } else { return error_data('账号密码错误'); } } } <file_sep><?php Route::group(['prefix' => 'customer', 'namespace' => 'Customer', 'as' => 'customer.'], function () { Route::post('login', 'LoginController@login')->name('login'); Route::post('phone_login', 'RegisterController@phone_login')->name('phone_login'); Route::post('change_password', 'RegisterController@change_password')->name('change_password'); Route::get('logout', 'LoginController@logout')->name('logout'); Route::middleware('auth:api')->any('update', 'CustomerController@update')->name('update'); Route::post('register', 'RegisterController@register')->name("register"); Route::middleware('auth:api')->post('reset', 'ResetPasswordController@reset')->name("reset"); Route::post('sms', 'RegisterController@sms')->name('sms'); });<file_sep><?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateConfigsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('configs', function (Blueprint $table) { $table->increments('id')->autoIncrement(); $table->string('title', 100)->comment('网站名称'); $table->string('keyword', 100)->comment('关键词'); $table->text('description')->comment('网站描述'); $table->string('icp', 100)->comment('icp备案号'); $table->string('copyright', 100)->comment('版权信息'); $table->string('author', 100)->comment('管理员'); $table->string('company', 100)->comment('公司名'); $table->string('qq',100)->comment('联系QQ'); $table->string('email',100)->comment('联系邮箱'); $table->string('mobile',100)->nullable()->comment('联系手机'); $table->string('telephone',100)->nullable()->comment('联系座机'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('configs'); } } <file_sep># gather 数据管理 <file_sep><?php namespace App\Http\Controllers\Admin\Tool; use App\Models\Tool\Slide; use Illuminate\Http\Request; use App\Http\Controllers\Controller; class SlideController extends Controller { /** * @param Request $request * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View */ public function index(Request $request) { $where = function ($query) use ($request) { if ($request->has('keyword') and $request->keyword != '') { $search = "%" . $request->keyword . "%"; $query->where('title', 'like', $search); } if ($request->has('is_show') and $request->is_show != '-1') { $query->where('is_show', $request->is_show); } }; $slides = Slide::where($where)->paginate(config('admin.page_size')); //分页处理 $page = isset($page) ? $request['page'] : 1; $slides = $slides->appends(array( 'title' => $request->keyword, 'page' => $page )); return view('admin.tool.slide.index', compact('slides')); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { return view('admin.tool.slide.create'); } /** * @param Request $request * @return \Illuminate\Http\RedirectResponse * @throws \Illuminate\Validation\ValidationException */ public function store(Request $request) { $messages = [ 'image.required' => '图片不能为空!' ]; $this->validate($request, [ 'image' => 'required', ],$messages); $slides = $request->all(); Slide::create($slides); return redirect(route('tool.slide.index'))->with('notice', '新增成功~'); } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { // } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { $slide = Slide::find($id); return view('admin.tool.slide.edit', compact('slide')); } /** * @param Request $request * @param Slide $slide * @return \Illuminate\Http\RedirectResponse * @throws \Illuminate\Validation\ValidationException */ public function update(Request $request, Slide $slide) { $messages = [ 'image.required' => '图片不能为空!' ]; $this->validate($request, [ 'image' => 'required', ],$messages); $slide->update($request->all()); return redirect(route('tool.slide.index'))->with('notice', '编辑成功~'); } /** * @param Slide $slide * @return \Illuminate\Http\RedirectResponse * @throws \Exception */ public function destroy(Slide $slide) { $slide->delete(); return back()->with('notice', '删数成功~'); } /** * Ajax修改属性 * @param Request $request * @return array */ function is_something(Request $request) { $attr = $request->attr; $slide = Slide::find($request->id); $value = $slide->$attr ? false : true; $slide->$attr = $value; $slide->save(); } /** * Ajax排序 * @param Request $request * @return array */ function sort_order(Request $request) { $slide = Slide::find($request->id); $slide->sort_order = $request->sort_order; $slide->save(); } } <file_sep><?php namespace App\Models\Cms; use Illuminate\Notifications\Notifiable; use Illuminate\Foundation\Auth\User as Authenticatable; use Spatie\Activitylog\Traits\LogsActivity; class Customer extends Authenticatable { use Notifiable,LogsActivity; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'phone','password', 'api_token','age','name','qq','email','api_token','sex','state','city','address','money' ]; protected $hidden = [ 'password', 'remember_token' ]; //黑名单 protected $guarded = ['']; /** * 用户图像 */ // public function avatar() // { // $photo = self::with('photo')->find($this->id)->photo; // $avatar = $photo ? $photo->identifier : Gravatar::src($this->email, 200); // return $avatar; // } } <file_sep><?php // Copyright (c) 2003-2015, CKSource - <NAME>. All rights reserved. // For licensing, see LICENSE.html or http://ckfinder.com/license // Defines the object for the language. return array ( 'ErrorUnknown' => '요청을 완료할 수 없었습니다. (오류 %1)', 'Errors' => array ( 10 => '올바르지 않은 명령.', 11 => '요청에서 리소스 유형이 특정되지 않았습니다.', 12 => '요청한 리소스 유형이 올바르지 않습니다.', 13 => '연결 설정 파일이 올바르지 않습니다.', 14 => '올바르지 않은 연결 플러그인: %1.', 102 => '올바르지 않은 파일 또는 폴더 이름.', 103 => '인증 제한 때문에 작업을 완료할 수 없었습니다.', 104 => '파일 시스템 권한 제한 때문에 작업을 완료할 수 없었습니다.', 105 => '올바르지 않은 파일 확장자.', 109 => '올바르지 않은 요청.', 110 => '알 수 없는 오류.', 111 => 'It was not possible to complete the request due to resulting file size.', 115 => '이미 같은 이름의 파일이나 폴더가 존재합니다.', 116 => '폴더를 찾지 못하였습니다. 새로고침을 해 보시고 다시 시도해 주십시오.', 117 => '파일을 찾지 못하였습니다. 새로고침을 해 보시고 다시 시도해 주십시오.', 118 => '원본 폴더와 대상 폴더가 동일합니다.', 201 => '이미 같은 이름의 파일이 존재합니다. 해당 업로드 파일의 이름이 "%1" 로 변경되었습니다.', 202 => '올바르지 않은 파일.', 203 => '올바르지 않은 파일. 파일 용량이 너무 큽니다.', 204 => '업로드한 파일이 손상되어 있습니다.', 205 => '서버에 업로드를 위한 임시 폴더가 사용가능하지 않습니다.', 206 => '보안상의 이유로 업로드가 중단되었습니다. 해당 파일은 HTML 같은 데이터가 포함되어 있습니다.', 207 => '업로드한 파일의 이름이 "%1" 로 변경되었습니다.', 300 => '파일(들) 이동 실패.', 301 => '파일(들) 복사 실패.', 302 => '파일(들) 삭제 실패.', 500 => '파일 브라우저가 보안상의 이유로 비활성화 되어있습니다. 당신의 시스템 관리자에게 연락을 해 보시고 CKFinder의 설정 파일을 확인해 주십시오.', 501 => '미리 보기 지원이 비활성화 되어 있습니다.' ) ); <file_sep><?php namespace CKSource\CKFinder\ResourceType; use CKSource\CKFinder\CKFinder; use Pimple\Container; class ResourceTypeFactory extends Container { protected $app; protected $config; protected $backendFactory; protected $thumbnailRepository; public function __construct(CKFinder $app) { $this->app = $app; $this->config = $app['config']; $this->backendFactory = $app['backend_factory']; $this->thumbnailRepository = $app['thumbnail_repository']; $this->resizedImageRepository = $app['resized_image_repository']; } /** * Returns resource type object with given name * * @param string $name resource type name * * @return ResourceType */ public function getResourceType($name) { if (!$this->offsetExists($name)) { $resourceTypeConfig = $this->config->getResourceTypeNode($name); $backend = $this->backendFactory->getBackend($resourceTypeConfig['backend']); $this[$name] = new ResourceType($name, $resourceTypeConfig, $backend, $this->thumbnailRepository, $this->resizedImageRepository); } return $this[$name]; } } <file_sep><?php namespace App\Http\Controllers\Admin\System; use App\Models\System\Permission; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use App\Http\Requests\Admin\System as Requests; use App\Models\System\Role; class PermissionController extends Controller { /** * 权限列表 * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View */ function index() { $permissions = Permission::get_permissions(); return view('admin.system.permission.index', compact('permissions')); } /** * 保存 * @param Request $request * @return \Illuminate\Http\RedirectResponse */ function store(Request $request) { if ($request->parent_id != 0 && !\Route::has($request->name)) { return ['status' => 0, 'msg' => '路由名称不存在,请修改后再保存~']; } Permission::create($request->all()); Permission::clear(); return ['status' => 1, 'permissions' => Permission::get_permissions()]; } /** * 编辑 * @param $id * @return mixed */ function edit($id) { return Permission::find($id); } function update(Request $request, $id) { if ($request->parent_id != 0 && !\Route::has($request->name)) { return ['status' => 0, 'msg' => '路由名称不存在,请修改后再保存~']; } $permission = Permission::find($id); $permission->update($request->all()); Permission::clear(); return ['status' => 1, 'permissions' => Permission::get_permissions()]; } function destroy($id) { if (!Permission::check_children($id)) { return ['status' => 0, 'msg' => '当前菜单有子菜单,请先将子菜单删除后再尝试删除~']; } Permission::destroy($id); Permission::clear(); return ['status' => 1, 'permissions' => Permission::get_permissions()]; } /** * 排序 * @param Request $request * @return array */ function sort_order(Request $request) { $sort_order = json_decode($request->sort_order); //一级 foreach ($sort_order as $key => $value) { Permission::sort_order($value->id, 0, $key); //二级 if (isset($value->children)) { foreach ($value->children as $key_children => $children) { Permission::sort_order($children->id, $value->id, $key_children); //三级 if (isset($children->children)) { foreach ($children->children as $key_c => $c) { Permission::sort_order($c->id, $children->id, $key_c); } } } } } Permission::clear(); } } <file_sep><?php namespace CKSource\CKFinder\Command; use CKSource\CKFinder\Acl\Permission; use CKSource\CKFinder\Filesystem\Folder\WorkingFolder; use Symfony\Component\HttpFoundation\Request; class CreateFolder extends CommandAbstract { protected $requires = array(Permission::FOLDER_CREATE); public function execute(Request $request, WorkingFolder $workingFolder) { $newFolderName = $request->query->get('newFolderName', ''); $workingFolder->createDir($newFolderName); return array('newFolder' => $newFolderName); } } <file_sep><?php namespace App\Http\Controllers\Customer; use App\Http\Controllers\Controller; use Exception; use Goutte\Client as GoutteClient; use GuzzleHttp\Client as GuzzleClient; use GuzzleHttp\Exception\ConnectException; use GuzzleHttp\Pool; use GuzzleHttp\Psr7\Request as GuzzleRequest; use GuzzleHttp\Exception\ClientException; use Illuminate\Support\Facades\Artisan; use Illuminate\Support\Facades\File; use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\Storage; use Illuminate\Http\Request; use Illuminate\Support\Facades\Validator; use Illuminate\Validation\ValidationException; use Illuminate\Support\Facades\Redis; class HomeController extends Controller { private $link; private $links = []; private $detail = []; /** * Create a new controller instance. * * @return void */ public function __construct() { // $this->middleware('auth'); } /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { return view('customer.index'); } public function customer() { // Redis::del('torrentkittyurl'); if (Redis::exists("torrentkittyurl")) { $this->link = Redis::get('torrentkittyurl'); // $this->links = Redis::lrange('torrentkittyurls', 0, -1); } else { Artisan::call('command:torrentkitty'); $this->link = Redis::get('torrentkittyurl'); // $this->links = Redis::lrange('torrentkittyurls', 0, -1); } return view('customer.customer'); } /** * @param Request $request * @throws ValidationException */ public function torrent(Request $request) { $this->link = Redis::get('torrentkittyurl'); $messages = [ 'keyword.required' => '关键词不能为空!', ]; $rules = [ 'keyword' => 'required', ]; $validator = Validator::make($request->all(), $rules, $messages); if ($validator->fails()) { $error = $validator->errors()->first(); try { throw new Exception($error); } catch (Exception $e) { throw ValidationException::withMessages(['keyword' => $e->getMessage()]); } } $keyword = $request->keyword; $url = $this->link . "/search/" . $keyword; $goutte_client = new GoutteClient(); $crawler = $goutte_client->request('GET', $url); $crawler->filter('.name')->slice(1) ->each(function ($node, $key) use ($goutte_client) { $this->detail[$key]['name'] = $node->text(); $this->detail[$key]['size'] = $node->siblings()->filter('.size')->text(); $this->detail[$key]['date'] = $node->siblings()->filter('.date')->text(); $article_url=$node->siblings()->filter('.action')->children('a')->attr('href'); // echo $name . '--' . $size . '--' . $date . '--' . $detail_url . '<br>'; $article = $goutte_client->request('GET', $this->link.$article_url); $this->detail[$key]['content'] = $article->filter('.magnet-link')->first()->text(); }); return back()->with('detail', $this->detail); } /** * @return string * @throws \GuzzleHttp\GuzzleException */ public function test() { $url = "http://www.5di.tv/"; // $request = new GuzzleRequest('GET', $url); // $guzzle_client=new GuzzleClient(); // $response = $guzzle_client->send($request, ['timeout' => 5]); // $content = $response->getBody()->getContents(); $goutte_client = new GoutteClient(); $crawler = $goutte_client->request('GET', $url); $navs = $crawler->filter('.qcontainer'); // $navs->each(function ($node) use ($goutte_client, $url) { // // $title = $node->filter('.link-hover')->first()->attr('title');//文章标题 // $image_url = $node->filter('.link-hover>img')->first()->attr('data-original'); //图片 // $type = substr(strrchr($image_url, '.'), 1); // // $path = public_path() . '/imgs'; // File::isDirectory($path) or File::makeDirectory($path, 0777, true, true); // // $goutte_client->getClient()->get($image_url, ['save_to' => $path . '/' . $title . '.' . $type, // 'headers' => ['Referer' => $image_url] // ]);//下载图片 // // // $link = $node->filter('.link-hover')->first()->attr('href'); //文章链接 // $article = $goutte_client->request('GET', $url . $link); //进入文章 // $content = $article->filter('#stab2')->first()->text(); //获取内容 // // // Log::info($title, ['url' => $image_url]); // echo $image_url . '<br>'; // // Storage::disk('my_file')->put('content/' . $title, $content); //储存在本地 // // }); ////点击链接: // $link = $crawler->selectLink('动作片')->link(); // $crawler = $goutte_client->click($link); ////提取数据: // $crawler->filter('.qcontainer')->each(function ($node) { // $title = $node->filter('.link-hover')->first()->attr('title');//文章标题 // echo $title . '<br>'; // }); //提交表单: // $crawler = $goutte_client->click($crawler->selectLink('Sign in')->link()); $form = $crawler->filter('.sj-nav-down-search form')->form(); $crawler = $goutte_client->submit($form, array('wd' => '2019')); $crawler->filter('.index-area>ul>li')->each(function ($node) { $title = $node->filter('.link-hover')->first()->attr('title');//文章标题 echo $title . '<br>'; }); } } <file_sep><?php /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | contains the "web" middleware group. Now create something great! | */ //前台 Route::group(['middleware' => ['uv'],'namespace' => 'Customer', 'domain' => env('HOME_DOMAIN')], function () { //前台首页 Route::get('/', 'HomeController@index'); //测试接口 Route::get('/test', 'HomeController@test'); //会员管理 Route::group(['prefix' => 'customer', 'as' => 'customer.'], function () { Route::get('/', 'HomeController@index')->middleware(['auth.customer']); Route::post('torrent', 'HomeController@torrent')->middleware(['auth.customer'])->name('torrent'); Route::get('login', 'LoginController@showLoginForm')->name('login'); Route::post('login', 'LoginController@login')->name('do_login');; Route::get('logout', 'LoginController@logout')->name('logout'); Route::post('register', 'RegisterController@register')->name("do_register"); Route::get('register', 'RegisterController@index')->name("register"); }); }); //后台 Route::group(['domain' => env('ADMIN_DOMAIN')], function () { //登录注册 Auth::routes(); Route::group(['middleware' => ['auth', 'sidebar', 'role'], 'namespace' => 'Admin'], function () { //后台首页 Route::group(['prefix' => 'admin'], function () { Route::get('/', 'HomeController@index')->name('admin'); Route::put('/{id}', 'HomeController@update')->name('admin.update'); Route::get('/link', 'HomeController@link')->name('admin.link'); }); //工具管理 require 'admin/tool.php'; //系统管理 require 'admin/system.php'; //内容管理 require 'admin/cms.php'; //消息管理 // require 'admin/information.php'; //服务中心 require 'admin/service.php'; }); }); <file_sep><?php use Illuminate\Database\Seeder; use App\Models\System\Permission; class PermissionsTableSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { /** * 后台首页 */ Permission::create([ 'id' => 1, 'name' => 'admin', 'label' => '首页', 'parent_id' => 0, 'icon' => 'am-icon-home', 'sort_order' => 1 ]); /** * 系统管理 */ Permission::create([ 'id' => 2, 'name' => 'system', 'label' => '系统管理', 'parent_id' => 0, 'icon' => 'am-icon-gear am-icon-spin', 'sort_order' => 2 ]); /** * 菜单与权限 */ Permission::create([ 'id' => 3, 'name' => 'system.permission.index', 'label' => '菜单与权限', 'parent_id' => 2, 'icon' => 'am-icon-lock', 'sort_order' => 3 ]); /*菜单与权限(删除)*/ Permission::create([ 'id' => 4, 'name' => 'system.permission.destroy', 'label' => '删除', 'parent_id' => 3, ]); /*菜单与权限(保存)*/ Permission::create([ 'id' => 5, 'name' => 'system.permission.store', 'label' => '保存', 'parent_id' => 3, ]); /*菜单与权限(新增)*/ Permission::create([ 'id' => 6, 'name' => 'system.permission.create', 'label' => '新增', 'parent_id' => 3, ]); /* 菜单与权限(编辑)*/ Permission::create([ 'id' => 7, 'name' => 'system.permission.edit', 'label' => '编辑', 'parent_id' => 3, ]); /*菜单与权限(更新)*/ Permission::create([ 'id' => 8, 'name' => 'system.permission.update', 'label' => '更新', 'parent_id' => 3, ]); /* 菜单与权限(排序)*/ Permission::create([ 'id' => 9, 'name' => 'system.permission.sort_order', 'label' => '排序', 'parent_id' => 3, ]); /** * 用户管理 */ Permission::create([ 'id' => 10, 'name' => 'system.user.index', 'label' => '用户管理', 'parent_id' => 2, 'icon' => 'am-icon-user', 'sort_order' => 4 ]); /*用户管理(删除)*/ Permission::create([ 'id' => 11, 'name' => 'system.user.destroy', 'label' => '删除', 'parent_id' => 10, ]); /*用户管理(保存)*/ Permission::create([ 'id' => 12, 'name' => 'system.user.store', 'label' => '保存', 'parent_id' => 10, ]); /*用户管理(新增)*/ Permission::create([ 'id' => 13, 'name' => 'system.user.create', 'label' => '新增', 'parent_id' => 10, ]); /* 用户管理(编辑)*/ Permission::create([ 'id' => 14, 'name' => 'system.user.edit', 'label' => '编辑', 'parent_id' => 10, ]); /*用户管理(更新)*/ Permission::create([ 'id' => 15, 'name' => 'system.user.update', 'label' => '更新', 'parent_id' => 10, ]); /** * 用户组管理 */ Permission::create([ 'id' => 16, 'name' => 'system.role.index', 'label' => '用户组管理', 'parent_id' => 2, 'icon' => 'am-icon-users', 'sort_order' => 5 ]); /*用户组管理(删除)*/ Permission::create([ 'id' => 17, 'name' => 'system.role.destroy', 'label' => '删除', 'parent_id' => 16, ]); /*用户组管理(保存)*/ Permission::create([ 'id' => 18, 'name' => 'system.role.store', 'label' => '保存', 'parent_id' => 16, ]); /*用户组管理(新增)*/ Permission::create([ 'id' => 19, 'name' => 'system.role.create', 'label' => '新增', 'parent_id' => 16, ]); /* 用户组管理(编辑)*/ Permission::create([ 'id' => 20, 'name' => 'system.role.edit', 'label' => '编辑', 'parent_id' => 16, ]); /*用户组管理(更新)*/ Permission::create([ 'id' => 21, 'name' => 'system.role.update', 'label' => '更新', 'parent_id' => 16, ]); /** * 系统设置 */ Permission::create([ 'id' => 22, 'name' => 'system.config.edit', 'label' => '系统设置', 'parent_id' => 2, 'icon' => 'am-icon-desktop', 'sort_order' => 6 ]); /*系统设置(更新)*/ Permission::create([ 'id' => 23, 'name' => 'system.config.update', 'label' => '更新', 'parent_id' =>22, ]); /** * 缓存管理 */ Permission::create([ 'id' => 24, 'name' => 'system.cache.index', 'label' => '缓存管理', 'parent_id' => 2, 'icon' => 'am-icon-refresh am-icon-spin', 'sort_order' => 8 ]); /*缓存管理(删除)*/ Permission::create([ 'id' => 25, 'name' => 'system.cache.destroy', 'label' => '删除', 'parent_id' => 24, ]); /** * 文件管理 */ Permission::create([ 'id' => 26, 'name' => 'system.photo.index', 'label' => '文件管理', 'parent_id' => 2, 'icon' => 'am-icon-file-image-o', 'sort_order' => 7 ]); /*文件管理(上传网站图标)*/ Permission::create([ 'id' => 27, 'name' => 'system.photo.upload_icon', 'label' => '上传网站图标', 'parent_id' => 26, ]); /*文件管理(上传网站背景图)*/ Permission::create([ 'id' => 28, 'name' => 'system.photo.upload_background_img', 'label' => '上传网站背景图', 'parent_id' => 26, ]); /*文件管理(上传文件)*/ Permission::create([ 'id' => 29, 'name' => 'system.photo.upload', 'label' => '上传文件', 'parent_id' => 26, ]); /*文件管理(读取文件)*/ Permission::create([ 'id' => 30, 'name' => 'system.photo.get_contents', 'label' => '读取文件', 'parent_id' => 26, ]); /*文件管理(上传公共文件)*/ Permission::create([ 'id' => 31, 'name' => 'system.photo.upload_public', 'label' => '上传公共文件', 'parent_id' => 26, ]); /*文件管理(删除文件)*/ Permission::create([ 'id' => 32, 'name' => 'system.photo.destroy_file', 'label' => '删除文件', 'parent_id' => 26, ]); /*文件管理(更新文件)*/ Permission::create([ 'id' => 33, 'name' => 'system.photo.update_file', 'label' => '更新文件', 'parent_id' => 26, ]); /*文件管理(上传图片文件)*/ Permission::create([ 'id' => 34, 'name' => 'system.photo.upload_img', 'label' => '上传图片文件', 'parent_id' => 26, ]); /*用户管理(更新属性)*/ Permission::create([ 'id' => 35, 'name' => 'system.user.is_something', 'label' => '更新属性', 'parent_id' => 10, ]); /** * 工具管理 */ Permission::create([ 'id' => 36, 'name' => 'tool', 'label' => '工具管理', 'parent_id' => 0, 'icon' => 'am-icon-paper-plane', ]); /* * 爬虫管理 */ Permission::create([ 'id' => 37, 'name' => 'tool.spider.index', 'label' => '爬虫管理', 'parent_id' => 36, 'icon' => 'am-icon-code-fork', ]); /*爬虫管理(新增)*/ Permission::create([ 'id' => 38, 'name' => 'tool.spider.create', 'label' => '新增', 'parent_id' => 37, ]); /*爬虫管理(保存)*/ Permission::create([ 'id' => 39, 'name' => 'tool.spider.store', 'label' => '保存', 'parent_id' => 37, ]); /*爬虫管理(更新属性)*/ Permission::create([ 'id' => 40, 'name' => 'tool.spider.is_something', 'label' => '更新属性', 'parent_id' => 37, ]); /*爬虫管理(编辑)*/ Permission::create([ 'id' => 41, 'name' => 'tool.spider.edit', 'label' => '编辑', 'parent_id' => 37, ]); /*爬虫管理(更新)*/ Permission::create([ 'id' => 42, 'name' => 'tool.spider.update', 'label' => '更新', 'parent_id' => 37, ]); /*爬虫管理(软删除)*/ Permission::create([ 'id' => 43, 'name' => 'tool.spider.destroy', 'label' => '软删除', 'parent_id' => 37, ]); /*爬虫管理(多选软删除)*/ Permission::create([ 'id' => 44, 'name' => 'tool.spider.destroy_checked', 'label' => '多选软删除', 'parent_id' => 37, ]); /*爬虫管理(回收站)*/ Permission::create([ 'id' => 45, 'name' => 'tool.spider.trash', 'label' => '回收站', 'parent_id' => 37, ]); /*爬虫管理(恢复)*/ Permission::create([ 'id' => 46, 'name' => 'tool.spider.restore', 'label' => '恢复', 'parent_id' => 37, ]); /*爬虫管理(多选恢复)*/ Permission::create([ 'id' => 47, 'name' => 'tool.spider.restore_checked', 'label' => '多选恢复', 'parent_id' => 37, ]); /*爬虫管理(删除)*/ Permission::create([ 'id' => 48, 'name' => 'tool.spider.force_destroy', 'label' => '删除', 'parent_id' => 37, ]); /*爬虫管理(多选删除)*/ Permission::create([ 'id' => 49, 'name' => 'tool.spider.force_destroy_checked', 'label' => '多选删除', 'parent_id' => 37, ]); } } <file_sep><?php Route::group(['prefix' => 'cms', 'namespace' => 'Cms', 'as' => 'cms.'], function () { //会员管理 Route::group(['prefix' => 'customer'], function () { Route::patch('is_something', 'CustomerController@is_something')->name('customer.is_something'); }); Route::resource('customer', 'CustomerController'); //栏目设置 Route::group(['prefix' => 'category'], function () { Route::patch('is_something', 'CategoryController@is_something')->name('category.is_something'); Route::patch('sort_order', 'CategoryController@sort_order')->name('category.sort_order'); }); Route::resource('category', 'CategoryController'); // 文章设置 Route::group(['prefix' => 'article'], function () { Route::delete('destroy_checked', 'ArticleController@destroy_checked')->name('article.destroy_checked'); Route::patch('is_something', 'ArticleController@is_something')->name('article.is_something'); //回收站 Route::get('trash', 'ArticleController@trash')->name('article.trash'); Route::get('{article}/restore', 'ArticleController@restore')->name('article.restore'); Route::delete('{article}/force_destroy', 'ArticleController@force_destroy')->name('article.force_destroy'); Route::delete('force_destroy_checked', 'ArticleController@force_destroy_checked')->name('article.force_destroy_checked'); Route::post('restore_checked', 'ArticleController@restore_checked')->name('article.restore_checked'); }); Route::resource('article', 'ArticleController'); });<file_sep><?php namespace CKSource\CKFinder; class Utils { /** * Convert shorthand php.ini notation into bytes, much like how the PHP source does it * @link http://pl.php.net/manual/en/function.ini-get.php * * @param string $val * * @return int */ public static function returnBytes($val) { $val = strtolower(trim($val)); if (!$val) { return 0; } $bytes = ltrim($val, '+'); if (0 === strpos($bytes, '0x')) { $bytes = intval($bytes, 16); } elseif (0 === strpos($bytes, '0')) { $bytes = intval($bytes, 8); } else { $bytes = intval($bytes); } switch (substr($val, -1)) { case 't': $bytes *= 1024; case 'g': $bytes *= 1024; case 'm': $bytes *= 1024; case 'k': $bytes *= 1024; } return $bytes; } /** * The absolute pathname of the currently executing script. * If a script is executed with the CLI, as a relative path, such as file.php or ../file.php, * $_SERVER['SCRIPT_FILENAME'] will contain the relative path specified by the user. */ public static function getRootPath() { if (isset($_SERVER['SCRIPT_FILENAME'])) { $sRealPath = dirname($_SERVER['SCRIPT_FILENAME']); } else { /** * realpath — Returns canonicalized absolute pathname */ $sRealPath = realpath('.'); } $sRealPath = static::trimPathTrailingSlashes($sRealPath); /** * The filename of the currently executing script, relative to the document root. * For instance, $_SERVER['PHP_SELF'] in a script at the address http://example.com/test.php/foo.bar * would be /test.php/foo.bar. */ $sSelfPath = dirname($_SERVER['PHP_SELF']); $sSelfPath = static::trimPathTrailingSlashes($sSelfPath); return static::trimPathTrailingSlashes(substr($sRealPath, 0, strlen($sRealPath) - strlen($sSelfPath))); } /** * @param string $path * * @return string */ protected static function trimPathTrailingSlashes($path) { return rtrim($path, DIRECTORY_SEPARATOR . '/\\'); } /** * Checks if array contains all specified keys * * @param array $array * @param array $keys * * @return true if array has all required keys, false otherwise */ public static function arrayContainsKeys(array $array, array $keys) { return count(array_intersect_key(array_flip($keys), $array)) === count($keys); } /** * Simulate the encodeURIComponent() function available in JavaScript * * @param string $str * * @return string */ public static function encodeURLComponent($str) { $revert = array('%21'=>'!', '%2A'=>'*', '%27'=>"'", '%28'=>'(', '%29'=>')'); return strtr(rawurlencode($str), $revert); } /** * Decodes URL component * * @param string $str * * @return string */ public static function decodeURLComponent($str) { return rawurldecode($str); } /** * Decodes URL parts * * @param string $str * * @return string */ public static function decodeURLParts($str) { return static::decodeURLComponent($str); } /** * Encodes URL parts * * @param string $str * * @return string */ public static function encodeURLParts($str) { $revert = array('%2F'=>'/'); return strtr(static::encodeURLComponent($str), $revert); } /** * Returns formatted date string generated for given timestamp * * @param int $timestamp * * @return string */ public static function formatDate($timestamp) { return date('YmdHis', $timestamp); } } <file_sep><?php namespace App\Providers; use App\Models\System\Config; use Illuminate\Support\Facades\View; use Illuminate\Support\ServiceProvider; class AppServiceProvider extends ServiceProvider { /** * Bootstrap any application services. * * @return void */ public function boot() { $config=Config::find(1); View::share('config',$config); } /** * Register any application services. * * @return void */ public function register() { // } } <file_sep><?php /** * Created by PhpStorm. * User: PengYaxiong * Date: 2020/2/11 * Time: 16:42 */ namespace App\Services; use Illuminate\Http\Request; use Illuminate\Support\Facades\Cache; class SMSService { /** * 发送验证码 * * @param string $mobile 手机号 * @param string $ip IP地址 * @return \Illuminate\Http\Response */ public function code($mobile, $ip) { $this->checkThrottle($mobile, $ip); if (!preg_match("/^1[0-9]{10}$/", $mobile)) { return error_data('手机号格式错误'); } $code = mt_rand(111111, 999999); $content = "【Leanzn】尊敬的客户,您的验证码为" . $code . ",请于2分钟内争取输入。如非本人操作,请忽略此短信。";//要发送的短信内容 $result = $this->NewSms($mobile, $content); $result = explode('/', $result); if ($result[0] == '000') { $smsId = str_replace('sid:', '', $result[4]); Cache::put('sms.' . $smsId, compact('mobile', 'code'), 1800); self::throttle($mobile, $ip); return success_data('发送成功', compact('mobile', 'smsId')); } else { return error_data('网络错误'); } } /** * 检查验证码 * * @param Request $request */ public function check(Request $request) { $smsId = $request->input('sms_id'); $code = $request->input('code'); $mobile = $request->input('phone'); $key = 'sms.' . $smsId; if (!Cache::has($key)) { return error_data('验证码已失效'); } $data = Cache::get($key); if ($mobile != $data['mobile'] || $code != $data['code']) { return error_data('验证码错误');# 验证码错误 } return success_data('验证成功', $data); } /** * 存储发送频率 * * @param string $mobile 手机号 * @param string $ip IP地址 */ private function throttle($mobile, $ip) { Cache::put('sms.throttle.' . $mobile, 1, 30); Cache::put('sms.throttle.' . $ip, 1, 10); } /** * 检查发送频率 * * @param string $mobile 手机号 * @param string $ip IP地址 */ private function checkThrottle($mobile, $ip) { if (Cache::has('sms.throttle.' . $mobile)) { return error_data('不能重复发送验证码'); } if (Cache::get('sms.throttle.' . $ip)) { return error_data('不能重复发送验证码'); } } public function NewSms($mobile, $content) { $url = "http://service.winic.org:8009/sys_port/gateway/index.asp?"; $data = "id=%s&pwd=%s&to=%s&Content=%s&time="; $id = urlencode(iconv("utf-8", "gb2312", "grubby")); $pwd = env('<PASSWORD>'); $to = $mobile; $content = urlencode(iconv("UTF-8", "GB2312", $content)); $rdata = sprintf($data, $id, $pwd, $to, $content); $ch = curl_init(); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $rdata); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $result = curl_exec($ch); curl_close($ch); return $result; } }<file_sep><?php return [ 'page_size' => 10, 'statistics' => true, 'os_type' => 'Linux', ];<file_sep><?php namespace App\Console\Commands; use Illuminate\Console\Command; use Illuminate\Support\Facades\Redis; class UV extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'command:uv'; /** * The console command description. * * @var string */ protected $description = 'UV'; /** * Create a new command instance. * * @return void */ public function __construct() { parent::__construct(); } /** * Execute the console command. * * @return mixed */ public function handle() { //查询所有WebStatistics缓存记录数据 $count = Redis::LLEN('WebStatistics'); $redisList = Redis::lrange('WebStatistics', 0, $count); $this->info($count); //3小时前 $time = date('Y-m-d H:i:s', strtotime("-3 hours")); array_walk($redisList, function ($value, $key) use ($time) { //返回并删除名称为key的list中的尾元素 $lpop = Redis::rpop('WebStatistics'); $saveParams = json_decode($lpop, true); $result = \App\Models\Tool\UV::where('ip', $saveParams['ip'])->where('created_at', '>', $time)->exists(); if (!$result) { \App\Models\Tool\UV::create($saveParams); } }); } } <file_sep><?php namespace CKSource\CKFinder\Command; use CKSource\CKFinder\Acl\Permission; use CKSource\CKFinder\Exception\InvalidRequestException; use CKSource\CKFinder\Filesystem\Folder\WorkingFolder; use Symfony\Component\HttpFoundation\Request; class RenameFolder extends CommandAbstract { protected $requires = array(Permission::FOLDER_RENAME); public function execute(Request $request, WorkingFolder $workingFolder) { // The root folder cannot be renamed. if ($workingFolder->getClientCurrentFolder() === '/') { throw new InvalidRequestException('Cannot rename resource type root folder'); } $newFolderName = $request->query->get('newFolderName'); return $workingFolder->rename($newFolderName); } } <file_sep><?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateSpidersTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('spiders', function (Blueprint $table) { $table->increments('id'); $table->string('name', 100)->comment('网站名称'); $table->string('url', 100)->comment('网站地址'); $table->text('description')->comment('网站描述'); $table->tinyInteger('state')->default(1); $table->timestamp('deleted_at')->nullable(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('spiders'); } } <file_sep># address API --- ## 选项 选项 | 类型 | 默认值 | 描述 --- | ---- | ------- | ----------- title | String | `'请选择地址'` | 窗口 title prov | String | `'北京'` | 省级 city | String | `'北京市'` | 市级 district | String | `'东城区'` | 县区级 selectNumber | Int | `0` | 配置可选项(2只选省市,1只选省) scrollToCenter | Boolean | `false` | 打开选择窗口时已选项是否滚动到中央 autoOpen | Boolean | `false` | 是否自动打开选择窗口 customOutput | Boolean | `false` | 自定义选择完毕输出,不执行内部填充函数 selectEnd | Function| `false` | 选择完毕回调事件 `return {prov,city,district,zip},address` ## 事件 ```javascript // 选择省级时触发 $("#address").on("provTap",function(event,activeli){ console.log(activeli.text()); }) // 选择市级时触发 $("#address").on("cityTap",function(event,activeli){ console.log(activeli.text()); }) ``` 事件 | 参数 | 描述 ------------ | -------- | ----------- provTap| event, activeli | 选择省级时触发 cityTap| event, activeli, iscroll | 选择市级时触发 <file_sep><?php namespace App\Http\Controllers\Api\Customer; use App\Http\Controllers\Controller; use Illuminate\Http\Request; class CustomerController extends Controller { /** * Create a new controller instance. * * @return void */ public function __construct() { //$this->middleware('auth:api'); } public function update(Request $request) { $type = $request->type; $customer = auth('api')->user(); switch ($type) { case('bank_info'): $customer->update([ 'card_name' => $request->card_name, 'card_id' => $request->card_id, 'bank_card' => $request->bank_card, 'bank_name' => $request->bank_name, 'bank_phone' => $request->bank_phone, ]); return success_data('提交成功'); break; // case('credit_info'): // $customer->update([ // 'credit_card' => $request->credit_card, // 'credit_name' => $request->credit_name, // 'credit_password' => $<PASSWORD>->credit_<PASSWORD>, // 'credit_phone' => $request->credit_phone, // ]); // return success_data('提交成功'); // break; // case('base_info'): // $customer->update([ // 'card_name' => $request->card_name, // 'card_id' => $request->card_id, // ]); // return success_data('提交成功'); // break; case('chat_info'): $customer->update([ 'alipay_num' => $request->alipay_num, 'weixin' => $request->weixin, 'qq' => $request->qq, 'email' => $request->email, ]); return success_data('提交成功'); break; case('office_info'): $customer->update([ 'office' => $request->office, 'city' => $request->city, 'address' => $request->address, 'office_phone' => $request->office_phone, 'office_type' => $request->office_type, 'office_money' => $request->office_money, ]); return success_data('提交成功'); break; case('linkman_info'): $customer->update([ 'linkman' => $request->linkman, 'linkman_relation' => $request->linkman_relation, 'linkman_phone' => $request->linkman_phone, ]); return success_data('提交成功'); break; case('phone_info'): $customer->update([ 'operator' => $request->operator, 'phone_password' => $request->phone_password, ]); return success_data('提交成功'); break; case('order_info'): if ($customer->order_state == 1) { $customer->update([ 'order_state' => 2, 'money' => $request->money, ]); } return success_data('提交成功'); break; case('auditing_info'): $customer->update([ 'sesame' => $request->sesame, 'credit_p' => $request->credit_p, 'taobao' => $request->taobao, 'jingdong' => $request->jingdong, 'accumulation' => $request->accumulation, 'social' => $request->social, ]); return success_data('提交成功'); break; case('base_info'): $customer->update([ 'phone' => $request->phone, 'card_name' => $request->card_name, 'card_id' => $request->card_id, 'sex' => $request->sex, 'bank_card' => $request->bank_card, 'bank_name' => $request->bank_name, 'aliplay_num' => $request->aliplay_num, 'credit_card' => $request->credit_card, ]); return success_data('提交成功'); break; case('credit_info'): $customer->update([ 'city' => $request->city, 'place_type' => $request->place_type, 'marriage' => $request->marriage, 'linkman' => $request->linkman, 'linkman_relation' => $request->linkman_relation, 'linkman_phone' => $request->linkman_phone, 'stability' => $request->stability, ]); return success_data('提交成功'); break; } } } <file_sep><?php namespace App\Http\Controllers\Admin\Cms; use App\Models\Cms\Customer; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use Illuminate\Pagination\LengthAwarePaginator; use Spatie\Activitylog\Models\Activity; class CustomerController extends Controller { /** * @param Request $request * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View */ public function index(Request $request) { $where = function ($query) use ($request) { if ($request->has('phone') and $request->phone != '') { $search = "%" . $request->phone . "%"; $query->where('phone', 'like', $search); } if ($request->has('created_at') and $request->created_at != '') { $time = explode(" ~ ", $request->input('created_at')); $start = $time[0] . ' 00:00:00'; $end = $time[1] . ' 23:59:59'; $query->whereBetween('created_at', [$start, $end]); } }; $customers = Customer::where($where)->paginate(config('admin.page_size')); //分页处理 $page = isset($page) ? $request['page'] : 1; $customers = $customers->appends(array( 'phone' => $request->phone, 'created_at' => $request->created_at, 'page' => $page )); return view('admin.cms.customer.index', compact('customers')); } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { $customer = Customer::find($id); return view('admin.cms.customer.edit', compact('customer')); } /** * @param Request $request * @param $id * @return \Illuminate\Http\RedirectResponse * @throws \Illuminate\Validation\ValidationException */ public function update(Request $request, $id) { $customer=Customer::find($id); $messages = [ 'password.min' => '密码最少为6位!' ]; if (!empty($request->password)){ $this->validate($request, [ 'password' => '<PASSWORD>' ],$messages); } if ($request->has('password') && $request->password != '') { if (!\Hash::check($request->old_password, $customer->password)) { return back()->with('alert', '原始密码错误~'); } $customer->password = bcrypt($request->password); } $customer->name = $request->name; $customer->sex = $request->sex; $customer->age = $request->age; $customer->city = $request->city; $customer->address = $request->address; $customer->money = $request->money; $customer->email = $request->email; $customer->phone = $request->phone; $customer->qq = $request->qq; $customer->state = $request->state; $customer->save(); return redirect(route('cms.customer.index'))->with('notice', '修改成功~'); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { Customer::destroy($id); return redirect(route('cms.customer.index'))->with('notice', '删除成功~'); } /** * Ajax修改属性 * @param Request $request * @return array */ function is_something(Request $request) { $attr = $request->attr; $customer = Customer::find($request->id); $value = $customer->$attr ? false : true; $customer->$attr = $value; $customer->save(); } } <file_sep><?php namespace App\Http\Controllers\Api\Tool; use App\Models\Tool\Spider; use Illuminate\Http\Request; use App\Http\Controllers\Controller; class SpiderController extends Controller { /** * Display a listing of the resource. * * @param Request $request * @return \Illuminate\Http\Response */ public function index(Request $request) { $where = function ($query) use ($request) { if ($request->has('keyword') and $request->keyword != '') { $search = "%" . $request->keyword . "%"; $query->where('title', 'like', $search); } }; $spiders = Spider::where($where)->paginate(config('admin.page_size')); //分页处理 $page = isset($page) ? $request['page'] : 1; $spiders = $spiders->appends(array( 'title' => $request->keyword, 'page' => $page )); return success_data('成功', $spiders); } public function show($id) { $spider = Spider::find($id); return success_data('成功', $spider); } } <file_sep># Amaze UI address ## qq群:82447172 --- **更新内容:** 1. 修复丢失省份 2. 修复移动端滑动失效BUG ### address Amaze UI 中国地区级联组件 - [使用示例](http://topoadmin.github.io/address/docs/demo.html) - [API文档](http://github.com/topoadmin/address/blob/master/docs/api.md) **使用说明:** 1. 获取 Amaze UI address - [直接下载](https://github.com/topoadmin/address/archive/master.zip) 2. 在 Amaze UI 样式之后引入 address 样式(`dist` 目录下的 CSS): Amaze UI address 依赖 Amaze UI 样式。 ```html <link rel="stylesheet" href="dist/amazeui.min.css"/> <link rel="stylesheet" href="dist/amazeui.address.min.css"/> ``` 3. 引入 address 插件(`dist` 目录下的 JS): ```html <script src="dist/jquery.min.js"></script> <script src="dist/amazeui.min.js"></script> `<!-- 可选: 建议引入 iscroll 原文件, 妹子内置 lite 版功能比较少 -->` <script src="dist/iscroll.min.js"></script> <script src="dist/address.min.js"></script> ``` 4. 初始化 address: ```js $(function() { $('#address').address(); }); ``` <file_sep><?php // Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved. // For licensing, see LICENSE.html or http://ckfinder.com/license // Defines the object for the Norwegian Bokmål language. return array ( 'ErrorUnknown' => 'Det var ikke mulig å utføre forespørselen. (Feil %1)', 'Errors' => array ( 10 => 'Ugyldig kommando.', 11 => 'Ressurstypen ble ikke spesifisert i forespørselen.', 12 => 'Ugyldig ressurstype.', 13 => 'Konfigurasjonsfilen for forbindelsen er ugyldig.', 14 => 'Ugyldig programvareutvidelse: %1.', 102 => 'Ugyldig fil- eller mappenavn.', 103 => 'Kunne ikke utføre forespørselen grunnet manglende tilgang.', 104 => 'Kunne ikke utføre forespørselen grunnet manglende tilgang til filsystemet.', 105 => 'Ugyldig filtype.', 109 => 'Ugyldig forespørsel.', 110 => 'Ukjent feil.', 111 => 'Det var ikke mulig å fullføre handlingen på grunn av filstørrelsen.', 115 => 'Det finnes allerede en fil eller mappe med dette navnet.', 116 => 'Kunne ikke finne mappen. Last vinduet på nytt og prøv igjen.', 117 => 'Kunne ikke finne filen. Last vinduet på nytt og prøv igjen.', 118 => 'Kilde- og mål-bane er like.', 201 => 'Det fantes allerede en fil med dette navnet. Den opplastede filens navn har blitt endret til "%1".', 202 => 'Ugyldig fil.', 203 => 'Ugyldig fil. Filen er for stor.', 204 => 'Den opplastede filen er korrupt.', 205 => 'Det finnes ingen midlertidig mappe for filopplastinger.', 206 => 'Opplastingen ble avbrutt av sikkerhetshensyn. Filen inneholder HTML-aktige data.', 207 => 'Den opplastede filens navn har blitt endret til "%1".', 300 => 'Klarte ikke å flytte fil(er).', 301 => 'Klarte ikke å kopiere fil(er).', 302 => 'Sletting av fil(er) feilet.', 500 => 'Filvelgeren ikke tilgjengelig av sikkerhetshensyn. Kontakt systemansvarlig og be ham sjekke CKFinders konfigurasjonsfil.', 501 => 'Funksjon for miniatyrbilder er skrudd av.' ) ); <file_sep><?php namespace CKSource\CKFinder\Command; use CKSource\CKFinder\Acl\Permission; use CKSource\CKFinder\Config; use CKSource\CKFinder\Exception\FileNotFoundException; use CKSource\CKFinder\Exception\InvalidRequestException; use CKSource\CKFinder\Filesystem\File\File; use CKSource\CKFinder\Filesystem\Folder\WorkingFolder; use CKSource\CKFinder\Filesystem\Path; use CKSource\CKFinder\ResizedImage\ResizedImage; use Symfony\Component\HttpFoundation\Request; class GetFileUrl extends CommandAbstract { protected $requires = array(Permission::FILE_VIEW); public function execute(WorkingFolder $workingFolder, Request $request, Config $config) { $fileName = $request->get('fileName'); $thumbnail = $request->get('thumbnail'); $fileNames = (array) $request->get('fileNames'); if (!empty($fileNames)) { $urls = array(); foreach ($fileNames as $fileName) { if (!File::isValidName($fileName, $config->get('disallowUnsafeCharacters'))) { throw new InvalidRequestException(sprintf('Invalid file name: %s', $fileName)); } $urls[$fileName] = $workingFolder->getFileUrl($fileName); } return array('urls' => $urls); } if (!File::isValidName($fileName, $config->get('disallowUnsafeCharacters')) || ($thumbnail && !File::isValidName($thumbnail, $config->get('disallowUnsafeCharacters')))) { throw new InvalidRequestException('Invalid file name'); } if (!$workingFolder->containsFile($fileName)) { throw new FileNotFoundException(); } return array( 'url' => $workingFolder->getFileUrl( $thumbnail ? Path::combine(ResizedImage::DIR, $fileName, $thumbnail) : $fileName ) ); } } <file_sep><?php namespace App\Models\System; use Illuminate\Database\Eloquent\Model; use Cache; class Permission extends Model { protected $guarded = []; public function roles() { return $this->belongsToMany(Role::class); } public function children() { return $this->hasMany(Permission::class, 'parent_id', 'id'); } public function parent() { return $this->belongsTo(Permission::class, 'parent_id', 'id'); } static function clear() { Cache::forget('system_permissions'); Cache::forget('system_children_permissions'); } static function get_permissions() { $permissions = Cache::rememberForever('system_permissions', function () { return self::with([ 'children' => function ($query) { $query->orderBy('sort_order')->orderBy('id'); $query->with([ 'children' => function ($query) { $query->orderBy('sort_order')->orderBy('id'); } ]); }, ])->where('parent_id', 0)->orderBy('sort_order')->orderBy('id')->get(); }); return $permissions; } static function get_children() { $children_permissions = Cache::rememberForever('system_children_permissions', function () { return self::with([ 'children' => function ($query) { $query->orderBy('sort_order'); } ])->where('parent_id', 0)->orderBy('sort_order')->get(); }); return $children_permissions; } /** * 检查是否有子栏目 */ static function check_children($id) { $permission = self::with('children')->find($id); if ($permission->children->isEmpty()) { return true; } return false; } static function sort_order($id, $parent_id, $sort_order) { $permission = self::find($id); $permission->sort_order = $sort_order; $permission->parent_id = $parent_id; $permission->save(); } } <file_sep><?php Route::group(['prefix' => 'service', 'namespace' => 'Service', 'as' => 'service.'], function () { //帮助中心 Route::group(['prefix' => 'helper'], function () { Route::get('/', 'HelperController@edit')->name('helper.edit'); Route::put('/', 'HelperController@update')->name('helper.update'); }); //联系客服 Route::group(['prefix' => 'content'], function () { Route::get('/', 'ContentController@edit')->name('content.edit'); Route::put('/', 'ContentController@update')->name('content.update'); }); //各类问题 Route::resource('problem', 'ProblemController'); //分享素材 Route::resource('share', 'ShareController'); });<file_sep><?php namespace App\Http\Controllers\Admin\Cms; use App\Models\Cms\Article; use App\Models\Cms\Category; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\Auth; class ArticleController extends Controller { public function __construct() { view()->share([ 'categories' => Category::get_categories(), ]); } /** * @param Request $request * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View */ public function index(Request $request) { //查找 $where = function ($query) use ($request) { if ($request->has('keyword') and $request->keyword != '') { $search = "%" . $request->keyword . "%"; $query->where('title', 'like', $search); } if ($request->has('category_id')) { $query->where('category_id', $request->category_id); } }; $articles = Article::with('category')->where($where) ->orderBy('is_top', 'desc')->orderBy('created_at', 'desc') ->paginate(config('admin.page_size')); //分页处理 $page = isset($page) ? $request['page'] : 1; $articles = $articles->appends(array( 'title' => $request->keyword, 'category_id' => $request->category_id, 'page' => $page )); return view('admin.cms.article.index', compact('articles')); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { return view('admin.cms.article.create'); } /** * @param Request $request * @return \Illuminate\Http\RedirectResponse * @throws \Illuminate\Validation\ValidationException */ function store(Request $request) { $this->validate($request, [ 'title' => 'required|max:255', ]); $article = $request->all(); Article::create($article); return back()->with('notice', '新增成功~'); } /** * @param Request $request * @param $id * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View */ public function show(Request $request,$id) { $article = Article::find($id); $ip = $request->getClientIp(); $activity = activity()->inLog('see_article') ->performedOn($article) ->withProperties(['ip' => $ip]) ->causedBy(Auth::user()) ->log('查看文章'); $activity->ip = $ip; $activity->save(); $article->see_num += 1; $article->save(); return view('admin.cms.article.show', compact('article')); } /** * @param $id * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View */ function edit($id) { $article = Article::find($id); return view('admin.cms.article.edit', compact('article')); } /** * @param Request $request * @param $id * @return \Illuminate\Http\RedirectResponse * @throws \Illuminate\Validation\ValidationException */ function update(Request $request, $id) { $this->validate($request, [ 'title' => 'required|max:255', ]); $article = Article::find($id); $article->update($request->all()); return back()->with('notice', '编辑成功~'); } /** * 删除 * @param $id * @return \Illuminate\Http\RedirectResponse */ function destroy($id) { Article::destroy($id); return back()->with('notice', '被删文章已进入回收站~'); } public function force_destroy($id) { Article::withTrashed()->where('id', $id)->forceDelete(); return back()->with('notice', '删除成功'); } /** * 多选删除 * @param Request $request * @return array */ function destroy_checked(Request $request) { $checked_id = $request->input("checked_id"); Article::destroy($checked_id); } /** * 多选永久删除 * @param Request $request * @return array */ function force_destroy_checked(Request $request) { $checked_id = $request->input("checked_id"); Article::withTrashed()->whereIn('id', $checked_id)->forceDelete(); } /** * 还原 * @param $id * @return \Illuminate\Http\RedirectResponse */ public function restore($id) { Article::withTrashed()->where('id', $id)->restore(); return back()->with('notice', '还原成功'); } /** * 多选还原 * @param Request $request * @return \Illuminate\Http\RedirectResponse */ public function restore_checked(Request $request) { $checked_id = $request->input("checked_id"); Article::withTrashed()->whereIn('id', $checked_id)->restore(); return back()->with('notice', '还原成功'); } /** * 回收站 * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View */ public function trash() { $articles = Article::with('category')->onlyTrashed()->paginate(config('admin.page_size')); return view('admin.cms.article.trash', compact('articles')); } /** * Ajax修改属性 * @param Request $request * @return array */ function is_something(Request $request) { $attr = $request->attr; $article = Article::find($request->id); $value = $article->$attr ? false : true; $article->$attr = $value; $article->save(); } } <file_sep>$(function () { var editor = editormd("markdown", { path: "/vendor/markdown/lib/", imageUpload: true, imageFormats: ["jpg", "jpeg", "gif", "png", "bmp", "webp"], imageUploadURL: "/vendor/markdown/php/upload.php", saveHTMLToTextarea: true,//获得html emoji: true,//表情 htmlDecode: "style,script,iframe|on*", width: "100%", height: "500", }); });<file_sep><?php namespace App\Models\System; use App\Models\Cms\Customer; use App\Models\Tool\PV; use Illuminate\Notifications\Notifiable; use Illuminate\Foundation\Auth\User as Authenticatable; use Spatie\Activitylog\Traits\LogsActivity; class User extends Authenticatable { use Notifiable, HasRoles, LogsActivity; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'name', 'email', 'password', 'real_name', 'state', 'phone', 'qq' ]; /** * The attributes that should be hidden for arrays. * * @var array */ protected $hidden = [ 'password', 'remember_token', ]; public function customers() { return $this->hasMany(Customer::class); } public function pvs() { return $this->hasMany(PV::class); } } <file_sep><?php namespace App\Http\Controllers\Admin\System; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use App\Http\Requests\Admin\System as Requests; use App\Models\System\User; use App\Models\System\Role; use Mail; class UserController extends Controller { /** * 用户列表 * @param Request $request * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View */ public function index(Request $request) { $where = function ($query) use ($request) { if ($request->has('keyword') and $request->keyword != '') { $search = "%" . $request->keyword . "%"; $query->where('name', 'like', $search); } }; $users = User::where($where)->paginate(config('admin.page_size')); //分页处理 $page = isset($page) ? $request['page'] : 1; $users = $users->appends(array( 'name' => $request->keyword, 'page' => $page )); return view('admin.system.user.index', compact('users')); } /** * 新增 * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View */ public function create() { $roles = Role::all(); return view('admin.system.user.create', compact('roles')); } /** * 保存 * @param Requests\UserStore $request * @return \Illuminate\Http\RedirectResponse */ public function store(Requests\UserStore $request) { $user = User::create([ 'name' => $request->name, 'real_name' => $request->real_name, 'state' => $request->state, 'email' => $request->email, 'phone' => $request->phone, 'password' => <PASSWORD>($request->password), ]); $user->roles()->sync($request->role_id); return redirect(route('system.user.index'))->with('notice', '新增成功~'); } public function show($id) { $user = User::find($id); return view('admin.system.user.show', compact('user')); } public function mail(Request $request) { $name=$request->name; $content=$request->markdown_html_code; // 第一个参数填写模板的路径,第二个参数填写传到模板的变量 Mail::send('layouts.admin.partials.user_mail',['name' => $name,'content'=>$content],function ($message)use ($request) { // 发件人(你自己的邮箱和名称) $message->from(env('MAIL_FROM_ADDRESS'), env('MAIL_FROM_NAME')); // 收件人的邮箱地址 $message->to($request->email); // 邮件主题 $message->subject($request->title); }); if(count(Mail::failures()) < 1){ return redirect(route('system.user.index'))->with('notice', '发送成功~'); }else{ return redirect(route('system.user.index'))->with('alert', '发送邮件失败,请重试~'); } } /** * 编辑用户信息 * @param $id * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View */ public function edit($id) { $user = User::with('roles')->find($id); $user_roles = $user->roles->pluck('id'); $roles = Role::all(); return view('admin.system.user.edit', compact('user', 'user_roles', 'roles')); } /** * 更新用户信息 * @param Requests\UserUpdate $request * @param $id * @return \Illuminate\Http\RedirectResponse */ public function update(Requests\UserUpdate $request, $id) { $user = User::find($id); $messages = [ 'password.min' => '密码最少为6位!' ]; if (!empty($request->password)) { $this->validate($request, [ 'password' => '<PASSWORD>' ], $messages); } if ($request->has('password') && $request->password != '') { if (!\Hash::check($request->old_password, $user->password)) { return back()->with('alert', '原始密码错误~'); } $user->password = <PASSWORD>($request->password); } $user->name = $request->name; $user->real_name = $request->real_name; $user->email = $request->email; $user->phone = $request->phone; $user->qq = $request->qq; $user->state = $request->state; $user->save(); //更新用户组信息 $user->roles()->sync($request->role_id); return redirect(route('system.user.index'))->with('notice', '修改成功~'); } public function destroy($id) { User::destroy($id); return redirect(route('system.user.index'))->with('notice', '删除成功~'); } /** * Ajax修改属性 * @param Request $request * @return array */ function is_something(Request $request) { $attr = $request->attr; $user = User::find($request->id); $value = $user->$attr ? false : true; if ($request->id == 1) { $value = true; } $user->$attr = $value; $user->save(); } } <file_sep><?php namespace App\Http\Controllers\Customer; use App\Exceptions\AuthenticatesLogout; use App\Models\System\Config; use App\Http\Controllers\Controller; use Illuminate\Http\Request; use Illuminate\Foundation\Auth\AuthenticatesUsers; class LoginController extends Controller { /* |-------------------------------------------------------------------------- | Login Controller |-------------------------------------------------------------------------- | | This controller handles authenticating users for the application and | redirecting them to your home screen. The controller uses a trait | to conveniently provide its functionality to your applications. | */ use AuthenticatesUsers, AuthenticatesLogout { AuthenticatesLogout::logout insteadof AuthenticatesUsers; } /** * Where to redirect users after login / registration. * * @var string */ protected $redirectTo = '/customer'; //protected $username; /** * Create a new controller instance. * * @return void */ public function __construct() { $this->middleware('guest.customer', ['except' => 'logout']); //$this->middleware('guest.home')->except('logout'); // $this->username = config('admin.global.username'); $configs = Config::first(); view()->share([ 'configs' => $configs, ]); } /** * 重写登录视图页面 */ public function showLoginForm() { return view('customer.login'); } /** * 自定义认证驱动 */ protected function guard() { return auth()->guard('customer'); } /** * 重写验证时使用的用户名字段 */ public function username() { if (!is_null(request()->get('merged_at'))) { return request()->get('merged_at'); } $login = request()->get('phone'); if ($this->isPhoneNo($login)) { $field = 'phone'; } else { $field = 'name'; } request()->merge([$field => $login, 'merged_at' => $field]); return $field; } private function isPhoneNo($phone) { $g = "/^1[34578]\d{9}$/"; return preg_match($g, $phone); } public function authenticated(Request $request, $user) { $ip = $request->getClientIp(); $activity = activity()->inLog('customer_login') ->performedOn($user) ->withProperties(['ip' => $ip]) ->causedBy($user) ->log('登录成功'); $activity->ip = $ip; $activity->save(); } } <file_sep><?php //API use Spatie\Activitylog\Models\Activity; function success_data($msg, $data = '') { return array('status' => 1, 'msg' => $msg, 'datas' => $data); } function error_data($msg, $data = '') { return array('status' => 0, 'msg' => $msg, 'datas' => $data); } //UV function uv() { return \App\Models\Tool\UV::count(); } //访问量 function see_num($type) { $data = Activity::where('log_name', $type)->distinct('ip')->count('ip'); return $data; } function getMobileLogo($mobile) { $phone_json = file_get_contents('http://sp0.baidu.com/8aQDcjqpAAV3otqbppnN2DJv/api.php?query={' . $mobile . '}&resource_id=6004&ie=utf8&oe=utf8&format=json'); $phone_array = json_decode($phone_json, true); if (is_array($phone_array) && $phone_array['data']) { $type = $phone_array['data'][0]['type']; } else { $type = ''; } switch ($type) { case '中国移动': return '/yd.png'; break; case '中国联通': return '/lt.png'; break; case '中国电信': return '/dx.png'; break; default: return '/404.png'; } } function getMobileLocation($mobile) { $phone_json = file_get_contents('http://sp0.baidu.com/8aQDcjqpAAV3otqbppnN2DJv/api.php?query={' . $mobile . '}&resource_id=6004&ie=utf8&oe=utf8&format=json'); $phone_array = json_decode($phone_json, true); if (is_array($phone_array) && $phone_array['data']) { $location = $phone_array['data'][0]['prov'] . $phone_array['data'][0]['city']; } else { $location = '未知错误'; } return $location; } function getMobileInfo($mobile) { if (!preg_match("/^1[345789]\d{9}$/", $mobile)) { $phone_info = array(); $phone_info['logo'] = '/404.png'; $phone_info['location'] = '手机号码错误'; $phone_info['type'] = '手机号码错误'; return ['status' => 0, 'msg' => '手机号码错误!', 'data' => $phone_info]; } else { $phone_json = file_get_contents('http://sp0.baidu.com/8aQDcjqpAAV3otqbppnN2DJv/api.php?query={' . $mobile . '}&resource_id=6004&ie=utf8&oe=utf8&format=json'); $phone_array = json_decode($phone_json, true); $phone_info = array(); $phone_info['mobile'] = $mobile; $phone_info['type'] = $phone_array['data'][0]['type']; $phone_info['location'] = $phone_array['data'][0]['prov'] . $phone_array['data'][0]['city']; switch ($phone_array['data'][0]['type']) { case '中国移动': $phone_info['logo'] = '/yd.png'; break; case '中国联通': $phone_info['logo'] = '/lt.png'; break; case '中国电信': $phone_info['logo'] = '/dx.png'; break; default: $phone_info['logo'] = '/404.png'; } return ['status' => 1, 'msg' => '查询成功', 'data' => $phone_info]; } } /** * @param $arr [要写入的数据] * @param $filename [文件路径] * @return bool|int [description] */ function writeArr($arr, $filename) { return file_put_contents($filename, "<?php\r\nreturn " . var_export($arr, true) . ";"); } //系统文件管理 function dir_info($path) { $result = []; $handle = opendir($path); //判断是否是图片 $types = '.gif|.jpeg|.png|.bmp|.ico|.jpg';//定义检查的图片类型 while ($file = readdir($handle)) { $array = []; if (substr($file, 0, 1) == ".") { continue; } $array["name"] = $file; if ($file == 'storage') { $array["type"] = "目录文件"; continue; } else { $array["type"] = get_file_type($file); } $array["size"] = get_file_size(filesize($path . "/" . $file)); $array["date"] = date("Y 年 m 月 j 日", filemtime($file)); $array["filemtime"] = strtotime(date("Y-m-d H:i:s", filemtime($file))); //获取文件扩展名 $array['file_type'] = substr(strrchr($file, '.'), 1); $array['is_image'] = stripos($types, substr(strrchr($file, '.'), 1)); $result[] = $array; } closedir($handle); return $result; } //声明一个函数用来返回文件的类型 function get_file_type($filename) { $type = ""; //通过filetype()函数返回的文件类型做为选择的条件 switch (filetype($filename)) { case 'file': $type .= "普通文件"; break; case 'dir': $type .= "目录文件"; break; case 'block': $type .= "块设备文件"; break; case 'char': $type .= "字符设备文件"; break; case 'fifo': $type .= "命名管道文件"; break; case 'link': $type .= "符号链接"; break; case 'unknown': $type .= "末知类型"; break; default: $type .= "没有检测到类型"; } //返回转换后的类型 return $type; } //自定义一个文件大小单位转换函数 function get_file_size($bytes) { //如果提供的字节数大于等于2的40次方,则条件成立 if ($bytes >= pow(2, 40)) { //将字节大小转换为同等的T大小 $return = round($bytes / pow(1024, 4), 2); //单位为TB $suffix = "TB"; //如果提供的字节数大于等于2的30次方,则条件成立 } elseif ($bytes >= pow(2, 30)) { //将字节大小转换为同等的G大小 $return = round($bytes / pow(1024, 3), 2); //单位为GB $suffix = "GB"; //如果提供的字节数大于等于2的20次方,则条件成立 } elseif ($bytes >= pow(2, 20)) { //将字节大小转换为同等的M大小 $return = round($bytes / pow(1024, 2), 2); //单位为MB $suffix = "MB"; //如果提供的字节数大于等于2的10次方,则条件成立 } elseif ($bytes >= pow(2, 10)) { //将字节大小转换为同等的K大小 $return = round($bytes / pow(1024, 1), 2); //单位为KB $suffix = "KB"; //否则提供的字节数小于2的10次方,则条件成立 } else { //字节大小单位不变 $return = $bytes; //单位为Byte $suffix = "Byte"; } //返回合适的文件大小和单位 return $return . " " . $suffix; } //function tree(&$arr, $pid, $step) //{ // global $tree; // foreach($arr as $key=>$val) { // if($val['pid'] == $pid) { // $flg = str_repeat('└―',$step); // $val['name'] = $flg.$val['name']; // $tree[] = $val; // tree($arr , $val['cid'] ,$step+1); // } // } // return $tree; //} /** * 截取, 并加上... * @param $string * @param $size * @param bool $dot 是否加上..., 默认true * @return string */ function sub($string, $size = 24, $dot = true) { $string = strip_tags(trim($string)); if (strlen($string) > $size) { $string = mb_substr($string, 0, $size); $string .= $dot ? '**' : ''; return $string; } return $string; } function hideStar($str) { //用户名、邮箱、手机账号中间字符串以*隐藏 if (strpos($str, '@')) { $email_array = explode("@", $str); $prevfix = (strlen($email_array[0]) < 4) ? "" : substr($str, 0, 3); //邮箱前缀 $count = 0; $str = preg_replace('/([\d\w+_-]{0,100})@/', '***@', $str, -1, $count); $rs = $prevfix . $str; } else { $pattern = '/(1[3458]{1}[0-9])[0-9]{4}([0-9]{4})/i'; if (preg_match($pattern, $str)) { $rs = preg_replace($pattern, '$1****$2', $str); // substr_replace($name,'****',3,4); } else { $rs = substr($str, 0, 3) . "***" . substr($str, -1); } } return $rs; } /* * millisecond 毫秒 * 返回时间戳的毫秒数部分 */ function get_millisecond() { list($usec, $sec) = explode(" ", microtime()); $msec = round($usec * 1000); return $msec; } /** * 按符号截取字符串的指定部分 * @param string $str 需要截取的字符串 * @param string $sign 需要截取的符号 * @param int $number 如是正数以0为起点从左向右截 负数则从右向左截 * @return string 返回截取的内容 */ function cut_str($str, $sign, $number) { $array = explode($sign, $str); $length = count($array); if ($number < 0) { $new_array = array_reverse($array); $abs_number = abs($number); if ($abs_number > $length) { return 'error'; } else { return $new_array[$abs_number - 1]; } } else { if ($number >= $length) { return 'error'; } else { return $array[$number]; } } } /** * 递归生成无限极分类数组 * @param $data * @param int $parent_id * @param int $count * @return array */ function tree(&$data, $parent_id = 0, $count = 1) { static $treeList = []; foreach ($data as $key => $value) { if ($value['parent_id'] == $parent_id) { $value['count'] = $count; $treeList [] = $value; unset($data[$key]); tree($data, $value['id'], $count + 1); } } return $treeList; } /** * 栏目名前面加上缩进 * @param $count * @return string */ function indent_category($count) { $str = ''; for ($i = 1; $i < $count; $i++) { $str .= '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'; } return $str; } function order_color($status) { switch ($status) { case '1': return 'uc-order-item-pay'; //橙 break; case '2': return 'uc-order-item-shipping'; //红 break; case '3': return 'uc-order-item-shipping'; //红 break; case '4': return 'uc-order-item-receiving'; //绿 break; case '5': return 'uc-order-item-finish'; //灰 break; default: return 'uc-order-item-finish'; } } //是否... function is_something($attr, $module) { return $module->$attr ? '<span class="am-icon-check is_something" data-attr="' . $attr . '"></span>' : '<span class="am-icon-close is_something" data-attr="' . $attr . '"></span>'; } //显示栏目对应文章 function show_articles($category) { if ($category->type == 2) { return '<a class="am-badge am-badge-secondary" href="' . route('cms.article.index', ['category_id' => $category->id]) . '">查看栏目文章</a>'; } } //显示分类对应商品 function show_category_products($category) { if (!$category->products->isEmpty()) { return '<a class="am-badge am-badge-secondary" href="' . route('shop.product.index', ['category_id' => $category->id]) . '">查看商品</a>'; } } function show_brand_products($brand) { if (!$brand->products->isEmpty()) { return '<a class="am-badge am-badge-secondary" href="' . route('shop.product.index', ['brand_id' => $brand->id]) . '">查看商品</a>'; } } function time_format($attr, $datetime) { if ($datetime == "") { return ""; } return date($attr, strtotime($datetime)); } /** * 根据类型,返回url或者key * @param $value * @return array */ function wechat_key_url($value) { $result = []; $result['type'] = $value['type']; $result['name'] = $value['name']; if ($value['type'] == "click") { $result['key'] = $value['value']; } else { $result['url'] = $value['value']; } return $result; } function category_indent($count) { $str = ''; for ($i = 0; $i < $count; $i++) { $str .= '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'; } return $str; } //生成image标签的其他属性 function build_image_attributes($attributes) { $attributes_html = ''; if ($attributes) { foreach ($attributes as $key => $value) { $attributes_html .= $key . '= "' . $value . '"'; } } return $attributes_html; } /** * 原始图片 * @param $model * @param string $class * @param string $alt * @return string */ function image_url($model, $attributes = [], $is_online = false) { $attributes_html = build_image_attributes($attributes); if ($model->image) { if ($is_online) { return ' <img src="' . env('QINIU_IMAGES_LINK') . $model->image . '" ' . $attributes_html . '>'; } else { return ' <img src="' . $model->image . '" ' . $attributes_html . '>'; } } else { return ' <img src="/no_img.jpg" ' . $attributes_html . '>'; } } /** * thumb缩略图 * @param $model * @param string $class * @param string $alt * @return string */ function thumb_url($model, $attributes = [], $is_online = false) { $attributes_html = build_image_attributes($attributes); if ($model->image) { if ($is_online) { return ' <img src="' . env('QINIU_IMAGES_LINK') . $model->image . '-thumb' . '" ' . $attributes_html . '>'; } else { return ' <img src="' . $model->image . '" ' . $attributes_html . '>'; } } else { return ' <img src="/no_img.jpg" ' . $attributes_html . '>'; } } /** * large 缩略图 * @param $model * @param string $class * @param string $alt * @return string */ function large_url($model, $attributes = [], $is_online = false) { $attributes_html = build_image_attributes($attributes); if ($model->image) { if ($is_online) { return ' <img src="' . env('QINIU_IMAGES_LINK') . $model->image . '-large' . '" ' . $attributes_html . '>'; } else { return ' <img src="' . $model->image . '" ' . $attributes_html . '>'; } } else { return ' <img src="/no_img.jpg" ' . $attributes_html . '>'; } }<file_sep><?php use Illuminate\Database\Seeder; use App\Models\System\Config; class ConfigsTableSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { /** * 系统设置 */ Config::create([ 'title' => 'LEANzn后台管理系统', 'keyword' => '权限管理系统', 'description' => '我认为最深沉的爱 ,莫过于你离开以后 ,我活成了你的样子', 'icp' => '鄂ICP备13016268号-2', 'copyright' => 'Copyright © 2018-2020 LEANzn公司版权所有', 'author' => 'Grubby', 'company' => 'LEANzn', 'qq' => '710925952', 'email' => '<EMAIL>', 'telephone' => '84909844', 'mobile' => '13886146473' ]); } } <file_sep><?php /* * CKFinder * ======== * http://cksource.com/ckfinder * Copyright (C) 2007-2015, CKSource - Frederico Knabben. All rights reserved. * * The software, this file and its contents are subject to the CKFinder * License. Please read the license.txt file before using, installing, copying, * modifying or distribute this file or part of its contents. The contents of * this file is part of the Source Code of CKFinder. */ namespace CKSource\CKFinder\Acl; /** * Acl interface * * @copyright 2015 CKSource - Frederico Knabben */ interface AclInterface { /** * Allows for permission in chosen folder * * @param string $resourceType resource type identifier (also * for all resource types) * @param string $folderPath folder path * @param int $permission permission numeric value * @param string $role user role name (also * for all roles) * * @return Acl $this * * @see Permission */ public function allow($resourceType, $folderPath, $permission, $role); /** * Disallows for permission in chosen folder * * @param string $resourceType resource type identifier (also * for all resource types) * @param string $folderPath folder path * @param int $permission permission numeric value * @param string $role user role name (also * for all roles) * * @return Acl $this * * @see Permission */ public function disallow($resourceType, $folderPath, $permission, $role); /** * Checks if role has required permission for a folder * * @param string $resourceType resource type identifier (also * for all resource types) * @param string $folderPath folder path * @param int $permission permission numeric value * @param string $role user role name (also * for all roles) * * @return bool true if role has required permission * * @see Permission */ public function isAllowed($resourceType, $folderPath, $permission, $role = null); /** * Computes a mask based on current user role and ACL rules * * @param string $resourceType resource type identifier (also * for all resource types) * @param string $folderPath folder path * @param string $role user role name (also * for all roles) * * @return int computed mask value * * @see MaskBuilder */ public function getComputedMask($resourceType, $folderPath, $role = null); } <file_sep><?php return [ /* |-------------------------------------------------------------------------- | Laravel CORS |-------------------------------------------------------------------------- | | allowedOrigins, allowedHeaders and allowedMethods can be set to array('*') | to accept any value. | */ 'supportsCredentials' => false, 'allowedOrigins' => ['*'],//http://localhost:8080 'allowedOriginsPatterns' => [], 'allowedHeaders' => ['*'], 'allowedMethods' => ['*'], // ex: ['GET', 'POST', 'PUT', 'DELETE'] 'exposedHeaders' => [], 'maxAge' => 0, // Response Header // //Access-Control-Allow-Origin : 指明哪些请求源被允许访问资源,值可以为 “*”,”null”,或者单个源地址。 // //Access-Control-Allow-Credentials : 指明当请求中省略 creadentials 标识时响应是否暴露。对于预请求来说,它表明实际的请求中可以包含用户凭证。 // //Access-Control-Expose-Headers : 指明哪些头信息可以安全的暴露给 CORS API 规范的 API。 // //Access-Control-Max-Age : 指明预请求可以在预请求缓存中存放多久。 // //Access-Control-Allow-Methods : 对于预请求来说,哪些请求方式可以用于实际的请求。 // //Access-Control-Allow-Headers : 对于预请求来说,指明了哪些头信息可以用于实际的请求中。 // //Origin : 指明预请求或者跨域请求的来源。 // //Access-Control-Request-Method : 对于预请求来说,指明哪些预请求中的请求方式可以被用在实际的请求中。 // //Access-Control-Request-Headers : 指明预请求中的哪些头信息可以用于实际的请求中。 // //Request Header // //Origin : 表明发送请求或预请求的来源。 // //Access-Control-Request-Method : 在发送预请求时带该请求头,表明实际的请求将使用的请求方式。 // //Access-Control-Request-Headers : 在发送预请求时带有该请求头,表明实际的请求将携带的请求头。 ]; <file_sep><?php Route::group(['middleware' => ['uv'], 'prefix' => 'tool', 'namespace' => 'Tool', 'as' => 'tool.'], function () { Route::get('spider', 'SpiderController@index')->name('spider'); Route::get('spider/{id}', 'SpiderController@show')->name('spider.show'); });<file_sep><?php namespace App\Models\Tool; use Illuminate\Database\Eloquent\Model; class UV extends Model { protected $guarded = []; protected $table = 'uvs'; } <file_sep><?php namespace App\Http\Controllers\Admin\System; use App\Models\System\Permission; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use App\Http\Requests\Admin\System as Requests; use App\Models\System\Role; class RoleController extends Controller { /** * 用户组列表 * @param Request $request * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View */ public function index(Request $request) { $where = function ($query) use ($request) { if ($request->has('keyword') and $request->keyword != '') { $search = "%" . $request->keyword . "%"; $query->where('name', 'like', $search); } }; $roles = Role::where($where)->paginate(config('admin.page_size')); return view('admin.system.role.index', compact('roles')); } /** * 新增 * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View */ public function create() { $permissions = Permission::get_permissions(); return view('admin.system.role.create', compact('permissions')); } /** * 保存 * @param Requests\RoleStore $request * @return \Illuminate\Http\RedirectResponse */ public function store(Requests\RoleStore $request) { $role = Role::create($request->all()); $role->permissions()->sync($request->permission_id); return redirect(route('system.role.index'))->with('notice', '新增成功~'); } /** * 编辑用户组 * @param $id * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View */ public function edit($id) { $role = Role::with('permissions')->find($id); $role_permissions = $role->permissions->pluck('id'); $permissions = Permission::get_permissions(); return view('admin.system.role.edit', compact('role', 'role_permissions', 'permissions')); } /** * 更新用户组 * @param Requests\RoleUpdate $request * @param $id * @return \Illuminate\Http\RedirectResponse */ public function update(Requests\RoleUpdate $request, $id) { $role = Role::find($id); $role->name = $request->name; $role->save(); $role->permissions()->sync($request->permission_id); return back()->with('notice', '修改成功~'); } /** * 删除 * @param $id * @return \Illuminate\Http\RedirectResponse */ public function destroy($id) { Role::destroy($id); return redirect(route('system.role.index'))->with('notice', '删除成功~'); } } <file_sep><?php namespace App\Http\Controllers\Admin\Cms; use App\Models\Cms\Category; use Illuminate\Http\Request; use App\Http\Controllers\Controller; class CategoryController extends Controller { public function __construct() { view()->share([ 'categories' => Category::get_categories(), ]); } /** * 栏目列表 * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View */ function index() { return view('admin.cms.category.index'); } /** * 新增 * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View */ public function create() { return view('admin.cms.category.create'); } /** * @param Request $request * @return \Illuminate\Http\RedirectResponse * @throws \Illuminate\Validation\ValidationException */ public function store(Request $request) { $this->validate($request, [ 'name' => 'required|unique:article_categories|max:255', ]); $category = $request->all(); Category::create($category); Category::clear(); return redirect(route('cms.category.index'))->with('notice', '添加栏目成功'); } /** * 编辑 * @param $id * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View */ public function edit($id) { $category = Category::find($id); return view('admin.cms.category.edit', compact('category')); } /** * @param Request $request * @param $id * @return \Illuminate\Http\RedirectResponse * @throws \Illuminate\Validation\ValidationException */ function update(Request $request, $id) { $this->validate($request, [ 'name' => 'required|max:255|unique:article_categories,name,'.$id, ]); $category = Category::find($id); $category->update($request->all()); Category::clear(); return redirect(route('cms.category.index'))->with('notice', '编辑成功~'); } /** * Ajax修改属性 * @param Request $request * @return array */ function is_something(Request $request) { $attr = $request->attr; $category = Category::find($request->id); $value = $category->$attr ? false : true; $category->$attr = $value; $category->save(); Category::clear(); } /** * Ajax排序 * @param Request $request * @return array */ function sort_order(Request $request) { $category = Category::find($request->id); $category->sort_order = $request->sort_order; $category->save(); Category::clear(); } /** * 删除 * @param $id * @return \Illuminate\Http\RedirectResponse */ function destroy($id) { if (!Category::check_children($id)) { return back()->with('alert', '当前栏目有子栏目,请先将子栏目删除后再尝试删除~'); } if (!Category::check_articles($id)) { return back()->with('alert', '当前栏目有文章,请先将对应文章删除后再尝试删除~'); } Category::destroy($id); Category::clear(); return back()->with('notice', '删除成功'); } } <file_sep><?php namespace CKSource\CKFinder\Command; use CKSource\CKFinder\Acl\Permission; use CKSource\CKFinder\Filesystem\Folder\WorkingFolder; use CKSource\CKFinder\Utils; class GetFiles extends CommandAbstract { protected $requires = array(Permission::FILE_VIEW); public function execute(WorkingFolder $workingFolder) { $data = new \stdClass(); $files = $workingFolder->listFiles(); $data->files = array(); foreach ($files as $file) { $size = $file['size']; $size = ($size && $size < 1024) ? 1 : (int) round($size / 1024); $fileObject = array( 'name' => $file['basename'], 'date' => Utils::formatDate($file['timestamp']), 'size' => $size ); $data->files[] = $fileObject; } // Sort files usort($data->files, function($a, $b) { return strnatcasecmp($a['name'], $b['name']); }); return $data; } } <file_sep><?php /* * CKFinder * ======== * http://cksource.com/ckfinder * Copyright (C) 2007-2015, CKSource - <NAME>. All rights reserved. * * The software, this file and its contents are subject to the CKFinder * License. Please read the license.txt file before using, installing, copying, * modifying or distribute this file or part of its contents. The contents of * this file is part of the Source Code of CKFinder. */ namespace CKSource\CKFinder\Filesystem\File; use CKSource\CKFinder\CKFinder; use CKSource\CKFinder\Exception\AlreadyExistsException; use CKSource\CKFinder\Exception\FileNotFoundException; use CKSource\CKFinder\Exception\InvalidNameException; use CKSource\CKFinder\Exception\InvalidRequestException; use CKSource\CKFinder\Filesystem\Folder\WorkingFolder; use CKSource\CKFinder\Filesystem\Path; /** * Class EditedFile * * Represents an existing file being edited, i.e. content * of the file is going to be replaced with new content. */ class EditedFile extends ExistingFile { /** * @var WorkingFolder */ protected $workingFolder; /** * @var string */ protected $newFileName; protected $saveAsNew = false; public function __construct($fileName, CKFinder $app, $newFileName = null) { $this->workingFolder = $app['working_folder']; $this->newFileName = $newFileName; parent::__construct($fileName, $this->workingFolder->getClientCurrentFolder(), $this->workingFolder->getResourceType(), $app); } public function isValid() { if (!$this->saveAsNew && !$this->exists()) { throw new FileNotFoundException(); } if ($this->newFileName) { if (!File::isValidName($this->newFileName, $this->config->get('disallowUnsafeCharacters'))) { throw new InvalidNameException('Invalid file name'); } if ($this->workingFolder->containsFile($this->newFileName)) { throw new AlreadyExistsException('File already exists'); } if ($this->resourceType->getBackend()->isHiddenFile($this->newFileName)) { throw new InvalidRequestException('New provided file name is hidden'); } } if (!$this->hasValidFilename() || !$this->hasValidPath()) { throw new InvalidRequestException('Invalid filename or path'); } if ($this->isHidden() || $this->hasHiddenPath()) { throw new InvalidRequestException('Edited file is hidden'); } return true; } public function getNewFilename() { return $this->newFileName; } public function saveAsNew($saveAsNew) { $this->saveAsNew = $saveAsNew; } public function setContents($contents, $filePath = null) { return parent::setContents($contents, $this->newFileName ? Path::combine($this->getPath(), $this->newFileName) : null); } } <file_sep><?php namespace App\Http\Controllers\Admin\Tool; use App\Models\Tool\Help; use Illuminate\Http\Request; use App\Http\Controllers\Controller; class HelpController extends Controller { /** * @param Request $request * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View */ public function index(Request $request) { $where = function ($query) use ($request) { if ($request->has('keyword') and $request->keyword != '') { $search = "%" . $request->keyword . "%"; $query->where('title', 'like', $search); } }; $helps = Help::where($where)->paginate(config('admin.page_size')); //分页处理 $page = isset($page) ? $request['page'] : 1; $helps = $helps->appends(array( 'title' => $request->keyword, 'page' => $page )); return view('admin.tool.help.index', compact('helps')); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { return view('admin.tool.help.create'); } /** * @param Request $request * @return \Illuminate\Http\RedirectResponse * @throws \Illuminate\Validation\ValidationException */ public function store(Request $request) { $messages = [ 'title.unique' => '标题不能重复!' ]; if (!empty($request->title)){ $this->validate($request, [ 'title' => 'unique:tool_help,title', ],$messages); } $helps = $request->all(); Help::create($helps); return redirect(route('tool.help.index'))->with('notice', '新增成功~'); } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { // } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { $help = Help::find($id); return view('admin.tool.help.edit', compact('help')); } /** * @param Request $request * @param Help $help * @return \Illuminate\Http\RedirectResponse * @throws \Illuminate\Validation\ValidationException */ public function update(Request $request, Help $help) { $messages = [ 'title.unique' => '标题不能重复!', ]; if (!empty($request->title)){ $this->validate($request, [ 'title' => 'unique:tool_help,title,'.$help->id, ],$messages); } $help->update($request->all()); return redirect(route('tool.help.index'))->with('notice', '编辑成功~'); } /** * @param Help $help * @return \Illuminate\Http\RedirectResponse * @throws \Exception */ public function destroy(Help $help) { $help->delete(); return back()->with('notice', '删数成功~'); } } <file_sep><?php use Illuminate\Database\Seeder; use App\Models\System\Role; use App\Models\System\Permission; class RolesTableSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { $adminRole = Role::create([ 'name' => '超级管理员', 'slug' => 'admin', 'description' => '超级管理员', ]); $userRole = Role::create([ 'name' => '普通用户', 'slug' => 'user', 'description' => '普通用户', ]); /*管理员初始化所有权限*/ $all_permissions = Permission::all(); $role_permissions = $all_permissions->pluck('id'); $adminRole->permissions()->sync($role_permissions); /*普通用户赋予一般权限*/ $dashBackendPer = Permission::where('name', 'admin')->first(); $userRole->permissions()->sync($dashBackendPer->id); } } <file_sep><?php namespace App\Http\Controllers\Admin\System; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use Illuminate\Pagination\LengthAwarePaginator; use Illuminate\Pagination\Paginator; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Storage; class PhotoController extends Controller { private $path; public function __construct(Request $request) { $this->path = isset($request->path) ? $request->path : getcwd(); } /** * @param Request $request * @return $this|\Illuminate\Contracts\View\Factory|LengthAwarePaginator|\Illuminate\View\View */ public function index(Request $request) { //多条件查找 // $where = function ($query) use ($request) { // if ($request->has('name') and $request->name != '') { // $search = "%" . $request->name . "%"; // $query->where('name', 'like', $search); // } // // if ($request->has('file_type') and $request->file_type != -1) { // $search = "%" . $request->file_type . "%"; // $query->where('file_type', 'like', $search); // } // if ($request->has('created_at') and $request->created_at != '') { // $time = explode(" ~ ", $request->input('created_at')); // foreach ($time as $k => $v) { // $time["$k"] = $k == 0 ? $v . " 00:00:00" : $v . " 23:59:59"; // } // $query->whereBetween('created_at', $time); // } // }; $path = $this->path; //手动分页 $file_list = dir_info($path);//打算输出的数组,二维 foreach ($file_list as $k => $file) { if ($request->has('file_type') and $request->file_type != -1 and $request->file_type != $file['file_type']) { unset($file_list[$k]); } if ($request->has('name') and $request->name != '' and $request->name != $file['name']) { unset($file_list[$k]); } if ($request->has('created_at') and $request->created_at != '') { $time = explode(" ~ ", $request->input('created_at')); foreach ($time as $k => $v) { $time["$k"] = $k == 0 ? $v . " 00:00:00" : $v . " 23:59:59"; } if ($file['filemtime'] <= strtotime($time[0]) or $file['filemtime'] >= strtotime($time[1])) { unset($file_list[$k]); } } } $file_type = array(); foreach ($file_list as $file) { if (!$file['file_type']) { continue; } $file_type[] = $file['file_type']; } $file_type = array_unique($file_type); $perPage = config('admin.page_size'); //分页处理 $page = isset($request->page) ? $request->page : 1; //计算每页分页的初始位置 $offset = ($page * $perPage) - $perPage; $item = array_slice($file_list, $offset, $perPage, true); // array_slice(array,start,length) 从start位置,去获取length参数。结果返回一条数据 $total = count($file_list); $files = new LengthAwarePaginator($item, $total, $perPage, $page, [ 'path' => Paginator::resolveCurrentPath(), //就是设定个要分页的url地址。也可以手动通过 $paginator ->setPath(‘路径’) 设置 'query' => $request->query(), 'pageName' => 'page' ]); return view("admin.system.file", compact('files', 'path', 'file_type')); } /** * @param Request $request * @return bool|string */ function get_contents($name) { $contents = file_get_contents($this->path . '/' . $name); return view("admin.system.file_edit", compact('contents','name')); } function upload_public(Request $request) { $extension = $request->file('file')->getClientOriginalExtension(); $dir = Auth::user()->name . '_' . Auth::user()->id; Storage:: disk('my_file')->putFileAs($dir, $request->file('file'), time().'.'.$extension); } public function destroy_file($name) { $dir = Auth::user()->name . '_' . Auth::user()->id; if ($dir==$name){ Storage::disk('my_file')->deleteDirectory($name); }else{ Storage::disk('my_file')->delete($name); } return redirect(route('system.photo.index'))->with('notice', '删除成功~'); } public function update_file(Request $request) { rename($this->path . '/' . $request->old_name, $this->path . '/' . $request->name); file_put_contents($this->path . '/' . $request->name, $request->contents); return redirect(route('system.photo.index'))->with('notice', '修改成功~'); } /** * 文件上传类 * @param Request $request * @return array */ public function upload(Request $request) { if ($request->hasFile('file') and $request->file('file')->isValid()) { //文件大小判断$filePath $max_size = 1024 * 1024 * 3; $size = $request->file('file')->getClientSize(); if ($size > $max_size) { return ['status' => 0, 'msg' => '文件大小不能超过3M']; } $extension = $request->file('file')->getClientOriginalExtension(); // $dir = Auth::user()->name . '_' . time(); //original $path=$request->file->store('images','my_file'); return ['status' => 1, 'image' => '/'.$path, 'image_url' => '/'.$path]; } } /** * 文件上传类 * @param Request $request * @return array */ public function upload_img(Request $request) { if ($request->hasFile('file') and $request->file('file')->isValid()) { //数据验证 $allow = array('image/jpeg', 'image/png', 'image/gif'); $mine = $request->file('file')->getMimeType(); if (!in_array($mine, $allow)) { return ['status' => 0, 'msg' => '文件类型错误,只能上传图片']; } //文件大小判断$filePath $max_size = 1024 * 1024 * 3; $size = $request->file('file')->getClientSize(); if ($size > $max_size) { return ['status' => 0, 'msg' => '文件大小不能超过3M']; } //original图片 $path = $request->file->store('images'); //绝对路径 $file_path = storage_path('app/') . $path; $url = '/storage/' . $path; //保存到七牛 //qiniu_upload($file_path); //返回文件名 // $image = basename($path); // return ['status' => 1, 'image' => $image, 'image_url' => env('QINIU_IMAGES_LINK') . $image]; return ['status' => 1, 'image' => $url, 'image_url' => $url]; } } /** * 上传网站ico图标 * @param Request $request * @return array */ public function upload_icon(Request $request) { if ($request->hasFile('file') and $request->file('file')->isValid()) { //取得之前文件的扩展名 $extension = $request->file('file')->getClientOriginalExtension(); if ($extension != 'ico') { return ['status' => 0, 'msg' => '文件类型错误,只能上传ico格式的图片']; } //文件大小判断 $max_size = 1024 * 1024; $size = $request->file('file')->getClientSize(); if ($size > $max_size) { return ['status' => 0, 'msg' => '文件大小不能超过1M']; } //上传文件夹,如果不存在,建立文件夹 $path = getcwd(); $file_name = "favicon.ico"; $request->file('file')->move($path, $file_name); } } /** * 上传背景图 * @param Request $request * @return array */ public function upload_background_img(Request $request) { if ($request->hasFile('file') and $request->file('file')->isValid()) { $allow = array('image/jpeg', 'image/png', 'image/gif'); $mine = $request->file('file')->getMimeType(); if (!in_array($mine, $allow)) { return ['status' => 0, 'msg' => '文件类型错误,只能上传图片']; } //文件大小判断$filePath $max_size = 1024 * 1024 * 3; $size = $request->file('file')->getClientSize(); if ($size > $max_size) { return ['status' => 0, 'msg' => '文件大小不能超过3M']; } //上传文件夹,如果不存在,建立文件夹 $path = getcwd() . '/vendor/particles'; $file_name = "timg.jpg"; $request->file('file')->move($path, $file_name); } } } <file_sep><?php /* * This file is part of the Monolog package. * * (c) <NAME> <<EMAIL>> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Monolog\Handler; use Monolog\Logger; /** * Used for testing purposes. * * It records all records and gives you access to them for verification. * * @author <NAME> <<EMAIL>> * * @method boolean hasEmergency($record) * @method boolean hasAlert($record) * @method boolean hasCritical($record) * @method boolean hasError($record) * @method boolean hasWarning($record) * @method boolean hasNotice($record) * @method boolean hasInfo($record) * @method boolean hasDebug($record) * * @method boolean hasEmergencyRecords() * @method boolean hasAlertRecords() * @method boolean hasCriticalRecords() * @method boolean hasErrorRecords() * @method boolean hasWarningRecords() * @method boolean hasNoticeRecords() * @method boolean hasInfoRecords() * @method boolean hasDebugRecords() * * @method boolean hasEmergencyThatContains($message) * @method boolean hasAlertThatContains($message) * @method boolean hasCriticalThatContains($message) * @method boolean hasErrorThatContains($message) * @method boolean hasWarningThatContains($message) * @method boolean hasNoticeThatContains($message) * @method boolean hasInfoThatContains($message) * @method boolean hasDebugThatContains($message) * * @method boolean hasEmergencyThatMatches($message) * @method boolean hasAlertThatMatches($message) * @method boolean hasCriticalThatMatches($message) * @method boolean hasErrorThatMatches($message) * @method boolean hasWarningThatMatches($message) * @method boolean hasNoticeThatMatches($message) * @method boolean hasInfoThatMatches($message) * @method boolean hasDebugThatMatches($message) * * @method boolean hasEmergencyThatPasses($message) * @method boolean hasAlertThatPasses($message) * @method boolean hasCriticalThatPasses($message) * @method boolean hasErrorThatPasses($message) * @method boolean hasWarningThatPasses($message) * @method boolean hasNoticeThatPasses($message) * @method boolean hasInfoThatPasses($message) * @method boolean hasDebugThatPasses($message) */ class TestHandler extends AbstractProcessingHandler { protected $records = array(); protected $recordsByLevel = array(); public function getRecords() { return $this->records; } protected function hasRecordRecords($level) { return isset($this->recordsByLevel[$level]); } protected function hasRecord($record, $level) { if (is_array($record)) { $record = $record['message']; } return $this->hasRecordThatPasses(function($rec) use ($record) { return $rec['message'] === $record; }, $level); } public function hasRecordThatContains($message, $level) { return $this->hasRecordThatPasses(function($rec) use ($message) { return strpos($rec['message'], $message) !== false; }, $level); } public function hasRecordThatMatches($regex, $level) { return $this->hasRecordThatPasses(function($rec) use ($regex) { return preg_match($regex, $rec['message']) > 0; }, $level); } public function hasRecordThatPasses($predicate, $level) { if (!is_callable($predicate)) { throw new \InvalidArgumentException("Expected a callable for hasRecordThatSucceeds"); } if (!isset($this->recordsByLevel[$level])) { return false; } foreach ($this->recordsByLevel[$level] as $i => $rec) { if (call_user_func($predicate, $rec, $i)) { return true; } } return false; } /** * {@inheritdoc} */ protected function write(array $record) { $this->recordsByLevel[$record['level']][] = $record; $this->records[] = $record; } public function __call($method, $args) { if (preg_match('/(.*)(Debug|Info|Notice|Warning|Error|Critical|Alert|Emergency)(.*)/', $method, $matches) > 0) { $genericMethod = $matches[1] . 'Record' . $matches[3]; $level = constant('Monolog\Logger::' . strtoupper($matches[2])); if (method_exists($this, $genericMethod)) { $args[] = $level; return call_user_func_array(array($this, $genericMethod), $args); } } throw new \BadMethodCallException('Call to undefined method ' . get_class($this) . '::' . $method . '()'); } } <file_sep><?php namespace App\Http\Middleware; use Closure; use App\Models\System\Permission; use Auth, Gate, Route; class Sidebar { /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { view()->share([ 'systems' => config('admin.systems'), ]); $this->menus(); $this->bibel(); $this->active_menu(); return $next($request); } /** * 自动选择菜单 */ private function active_menu() { $name = Route::currentRouteName(); $parent_menu = $children_menu = ''; //如果不是后台首页, 首页直接为 '' if ($name != 'admin') { $permission = Permission::with('parent')->where('name', $name)->first(); //判断当前是二级还是三级 if ($permission->parent->parent_id == 0) { $parent_menu = $permission->parent->name; $children_menu = $permission->name; } else { $parent_menu = $permission->parent->parent->name; $children_menu = $permission->parent->name; } } view()->share(compact('parent_menu', 'children_menu')); } /** * 所有菜单 */ private function menus() { $permissions = Permission::get_children(); //如果是超级管理员,则拥有所有菜单。否则自动获取该用户拥有权限的菜单。 $menus = Auth::user()->hasRole('超级管理员') ? $permissions : $this->get_menus($permissions); view()->share('menus', $menus); } /** * 获取有权限访问的菜单 * @param $permissions * @return mixed */ private function get_menus($permissions) { foreach ($permissions as $key => $permission) { if (Gate::denies($permission->name)) { unset($permissions[$key]); continue; } foreach ($permission->children as $k => $children) { if (Gate::denies($children->name)) { unset($permissions[$key]['children'][$k]); } } } return $permissions; } //思考, 源自Holy Bible private function bibel() { @$bibels = file('bibel.txt'); $size = count($bibels) / 2 - 1; $rand = rand(0, $size) * 2; $bibel = array( 'cn' => $bibels[$rand + 1], 'en' => $bibels[$rand] ); view()->share('bibel', $bibel); } } <file_sep><?php namespace App\Http\Controllers\Admin\Tool; use App\Models\Tool\Spider; use Illuminate\Http\Request; use App\Http\Controllers\Controller; class SpiderController extends Controller { /** * Display a listing of the resource. * * @param Request $request * @return \Illuminate\Http\Response */ public function index(Request $request) { $where = function ($query) use ($request) { if ($request->has('keyword') and $request->keyword != '') { $search = "%" . $request->keyword . "%"; $query->where('title', 'like', $search); } }; $spiders = Spider::where($where)->paginate(config('admin.page_size')); //分页处理 $page = isset($page) ? $request['page'] : 1; $spiders = $spiders->appends(array( 'title' => $request->keyword, 'page' => $page )); return view('admin.tool.spider.index', compact('spiders')); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { return view('admin.tool.spider.create'); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { $messages = [ 'title.unique' => '广告名称不能重复!', 'image.required' => '图片不能为空!' ]; if (!empty($request->title)){ $this->validate($request, [ 'title' => 'unique:spiders,title', 'image' => 'required' ],$messages); } $spiders = $request->all(); Spider::create($spiders); return redirect(route('tool.spider.index'))->with('notice', '新增成功~'); } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { // } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { $spider = Spider::find($id); return view('admin.tool.spider.edit', compact('spider')); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param Spider $spider * @return \Illuminate\Http\Response */ public function update(Request $request, Spider $spider) { $messages = [ 'title.unique' => '广告名称不能重复!', 'image.required' => '图片不能为空!' ]; if (!empty($request->title)){ $this->validate($request, [ 'title' => 'unique:spiders,title,'.$spider->id, 'image' => 'required' ],$messages); } $spider->update($request->all()); return redirect(route('tool.spider.index'))->with('notice', '编辑成功~'); } /** * Remove the specified resource from storage. * * @param Spider $spider * @return \Illuminate\Http\Response */ public function destroy(Spider $spider) { $spider->delete(); return back()->with('notice', '被删数据已进入回收站~'); } /** * 永久删除 * @param $id * @return \Illuminate\Http\RedirectResponse */ public function force_destroy($id) { Spider::withTrashed()->where('id', $id)->forceDelete(); return back()->with('notice', '删除成功'); } /** * 多选删除到回收站 * @param Request $request * @return array */ function destroy_checked(Request $request) { $checked_id = $request->input("checked_id"); Spider::destroy($checked_id); } /** * 多选永久删除 * @param Request $request * @return array */ function force_destroy_checked(Request $request) { $checked_id = $request->input("checked_id"); Spider::withTrashed()->whereIn('id', $checked_id)->forceDelete(); } /** * 还原 * @param $id * @return \Illuminate\Http\RedirectResponse */ public function restore($id) { Spider::withTrashed()->where('id', $id)->restore(); return back()->with('notice', '还原成功'); } /** * 多选还原 * @param Request $request * @return array */ public function restore_checked(Request $request) { $checked_id = $request->input("checked_id"); Spider::withTrashed()->whereIn('id', $checked_id)->restore(); } /** * 回收站 * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View */ public function trash(Request $request) { $spiders = Spider::select()->onlyTrashed()->paginate(config('admin.page_size')); //分页处理 $page = isset($page) ? $request['page'] : 1; $spiders = $spiders->appends(array( 'title' => $request->keyword, 'page' => $page )); return view('admin.tool.spider.trash', compact('spiders')); } /** * Ajax修改属性 * @param Request $request * @return array */ function is_something(Request $request) { $attr = $request->attr; $spider = Spider::find($request->id); $value = $spider->$attr ? false : true; if ($request->id == 1) { $value = true; } $spider->$attr = $value; $spider->save(); } } <file_sep><?php namespace App\Http\Middleware; use Closure; use Illuminate\Support\Facades\Redis; class UV { public $return_array = [];// 返回带有MAC地址的字串数组 public $mac_addr; /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ // public function handle($request, Closure $next) // { // return $next($request); // } public function handle($request, Closure $next, $guard = null) { if (config('admin.statistics') == true) { // 此处可以不定义配置开关。 // 清空Redis数据库 // Redis::flushall(); //查询所有WebStatistics缓存记录数据 $count = Redis::LLEN('WebStatistics'); $redisList = Redis::lrange('WebStatistics', 0, $count); $redisLine = [ 'ip' => $this->getIp(), 'brow' => $this->browseInfo(), 'mac' => $this->GetMacAddr(config('admin.os_type')), 'created_at' => time(), ]; Redis::lpush('WebStatistics', json_encode($redisLine, JSON_UNESCAPED_UNICODE)); return $next($request); } else { return $next($request); } } /** * 访问者IP * @return string */ private function getIp() { if (!empty($_SERVER["HTTP_CLIENT_IP"])) { $cip = $_SERVER["HTTP_CLIENT_IP"]; } else if (!empty($_SERVER["HTTP_X_FORWARDED_FOR"])) { $cip = $_SERVER["HTTP_X_FORWARDED_FOR"]; } else if (!empty($_SERVER["REMOTE_ADDR"])) { $cip = $_SERVER["REMOTE_ADDR"]; } else { $cip = ''; } preg_match("/[\d\.]{7,15}/", $cip, $cips); $cip = isset($cips[0]) ? $cips[0] : 'unknown'; unset($cips); return $cip; } /** * 访问者浏览器 * @return string */ private function browseInfo() { if (!empty($_SERVER['HTTP_USER_AGENT'])) { $br = $_SERVER['HTTP_USER_AGENT']; if (preg_match('/MSIE/i', $br)) { $br = 'MSIE'; } else if (preg_match('/Firefox/i', $br)) { $br = 'Firefox'; } else if (preg_match('/Chrome/i', $br)) { $br = 'Chrome'; } else if (preg_match('/Safari/i', $br)) { $br = 'Safari'; } else if (preg_match('/Opera/i', $br)) { $br = 'Opera'; } else { $br = 'Other'; } return $br; } else { return 'unknow'; } } /** * MAC地址 * @param $os_type * @return mixed */ private function GetMacAddr($os_type) { switch (strtolower($os_type)) { case "linux": self::forLinux(); break; case "solaris": break; case "unix": break; case "aix": break; default: self::forWindows(); break; } $temp_array = array(); foreach ($this->return_array as $value) { if ( preg_match("/[0-9a-f][0-9a-f][:-]" . "[0-9a-f][0-9a-f][:-]" . "[0-9a-f][0-9a-f][:-]" . "[0-9a-f][0-9a-f][:-]" . "[0-9a-f][0-9a-f][:-]" . "[0-9a-f][0-9a-f]/i", $value, $temp_array)) { $this->mac_addr = $temp_array[0]; break; } } unset($temp_array); return $this->mac_addr; } function forWindows() { @exec("ipconfig /all", $this->return_array); if ($this->return_array) return $this->return_array; else { $ipconfig = $_SERVER["WINDIR"] . "\system32\ipconfig.exe"; if (is_file($ipconfig)) @exec($ipconfig . " /all", $this->return_array); else @exec($_SERVER["WINDIR"] . "\system\ipconfig.exe /all", $this->return_array); return $this->return_array; } } function forLinux() { @exec("ifconfig -a", $this->return_array); return $this->return_array; } } <file_sep><?php namespace App\Http\Controllers\Admin; use App\Models\System\User; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use Auth, DB; use App\Http\Requests\Admin\System as Requests; class HomeController extends Controller { /** * 系统后台首页 * @param Request $request * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View */ public function index(Request $request) { $id = Auth::user()->id; $user = User::with('roles')->find($id); $user_roles = $user->roles->pluck('name'); return view('admin.index', compact('user', 'user_roles')); } public function update(Requests\ChildUpdate $request, $id) { $user = User::find($id); $user->password = <PASSWORD>($request->password); $user->name = $request->name; $user->phone = $request->phone; $user->save(); return back()->with('notice', '编辑信息成功~'); } public function link() { $host = 'http://suo.im'; $path = '/api.php'; $data = "?format=json&url=" . urlencode(route('customer.register', ['user_id' => auth()->id()])) . '&key=5cdbccf78e676d624f77a0cd@1fa1ba52d936a626405b288b3a81d32c'; $url = $host . $path . $data; // var_dump($url); $curl = curl_init(); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_TIMEOUT, 500); curl_setopt($curl, CURLOPT_URL, $url); $res = curl_exec($curl); curl_close($curl); //读取响应 return json_decode($res, true); } } <file_sep><?php namespace App\Http\Controllers\Api\Customer; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\Validator; class ResetPasswordController extends Controller { public function __construct() { // $this->middleware('auth:api'); } public function reset(Request $request) { $customer = auth('api')->user(); $messages = [ 'password.min' => '密码最少为6位!' ]; $rules = [ 'password' => 'confirmed|max:255|min:6' ]; $validator = Validator::make($request->all(), $rules, $messages); if ($validator->fails()) { $error = $validator->errors()->first(); return error_data($error); } if ($request->has('password') && $request->password != '') { if (!\Hash::check($request->old_password, $customer->password)) { return error_data('原始密码错误~'); } $customer->password = <PASSWORD>($request->password); } $customer->save(); return success_data('修改成功', $customer); } } <file_sep><?php Route::group(['prefix' => 'tool', 'namespace' => 'Tool', 'as' => 'tool.'], function () { Route::group(['prefix' => 'spider'], function () { Route::delete('destroy_checked', 'SpiderController@destroy_checked')->name('spider.destroy_checked'); Route::patch('is_something', 'SpiderController@is_something')->name('spider.is_something'); //回收站 Route::get('trash', 'SpiderController@trash')->name('spider.trash'); Route::get('{spider}/restore', 'SpiderController@restore')->name('spider.restore'); Route::delete('{spider}/force_destroy', 'SpiderController@force_destroy')->name('spider.force_destroy'); Route::delete('force_destroy_checked', 'SpiderController@force_destroy_checked')->name('spider.force_destroy_checked'); Route::post('restore_checked', 'SpiderController@restore_checked')->name('spider.restore_checked'); }); Route::resource('spider', 'SpiderController'); //公告 Route::resource('notice', 'NoticeController'); //帮助中心 Route::resource('help', 'HelpController'); //轮播图 Route::group(['prefix' => 'slide'], function () { Route::patch('sort_order', 'SlideController@sort_order')->name('slide.sort_order'); Route::patch('is_something', 'SlideController@is_something')->name('slide.is_something'); }); Route::resource('slide', 'SlideController'); //关于我们 Route::group(['prefix' => 'about'], function () { Route::get('/', 'AboutController@edit')->name('about.edit'); Route::put('/', 'AboutController@update')->name('about.update'); }); });<file_sep>//文件上传 var opts = { url: "/system/photo/upload", type: "POST", beforeSend: function () { $("#loading").attr("class", "am-icon-spinner am-icon-pulse"); }, success: function (result, status, xhr) { if (result.status == "0") { alert(result.msg); $("#loading").attr("class", "am-icon-cloud-upload"); return false; } console.log(result); $("input[name='image']").val(result.image); $("#img_show").attr('src', result.image_url); $("#loading").attr("class", "am-icon-cloud-upload"); }, error: function (result, status, errorThrown) { alert('文件上传失败'); } } $('#image_upload').fileUpload(opts);
b5c2c12abfbad86289491c7cd8f4b69f011976a7
[ "JavaScript", "Markdown", "Text", "PHP" ]
80
PHP
pengyaxiong/gather
133a1006dfccc2e4be933d274fc5e69c78a282b7
d24c8971d64393caa46820f67823ba120fe2f475
refs/heads/master
<file_sep> <?php header("Content-Type: text/html;charset=utf-8"); ?> <meta http-equiv="Content-Type" content="text/html;charset=utf=8"/> <?php if (!empty($POST['data'])) { echo 'stroka iz forma1:' . $POST['data']; }elseif (!empty($POST['data'])) { echo 'stroka iz forma2:' . $GET['data']; } <file_sep><?php header("Content-Type: text/html;charset=utf-8"); ?> <meta http-equiv="Content-Type" content="text/html;charset=utf=8"/> <?php //основные операторы// //оператор присваивания// $firstName = "имя"; $lastName = "фамилия"; $fullName = $firstName . $lastName;// оператор конкатенации// //$fullName = $firstName . " - " . $lastName;//изменили вывод.Почему вывелось один раз// echo $fullName ; //условные операторы// //if состоит из условия и одного или нескольких операторов,сгруппированных в виде блока.///* echo '<br>=================================================</br>'; $a = 7; $b = 6; if ($a == $b) { echo 'А равно В'; } else { echo "А не равно В "; } echo '<br>=================================================</br>'; //оператор elseif// $c = 10; $d = 5; if($a==$b) { echo 'А равно В'; }elseif ($a==$c) { echo 'А равно С'; }elseif ($a==$d) { echo 'А равно D'; } else { echo 'А ничему не равно'; } echo '<br>=================================================</br>'; switch ($a) { case $b: echo 'А равно В'; break; case $c: echo 'А равно С'; break; case $d: echo 'А равно D'; break; default: echo 'А ничему не равно'; break; } echo '<br>=================================================</br>'; //циклы// for ($i = 1; $i < 101; $i = $i + 1) { echo $i . '<br>'; } echo '<br>=================================================</br>'; $i = 1; while ($i < 101) { echo $i . '<br>'; $i = $i + 1; } //foreach// echo '<br>=================================================</br>'; $myArray = array('ПРивет','Мир','родился','новый','программист'); foreach ($myArray as $value) { echo $value . '<br>'; }<file_sep><?php header("Content-Type: text/html;charset=utf-8"); ?> <meta http-equiv="Content-Type" content="text/html;charset=utf=8"/> <html> <body> <form method="post" action="collect.php"> <h1>forma1</h1> <imput name="data" placeholder="vvod" type="text"/> <button type="submit">otpravit</button> </form> <form method="get" action="collect.php"> <h2>forma2</h2> <imput name="data" placeholder="vvod" type="text"/> <button type="submit">otpravit</button> </form> </html>
9fd2f4177683f10336f7eb33979636b478ad8d5f
[ "PHP" ]
3
PHP
LarissaTihh/myTests
87798304cfdd46943dacef000ca29d8d6ddba11e
ec29cfa8ac77901995c45869d0aca03ecdbd1ece
refs/heads/master
<file_sep>package com.cg.AngularJs.repo; import org.springframework.data.repository.CrudRepository; import com.cg.AngularJs.bean.Employee; public interface EmployeeRepository extends CrudRepository<Employee,Integer>{ }
2de9bee552d0becd89950414ce49be14a59221c2
[ "Java" ]
1
Java
Dhavasree/StatusReportMVC
bb498048de6a388dca841d915f1b9dcbb327e14c
511b2af88d60c92472271a42c6b7ab81a24190ec
refs/heads/master
<repo_name>pcobrien/DoubleShadows<file_sep>/convert.py import sys from glob import glob import matplotlib.pyplot as plt import numpy as np min_lat = np.deg2rad(89.0) resolution = 5.0 R = 1737.4e3 area_deg = 90.0 - np.rad2deg(min_lat) radius_pix = round(np.pi * R * area_deg / 180.0 / resolution) files = glob("../DPSR/MapsNew/DPSR/*{}M*deg.npy".format(int(resolution))) for f in files: arr = np.load(f) arr = np.unpackbits(arr, axis=None) arr = arr.reshape((round(np.sqrt(arr.shape[0])), round(np.sqrt(arr.shape[0])))).astype(bool) print(arr.shape) grid_size = arr.shape[0] min_ind = round(grid_size / 2 - radius_pix) max_ind = round(grid_size / 2 + radius_pix) arr = arr[min_ind:max_ind, min_ind:max_ind] arr = np.array(arr, dtype=bool) print(arr.shape) filename = "./Maps/" + f[16:-11] np.save(filename, np.packbits(arr, axis=None))
bd44a2dec4aa488f2e6a0025bf8fafc397a5f18e
[ "Python" ]
1
Python
pcobrien/DoubleShadows
3dfb7708d1926158de0e00bb50f07b92c380c086
b275ed02fb15d3b0fff389e2ef563bb67bd0e917
refs/heads/main
<repo_name>samanthaglasson/Amazon_Product_Reviews<file_sep>/app.py from flask import Flask, request, jsonify import pickle app = Flask(__name__) model = pickle.load(open("rus_svc_ngram.sav", "rb")) @app.route("/sentiment", methods = ["post"]) def sentiment(): review = [request.json["review"]] predictions = model.predict(review) return jsonify({"pred": predictions[0]}) if (__name__ == "__main__"): app.run(debug = True)
95063af3860cfd5c123b2c9dc727d9073d83a77a
[ "Python" ]
1
Python
samanthaglasson/Amazon_Product_Reviews
6f2088beb0e5feb9daacef94ccccbfcbb12125d1
6304840775f18765fd99662493473267d8fe0014
refs/heads/master
<repo_name>Void-TK-57/Helth<file_sep>/main.py import numpy as np import pandas as pd from matplotlib import pyplot as plt from matplotlib.ticker import FuncFormatter import seaborn as sns; sns.set() def main(path): # read csv data = pd.read_csv(path) # get values y_values = data["Peso"].values x_values = data["Data"].values print(data) fig, axes = plt.subplots(2, 1) # set title and labels axes[0].set_ylabel("Peso") # function to format labels fmt = lambda x, pos: "{}kg".format( round(x, 1) ) # ticks #axes[0].yaxis.set_major_formatter(FuncFormatter(fmt)) # set y label axes[0].set_ylim(min(y_values)*0.99, max(y_values)*1.01) # plot values axes[0].plot(x_values, y_values) # set title and labels axes[1].set_xlabel("Dias") axes[1].set_ylabel("Variação") # function to format labels fmt = lambda x, pos: "{}kg".format( x ) axes[1].plot(x_values[1:], y_values[1:] - y_values[:-1], linestyle="dashed", color='green') axes[1].plot( [np.min(x_values[1:]), np.max(x_values[2:])], [0, 0], color='red') # show plot plt.show() if __name__ == "__main__": main("weigths.csv")<file_sep>/README.md # Helth Helth Analisys
6aa9b2f78cc6e790623278324f1197aa037bd984
[ "Markdown", "Python" ]
2
Python
Void-TK-57/Helth
a3a6aa05c98b06fb7d2c24fd5b6c419e62d39ffd
b3215a3093ee7a62ef9cfc4d5891a4bcc667c733
refs/heads/master
<repo_name>charlatteD/RecordOrders<file_sep>/README.md # Record Orders This repository develops a system that records purchase orders using R shiny app and save them in google sheet. <file_sep>/ShinyApp.R require(shiny) require(tidyr) require(dplyr) #> Loading required package: shiny library(tidyverse) #> ── Attaching packages ────────────────────────────────────────────────────────── tidyverse 1.2.1 ── #> ✔ ggplot2 2.2.1.9000 ✔ purrr 0.2.4 #> ✔ tibble 1.4.1 ✔ dplyr 0.7.4 #> ✔ tidyr 0.7.2 ✔ stringr 1.2.0 #> ✔ readr 1.1.1 ✔ forcats 0.2.0 #> ── Conflicts ───────────────────────────────────────────────────────────── tidyverse_conflicts() ── #> ✖ dplyr::filter() masks stats::filter() #> ✖ dplyr::lag() masks stats::lag() library(rdrop2) #Define output directory outputDir <- "output" #Define all variables to be collected fieldsAll <- c("Restaurant", "Pho", "Steam_Smallcut", "Steam_Bigcut", "Steam_Nocut","Pancit", "EggNoodle_Smallcut", "EggNoodle_Bigcut") #Define all mandatory variables fieldsMandatory <- c("Restaurant") #Label mandatory fields labelMandatory <- function(label) { tagList(label, span("*", class = "mandatory_star")) } #Get current Epoch time epochTime <- function() { return(as.integer(Sys.time())) } #Get a formatted string of the timestamp humanTime <- function() { format(Sys.time(), "%Y%m%d-%H%M%OS") } #CSS to use in the app appCSS <- ".mandatory_star { color: red; } .shiny-input-container { margin-top: 25px; } #thankyou_msg { margin-left: 15px; } #error { color: red; } body { background: #fcfcfc; } #header { background: #fff; border-bottom: 1px solid #ddd; margin: -20px -15px 0; padding: 15px 15px 10px; } " #UI ui <- shinyUI( fluidPage( shinyjs::useShinyjs(), shinyjs::inlineCSS(appCSS), headerPanel( 'Purchase order' ), sidebarPanel( id = "form", textInput("Restaurant", labelMandatory("Restaurant"), value = ""), textInput("Pho", labelMandatory("Pho"), value = "0"), textInput("Steam_Smallcut", labelMandatory("Steam(Small cut)"), value = "0"), textInput("Steam_Bigcut", labelMandatory("Steam(Big cut)"), value = "0"), textInput("Steam_Nocut", labelMandatory("Steam(No cut)"), value = "0"), textInput("Pancit", labelMandatory("Pancit"), value = "0"), textInput("EggNoodle_Smallcut", labelMandatory("EggNoodle(Small cut)"), value = "0"), textInput("EggNoodle_Bigcut", labelMandatory("EggNoodle(Big cut)"), value = "0"), ), mainPanel( br(), p( "After you are happy with your guesses, press submit to send data to the database." ), br(), tableOutput("table"), br(), actionButton("Submit", "Submit"), fluidRow(shinyjs::hidden(div( id = "thankyou_msg", h3("Thanks, your response was submitted successfully!") ))) ) ) ) #Server server <- shinyServer(function(input, output, session) { # Gather all the form inputs formData <- reactive({ x <- reactiveValuesToList(input) data.frame(names = names(x), values = unlist(x, use.names = FALSE)) }) #Save the results to a file saveData <- function(data) { # Create a unique file name fileName <-"test.csv" # Write the data to a temporary file locally filePath <- file.path('/Users/hdeng/Desktop/Random/ShinyApp/Order', fileName) write.csv(data, filePath, row.names = TRUE, quote = TRUE) # Upload the file to Dropbox #drop_upload(filePath, path = outputDir) } # When the Submit button is clicked, submit the response observeEvent(input$Submit, { # User-experience stuff shinyjs::disable("Submit") shinyjs::show("thankyou_msg") tryCatch({ #saveData(formData()) shinyjs::reset("form") shinyjs::hide("form") shinyjs::show("thankyou_msg") }) #write.csv(create_table(),'submitted.csv') saveData(create_table()) }, ignoreInit = TRUE, once = TRUE, ignoreNULL = T) #Observe for when all mandatory fields are completed observe({ fields_filled <- fieldsMandatory %>% sapply(function(x) ! is.na(input[[x]]) && input[[x]] != "") %>% all shinyjs::toggleState("Submit", fields_filled) }) # isolate data input values <- reactiveValues() create_table <- reactive({ input$addButton Restaurant <- input$Restaurant Pho <- input$Pho Steam_Smallcut <- input$Steam_Smallcut Steam_Bigcut <- input$Steam_Bigcut Steam_Nocut <- input$Steam_Nocut Pancit <- input$Pancit EggNoodle_Smallcut <- input$EggNoodle_Smallcut EggNoodle_Bigcut <- input$EggNoodle_Bigcut df <-tibble(Restaurant, Pho, Steam_Smallcut, Steam_Bigcut, Steam_Nocut,Pancit, EggNoodle_Smallcut, EggNoodle_Bigcut) df }) output$table <- renderTable(create_table()) }) # Run the application shinyApp(ui = ui, server = server)<file_sep>/googlesheet.R #load libraries library(shiny) library(shinydashboard) library(googledrive) library(googlesheets4) library("DT") #get your token to access google drive gs4_auth_configure(api_key = "<KEY>") #google_app <- gs_auth(key = "350761824600-3lerqmu2cebe9pd12h4k11e6d955cge9.apps.googleusercontent.com", # secret = "<KEY>") drive_auth() gs4_auth(scope = "https://www.googleapis.com/auth/drive") initial_sheet <- data.frame(Restaurant = 0, Rice_Noodle = 0, Egg_Noodle = 0) (ss <- gs4_create("order", sheets = initial_sheet))
1c217384f7c4b811851f0dc394e0a4c1f96c0d6c
[ "Markdown", "R" ]
3
Markdown
charlatteD/RecordOrders
9ce0502ac94a8de74e7bd95c102b1be4f1010825
c9dfb370b387c9671e631a662dfb176411f26b59
refs/heads/master
<repo_name>MirrorNightMaz/AHJZU-2019-Android-Design-OA<file_sep>/OA/app/src/main/java/com/example/oa10/Beans/PhoneEntity.java package com.example.oa10.Beans; /** * Created by asus on 2018/12/28. */ public class PhoneEntity { private String phoneNumber;//手机号 private String phoneName;//手机联系人 public PhoneEntity() { } public PhoneEntity(String phoneNumber, String phoneName){ this.phoneName=phoneName; this.phoneNumber = phoneNumber; } /** * @return the phoneNumber */ public String getPhoneNumber() { return phoneNumber; } /** * @param phoneNumber the phoneNumber to set */ public void setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; } /** * @return the phoneName */ public String getPhoneName() { return phoneName; } /** * @param phoneName the phoneName to set */ public void setPhoneName(String phoneName) { this.phoneName = phoneName; } @Override public String toString() { return "PhoneEntity{" + "phoneNumber='" + phoneNumber + '\'' + ", phoneName='" + phoneName + '\'' + '}'; } } <file_sep>/OA/app/src/main/java/com/example/oa10/Adapter/ScheduleAdapter.java package com.example.oa10.Adapter; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.view.View; import com.example.oa10.Fragment.FragmentHistory; import com.example.oa10.Fragment.FragmentToday; import com.example.oa10.Fragment.FragmentTomorrow; /** * Created by asus on 2018/12/30. */ public class ScheduleAdapter extends FragmentPagerAdapter { private String[] mTitles = new String[]{"今日日程","明日日程","历史日程"}; public ScheduleAdapter(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int position) { if (position == 1) { return new FragmentTomorrow(); } else if (position == 2) { return new FragmentHistory(); } return new FragmentToday(); } @Override public int getCount() { return mTitles.length; } //ViewPager与TabLayout绑定后,这里获取到PageTitle就是Tab的Text @Override public CharSequence getPageTitle(int position) { return mTitles[position]; } @Override public boolean isViewFromObject(View view, Object object) { return view ==((Fragment) object).getView();} } <file_sep>/OA/app/src/main/java/com/example/oa10/Adapter/ScheAdapter.java package com.example.oa10.Adapter; import android.content.Context; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import com.example.oa10.R; import com.example.oa10.entity.News; import com.example.oa10.entity.Schedule; import java.util.List; public class ScheAdapter extends BaseAdapter { private List<Schedule.ScheduleBean> list; private Context context; //通过构造方法接受要显示的新闻数据集合 public ScheAdapter(Context context, List<Schedule.ScheduleBean> list) { this.list = list; this.context = context; } @Override public int getCount() { return list.size(); } @Override public Object getItem(int position) { return list.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { View view = null; //1.复用converView优化listview,创建一个view作为getview的返回值用来显示一个条目 if(convertView != null){ view = convertView; }else { view = View.inflate(context, R.layout.item_sche, null);//将一个布局文件转换成一个view对象 } TextView item_tv_des = (TextView) view.findViewById(R.id.item_tv_des); TextView item_tv_time = (TextView) view.findViewById(R.id.item_tv_time); Schedule.ScheduleBean scheduleBean = list.get(position); String str=scheduleBean.getSche_time(); str = str.substring(0,10); item_tv_time.setText(" ["+str+"] "); item_tv_des.setText(scheduleBean.getSche_content()); return view; } } <file_sep>/OA/app/src/main/java/com/example/oa10/Activity/LogActivity.java package com.example.oa10.Activity; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import com.example.oa10.Adapter.LogAdapter; import com.example.oa10.Beans.LogBeans; import com.example.oa10.R; import com.example.oa10.Utils.MyDatabase; import java.util.ArrayList; public class LogActivity extends AppCompatActivity { ListView listView; FloatingActionButton floatingActionButton; LayoutInflater layoutInflater; ArrayList<LogBeans> arrayList; MyDatabase myDatabase; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_log); listView = (ListView)findViewById(R.id.layout_listview); floatingActionButton = (FloatingActionButton)findViewById(R.id.add_note); layoutInflater = getLayoutInflater(); myDatabase = new MyDatabase(this); arrayList = myDatabase.getarray(); LogAdapter adapter = new LogAdapter(layoutInflater,arrayList); listView.setAdapter(adapter); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { //点击一下跳转到编辑页面(编辑页面与新建页面共用一个布局) @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Intent intent3 = new Intent(getApplicationContext(),LogNewBuild.class); intent3.putExtra("ids",arrayList.get(position).getLog_ids()); startActivity(intent3); LogActivity.this.finish(); } }); listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { //长按删除 @Override public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) { new AlertDialog.Builder(LogActivity.this) //弹出一个对话框 //.setTitle("确定要删除此便签?") .setMessage("确定要删除此便签?") .setNegativeButton("取消",new DialogInterface.OnClickListener(){ @Override public void onClick(DialogInterface dialog, int which) { } }) .setPositiveButton("确定",new DialogInterface.OnClickListener(){ @Override public void onClick(DialogInterface dialog, int which) { myDatabase.toDelete(arrayList.get(position).getLog_ids()); LogAdapter myAdapter = new LogAdapter(layoutInflater,arrayList); listView.setAdapter(myAdapter); } }) .create() .show(); return true; } }); floatingActionButton.setOnClickListener(new View.OnClickListener() { //点击悬浮按钮时,跳转到新建页面 @Override public void onClick(View v) { Intent intent1 = new Intent(getApplicationContext(),LogNewBuild.class); startActivity(intent1); LogActivity.this.finish(); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.log_menu,menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()){ case R.id.menu_newnote: Intent intent2 = new Intent(getApplicationContext(),LogNewBuild.class); startActivity(intent2); LogActivity.this.finish(); break; case R.id.menu_exit: LogActivity.this.finish(); break; default: break; } return true; //return false;????是用哪个true or false? } } <file_sep>/OA/app/src/main/java/com/example/oa10/Activity/LoginActivity.java package com.example.oa10.Activity; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.example.oa10.MainActivity; import com.example.oa10.R; import com.example.oa10.Utils.LoginFlag; import com.example.oa10.entity.Inform; import com.example.oa10.entity.News; import com.example.oa10.entity.ResultBean; import com.example.oa10.entity.Schedule; import com.example.oa10.presenter.MyPresenter; import com.example.oa10.view.MVPView; public class LoginActivity extends AppCompatActivity implements MVPView,View.OnClickListener{ private EditText mLoginUserName; private EditText mLoginUserPass; private TextView mLoginTextview; public final static String LOGIN_ACTION="LOGIN_ACTION"; //private ImageView imageView; private static final String TAG = "MainActivity"; private static final String APP_ID = "1106758439";//官方获取的APPID private MyPresenter myPresenter; private LoginFlag loginFlag; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); myPresenter=new MyPresenter(getApplicationContext()); myPresenter.attachView(this); loginFlag = LoginFlag.getInstance(); mLoginUserName = (EditText) findViewById(R.id.login_user_name); mLoginUserPass = (EditText) findViewById(R.id.login_user_pass); mLoginTextview = (TextView) findViewById(R.id.login_textview); mLoginTextview.setOnClickListener(this); } @Override public void onClick(View v) { switch(v.getId()){ case R.id.login_textview: Log.e("gggggg",mLoginUserName.getText().toString()+mLoginUserPass.getText().toString()+""); myPresenter.login(mLoginUserName.getText().toString(),mLoginUserPass.getText().toString()); break; } } @Override public void onSuccess_news(News news) { } @Override public void onSuccess_login(ResultBean resultBean) { Toast.makeText(getApplicationContext(),"登录成功",Toast.LENGTH_LONG).show(); //Log.e("login",resultBean.toString()); loginFlag.setResultBean(resultBean); finish(); } @Override public void onSuccess_inform(Inform inform) { } @Override public void onSuccess_schedule(Schedule schedule) { } @Override public void onError() { Toast.makeText(getApplicationContext(),"登录失败",Toast.LENGTH_LONG).show(); loginFlag.setResultBean(null); } } <file_sep>/OA/app/src/main/java/com/example/oa10/Adapter/RecyclerAdapter1.java package com.example.oa10.Adapter; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.example.oa10.Activity.DetailActivity; import com.example.oa10.R; import com.example.oa10.entity.Inform; import java.util.List; public class RecyclerAdapter1 extends RecyclerView.Adapter<RecyclerAdapter1.ViewHolder>{ private Context context; private OnItemClickListener onItemClickListener= null; //② 创建ViewHolder public static class ViewHolder extends RecyclerView.ViewHolder{ public TextView title,time; public ViewHolder(View v) { super(v); title = (TextView) v.findViewById(R.id.item_title); time = (TextView) v.findViewById(R.id.item_time); } } private List<Inform.NoticeBean> mDatas = null; public RecyclerAdapter1(Context context) { this.context = context; } public void setmDatas(List<Inform.NoticeBean> list){ this.mDatas = list; this.notifyDataSetChanged(); } //③ 在Adapter中实现3个方法 @Override public void onBindViewHolder(RecyclerAdapter1.ViewHolder holder, final int position) { if(null==mDatas){ return; } holder.title.setText(mDatas.get(position).getNotice_title()); holder.time.setText(" ["+mDatas.get(position).getNotice_time()+" ]"); holder.itemView.setTag(position); } @Override public int getItemCount() { if(null==mDatas){ return 0; } return mDatas.size(); } @Override public RecyclerAdapter1.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { //LayoutInflater.from指定写法 View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_item, parent, false); v.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(onItemClickListener!=null){ onItemClickListener.onItemClick((Integer) v.getTag()); } } }); return new RecyclerAdapter1.ViewHolder(v); } public void setOnItemClickListener(OnItemClickListener onItemClickListener) { this.onItemClickListener = onItemClickListener; } public static interface OnItemClickListener { void onItemClick(int position); } } <file_sep>/OA/app/src/main/java/com/example/oa10/Fragment/FragmentAnnouncement.java package com.example.oa10.Fragment; import android.support.v4.app.Fragment; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ListView; import com.example.oa10.Activity.DetailActivity; import com.example.oa10.Adapter.NewsAdapter; import com.example.oa10.Adapter.RecyclerAdapter; import com.example.oa10.Beans.NewsBeans; import com.example.oa10.R; import com.example.oa10.Utils.LoginFlag; import com.example.oa10.Utils.NewsUtils; import com.example.oa10.entity.Inform; import com.example.oa10.entity.News; import com.example.oa10.entity.ResultBean; import com.example.oa10.entity.Schedule; import com.example.oa10.presenter.MyPresenter; import com.example.oa10.view.MVPView; import java.util.ArrayList; import java.util.List; /** * Created by asus on 2018/12/30. */ //公告 public class FragmentAnnouncement extends Fragment { private View view; private Context mContext; private RecyclerView recyclerView; private LinearLayoutManager mLayoutManager; private RecyclerAdapter recyclerAdapter; public FragmentAnnouncement() { } public void getInstance(Context context){ this.mContext = context; } List<Inform.AnnouncementBean> list; public void setData(List<Inform.AnnouncementBean> list1){ this.list = list1; recyclerAdapter.setmDatas(list1); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { view = inflater.inflate(R.layout.fragment_anno,null); //mContext=getContext(); recyclerView = (RecyclerView)view.findViewById(R.id.recyclerview01); recyclerView.setHasFixedSize(true); mLayoutManager = new LinearLayoutManager(getActivity()); recyclerView.setLayoutManager(mLayoutManager); recyclerView.setItemAnimator(new DefaultItemAnimator()); recyclerAdapter=new RecyclerAdapter(mContext); recyclerAdapter.setOnItemClickListener(new RecyclerAdapter.OnItemClickListener() { @Override public void onItemClick(int position) { Log.e("item",position+""); Intent intent = new Intent(mContext,DetailActivity.class); Bundle bundle = new Bundle(); bundle.putString("content",list.get(position).getAnno_content()); intent.putExtras(bundle); startActivity(intent); } }); recyclerView.setAdapter(recyclerAdapter); return view; } /** @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Announcement.AnnouncementBean announcementBean=(Announcement.AnnouncementBean) recyclerAdapter.get(position); Intent intent = new Intent(mContext, DetailActivity.class); Bundle bundle = new Bundle(); bundle.putString("content",announcementBean.getAnno_content()); intent.putExtras(bundle); startActivity(intent); } **/ } <file_sep>/README.md # AHJZU-2019-Android-Design-OA Project team members are <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>. OA - Android front end; server_oa-master - Android backend. <file_sep>/OA/app/src/main/java/com/example/oa10/entity/News.java package com.example.oa10.entity; import java.util.List; public class News { private List<NewsBean> news; //<>中指定了列表的泛型 public List<NewsBean> getNews() { return news; } public void setNews(List<NewsBean> news) { this.news = news; } public static class NewsBean { /** * news_id : 77 * news_title : 美方代表团将于1月7日至8日访华 * news_content : 【环球网综合报道】2019年1月4日外交部发言人陆慷主持例行记者会,有记者问道, 我们注意到中国商务部新闻发言人今天上午表示,美方代表团将于1月7日至8日访华进行经贸磋商。你能否证实? * news_time : 2019-01-04 17:55 * news_icon : http://5b0988e595225.cdn.sohucs.com/images/20190104/9e3177f41c04480385986075eb0c872f.jpeg */ private int news_id; private String news_title; private String news_content; private String news_time; private String news_icon; public int getNews_id() { return news_id; } public void setNews_id(int news_id) { this.news_id = news_id; } public String getNews_title() { return news_title; } public void setNews_title(String news_title) { this.news_title = news_title; } public String getNews_content() { return news_content; } public void setNews_content(String news_content) { this.news_content = news_content; } public String getNews_time() { return news_time; } public void setNews_time(String news_time) { this.news_time = news_time; } public String getNews_icon() { return news_icon; } public void setNews_icon(String news_icon) { this.news_icon = news_icon; } } } <file_sep>/OA/app/src/main/java/com/example/oa10/Activity/DetailActivity.java package com.example.oa10.Activity; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.TextView; import com.example.oa10.R; public class DetailActivity extends AppCompatActivity{ private TextView textView; private Intent intent; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_detail); textView = (TextView)findViewById(R.id.text01); Bundle bundle = this.getIntent().getExtras(); textView.setText(bundle.getString("content")); } } <file_sep>/server_oa-master/src/main/java/com/xleone/server_oa/bean/AnnoEntity.java package com.xleone.server_oa.bean; public class AnnoEntity { private Integer anno_id; private String anno_title; private String anno_content; private String anno_time; public Integer getAnno_id() { return anno_id; } public void setAnno_id(Integer anno_id) { this.anno_id = anno_id; } public String getAnno_title() { return anno_title; } public void setAnno_title(String anno_title) { this.anno_title = anno_title; } public String getAnno_content() { return anno_content; } public void setAnno_content(String anno_content) { this.anno_content = anno_content; } public String getAnno_time() { return anno_time; } public void setAnno_time(String anno_time) { this.anno_time = anno_time; } } <file_sep>/server_oa-master/README.md # server_oa-master Android backend. <file_sep>/OA/app/src/main/java/com/example/oa10/Utils/NewsUtils.java package com.example.oa10.Utils; import android.content.Context; import android.support.v4.content.ContextCompat; import com.example.oa10.Beans.NewsBeans; import com.example.oa10.R; import java.util.ArrayList; /** * Created by asus on 2018/12/28. */ public class NewsUtils { //封装新闻的假数据到list中返回,以后数据会从数据库中获取 public static ArrayList<NewsBeans> getAllNews(Context context) { ArrayList<NewsBeans> arrayList = new ArrayList<NewsBeans>(); for(int i = 0 ;i <100;i++) { NewsBeans newsBean = new NewsBeans(); newsBean.title ="火箭发射成功"; newsBean.des= "搜索算法似懂非懂三分得手房贷首付第三方的手"; newsBean.news_url= "http://www.sina.cn"; newsBean.icon = ContextCompat.getDrawable(context, R.drawable.about);; //通过context对象将一个资源id转换成一个Drawable对象。 arrayList.add(newsBean); NewsBeans newsBean1 = new NewsBeans(); newsBean1.title ="似懂非懂瑟瑟发抖速度"; newsBean1.des= "地方上的房贷首付读书首付第三方的手房贷首付第三方的手负担"; newsBean1.news_url= "http://www.baidu.cn"; newsBean1.icon = ContextCompat.getDrawable(context, R.drawable.about);;//通过context对象将一个资源id转换成一个Drawable对象。 arrayList.add(newsBean1); NewsBeans newsBean2 = new NewsBeans(); newsBean2.title ="豆腐皮人热舞"; newsBean2.des= "费解的是离开房间打扫李开复离开独守空房迪斯科浪费电锋克劳利分级恐龙快打"; newsBean2.news_url= "http://www.qq.com"; //通过context对象将一个资源id转换成一个Drawable对象。 newsBean2.icon = ContextCompat.getDrawable(context, R.drawable.about); arrayList.add(newsBean2); } return arrayList; } } <file_sep>/OA/app/src/main/java/com/example/oa10/Fragment/FragmentSche.java package com.example.oa10.Fragment; import android.content.Intent; import android.support.v4.app.Fragment; import android.content.Context; import android.os.Build; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.annotation.RequiresApi; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ListView; import com.example.oa10.Activity.LoginActivity; import com.example.oa10.Adapter.NewsAdapter; import com.example.oa10.Adapter.ScheAdapter; import com.example.oa10.MainActivity; import com.example.oa10.R; import com.example.oa10.Utils.LoginFlag; import com.example.oa10.entity.Inform; import com.example.oa10.entity.News; import com.example.oa10.entity.ResultBean; import com.example.oa10.entity.Schedule; import com.example.oa10.presenter.MyPresenter; import com.example.oa10.view.MVPView; public class FragmentSche extends Fragment implements AdapterView.OnItemClickListener { private View view; private Context mContext; private MyPresenter myPresenter; private ScheAdapter scheAdapter; private ListView lv_news; private MVPView mvpView = new MVPView() { @Override public void onSuccess_news(News news) { } @Override public void onSuccess_login(ResultBean resultBean) { } @Override public void onSuccess_inform(Inform inform) { } @Override public void onSuccess_schedule(Schedule schedule) { scheAdapter = new ScheAdapter(mContext,schedule.getSchedule()); lv_news.setAdapter(scheAdapter); scheAdapter.notifyDataSetChanged(); } @Override public void onError() { } }; private String type=null; public static FragmentSche getInstance(){ FragmentSche fragmentSche = new FragmentSche(); return fragmentSche; } public void setType(String type){ this.type = type; } private LoginFlag loginFlag; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { view = LayoutInflater.from(getActivity()).inflate(R.layout.fragmentnews, container, false); mContext=getContext(); myPresenter=new MyPresenter(mContext); myPresenter.attachView(mvpView); lv_news = (ListView) view.findViewById(R.id.lv_news); lv_news.setOnItemClickListener(this); Log.e("type",type); loginFlag = LoginFlag.getInstance(); if(loginFlag.getResultBean()!=null){ myPresenter.getSche(type,loginFlag.getResultBean().getUserEntity().getUser_id()); } return view; } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { } } <file_sep>/OA/app/src/main/java/com/example/oa10/Fragment/Fragmentabout.java package com.example.oa10.Fragment; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.example.oa10.R; import com.example.oa10.Utils.APKVersionCodeUtils; /** * Created by asus on 2018/12/26. */ public class Fragmentabout extends Fragment { private TextView mTv_version; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragmentinabout, container, false); mTv_version = (TextView)view.findViewById(R.id.tv_about_version); String versionCode = APKVersionCodeUtils.getVersionCode(this.getActivity()) + ""; mTv_version.setText("版本:"+versionCode); //String versionName = APKVersionCodeUtils.getVerName(this); return view; } } <file_sep>/OA/app/src/main/java/com/example/oa10/Activity/PhoneContentActivity.java package com.example.oa10.Activity; import android.app.Activity; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import android.widget.TextView; import com.example.oa10.Adapter.PhoneAdapter; import com.example.oa10.R; import com.example.oa10.Utils.GetPhoneContacts; public class PhoneContentActivity extends Activity { private ListView ls; private PhoneAdapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_phone_content); GetPhoneContacts.getNumber(this);//调用getNumber方法,将数据封装到List<PhoneEntity>集合中。 ls=(ListView) findViewById(R.id.list_phone);//得到ListView对象 adapter=new PhoneAdapter(this, GetPhoneContacts.list);//得到适配器对象 ls.setAdapter(adapter);//为listView设置适配器 // 初始化监听 initListener(); } /** * 初始化监听 */ private void initListener() { Log.e("initListener","......."); ls.setOnItemClickListener(new onItemClickListener()); } /** * 点击监听实现 * <p/> * * 实现:获得选中项的电话号码并拨号 * * 注意:不能使用仅是继承于BaseAdapter,因为Object对象不能转型为Cursor。 * 所以:使用的Adapter是继承于CursorAdapter,才能转型为CursorWrapper。 */ private class onItemClickListener implements AdapterView.OnItemClickListener { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { final TextView content=(TextView) view.findViewById(R.id.tx_phoneNumber); Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel://" + content)); startActivity(intent); } } } <file_sep>/OA/app/src/main/java/com/example/oa10/Fragment/FragmentSchedule.java package com.example.oa10.Fragment; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.design.widget.TabLayout; import android.support.v4.app.Fragment; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.example.oa10.Adapter.ScheduleAdapter; import com.example.oa10.Adapter.ViewPagerAdapter; import com.example.oa10.R; import java.util.ArrayList; import java.util.List; /** * Created by asus on 2018/12/26. */ public class FragmentSchedule extends Fragment { private TabLayout mTabLayout; private ViewPager mViewPager; private PagerAdapter pagerAdapter; private ScheduleAdapter mScheduleAdapter; private TabLayout.Tab one; private TabLayout.Tab two; private TabLayout.Tab three; private View mView; private List<FragmentSche> fragments = new ArrayList<>(); @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { mView = LayoutInflater.from(getActivity()).inflate(R.layout.fragmentschedule, container, false); initViews(); return mView; } private void initViews() { //使用适配器将ViewPager与Fragment绑定在一起 mViewPager= (ViewPager) mView.findViewById(R.id.viewPager); mTabLayout = (TabLayout) mView.findViewById(R.id.tab_schedule); //mScheduleAdapter= new ScheduleAdapter(getChildFragmentManager()); //mViewPager.setAdapter(mScheduleAdapter); String type[]=new String[]{"new","tom","old"}; FragmentSche fragmentSche1= FragmentSche.getInstance(); fragmentSche1.setType(type[0]); fragments.add(fragmentSche1); FragmentSche fragmentSche2= FragmentSche.getInstance(); fragmentSche2.setType(type[1]); fragments.add(fragmentSche2); FragmentSche fragmentSche3= FragmentSche.getInstance(); fragmentSche3.setType(type[2]); fragments.add(fragmentSche3); for(int i=0;i<3.;i++){ mTabLayout.addTab(mTabLayout.newTab()); } pagerAdapter = new ViewPagerAdapter(getChildFragmentManager(),fragments); mViewPager.setAdapter(pagerAdapter); //将TabLayout与ViewPager绑定在一起 mTabLayout.setupWithViewPager(mViewPager,true); String titles[]=new String[]{"今日日程","明日日程","历史日程"}; for(int i=0;i<titles.length;i++){ mTabLayout.getTabAt(i).setText(titles[i]); } } } <file_sep>/server_oa-master/src/main/java/com/xleone/server_oa/mapper/MainMapper.java package com.xleone.server_oa.mapper; import com.xleone.server_oa.bean.*; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Select; import java.util.List; @Mapper public interface MainMapper { @Select("select * from news") public List<NewsEntity> getAllNews(); @Select("select * from announcement") public List<AnnoEntity> getAnno(); @Select("select * from notice") public List<NoticeEntity> getNotice(); @Select("select * from admin where user_name=#{admin.user_name} and user_pass=#{admin.user_pass}") public admin login(@Param(value = "admin") admin admin); @Select("select * from schedule where 1=1 and date_format(sche_time,'%Y-%m-%d')=#{date} and user_id=#{user_id}") public List<ScheEntity> getNewSche(@Param("date") String date,@Param("user_id") String user_id); @Select("select * from schedule where 1=1 and date_format(sche_time,'%Y-%m-%d')>#{date} and user_id=#{user_id}") public List<ScheEntity> getTomSche(@Param("date")String date,@Param("user_id") String user_id); @Select("select * from schedule where 1=1 and date_format(sche_time,'%Y-%m-%d')<#{date} and user_id=#{user_id}")// 1 = 1 ???? public List<ScheEntity> getOldSche(@Param("date")String date,@Param("user_id") String user_id); } <file_sep>/server_oa-master/src/main/java/com/xleone/server_oa/bean/ResultBean.java package com.xleone.server_oa.bean; /** * 用于返回结果的JavaBean */ public class ResultBean { /** * 结果码: * 100--代表登陆操作返回结果码 * 成功登陆--101 * 登陆失败--102 * * */ private int resultCode; public int getResultCode() { return resultCode; } public void setResultCode(int resultCode) { this.resultCode = resultCode; } private admin userEntity; public admin getUserEntity() { return userEntity; } public void setUserEntity(admin userEntity) { this.userEntity = userEntity; } } <file_sep>/OA/README.md # OA Android front end. <file_sep>/OA/app/src/main/java/com/example/oa10/Activity/LogNewBuild.java package com.example.oa10.Activity; import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.design.widget.FloatingActionButton; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.EditText; import com.example.oa10.Beans.LogBeans; import com.example.oa10.R; import com.example.oa10.Utils.MyDatabase; import java.text.SimpleDateFormat; import java.util.Date; /** * Created by asus on 2018/12/30. */ public class LogNewBuild extends AppCompatActivity { EditText ed_title; EditText ed_content; FloatingActionButton floatingActionButton; MyDatabase myDatabase; LogBeans data; int ids; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.log_detail); ed_title = (EditText)findViewById(R.id.log_title); ed_content = (EditText)findViewById(R.id.log_content); floatingActionButton = (FloatingActionButton)findViewById(R.id.log_finish); myDatabase = new MyDatabase(this); Intent intent = this.getIntent(); ids = intent.getIntExtra("ids",0); if (ids != 0){ data = myDatabase.getTiandCon(ids); ed_title.setText(data.getLog_title()); ed_content.setText(data.getLog_content()); } floatingActionButton.setOnClickListener(new View.OnClickListener() { //为悬浮按钮设置监听事件 @Override public void onClick(View v) { isSave(); } }); } @Override public void onBackPressed() { //重写返回建方法,如果是属于新建则插入数据表并返回主页面,如果是修改,修改表中数据并返回主页面 SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");//编辑便签的时间,格式化 Date date = new Date(System.currentTimeMillis()); String time = simpleDateFormat.format(date); String title = ed_title.getText().toString(); String content = ed_content.getText().toString(); if(ids!=0){ data=new LogBeans(title,content,time,ids); myDatabase.toUpdate(data); Intent intent=new Intent(LogNewBuild.this,LogActivity.class); startActivity(intent); LogNewBuild.this.finish(); } //新建日记 else{ data=new LogBeans(title,content,time); myDatabase.toInsert(data); Intent intent=new Intent(LogNewBuild.this,LogActivity.class); startActivity(intent); LogNewBuild.this.finish(); } } private void isSave(){ //写一个方法进行调用,如果是属于新建则插入数据表并返回主页面,如果是修改,修改表中数据并返回主页面 SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy.MM.dd HH:mm"); Date date = new Date(System.currentTimeMillis()); String time = simpleDateFormat.format(date); Log.d("new_note", "isSave: "+time); String title = ed_title.getText().toString(); String content = ed_content.getText().toString(); if(ids!=0){ data=new LogBeans(title,content,time,ids); myDatabase.toUpdate(data); Intent intent=new Intent(LogNewBuild.this,LogActivity.class); startActivity(intent); LogNewBuild.this.finish(); } //新建日记 else{ data=new LogBeans(title,content,time); myDatabase.toInsert(data); Intent intent=new Intent(LogNewBuild.this,LogActivity.class); startActivity(intent); LogNewBuild.this.finish(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.newbuild_menu,menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()){ case R.id.new_share : //分享功能 Intent intent=new Intent(Intent.ACTION_SEND); intent.setType("text/plain"); intent.putExtra(Intent.EXTRA_TEXT,//分享类型设置为文本型 "标题:"+ed_title.getText().toString()+" " + "内容:"+ed_content.getText().toString()); startActivity(intent); break; default: break; } return false; } }
bdfe9193ec684f91e50696339e0d04ca72608c2a
[ "Markdown", "Java" ]
21
Java
MirrorNightMaz/AHJZU-2019-Android-Design-OA
a7e1b2b9c13dcfc5c4665dfd33f4bed44a79fc5c
ed1d6d04ee06757089c435f78dbbaa94aaf1b490
refs/heads/master
<file_sep>const request = require("request"); /* without using callback pattern const url = "https://api.darksky.net/forecast/3552a1079fa54b6c812bb07c53d9caaa/37.8267,-122.4233?units=si"; //request is a function that takes in an object and a callback ffunction that runs once we get the data or something goes wrong request({ url: url, json: true }, (error, response) => { if (error) { //for low level OS errors console.log("Hey! There was an error connecting to weather service."); } else if (response.body.error) { console.log("Unable to find location"); } else { var x = response.body.currently; console.log("Daily Forecast"); console.log( `Summary: ${response.body.daily.data[0].summary} | There is a ${x.precipProbability}% chance of rain | The temperature is ${x.temperature} degrees outside.` ); } }); */ //using callback pattern function forecast(latitude, longitude, callback) { const url = `https://api.darksky.net/forecast/3552a1079fa54b6c812bb07c53d9caaa/${latitude},${longitude}?units=si`; request({ url, json: true }, (error, { body }) => { if (error) { //for low level OS errors callback("Unable To Connect To Forecast API", undefined); } else if (body.error) { callback("Unable to find location. Bad Lat & Long requested", undefined); } else { var x = body.currently; var y = `Summary: ${body.daily.data[0].summary} || There is a ${x.precipProbability}% chance of rain || The temperature is ${x.temperature} degrees outside.`; callback(undefined, y); } }); } module.exports = forecast; <file_sep>console.log("From Satic Assets JS File"); console.log("New Chnage For Github!"); const weatherForm = document.querySelector("form"); //select the html element youre trying to work with const search = document.querySelector("input"); //we want to grab the value the user enetered const messageOne = document.querySelector("#message-1"); const messageTwo = document.querySelector("#message-2"); //add an event listener to the element you selected. so when the form SUBMITS, do my code weatherForm.addEventListener("submit", e => { e.preventDefault(); //default behaviour of forms is to refresh the page, made sense in old times, but now so prevent default var location = search.value; messageOne.textContent = "Loading..."; messageTwo.textContent = ""; console.log(typeof location); fetch(`/weather?address=${location}`).then(response => { response.json().then(data => { console.log(data); if (data.error) { messageOne.textContent = data.error; } else { messageOne.textContent = data.location; messageTwo.textContent = data.forecast; search.value = ""; } }); }); });
bee800cfbf64f90f1e5685259b4925b6fd56fb03
[ "JavaScript" ]
2
JavaScript
rohansoodx/node3-weather-website
3e76536e52717240f7d2dc9234234bc5d6bd9d41
f01cc3fd223034f04962317f5feab655a82d1d49
refs/heads/master
<file_sep>/* tools and other randomness */ /** * Define a function func as the given name for a class. **/ Function.prototype.method = function (name, func) { this.prototype[name] = func; return this; };<file_sep>function GameBoard(parentid, bokeh, rows, cols) { this.parentid = parentid; this.parentnode = $(parentid); this.bokeh = bokeh; // set global game = this; // note that this should always be even numbers this.rows = rows; this.cols = cols; // default sphere/box size this.radius = '40px'; // init the board // -------------------------------------- var blockcontainer = $("<div />"); blockcontainer.attr('id', 'blockcontainer'); this.blockcontainer = blockcontainer; this.parentnode.append(blockcontainer); // bottom score/control box this.scorebox = new Scorebox(this.parentnode); // how many points to remove when a hint is used this.score_remove_on_hint = -15; // show welcome message // -------------------------------------- var m = new Modal( 'Welcome!', 'To begin playing, close this window and click ' + '<strong>NEW GAME</strong> or the <strong>START</strong> button ' + 'below. Instructions are available under ' + '<strong>HELP</strong>. Enjoy!' ); var mstart = m.addbutton("Start"); var mclose = m.addbutton("Close"); mclose.on('click', function() { m.div.remove(); }); mstart.on('click', function() { m.div.remove(); game.start(); }); m.show(); } /** * Display help dialog */ GameBoard.method('help', function() { // create help dialog // -------------------------------------- var h = new Modal( 'OMG HELP MEEEE', "It's matching tiles but with a twist! Complete the board before the " + "time runs out! Also, there must be a clear, unbroken path between each of " + "the tiles as shown below.<br /><br />Note: Click the [+] next to the time to add more time, or the [?] for a hint near your score. The [+] is limited in use, and the [?] will remove points!" ); h.container.addClass('help'); var btnClose = h.addbutton('Close'); btnClose.on('click', function() { h.div.remove(); }); // each move type var contents = h.eContents; var moves = $("<div />"); moves.addClass("moves"); contents.append(moves); moves.append( $("<div />") .append($("<img />").attr('src', 'img/straight.png')) .append($("<span />").html("No turns, a straight path.")) ); moves.append( $("<div />") .append($("<img />").attr('src', 'img/1turn.png')) .append($("<span />").html("A single turn, creating an L shape.")) ); moves.append( $("<div />") .append($("<img />").attr('src', 'img/2turna.png')) .append($("<span />").html("2 turns, creating a sort of S shape.")) ); moves.append( $("<div />") .append($("<img />").attr('src', 'img/2turnb.png')) .append($("<span />").html("2 turns, creating a sort of U shape.")) ); h.show(); }); /** * Temporarily highlight a block that has a valid move remaining */ GameBoard.method('give_hint', function() { // just find the first valid block with a path and highlight it for (var k1 in this.paths) { for (var k2 in this.paths[k1]) { this.paths[k1][k2][0].hint(); game.scorebox.add_to_score(this.score_remove_on_hint); return; } } }); /** * Start the game */ GameBoard.method('start', function() { this.reset(); $(".block").remove(); // should always be an even number this.start_rows = 4; this.start_cols = 4; // populate this.populate(this.start_cols, this.start_rows, num_block_types, true); this.find_paths(); this.scorebox.begintimer(); bokeh.reset(); }); /** * Refresh board and move on to next round */ GameBoard.method('next_round', function() { this.reset(false); $(".block").remove(); if ( this.start_rows > this.start_cols ) { this.start_cols = Math.min(this.start_cols + 2, this.cols); } else { this.start_rows = Math.min(this.start_rows + 2, this.rows); } // populate this.populate(this.start_cols, this.start_rows, num_block_types, true); this.find_paths(); this.scorebox.begintimer(); this.scorebox.extendtime(this.start_cols < this.cols ? this.start_rows * 2 : 0); this.scorebox._timeHelpsLeft = this.scorebox._timeHelpsLeft + 1; bokeh.reset(); }); /** * Display round win dialog */ GameBoard.method('do_win', function() { if ( this.winbox != null ) { // remove old box first this.winbox.div.remove(); } var m = new Modal( 'You Finished!', 'Congrats, you finished this round with <strong>' + this.scorebox.getscore() + 'pts!</strong>' + '<br /><br />' + 'To continue to the next round click <strong>NEXT</strong> or <strong>NEW GAME</strong> to start over.' ); var btnNext = m.addbutton("Next"); var btnNew = m.addbutton("New Game"); // set binds btnNew.on('click', function() { m.div.remove(); game.start(); }); btnNext.on('click', function() { m.div.remove(); game.next_round(); }); this.scorebox.stoptimer(); this.scorebox.stoptimer(); m.show(); this.winbox = m; }); /** * Display time ran out dialog */ GameBoard.method('lose', function() { this.scorebox.stoptimer(); if ( this.losebox != null ) { // remove old box first this.losebox.div.remove(); } var m = new Modal( 'Time ran out :(', 'The time ran out! :( Click <strong>NEW GAME</strong> to start over.' ); var btnNew = m.addbutton("New Game"); // set binds btnNew.on('click', function() { m.div.remove(); m.hide(); game.start(); }); m.show(); this.losebox = m; // TODO fix the bug where if you force close the modal window (remove hash // from the URL) you can continue playing the game as normal :/ }); /** * Find all valid paths between any two blocks of the same type across entire * board */ GameBoard.method('find_paths', function() { this.paths = {}; // check the paths for every block still on the board for (var typeid in this.blocks_by_type) { var blocks = this.blocks_by_type[typeid]; if (blocks.length > 1) { for (var index in blocks) { var pos = blocks[index]; var curblock = this.blocks[pos[0]][pos[1]]; if (curblock.type != BLOCK_BLANK_TYPE_ID) { var paths = Gameboard__find_path(this, curblock); $.extend(this.paths, paths); } } } } // see how many paths we have, if we don't have any, we need to repopulate // the board or we've won if ( Object.keys(game.paths).length == 0 ) { if ( this.num_blocks_left == 0 ) { this.do_win(); } else { // no moves left this.repopulate(); } } }); /** * Remove the specified block from the gameboard and replace with a blank tile */ GameBoard.method('remove_block', function(block) { // update board vars var pos = this.blocks_by_type[block.type]; for (var index in pos) { var curpos = pos[index]; if (curpos[0] == block.x && curpos[1] == block.y) { delete this.blocks_by_type[block.type][index]; break; } } this.num_blocks_left = this.num_blocks_left - 1; // remove from board block.deselect(); block.clear(); }); /** * Find all valid paths originating from the given block * * Basically just a brute force search...it's slow but shouldn't be too bad * since we've got a pretty small board */ var Gameboard__find_path = function(board, block) { // movement directions [x, y] // assumes grid starts top left, x expands to right and y expands to bottom var _up = [0, -1]; var _down = [0, 1]; var _left = [-1, 0]; var _right = [1, 0]; var _none = [0, 0]; var M_UP = 0; var M_DOWN = 1; var M_LEFT = 2; var M_RIGHT = 3; var M_NONE = 4; // arr[Block()][Block()] -> Shortest path between the two blocks as an // array of Block()'s in between, including the starting and ending blocks var valid_path = {}; var all_nodes = []; // [Block(), ...] for (var idx in board.blocks) { for (var idy in board.blocks[idx]) { all_nodes.push(board.blocks[idx][idy]); } } // check the give pos[x,y] is within game board bounds var is_in_bounds = function(pos) { return ( pos[0] >= 0 && pos[0] < board.cols && pos[1] >= 0 && pos[1] < board.rows ); }; // the actual brute force path finding var do_pathfinding = function( node, last_move, turns_left, nodes_left, cur_path) { // no movement left if ( turns_left < 0 ) return []; // encountered same block if ( block.type == node.type && block !== node ) { if ( !(block.bID in valid_path) ) { valid_path[block.bID] = {}; } if ( !(node.bID in valid_path[block.bID]) ) { valid_path[block.bID][node.bID] = cur_path; } else { // only replace if shorter var len = valid_path[block.bID][node.bID].length; if ( len > cur_path.length ) { valid_path[block.bID][node.bID] = cur_path; } } return cur_path; } // encounter non empty block of different type if ( node.type != BLOCK_BLANK_TYPE_ID && block !== node ) return []; var cur_pos = [node.x, node.y]; // get new positions var top_pos = [cur_pos[0] + _up[0], cur_pos[1] + _up[1]]; var bot_pos = [cur_pos[0] + _down[0], cur_pos[1] + _down[1]]; var lef_pos = [cur_pos[0] + _left[0], cur_pos[1] + _left[1]]; var rig_pos = [cur_pos[0] + _right[0], cur_pos[1] + _right[1]]; var res_top = []; var res_bot = []; var res_lef = []; var res_rig = []; // check each top/bot/left/right if ( is_in_bounds(top_pos) && last_move != M_DOWN ) res_top = do_move(top_pos, M_UP, nodes_left, last_move, turns_left, cur_path); if ( is_in_bounds(bot_pos) && last_move != M_UP ) res_bot = do_move(bot_pos, M_DOWN, nodes_left, last_move, turns_left, cur_path); if ( is_in_bounds(lef_pos) && last_move != M_RIGHT ) res_lef = do_move(lef_pos, M_LEFT, nodes_left, last_move, turns_left, cur_path); if ( is_in_bounds(rig_pos) && last_move != M_LEFT ) res_rig = do_move(rig_pos, M_RIGHT, nodes_left, last_move, turns_left, cur_path); var res = []; if (res_top.length > 0) res.push(res_top); if (res_bot.length > 0) res.push(res_bot); if (res_lef.length > 0) res.push(res_lef); if (res_rig.length > 0) res.push(res_rig); return res; }; // recurse do_pathfinding at the new_pos var do_move = function(new_pos, _move, nodes_left, last_move, turns_left, cur_path) { var top_block = board.blocks[new_pos[0]][new_pos[1]]; var top_nodes_left = nodes_left.slice(0); var top_node_del_idx = top_nodes_left.indexOf(top_block); delete top_nodes_left[top_node_del_idx]; var top = do_pathfinding( top_block, _move, (last_move == _move || last_move == M_NONE) ? turns_left : turns_left - 1, top_nodes_left, cur_path.concat(top_block) ); return top; } var paths = do_pathfinding(block, M_NONE, 2, all_nodes, [block]); return valid_path; }; /** * Select the block at the given x/y if possible */ GameBoard.method('select_block', function(x, y) { var curblock = this.blocks[x][y]; // ignore empty blocks if (curblock.type == BLOCK_BLANK_TYPE_ID) return; // check if a block is already selected if ( this.selected == null ) { // nothing selected curblock.select(); this.selected = curblock; } else { // something selected // if it's the same one, then deselect and return if ( this.selected == curblock ) { curblock.deselect(); this.selected = null; return; } // otherwise, check to see if type's match before we do anything // if they do, then we'll see if there is a valid path between the // two and remove them from the board if ( this.selected.type == curblock.type ) { if (this.selected.bID in this.paths) { console.log("Paths exist for pre-selected item..."); var paths = this.paths[this.selected.bID]; if ( curblock.bID in paths ) { console.log("and a path between the two clicked!", paths[curblock.bID]); for (var index in paths[curblock.bID]) { var b = paths[curblock.bID][index]; b.highlight(); } this.remove_block(this.selected); this.remove_block(curblock); this.selected = null; this.scorebox.addScore(); this.find_paths(); return; } } } // otherwise, we just simply select the new block this.selected.deselect(); curblock.select(); this.selected = curblock; } }); /** * Similar to populate(), but replaces only existing non empty tiles. Will also * re-evaluate paths. */ GameBoard.method('repopulate', function() { this.populate(this.start_cols, this.start_rows, num_block_types, false); this.find_paths(); }); /** * Pseudo-randomly populate the game board with specified # cols/rows. * * Tries to make sure all the blocks are pairs. Should be fine as long as: * (start_cols * start_rows) % 2 == 0 */ GameBoard.method('populate', function (start_cols, start_rows, num_types, fresh) { var x = 0; var y = 0; var id = 0; var padding_x = (this.cols - start_cols) / 2; var padding_y = (this.rows - start_rows) / 2; var types_used = { // type_id -> [[x,y], [x,y], ...] }; // pass 0: // create random distribution of blocks for (x = 0; x < this.cols; x++) { if (fresh) this.blocks[x] = {}; for (y = 0; y < this.rows; y++) { if (fresh) { this.blocks[x][y] = null; } else if (this.blocks[x][y].type == BLOCK_BLANK_TYPE_ID) { // if this is an empty block type, we skip it continue; } var xdelta = x - padding_x; var ydelta = y - padding_y; var curblocktype = BLOCK_BLANK_TYPE_ID; if ( xdelta >= 0 && xdelta < start_cols && ydelta >= 0 && ydelta < start_rows ) { curblocktype = Math.floor((Math.random() * num_types)) % num_types; } if (!(curblocktype in types_used)) types_used[curblocktype] = []; types_used[curblocktype].push([x, y]); } } this.blocks_by_type = GameBoard__fix_block_pairings(this, types_used, fresh); }); var GameBoard__fix_block_pairings = function(board, types_used, fresh) { // pass 1: // compile list of odd numbered length keys var odds = []; for (var key in types_used) { if (types_used[key].length % 2 != 0) { odds.push(key); } } // add one from the odds to another odd, remove both from list while (odds.length > 0) { var oddid_1 = odds.pop(); var oddid_2 = odds.pop(); var loc1 = types_used[oddid_1].pop(); types_used[oddid_2].push(loc1); } // pass 2: // finally create/display blocks for (var key in types_used) { for (var index in types_used[key]) { var val = types_used[key][index]; var x = val[0]; var y = val[1]; if (fresh) { board.blocks[x][y] = new Block(board.blockcontainer, board.radius, x, y, key); if ( key != BLOCK_BLANK_TYPE_ID ) board.num_blocks_left = board.num_blocks_left + 1; } else { board.blocks[x][y].changetype(key); } } } return types_used; }; GameBoard.method('reset', function (scorereset) { if ( scorereset == null ) scorereset = true; // currently selected block as Block() if any this.selected = null; // array in format // arr[xpos][ypos] -> Block() this.blocks = {}; // Block().type -> [[x,y], [x,y], ...] this.blocks_by_type = {}; // All the paths between any valid pair // arr[Block().bID][Block().bID] -> [Block(), Block(), ..., Block()] // Note that the starting element is of the first block and ending element // is the second, inclusive this.paths = {}; // counter for how many non blank blocks are left on the board this.num_blocks_left = 0; // modal box to display when you win a round this.winbox = null; if ( scorereset ) this.scorebox.reset(); });<file_sep>/* * Generate random bokeh bg dawg * * NOTE: this version requires jQuery */ function BokehBG(parentid) { this.parentid = parentid; this.parentnode = null; this.numcolors = 5; // bokeh_color_[1,5] this.numsizes = 7; // bokeh_size_[1,7] this.numanim = 7; // bokeh_anim_[1,5] // max offset in px this.offset_x = screen.width / 5; this.offset_y = screen.height / 5; // this is the step for the number of points we're going to generate along // the curve... at each step we place a random bokeh near the point // // the smaller this number, the more bokeh.. essentially you get // x / res = # of points along the line this.res = 25; // how many frames to spread the animations out over for the base size of // a sphere (i.e. size=1) this.animlength = 200; // how many ms to wait between each frame this.animrate = 50; this.bokehs = []; /* init */ this.parentnode = $(parentid); console.log('this.parentnode', this.parentnode); this.go(); } BokehBG.method('reset', function () { /** * REMAKE all the bokeh! */ for (var index in this.bokehs) { var cb = this.bokehs[index]; cb.remove(); } this.go(); }); BokehBG.method('go', function () { /** * Make all the bokeh! */ // the idea is to generate a sine wave stretched across the users monitor // display width and height, and then place bokeh elements along it // could probably make this code a hell of a lot more efficient...but // doesn't really matter much; it takes longer to render everything than it // does to make these calcs... var x = screen.width; var y = screen.height; var sV = Math.round(x / Math.sin(1), 1); // Math.sin(p1) (bottom left) p1=4.71238898038469 // -> to -> // Math.sin(p2) (top right) p2=7.853981633974483 // var p1 = 3 * Math.PI / 2; // var p2 = 5 * Math.PI / 2; // Math.sin(p1) (top left) // -> to -> // Math.sin(p2) (bottom right) var p1 = Math.PI / 2; var p2 = 3 * Math.PI / 2; var res = this.res; var stepsize = (p2 - p1) / x * res; var numstep = x / res; var pts = []; var start = p1; var xbase = x / numstep; var y2 = (y / 2); for (var i = 0; i < numstep; i++) { var n = [ xbase * i, ((y2 * Math.sin(p1 + (stepsize * i))) - y2) * -1 ]; pts.push(n); } this.bokehs = []; for (var index in pts) { var cp = pts[index]; var cpx = cp[0]; var cpy = cp[1]; this.create_at(cpx, cpy); } }); BokehBG.method('create_at', function (x, y) { /** * Make one bokehs at the given x/y co-ordinates :o */ var b = $('<div />'); b.id = 'bokeh_' + x; b.addClass('bokeh'); // choose random color var cnum = Math.round(Math.random() * (this.numcolors - 1)) + 1; b.addClass('bokeh_color_' + cnum); // choose random size var snum = Math.round(Math.random() * (this.numsizes - 1)) + 1; b.addClass('bokeh_size_' + snum); // choose random animation ///* too slow :( looks really cool though :o if ( Math.random() > .5 ) { var anum = Math.round(Math.random() * (this.numanim - 1)) + 1; b.addClass('bokeh_anim_' + anum); } //*/ // apply positioning var xoff = Math.round(Math.random() * this.offset_x) * (Math.random() > 0.5 ? 1 : -1); var yoff = Math.round(Math.random() * this.offset_y) * (Math.random() > 0.5 ? 1 : -1); b.css('top', Math.round(y + yoff) + "px"); b.css('left', Math.round(x + xoff) + "px"); this.bokehs.push(b); this.parentnode.append(b); });<file_sep>var game = null; /** CSS styles for each sphere color available */ var num_block_types = 16; var block_types = { '-1' : 'block0', '0' : 'block1', '1' : 'block2', '2' : 'block3', '3' : 'block4', '4' : 'block5', '5' : 'block6', '6' : 'block7', '7' : 'block8', '8' : 'block9', '9' : 'block10', '10' : 'block11', '11' : 'block12', '12' : 'block13', '13' : 'block14', '14' : 'block15', '15' : 'block16' };<file_sep>/* Create a new modal dialog with the given title and contents */ function Modal(title, contents, hashID) { this.div = null; this.eTitle = null; this.eContents = null; this.eButtons = null; this.txttitle = title; this.txtcontents = contents; this.hashID = hashID; // true iff the modal window is being displayed this.displayed = false; var generateHash = function(length) { // generate a random hex hash of given length var h = []; for (var i=0; i<length; i++) h.push((Math.random()*16|0).toString(16)); return h.join(""); }; /* init */ if ( hashID == null ) this.hashID = "modal" + generateHash(5); if ( this.txttitle == null ) this.txttitle = ""; if ( this.txtcontents == null ) this.txtcontents = "<br />"; // generate the elements for our modal this.div = $('<div />'); this.div.data('themodal', this); this.div.attr('id', this.hashID); this.div.addClass('modal'); var container = $('<div />'); this.container = container; this.div.append(container); this.container.addClass('mcontainer'); var eTitle = $("<h1 />"); this.eTitle = eTitle; this.eTitle.html(this.txttitle); this.container.append(eTitle); var eContents = $("<div />"); this.eContents = eContents; this.container.append(eContents); eContents.addClass('mcontent'); eContents.html(this.txtcontents); var eButtons = $("<div />"); this.eButtons = eButtons; this.container.append(eButtons); eButtons.addClass('mbuttons'); $("body").append(this.div); } Modal.method('addbutton', function (text, link, title) { /** * Add a button to this window */ if ( link == null ) link = '#'; if ( title == null ) title = text; var btn = $("<a />"); this.eButtons.append(btn); btn.attr('href', link); btn.attr('title', title); btn.html(text); return btn; }); Modal.method('show', function () { /** * Display this modal window */ location.hash = this.hashID; this.displayed = true; }); Modal.method('hide', function () { /** * Hide this modal window */ location.hash = ''; this.displayed = false; });<file_sep>QQ-Lianliankan ============== My version of the game found here http://www.g12345.com/2042.html <file_sep>BLOCK_BLANK_TYPE_ID = -1; function Block(parentnode, radius, x, y, type) { this.parentnode = parentnode; this.radius = radius; this.x = x; this.y = y; this.type = type; this.bID = Block__getID(x, y, type); this.div = null; this.o = null; this.create(); this.is_selected = false; } var Block__getID = function(x, y, type) { return [x,y,type].join("|"); } var Block__onDivClick = function(e) { var $this = $(e.currentTarget).data('block'); console.log('click', e, 'pos', $this.x, $this.y); if ($this.type != -1) { console.log('not a blank tile'); game.select_block($this.x, $this.y); } }; Block.method('clear', function () { this.o.fadeOut(); this.o.removeClass(block_types[this.type]); this.type = BLOCK_BLANK_TYPE_ID; this.bID = Block__getID(this.x, this.y, this.type); this.o.addClass(block_types[this.type]); }); Block.method('changetype', function (newtype) { this.o.removeClass(block_types[this.type]); this.type = newtype; this.bID = Block__getID(this.x, this.y, this.type); this.o.addClass(block_types[this.type]); }); Block.method('select', function () { this.is_selected = true; this.div.addClass('selected'); }); Block.method('deselect', function () { this.is_selected = false; this.div.removeClass('selected'); }); Block.method('highlight', function () { this.div.addClass('pathway'); var Block__highlight__removeClass = function(block) { block.div.removeClass('pathway'); } var $this = this; this.timer = window.setTimeout(function() { Block__highlight__removeClass($this); }, 200); }); Block.method('hint', function () { this.div.addClass('hint'); if ( this.is_selected ) this.div.removeClass('selected'); var Block__hint__removeClass = function(block) { block.div.removeClass('hint'); if ( block.is_selected ) block.div.addClass('selected'); } var $this = this; this.timer = window.setTimeout(function() { Block__hint__removeClass($this); }, 600); }); /** * Create the block at its current x/y/type */ Block.method('create', function () { // positioning div var div = $("<div />"); this.parentnode.append(div); div.addClass('block'); div.addClass('col' + this.x); div.addClass('row' + this.y); // image block itself var o = $("<div />"); o.addClass(block_types[this.type]); // set in index.js div.append(o); this.div = div; this.o = o; div.data('block', this); o.data('block', this); // bind events div.on('click', Block__onDivClick); });
80ac6af60b5fa9fb79b38001a4a4b802e7bdec98
[ "JavaScript", "Markdown" ]
7
JavaScript
ootz0rz/QQ-Lianliankan
a53be9a965c9a0745ddd8cc87c0273ae8cea98d8
f18f1fe4829e1a6621391eb64d45e66428a8bc6d
refs/heads/master
<repo_name>apechir/recursive-stack<file_sep>/src/MyStack.java public class MyStack { private Node top; private int capacity; public MyStack() { this.top = null; this.capacity = 0; } public boolean isEmpty() { return top == null; } public void push(int value) { Node aux = new Node(value, this.top); this.top = aux; this.capacity++; } public int pop() { int num; if (this.isEmpty()) { System.out.println("Error: Stack is empty!"); num = -9999; } else { num = this.top.getValue(); this.top = this.top.getNext(); this.capacity--; } return num; } public int peek() { int valor; if (this.isEmpty()) { System.out.println("Error: Stack is empty!"); valor = -9999; } else { valor = this.top.getValue(); } return valor; } public void removeTop() { if (this.isEmpty()) { System.out.println("Error: Stack is empty!"); } else { this.top = this.top.getNext(); this.capacity--; } } public int getCapacity() { return this.capacity; } public void printContents() { Node aux = this.top; System.out.println("Stack contents:"); while (aux != null) { System.out.println(aux.getValue()); aux = aux.getNext(); } System.out.println("END"); } } <file_sep>/README.md # recursive-stack These are some recursive algorithms I made for stacks in Java. I use generic **Stack** and **Node** classes that I didn't make. The abstract data type was implemented with linked lists. ## This project includes: * **sumN:** Method which sums the first _n_ elements from the given stack. * **copy:** Method which makes a copy of the given stack, leaving the original untouched.
02abd0a2af9bdb29a9bfaf4138c0f9305e5d622e
[ "Markdown", "Java" ]
2
Java
apechir/recursive-stack
5dca9b888f1379c395b54bf4df3327f4ee2706b0
0953746dd623ec63af1507710fe8e95a5db5bb2f
refs/heads/master
<repo_name>daydaystudylab/Hi-Vim<file_sep>/doc/句型.md #### 句型 - (某人)は (某人2)に (物)を あげます 某人给某人2某物,**只能用在给别人东西时** 只能近的给远的 - (某人)は 私に (物)を くれます 某人给我什么。可以理解为跟别人要什么东西(还有主动索要的意思) - (接受方)は (给予方)に/から (物)を  もらいます もらう 类似中文的“得到” 某人从他人那里得到了什么东西,强调得到 ​ に:在这里表示被施予操作的对象 - 备注:くれる一般用在别人给我东西时,但是如果别人是给我身边很亲近的人(如兄弟姐妹)还是用くれる句型 #### 例句 - 山田(やまだ)さんは 木村(きむら)に 花(はな)を あげます 山田送花给木村 - 木村さんは 山田さんに 花を もらいました 木村收到了山田送的花 - 友達(ともだち)は 私に チコレートを くれます 我向朋友要巧克力<file_sep>/doc/Windows 下 Vim 安装.md ### Vim 安装以及打开、保存文件 #### 命令行版 #### GUI版 Windows 下的 GUI 版 Vim 叫 Gvim,这里讲 Gvim 的安装。 在 Vim 官网下载 Gvim,在[官网](http://www.vim.org/download.php#pc)找到 `PC: MS-DOS and MS-Windows`,下载 `gvim74.exe`(当前最新版本的7.4)。 ![](https://o8l6oohcu.qnssl.com/hi-vim:install.png) 然后像普通 Windows 软件一样安装即可,可以修改安装位置,也可以选择默认。安装完成后会出现三个快捷方式。 ![](https://o8l6oohcu.qnssl.com/hi-vim:win-install.png) 区别如下: > gvim74 正常模式标准的VIM(正常开发的时候用); > > gvim read-only 只读模式的VIM(防误删误改方便查阅代码); > > gvim easy 启动的时候是insert模式,适合普通windows用户的习惯; 这里我们说的 Vim 都是第一个。 ### macOS 下 Vim 安装 #### 桌面版 Mac 下的桌面版有 [MacVim](http://macvim-dev.github.io/macvim/) 和 [Vimr](http://vimr.org/),都是可以直接下载安装的。 #### 命令行版 macOS 自带 Vim,只是版本一般都会落后最新版不少,如果不介意这个问题可以直接使用 Mac 自带的 Vim。 同时如果像装最新的 Vim,推荐使用 [brew](http://brew.sh/index_zh-cn.html) 安装。先安装好 brew,然后执行下面的语句即可。 ```shell Laily@Laily:~|⇒ brew search vim macvim pacvim vim ✔ vimpc neovim/neovim/neovim ✔ pyvim vimpager Caskroom/versions/macvim-kaoriya Laily@Laily:~|⇒ brew install vim ``` ### Linux 下 Vim 安装 #### 桌面版 #### 命令行版 使用 yum,apt-get 等工具直接安装。 <file_sep>/controller/hivim.go package controller import ( "github.com/labstack/echo" "net/http" ) func Index(c echo.Context) error { return c.Render(http.StatusOK, "index.html", nil) } func InteractiveIndex(c echo.Context) error { return c.Render(http.StatusOK, "openvim/index.html", nil) } <file_sep>/static/Gulpfile.js var gulp = require('gulp'), less = require('gulp-less'), minifyCSS = require('gulp-minify-css'), gulpUtil = require('gulp-util'), uglify = require('gulp-uglify'); gulp.task('less', function () { gulp.src('css/**/*.less') .pipe(less()) .pipe(gulp.dest('build/css/')); }); //// 压缩 css //gulp.task('css',function(){ // gulp.src('public/stylesheets/user/share/index.css') // .pipe(minifyCSS()) // .pipe(gulp.dest('public/stylesheets/user/share/')) //}); gulp.task("js", function(){ gulp.src("js/**/*.js") .pipe(uglify().on("error",gulpUtil.log)) .pipe(gulp.dest("build/js/")); }) gulp.task("w", function () { gulp.watch("css/**/*.less", ['less']); }); <file_sep>/server.go package main import ( "github.com/Hi-Vim/Hi-Vim/router" ) func main() { e := router.Init() e.Start(":4004") } <file_sep>/doc/02.打开 Vim.md 只将保存命令`:w`,在普通模式下输入`:`会 ### GUI 版 Vim 打开/关闭文件 ### 命令行版 Vim 打开文件 首先进入命令行。 Windows 需要进 Linux 直接进入终端,输入`vim`回车。 打开 Vim 界面是这样的(不同平台下显示有稍微的区别,但是大体都是一样的) ![](http://o8l6oohcu.qnssl.com/hi-vim:install-vim-open.png) 注意这时 Vim 底部是没有任何提示文字的,这时按`:`键后会变成这样 ![](http://o8l6oohcu.qnssl.com/hi-vim:install-command.png) 底部出现`:`提示符之后就表示可以在这里输入一些命令了,这里我们只是简单介绍打开/新建文件和保存/关闭文件的命令,更详细的内容会在后面的文章中给出。 此时在`:`后输入 `e a.txt`,`e`这个命令表示`edit`,这样就能打开当前目录(即在命令行中开启vim时命令行所在的目录)下的`a.txt`文件,如果`a.txt`不存在 Vim 则会创建该文件。<file_sep>/doc/### 开始编辑吧,移动光标新技巧.md ### 开始编辑吧,移动光标新技巧 #### 方向键的替换 我们已经知道了如何进入编辑模式编辑文章,编辑完如何保存。但是在这之中有个小细节需要不断练习以适应 Vim 的法则。**Vim 中使用 h, j, k, l 代替方向键**。因为方向键离键盘主操作区太远,所以选中了这四个键来代替方向键。 四个键分别代替什么方向了,我是这么记的。`h`,`l` 分别位于这四个键的左右,所以分别用于向左向右移动,`j`下面有个勾,所以`j`表示向下移动,剩余的`k`就是向上移动了。在开始练习的时候可以这样记,然后不断练习,让手指记住这个操作。 开始的时候会觉得很繁琐,编辑时要移动光标,需要切换到普通模式然后按hjkl,切换完又要按i键进入插入模式继续编辑。我们需要不断练习来适应这种操作方式,在以后的使用中就能感受到它的便捷。所以强烈建议**在 Vim 中不要使用键盘区的方向键**。 #### 单词级别的移动 刚刚的`h`, `j`, `k`, `l`可以移动光标,每次移动一个字符,有的时候显然会觉得移动的太慢,所以 Vim 提供了单词级别的光标移动`w`, `b`, `e`。 w 移动到下一个单词的词首。 b 移动到上一个单词的词首。 e 移动到下一个单词的词尾。 同时 `W`, `B`, `E`也有类似的效果,不过 `W`, `B`, `E`并不是一个一个单词间移动,而是在以空白字符间隔的字串之间移动。 ![](http://o8l6oohcu.qnssl.com/hi-vim:move-0.png) 如上图所示,小写的命令的移动以 Vim 认为的单词为单位,`between`是一个单词,按一次`w`键光标就移动到`w`,再按一次`w`则移动到下一个认为是单词的字符`,`;而大写的命令则以空白字符分隔的字串为单位,`between`为一个字串,`w,b,e`为第二个字串,所以第二次按`W`之后就会到第三个字串`and`的开头了。 另外,配置文件里的`iskeyword`选项可以改变 Vim 认为是单词组成部分的字符。 #### 移动到行首或者行尾 通常我们用`^`和`$`分别来将光标移动到当前行的行首或者行尾。 另外还有一个`0`命令也可以将光标移动到行首。 这两个命令的区别是`^`将光标移动到该行的第一个非空字符,而`0`则完全的移动到该行的第一个字符。 ``` ^ <------------ .....This is a line for example <----------------- ---------> 0 $ "....."表示行首的空白字符 ``` <file_sep>/README.md # hi-vim [![Build Status](https://travis-ci.org/hi-vim/hi-vim.svg?branch=master)](https://travis-ci.org/hi-vim/hi-vim) [![Gitter](https://badges.gitter.im/hi-vim/hi-vim.svg)](https://gitter.im/hi-vim/hi-vim?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge) 一个用来介绍 VIM 的网页 ## 网站结构 网站使用Golang 的 Echo 框架开发 ## 感谢🙏 [openvim](https://github.com/egaga/openvim) 项目 [vim-awesome](https://github.com/vim-awesome/vim-awesome) 项目 <file_sep>/doc/01.vim的模式.md ### 新建一个文件试试看——Vim的模式介绍 Vim 与普通编辑器最大的不同就是它具有多种编辑模式,在插入模式(INSERT)下用于类似与普通编辑器的编辑修改。在普通模式下可以使用指令快捷的进行一些快捷的操作,而不需要使用到鼠标。 #### 新建 打开 Vim 界面显示如下 ![](http://o8l6oohcu.qnssl.com/hi-vim:install-vim-open.png) 注意:以`~`开始的行表示该行在原文件中不存在。 这个时候我们使用`:e [path/filename]`命令来新建/打开一个文件。 首先输入`:`,你会发现 Vim 把光标移动到了窗口的最后一行。像这样 ![](http://o8l6oohcu.qnssl.com/hi-vim:install-command.png) 这里被称为输入“冒号命令”(以冒号开头的命令)的地方。然后回车结束命令输入并执行命令。 比如我们输入`e ./a.txt`,该命令将会在当前目录下新建`a.txt`文件(不知道当前目录在哪里,请看这里?),如果当前目录有`a.txt`这个文件,Vim则会打开该文件。 ![](http://o8l6oohcu.qnssl.com/hi-vim:create-file-1.png) ![](http://o8l6oohcu.qnssl.com/hi-vim:create-file-2.png) 如上图底部显示的文字即表示创建了这样一个新文件。 #### 编辑 然后按`i`键,界面会变成这样 ![](http://o8l6oohcu.qnssl.com/hi-vim:insert-1.png) 在底部出现了“INSERT”字样。这个时候就和想记事本那样直接输入内容了。 ![](http://o8l6oohcu.qnssl.com/hi-vim:insert-2.png) #### 保存 输入完了我们想要保存怎么办了?保存的命令是`:w`,但是这个时候我们不能直接输入“:w”,那样的话会输入到当前文本。需要先按一下`<ESC>`(即键盘左上角到键),让底部的“INSERT”字样消失(如果按一次<ESC>,字样没有消失,可以再按一次)。在然后输入":w"命令即可。 ![](http://o8l6oohcu.qnssl.com/hi-vim:save-1.png) 保存成功,底部提示 27 个字符被写入。如果需要退出 Vim 则使用`:q` 命令即可。 #### 普通模式(NORMAL)和插入模式(INSERT) 刚刚我们简单的创建了一个文件。 其中我们涉及到了 Vim 最重要的一个特性——模式。Vim 是一个多模式编辑器。刚打开 Vim 的时候处于`普通模式(NORMAL)`(也有叫做命令模式的),这个时候可以输入很多命令,比如我们使用的`:e`,`:w`,`:q`这些。在这个模式下,键盘的上的按键并不是用于字符,而是执行各种操作。然后我们按了`i`之后则进入了`插入模式(INSERT)`,插入模式下在 Vim 的底部有"INSERT"的文字提示。插入模式下的 Vim 就和记事本差不多了,按键盘上的按键则输入相应字符。 其中在普通模式`i`可以进入插入模式,插入模式下按`<ESC>`回到普通模式。 #### 普通模式进入插入模式的方法 除了上面的使用`i`键进入插入模式还有其他的方法,我把它简单记作 AISO(a is o),下面挨着分析它们的用法(所有按键大小写功能都不同)。 - a:会让光标向后移动一个字符,然后进入插入模式。 如普通模式下显示的内容是这样”abc[d]ef“,光标在字符d上,按下a后会成为这样"abcd[e]f"并进入到插入模式,如果你此时输入g,则显示成这样“abcdg[e]f”。即当你需要在当前位置的后面插入字符时,可以按a进入插入模式。 A:会将光标移动该行的最后一个字符后面,然后进入插入模式。当你需要在行尾插入字符时可以选中A。 - I (Insert) i:直接进入插入模式,光标不变。最常用的操作,当你需要在当前位置插入字符的时候,使用i。 I:光标移动到该行第一个非空白字符,然后进入插入模式。与A的功能相反。 - S (Substute) s: 会删除掉当前光标所在的字符,然后进入插入模式。 S: 会删除掉当前光标所在的行,然后进入插入模式。 - O o: 在当前行下侧开启新的一行,光标位于行首,进入插入模式。 O:在当前行上侧开启新的一行,光标位于行首,进入插入模式。 #### 退回普通模式 如何从插入模式返回到普通模式,最常用的是按 `<ESC> `键,另外`CTRL+[`也可以。 注意:有时候按一次<ESC>无法返回普通模式,比如在试图模式(这个以后会讲到)下,一般是因为当前还有其他正在进行中的操作,这个时候多按几次先退出当前操作,然后就可以回到普通模式了。 <file_sep>/doc/目录.md ### 基础目录 1. 安装 2. 光标的移动 单词级别的移动 3. 深入了解插入模式 4. 替换修改 r 5. 删除 6. 复制,剪切,粘贴 7. 统计修改和跨行 8. 查找和替换 9. 使用窗口和标签页 10. 标记文件 11. 同步 12. 冒号设置 1. Preface 2. Introduction 3. Installation 4. First Steps 5. Modes 6. Typing Skills 7. Moving Around 8. Help 9. Editing Basics 10. More Editing 11. Multiplicity 12. Personal Information Management ​ 13. Scripting 14. Plugins 15. Programmers Editor 16. More 17. What Next 18. Feedback 19. Charityware 20. Colophon 21. Versions <file_sep>/router/router.go package router import ( "github.com/Hi-Vim/Hi-Vim/controller" "github.com/MarcusMann/pongor-echo" "github.com/labstack/echo" ) // Init 用于初始化 func Init() *echo.Echo { e := echo.New() r:= pongor.GetRenderer() e.Renderer = r e.Static("/static", "static/build/") e.Static("/js", "static/build/js/") e.Static("/css", "static/build/css/") e.Static("/img", "static/img/") e.GET("/", controller.Index) e.GET("/interactive/index", controller.InteractiveIndex) return e } <file_sep>/doc/ref.md 参考资料 ​ youtube 视频 ​ 官方文档
3079c2a15fbdfdc848d6c14207c3fcb0264faeb8
[ "Markdown", "JavaScript", "Go" ]
12
Markdown
daydaystudylab/Hi-Vim
0695bc694755cc74272ba6e508e31eb6694f4824
cef5f58dc32330de533ec0da0759760c8022299f
refs/heads/master
<file_sep># DirectoryStructure ## 输出指定文件夹下面的文件结构。</br> 输入路径,输出此路径下面的所有子文件夹、文件清单。</br> 可将此清单以"yyyyMMddHHmmssffff_文件夹目录结构"命名的TXT格式保存在输入路径下面。</br> ## 示例:</br> `Please enter a path:`</br> ![](https://github.com/MRZ1514/DirectoryStructure/blob/master/ScreenShot01.png)</br> `The file directory is loaded!Press 'Y' to save,press 'N' to exit!` <file_sep>using System; using System.Text; using System.IO; namespace GenDir { class Program { static int j = 1; static StringBuilder sb = new StringBuilder(); static void Main(string[] args) { //测试D:\ Console.WriteLine("Please enter a path:"); string path = Console.ReadLine(); if (!string.IsNullOrWhiteSpace(path)) { GenFileStructure(path, j); } Console.WriteLine("The file directory is loaded!Press 'Y' to save,press 'N' to exit!"); ConsoleKeyInfo key = Console.ReadKey(); if (key.Key == ConsoleKey.Y) { File.WriteAllText(Path.Combine(path, DateTime.Now.ToString("yyyyMMddHHmmssffff") + "_文件夹目录结构.txt"), sb.ToString(), Encoding.UTF8); } else if (key.Key == ConsoleKey.N) { Environment.Exit(0); } } static void GenFileStructure(string path, int index) { try { bool isDirectory = IsDirectory(path); if (isDirectory) { string[] entries = Directory.GetFileSystemEntries(path); if (entries.Length > 0) { foreach (var v in entries) { Console.WriteLine(string.Format(new string('.', index) + "{0}", Path.GetFileName(v))); sb.Append(string.Format(new string('.', index) + "{0}\r\n", Path.GetFileName(v))); if (IsDirectory(v)) { ++j; GenFileStructure(v, j); j--; } } } } else { Console.WriteLine(path); sb.Append(path + "\r\n"); } } catch (Exception ex) { Console.WriteLine(ex.Message); } } static bool IsDirectory(string path) { FileAttributes fi = File.GetAttributes(path); if (fi==FileAttributes.Directory|| fi == (FileAttributes.ReadOnly|FileAttributes.Directory)) { return true; } else { return false; } } } }
2e5d1c29ed55d87d9eb1136f9c057232f41893db
[ "Markdown", "C#" ]
2
Markdown
MRZ1514/DirectoryStructure
5ae98decad34cde8a0a139b8e3ca4058fde0ee92
0687e9b272bd969adbeb7e57250200aec789284b
refs/heads/master
<repo_name>llanTang/create-data-randomly<file_sep>/main.cpp // // main.cpp // create Big Data Randomly // // Created by <EMAIL> on 17/1/18. // Copyright © 2018 <EMAIL>. All rights reserved. // #include <iostream> #define MAX_LINE_LENGTH 200 #define MAX_Record_LENGTH 60000 int main(int argc, char * argv[]) { char *data_file; int num[MAX_LINE_LENGTH]; char *token; FILE *f_in; int i,n_cases=20000; srand(time(0)); for(int i=0;i<MAX_LINE_LENGTH;i++) { num[i]=rand()%10+1; printf("%d ",num[i]); } const char *separators="\n"; data_file = argv[1]; printf("%s",data_file); f_in=fopen(data_file, "w+"); if (!f_in) { perror("Failed to open file"); exit(1); } srand(time(0)); for(unsigned int i=0;i<MAX_Record_LENGTH;i++){ for(int j=0;j<MAX_LINE_LENGTH;j++){ fprintf(f_in,"%d\t",(rand()%num[j])+1); } fprintf(f_in,"\n"); } fclose(f_in); return 0; } <file_sep>/README.md # create-data-randomly
f2432be4c331531109ca8441478ee84b03b33a43
[ "Markdown", "C++" ]
2
C++
llanTang/create-data-randomly
5f4e1246bce91b5ca65a290992bb1d1386fbd604
ff4ccbc5b4fac7f86b0def0ad4dd2b7ad4d8c05a
refs/heads/master
<file_sep>url=https://www.freecrm.com browser=chrome username=naveenk password=<PASSWORD> framename =processFrame sheetName=Sheet1<file_sep>package com.crm.qa.webpages; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.PageFactory; import com.crm.qa.base.TestBase; public class LoginPage extends TestBase { //object reporsitory(OR)/webelements @FindBy(name="username") WebElement username; @FindBy(name="password") WebElement password; @FindBy(xpath="//input[contains(@value,'Login')]") WebElement loginbtn; @FindBy(xpath="//button[text()='Sign Up']") WebElement signupbtn; @FindBy(xpath="//img[contains(@src,'https://d19rqa8v8yb76c.cloudfront.net/img/freecrm.jpg')]") WebElement freecrmlogo; //this refer the current class objects public LoginPage(){ PageFactory.initElements(driver, this); } //Actions public String validateloginpagetitle(){ return driver.getTitle(); } public boolean validatecrmlogo(){ return freecrmlogo.isDisplayed(); } public HomePage login(String un,String pswd){ username.sendKeys(un); password.sendKeys(<PASSWORD>); //login btn click JavascriptExecutor js = (JavascriptExecutor)driver; js.executeScript("arguments[0].click();",loginbtn); return new HomePage(); } } <file_sep>package com.crm.qa.webpages; public class DealsPage { } <file_sep>package com.crm.qa.testcases; import org.apache.log4j.BasicConfigurator; import org.apache.log4j.Logger; import org.testng.Assert; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import com.crm.qa.base.TestBase; import com.crm.qa.utils.Utility; import com.crm.qa.webpages.ContactsPage; import com.crm.qa.webpages.HomePage; import com.crm.qa.webpages.LoginPage; public class HomePageTest extends TestBase { LoginPage loginpage; HomePage homepage; Utility testutil; ContactsPage contactspage; public HomePageTest(){ super(); } Logger log = Logger.getLogger(HomePage.class); @BeforeMethod public void setup(){ initialization(); loginpage = new LoginPage(); homepage =loginpage.login(prop.getProperty("username"), prop.getProperty("password")); testutil = new Utility(); contactspage = new ContactsPage(); } @Test(priority=1) public void verifyHomePageTitle(){ log.info("****************************** starting test case *****************************************"); log.info("******************************VerifyHomePageTitle *****************************************"); String homepagetitle = homepage.verifyHomePageTitle(); Assert.assertEquals(homepagetitle, "CRMPRO","Homepage title is not matched"); } @Test(priority=2) public void verifyUserName(){ testutil.switchtoframe(); Assert.assertTrue(homepage.verifycorrectUserName(), "username is not matching"); } @Test(priority=3) public void verifyContactsLinkTest(){ testutil.switchtoframe(); contactspage = homepage.clickOnContactsLink(); } @AfterMethod public void teardown(){ driver.quit(); } } <file_sep>package com.crm.qa.webpages; import java.util.List; import org.openqa.selenium.By; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.PageFactory; import org.openqa.selenium.support.ui.Select; import com.crm.qa.base.TestBase; public class ContactsPage extends TestBase { @FindBy(xpath="//td[contains(text(),'Contacts')]") WebElement contactslabel; @FindBy(xpath ="//select[@name='title']/option") WebElement selectTitle; @FindBy(name="title") WebElement selecttitle; @FindBy(id="first_name") WebElement firstName; @FindBy(id ="surname") WebElement lastName; /*@FindBy(xpath="//a[text()='987654 321']//parent::td[@class='datalistrow']//preceding-sibling::td[@class='datalistrow']//input[@name='contact_id']") */ @FindBy(name ="client_lookup") WebElement Company; @FindBy(xpath="//input[@type='submit' and @value='Save']") WebElement saveBtn; public ContactsPage(){ PageFactory.initElements(driver, this); } public boolean verifyContactslabel(){ return contactslabel.isDisplayed(); } public void selectContactsCheckBox(String name){ driver.findElement(By.xpath("//a[text()='"+name+"']//parent::td[@class='datalistrow']//preceding-sibling::td[@class='datalistrow']//input[@name='contact_id']")).click(); } public void creatNewContact(String title,String firstname,String lastname,String company){ /* Select select = new Select(selectTitle); List<WebElement> listOfTitleoptions = select.getOptions(); for(WebElement titles : listOfTitleoptions){ String listTitles = titles.getText(); if(listTitles.equalsIgnoreCase(title)){ titles.click(); } }*/ Select select = new Select(selecttitle); select.selectByVisibleText(title); firstName.sendKeys(firstname); lastName.sendKeys(lastname); Company.sendKeys(company); saveBtn.click(); } } <file_sep>package com.crm.qa.webpages; public class SignupPage { }
5b0f8646aebd8470e72a080ce2e9a30e0536703d
[ "Java", "INI" ]
6
INI
sivareddy939/Pageobjectmodle
01835c185385b60bb43b2df5b0be2abe9985ce55
e23ec3dc348e4d2d60554a641ea3445e3a36cdbd
refs/heads/master
<file_sep><?xml version="1.0"?> <project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <modelVersion>4.0.0</modelVersion> <name>book-service</name> <parent> <groupId>com.spike</groupId> <artifactId>book</artifactId> <version>0.0.1-SNAPSHOT</version> </parent> <artifactId>book-service</artifactId> <properties> <mysql.version>5.1.22</mysql.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> <version>${spring.boot.version}</version> </dependency> <!-- validation start --> <!-- JSR 349: Bean Validation --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>5.0.3.Final</version> </dependency> <!-- JSR 341: Unified Expression Language --> <dependency> <groupId>javax.el</groupId> <artifactId>javax.el-api</artifactId> <version>2.2.4</version> </dependency> <dependency> <groupId>org.glassfish.web</groupId> <artifactId>javax.el</artifactId> <version>2.2.4</version> </dependency> <!-- validation end --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.version}</version> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> <version>${spring.boot.version}</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <version>${spring.boot.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> <version>${spring.boot.version}</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-redis</artifactId> <version>${spring.boot.version}</version> </dependency> <!--<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-amqp</artifactId> <version>${spring.boot.version}</version> </dependency> --> <dependency> <groupId>com.alibaba</groupId> <artifactId>dubbo</artifactId> <version>2.4.9</version> <exclusions> <exclusion> <groupId>org.springframework</groupId> <artifactId>spring</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>com.github.sgroschupf</groupId> <artifactId>zkclient</artifactId> <version>0.1</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.4</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-amqp</artifactId> <version>1.2.5.RELEASE</version> </dependency> </dependencies> <build> <finalName>book-service</finalName> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>${java.version}</source> <target>${java.version}</target> </configuration> </plugin> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <version>${spring.boot.version}</version> </plugin> </plugins> </build> </project> <file_sep># 1 Maven commands: mvn clean install -Dmaven.test.skip=true # compile mvn eclipse:clean eclipse:eclipse # build eclipse facets mvn dependency:sources -DdownloadSources=true # download resource mvn dependency:tree > tree.txt # solve dependency conflicts <file_sep>CREATE SCHEMA `books` DEFAULT CHARACTER SET utf8 ; ALTER TABLE `books`.`user` CHANGE COLUMN `update_date` `update_date` DATETIME NULL DEFAULT CURRENT_TIMESTAMP ; <file_sep># 1 Motivation As Big Data, scalable and extendable system, system with intelligence become regular words in daily development work, I found that I cannot get any understanding or usage of frameworks, such as Message Solution, NoSQL, Lucene/Solr, Hadoop, Spark, without a touchable supporting system. So I decide to build my own. Since I have recently switched to Spring-EE stack, I will use the Spring framework heavily. # 2 Schedule Under information is my current plan of the system, the phases may overlap with each other in the same time. ## Phase 1: J2EE maintain basic information of books, and borrow relationship management ## Phase 2: J2EE/Text Search book retrieval, comments and relativity relationship ## Phase 3: NoSQL reader activities and study area ## Phase 4: Semantic Web/NLP knowledge structure of book, and their semantic connections ## Phase 5: Semantic Web semantic connections of reader informations ## Phase 6: Data Analysis - the knowledge view statistic information of domain books ## Phase 7: Data Analysis - the cognition view the cognition phases of domain knowledge in a reader's view ## Phase 8: Recommendation recommend books for readers <file_sep> # 1 favicon <link rel="shortcut icon" type="image/x-icon" href="resources/images/favicon.ico" /> # 2 service access url http://localhost:8888/service/login?a=123&b=123 http://localhost:8888/service/login?params={a: 1, b: 2} # 3 UEditor configuration ## 3.1 lib/ueditor.jar \*.jar to **CLASSPATH** ## 3.2 Spring MVC controller: UeditorController cite from controller.jsp ## 3.3 ueditor.config.js // 服务器统一请求接口路径 // , serverUrl: URL + "jsp/controller.jsp" , serverUrl: "/scripts/UEditor/jsp/contorller.jsp" ## 3.4 add to local repository TODO <file_sep># 1 Motivation # 2 Architecture # 3 Progress <file_sep>mvn spring-boot:run java -jar target/book-serive.jar # JPA Repository使用注意事项 provider.xml中`initDataService`原先使用`bookCategoryRepository`注入,且`bookCategoryService`也使用`bookCategoryRepository`注入,启动时报无法初始化``bookCategoryRepository`错误。 **Solution**: 服务接口实现各依赖单个Repository,可以依赖多个服务接口<file_sep>package com.spike.book.service.impl; import java.util.HashMap; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import com.spike.book.domain.BookCategory; import com.spike.book.repository.BookCategoryRepository; import com.spike.book.service.BookCategoryService; public class BookCategoryServiceImpl implements BookCategoryService { @Autowired private BookCategoryRepository bookCategoryRepository; @Override public Map<String, Object> save(Map<String, Object> map) { Map<String, Object> result = new HashMap<String, Object>(); BookCategory bookCategory = (BookCategory) map.get("bookCategory"); bookCategory = bookCategoryRepository.save(bookCategory); result.put("bookCategory", bookCategory); return result; } @Override public Map<String, Object> findByName(Map<String, Object> map) { Map<String, Object> result = new HashMap<String, Object>(); String name = (String) map.get("name"); BookCategory bookCategory = bookCategoryRepository.findByName(name); result.put("bookCategory", bookCategory); return result; } } <file_sep>package com.spike.book.service.impl; import static com.spike.book.util.ServiceConstants.RESULT_INFO; import static com.spike.book.util.ServiceConstants.RESULT_KEY; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.validation.ConstraintViolation; import javax.validation.ConstraintViolationException; import org.springframework.beans.factory.annotation.Autowired; import com.spike.book.domain.User; import com.spike.book.repository.UserRepository; import com.spike.book.service.UserService; import com.spike.book.util.ServiceExceptionHandler; public class UserServiceImpl implements UserService { @Autowired private UserRepository userRepository; @Override public boolean existEmail(Map<String, Object> map) { boolean result = false; User user = userRepository.findByEmail(map.get("email").toString()); if (user != null) { result = true; } return result; } @Override public boolean existLoginName(Map<String, Object> map) { boolean result = false; User user = userRepository.findByLoginName(map.get("loginName").toString()); if (user != null) { result = true; } return result; } @Override public Map<String, Object> register(Map<String, Object> map) { Map<String, Object> result = new HashMap<String, Object>(); String loginName = map.get("loginName").toString(); String firstName = map.get("firstName").toString(); String lastName = map.get("lastName").toString(); String email = map.get("email").toString(); User user = userRepository.findByLoginNameOrEmail(loginName, email); if (user != null) { result.put(RESULT_KEY, false); result.put(RESULT_INFO, "用户已存在"); return result; } try { user = new User(loginName, firstName, lastName, email); user = userRepository.save(user); } catch (Exception e) { result.put(RESULT_KEY, false); if (e instanceof ConstraintViolationException) { List<String> messages = new ArrayList<String>(); for (ConstraintViolation<?> violation : ServiceExceptionHandler.handleConstraintViolation(e)) { // + violation.getMessageTemplate() + ":" messages.add(violation.getMessage() + ":" + violation.getInvalidValue()); } result.put(RESULT_INFO, messages); } else { result.put(RESULT_INFO, e); } return result; } result.put(RESULT_KEY, true); result.put(RESULT_INFO, "成功"); return result; } @Override public Map<String, Object> unregister(Map<String, Object> map) { return null; } @Override public boolean validRegisteredUser(Map<String, Object> map) { boolean result = true; String loginName = map.get("loginName").toString(); String email = map.get("email").toString(); User user = userRepository.findByLoginNameOrEmail(loginName, email); if (user != null) { result = false; } return result; } } <file_sep>package com.spike.book.config; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.ImportResource; @Configuration @ImportResource("classpath:provider.xml") public class DubboServiceConfig { } <file_sep>package com.spike.book.service; import static org.junit.Assert.*; import java.util.HashMap; import java.util.Map; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.spike.book.TestApplication; import com.spike.book.service.DemoService; @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = TestApplication.class) public class DemoServiceTest { @Autowired DemoService demoService; @Test public void sayHello() { String name = "zhoujiagen"; Map<String, Object> map = new HashMap<String, Object>(); map.put("name", name); String seriveResult = demoService.sayHello(map); String expectedResult = "Hello " + name; assertEquals(expectedResult, seriveResult); } } <file_sep>package com.spike.book.repository; import static org.junit.Assert.*; import java.util.List; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.spike.book.TestApplication; import com.spike.book.domain.User; @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = TestApplication.class) public class UserRepositoryTest { @Autowired CustomerRepository customerRepository; @Test public void create() { customerRepository.save(new User("jack", "Jack", "Bauer")); customerRepository.save(new User("chloe", "Chloe", "O'Brian")); customerRepository.save(new User("kim", "Kim", "Bauer")); customerRepository.save(new User("david", "David", "Palmer")); customerRepository.save(new User("michelle", "Michelle", "Dessler")); customerRepository.save(new User("zhoujiagen", "Zhou", "Jiagen")); } @Test public void findAll() { Iterable<User> customerIterable = customerRepository.findAll(); int count = 0; for (User customer : customerIterable) { System.out.println(customer); count++; } assertEquals(6, count); } @Test public void findByName() { List<User> customers = customerRepository.findByLastName("Bauer"); assertNotNull(customers); System.out.println(customers); } } <file_sep><?xml version="1.0"?> <project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <modelVersion>4.0.0</modelVersion> <name>book-web</name> <parent> <groupId>com.spike</groupId> <artifactId>book</artifactId> <version>0.0.1-SNAPSHOT</version> </parent> <!-- <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.2.5.RELEASE</version> </parent> --> <artifactId>book-web</artifactId> <packaging>war</packaging> <dependencies> <!-- <dependency> <groupId>com.spike</groupId> <artifactId>book-service</artifactId> <version>0.0.1-SNAPSHOT</version> </dependency> --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <version>${spring.boot.version}</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <version>${spring.boot.version}</version> <scope>test</scope> </dependency> <!-- <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> <version>${spring.boot.version}</version> </dependency> --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> <version>${spring.boot.version}</version> </dependency> <!-- <dependency> <groupId>org.springframework.boot</groupId> <artifactId> spring-boot-starter-redis</artifactId> <version>${spring.boot.version}</version> </dependency> --> <dependency> <groupId>com.alibaba</groupId> <artifactId>dubbo</artifactId> <version>2.4.9</version> <exclusions> <exclusion> <groupId>org.springframework</groupId> <artifactId>spring</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>com.github.sgroschupf</groupId> <artifactId>zkclient</artifactId> <version>0.1</version> </dependency> <!-- 验证码kaptcha --> <!-- kaptcha --> <dependency> <groupId>com.github.axet</groupId> <artifactId>kaptcha</artifactId> <version>0.0.9</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-remote-shell</artifactId> <version>1.2.5.RELEASE</version> </dependency> </dependencies> <!-- <repositories> <repository> <id>google-maven-snapshot-repository</id> <name>Google Maven Snapshot Repository</name> <url>https://m2repos.googlecode.com/svn/nexus</url> <snapshots> <enabled>true</enabled> </snapshots> </repository> </repositories> --> <build> <finalName>book-web</finalName> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>${java.version}</source> <target>${java.version}</target> </configuration> </plugin> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <version>${spring.boot.version}</version> </plugin> </plugins> </build> </project> <file_sep>package com.spike.book.service; import static org.junit.Assert.assertNotNull; import java.util.HashMap; import java.util.Map; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.context.ApplicationContext; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.spike.book.TestApplication; import com.spike.book.domain.BookCategory; @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = TestApplication.class) public class BookCategoryServiceTest { @Autowired ApplicationContext applicationContext; @Autowired private BookCategoryService bookCategoryService; @Test public void createTopBookCategory() { // Assert.assertNotNull(bookCategoryService); BookCategory bookCategory = new BookCategory(); bookCategory.setName("计算机"); System.out.println(bookCategory); Map<String, Object> map = new HashMap<String, Object>(); map.put("bookCategory", bookCategory); bookCategory = (BookCategory) bookCategoryService.save(map); System.out.println(bookCategory); } @Test public void createChildBookCategory() { Map<String, Object> map = new HashMap<String, Object>(); map.put("name", "计算机"); BookCategory parentBookCategory = (BookCategory) bookCategoryService.findByName(map).get("bookCategory"); assertNotNull(parentBookCategory); BookCategory childBookCategory = new BookCategory(); childBookCategory.setName("网络"); childBookCategory.setParentBookCategory(parentBookCategory); map = new HashMap<String, Object>(); map.put("bookCategory", childBookCategory); childBookCategory = (BookCategory) bookCategoryService.save(map).get("bookCategory"); assertNotNull(childBookCategory.getId()); } } <file_sep>package com.spike.book.domain; import java.io.Serializable; import java.util.List; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import javax.persistence.ManyToOne; import javax.persistence.Table; import javax.persistence.UniqueConstraint; /** * 图书 * * @author zhoujiagen<br/> * Jul 30, 2015 9:56:53 PM */ @Entity @Table(name = "BOOKS", uniqueConstraints = @UniqueConstraint(columnNames = { "isbn" })) public class Book extends BaseModel implements Serializable { private static final long serialVersionUID = 961084876355514712L; @Column(nullable=false) private String title;// 名称 @Column(nullable = false) private String isbn;// ISBN private String coverImageUrl;// 封面图片 private String introduction;// 简介 @ManyToOne @JoinColumn(name = "CATEGORY_ID") private BookCategory bookCategory;// 图书类别 @ManyToMany @JoinTable(name = "R_BOOK_AUTHOR", joinColumns = @JoinColumn(name = "BOOK_ID"), inverseJoinColumns = @JoinColumn(name = "AUTHOR_ID")) private List<Author> authors;// 作者 @ManyToOne @JoinColumn(name = "PRESS_ID") private Press press; public Book() { super(); } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getIsbn() { return isbn; } public void setIsbn(String isbn) { this.isbn = isbn; } public String getCoverImageUrl() { return coverImageUrl; } public void setCoverImageUrl(String coverImageUrl) { this.coverImageUrl = coverImageUrl; } public String getIntroduction() { return introduction; } public void setIntroduction(String introduction) { this.introduction = introduction; } public BookCategory getBookCategory() { return bookCategory; } public void setBookCategory(BookCategory bookCategory) { this.bookCategory = bookCategory; } public List<Author> getAuthors() { return authors; } public void setAuthors(List<Author> authors) { this.authors = authors; } public Press getPress() { return press; } public void setPress(Press press) { this.press = press; } @Override public String toString() { return "Book [title=" + title + ", isbn=" + isbn + ", coverImageUrl=" + coverImageUrl + ", introduction=" + introduction + ", id=" + id + "]"; } } <file_sep>package com.spike.book.service; /** * 初始化数据服务 * * @author zhoujiagen<br/> * Jul 30, 2015 11:34:26 PM */ public interface InitDataService extends AbstractBaseService { void doService(); } <file_sep>package com.spike.book; import java.io.IOException; import java.util.Arrays; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.ImportResource; //@SpringBootApplication is same as @Configuration @EnableAutoConfiguration @ComponentScan @SpringBootApplication @ImportResource(value = { "localtest_beans.xml" }) public class TestApplication { public static void main(String[] args) throws IOException { SpringApplication application = new SpringApplication(TestApplication.class); application.setWebEnvironment(false);// not a web environment ApplicationContext ctx = application.run(args); System.out.println("Let's inspect the beans provided by Spring Boot:"); String[] beanNames = ctx.getBeanDefinitionNames(); Arrays.sort(beanNames); for (String beanName : beanNames) { System.out.println(beanName); } System.in.read();// ~ } } <file_sep>package com.spike.book.service.impl; import java.util.HashMap; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import com.spike.book.domain.Book; import com.spike.book.repository.BookRepository; import com.spike.book.service.BookService; public class BookServiceImpl implements BookService { @Autowired private BookRepository bookRepository; @Override public Map<String, Object> save(Map<String, Object> map) { Map<String, Object> result = new HashMap<String, Object>(); Book book = (Book) map.get("book"); book = bookRepository.save(book); result.put("book", book); return result; } } <file_sep>package com.spike.book.repository; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; import com.spike.book.domain.BookCategory; //@Repository("bookCategoryRepository") @Repository public interface BookCategoryRepository extends CrudRepository<BookCategory, Long> { BookCategory findByName(String name); } <file_sep>package com.spike.book.web.support; import static org.junit.Assert.assertEquals; import org.junit.Test; public class RequestServiceMethodResolverTest { @Test public void constructor() { String requestURI = "/service/serviceName/serviceMethod"; RequestServiceMethodResolver resolver = new RequestServiceMethodResolver(requestURI); assertEquals("serviceNameService", resolver.getServiceName()); assertEquals("serviceMethod", resolver.getMethodName()); } } <file_sep>package com.spike.book.repository; import java.util.List; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; import com.spike.book.domain.User; //@Repository("customerRepository") @Repository public interface CustomerRepository extends CrudRepository<User, Long> { List<User> findByLastName(String lastName); } <file_sep>package com.spike.book; import java.util.Arrays; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.ImportResource; @SpringBootApplication // Dubbo service //@ImportResource("classpath:consumer.xml") public class WebApplication { public static void main(String[] args) { ApplicationContext ctx = SpringApplication.run(WebApplication.class, args); System.out.println("Let's inspect the beans provided by Spring Boot:"); String[] beanNames = ctx.getBeanDefinitionNames(); Arrays.sort(beanNames); System.out.println("ApplicationContext Bean definitions: "); for (String beanName : beanNames) { System.out.println("|-- " + beanName); } System.out.println("Application[book-web] started!"); } } <file_sep>package com.spike.book.service; import static org.junit.Assert.assertNotNull; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.spike.book.TestApplication; import com.spike.book.domain.Author; import com.spike.book.domain.Book; import com.spike.book.domain.BookCategory; import com.spike.book.domain.Press; import com.spike.book.repository.AuthorRepository; import com.spike.book.repository.PressRepository; @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = TestApplication.class) public class BookServiceTest { @Autowired private BookCategoryService bookCategoryService; @Autowired private BookService bookService; @Autowired private PressRepository pressRepository; @Autowired private AuthorRepository authorRepository; @Test public void createBook() { Book book = new Book(); book.setTitle("深入理解Scala"); book.setIsbn("1234567890"); book.setIntroduction("深入理解Scala,进阶篇"); book.setCoverImageUrl("/photo/scala-in-depth.jpg"); List<Author> authors = new ArrayList<Author>(); Author author = new Author(); author.setFirstName("<NAME>."); author.setLastName("Suereth"); author = authorRepository.save(author); assertNotNull(author.getId()); authors.add(author); book.setAuthors(authors); Map<String, Object> map = new HashMap<String, Object>(); map.put("name", "计算机"); BookCategory bookCategory = (BookCategory) bookCategoryService.findByName(map).get("bookCategory"); book.setBookCategory(bookCategory); Press press = pressRepository.findByName("人民邮电出版社"); book.setPress(press); map = new HashMap<String, Object>(); map.put("book", book); book = (Book) bookService.save(map); assertNotNull(book.getId()); } }
87a74a4cb87b38e2c084f988259823092af1ff53
[ "Markdown", "SQL", "Java", "Maven POM" ]
23
Maven POM
zhoujiagen/BookApplication
1613102bbc9183872f6d5e3ffae29d1e3e7bf1c4
5285780b364d4a6ff0ef45714350a2064ceda05f
refs/heads/master
<repo_name>avelitch/tehnadzor<file_sep>/techno/Controllers/HomeController.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace techno.Controllers { [RequireHttps] public class HomeController : Controller { public ActionResult Index() { return View(); } public ActionResult Inziniring() { return View(); } public ActionResult About() { ViewBag.Message = "Your application description page."; return View(); } public ActionResult contact() { return View(); } public ActionResult ProjectSite() { return View(); } public ActionResult Projects() { return View(); } public ActionResult CRM() { return View(); } public ActionResult Stoimost() { return View(); } [Authorize] public ActionResult Estimates() { return View(); } [Authorize] public ActionResult OderstockCloud() { return View(); } [Authorize] public ActionResult Docs() { return View(); } [Authorize] public ActionResult Cloud() { return View(); } } } <file_sep>/techno/Controllers/ProjectsController.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace techno.Controllers { public class ProjectsController : Controller { // GET: Inzenernye_uslugi public ActionResult Index() { return View(); } public ActionResult KompleksnoeUpravlenieStroitelnoiDeyatelnostyu() { return View(); } public ActionResult proektProizvodstwaRabot() { return View(); } public ActionResult ispolnitelnayaDokumentaciaVStroitelstweRb() { return View(); } } }<file_sep>/techno/Controllers/stoimostController.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace techno.Controllers { public class stoimostController : Controller { // GET: stoimost public ActionResult Index() { return View(); } public ActionResult kompleksnoyeUpravlenieStroitelstwomStoimost() { return View(); } public ActionResult predproektnayaDokumentaciyaStoimost() { return View(); } public ActionResult tehnadzorVStroitelstveStoimost() { return View(); } public ActionResult zakupkiVStroitelstveStoimost() { return View(); } public ActionResult okazanieInzenernyhUslugStoimost() { return View(); } public ActionResult polnoeSoporovozdeniePodryadchikaStoimost() { return View(); } public ActionResult proektnyOfficePodryadchikaStoimost() { return View(); } public ActionResult dokumentyOnlinePodryadchikaStoimost() { return View(); } public ActionResult zakupkiVStroitelstvePodryadchikaStoimost() { return View(); } public ActionResult priemkaIVvodObjektaVEkspluataciuStoimost() { return View(); } public ActionResult raschetStoimostiStroitelstwaStoimost() { return View(); } public ActionResult proverkaStoimostiStroitelstwaStoimost() { return View(); } public ActionResult sostavlenieAktovRabotStoimost() { return View(); } public ActionResult proektProizvodstwaRabotStoimost() { return View(); } public ActionResult ispolnitelnayaDokumentaciyaStoimost() { return View(); } } }<file_sep>/techno/Controllers/TehnadzorController.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace techno.Controllers { public class TehnadzorController : Controller { // GET: Tehnadzor public ActionResult Tehnadzor() { return View(); } public ActionResult Stoimost_stroitelstwa() { return View(); } } }<file_sep>/techno/App_Start/RouteConfig.cs using LowercaseDashedRouting; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing; namespace techno { public class RouteConfig { public static void RegisterRoutes(RouteCollection routes) { routes.MapRoute(name: "OnlyAction", url: "{action}", defaults: new { controller = "Home", action = "Index" }); routes.Add(new LowercaseDashedRoute("{controller}/{action}/{id}", new RouteValueDictionary( new { controller = "Home", action = "Index", id = UrlParameter.Optional }), new DashedRouteHandler() ) ); } } } <file_sep>/techno/Controllers/remontController.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace techno.Controllers { public class remontController : Controller { // GET: remont public ActionResult RemontIRekonstrucia() { return View(); } } }<file_sep>/techno/Models/AccountViewModels.cs using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace techno.Models { public class ExternalLoginConfirmationViewModel { [Required] [Display(Name = "Email")] public string Email { get; set; } } public class ExternalLoginListViewModel { public string ReturnUrl { get; set; } } public class SendCodeViewModel { public string SelectedProvider { get; set; } public ICollection<System.Web.Mvc.SelectListItem> Providers { get; set; } public string ReturnUrl { get; set; } public bool RememberMe { get; set; } } public class VerifyCodeViewModel { [Required] public string Provider { get; set; } [Required] [Display(Name = "Code")] public string Code { get; set; } public string ReturnUrl { get; set; } [Display(Name = "Remember this browser?")] public bool RememberBrowser { get; set; } public bool RememberMe { get; set; } } public class ForgotViewModel { [Required] [Display(Name = "Email")] public string Email { get; set; } } public class LoginViewModel { [Required] [Display(Name = "Email")] [EmailAddress] public string Email { get; set; } [Required] [DataType(DataType.Password)] [Display(Name = "Password")] public string Password { get; set; } [Display(Name = "Remember me?")] public bool RememberMe { get; set; } } public class RegisterViewModel { [Required] [EmailAddress] [Display(Name = "Email")] public string Email { get; set; } [Required] [StringLength(18)] [DataType(DataType.PhoneNumber)] [Display(Name = "Телефон - +375 xx xxxxxxx")] public string PhoneNumber { get; set; } [Required] [DataType(DataType.Text)] [StringLength(30)] [Display(Name = "Организация")] public string Organizac { get; set; } [Required] [DataType(DataType.Text)] [Display(Name = "Организационно-правовая форма - РУП, ООО, ОДО и т.д." )] public string FormaOragan { get; set; } [Required] [StringLength(100, ErrorMessage = " {0} не менее {2} символов", MinimumLength = 6)] [DataType(DataType.Password)] [Display(Name = "Пароль (должен содержать: латинские, минимум: одна заглавная, одна цифра, один знак (+,-.))")] public string Password { get; set; } [DataType(DataType.Password)] [Display(Name = "Подтверждение пароля")] [Compare("Password", ErrorMessage = "Пароль не подтвержден")] public string ConfirmPassword { get; set; } } public class ResetPasswordViewModel { [Required] [EmailAddress] [Display(Name = "Email")] public string Email { get; set; } [Required] [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)] [DataType(DataType.Password)] [Display(Name = "Password")] public string Password { get; set; } [DataType(DataType.Password)] [Display(Name = "Confirm password")] [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")] public string ConfirmPassword { get; set; } public string Code { get; set; } } public class ForgotPasswordViewModel { [Required] [EmailAddress] [Display(Name = "Email")] public string Email { get; set; } } }
67d797f44d17af81375bc34636394fca522d3e9b
[ "C#" ]
7
C#
avelitch/tehnadzor
d5bc882df574bc5160e25f7f1bb8f2e26e235fde
a7c98c7b2174beceb6b9822a274579e3c83e0c18
refs/heads/master
<file_sep>using ElectricCity.Dao; using ElectricCity.Entities; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace ElectricCity.Controllers { public class CategoryController : Controller { // GET: Category public ActionResult Index() { CategoryDao catDao = new CategoryDao(); List<ProductCategory> lst = catDao.GetAllCategory(); return View(lst); } [ChildActionOnly] public ActionResult CategoryLoad() { var model = new CategoryDao().GetAllCategory(); return PartialView(model); } } }<file_sep>using ElectricCity.Common; using ElectricCity.Dao; using ElectricCity.Entities; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using PagedList; namespace ElectricCity.Areas.Admin.Controllers { public class UserController : BaseController { // GET: Admin/User public ActionResult Index() { return View("GetAllUserPaging"); } public ActionResult GetAllUser() { UserDao usDao = new UserDao(); List<User> lst= usDao.GetAllUser(); return View(lst); } public ActionResult GetAllUserPaging(int page=1, int pagesize=5) { UserDao usDao = new UserDao(); IPagedList lst = usDao.GetAllUserPaging(page, pagesize); return View(lst); } } }<file_sep>using ElectricCity.Common; using ElectricCity.Entities; using System; using System.Collections.Generic; using System.Linq; using System.Web; using PagedList; namespace ElectricCity.Dao { public class UserDao { ElectricCityOnlineDBContext db = null; public UserDao() { db = new ElectricCityOnlineDBContext(); } public Result.InsertResult InsertUser(User u) { var res = db.Users.SingleOrDefault(x => x.UserName == u.UserName); if (res == null) { u.Status = true; u.Permission = 3; db.Users.Add(u); db.SaveChanges(); return Result.InsertResult.ThemThanhCong; } else { return Result.InsertResult.TaiKhoanTonTai; } } public Result.LoginResult Login(string userName, string password) { var result = db.Users.SingleOrDefault(x => x.UserName == userName ); int count = db.Users.Where(x => x.UserName == userName && x.Permission == 3).Count(); if (result == null) { return Result.LoginResult.TaiKhoanKhongTonTai; } else { if (result.Status==false) { return Result.LoginResult.TaiKhoanBiKhoa; } else { if (result.Password == password) { if (count >0) { return Result.LoginResult.KhongCoQuyen; } else { return Result.LoginResult.DangNhapThanhCong; } } else { return Result.LoginResult.MatKhauSai; } } } } public User GetUser(string username) { return db.Users.SingleOrDefault(x => x.UserName == username); } public List<User> GetAllUser() { List<User> lstUser = db.Users.ToList(); return lstUser; } public IPagedList GetAllUserPaging(int? pageTemp, int pageSize ) { int pageNumber = pageTemp ?? 1; IPagedList lst = db.Users.ToList().OrderBy(a => a.UserName).ToPagedList(pageNumber, pageSize); return lst; } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace ElectricCity.Dao { public class BrandDao { } }<file_sep>using ElectricCity.Entities; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace ElectricCity.Dao { public class ProductDao { ElectricCityOnlineDBContext db = null; public ProductDao() { db = new ElectricCityOnlineDBContext(); } public int InsertUser(Product p) { var res = db.Products.SingleOrDefault(x => x.Name == p.Name); if (res == null) { db.Products.Add(p); db.SaveChanges(); return 1; } else { return -1; } } } }<file_sep>using ElectricCity.Dao; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace ElectricCity.Areas.Admin.Controllers { public class CategoryAdminController : Controller { // GET: Admin/CategoryAdmin public ActionResult Index() { return View(); } [ChildActionOnly] public ActionResult CategoryLoad() { var model = new CategoryDao().GetAllCategory(); return PartialView(model); } } }<file_sep>namespace ElectricCity.Entities { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.Spatial; [Table("Product")] public partial class Product { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] public Product() { BillDetails = new HashSet<BillDetail>(); Images = new HashSet<Image>(); } public int ID { get; set; } [StringLength(200)] public string Name { get; set; } [StringLength(500)] public string Description { get; set; } [StringLength(100)] public string ImageLink { get; set; } public decimal? Price { get; set; } public decimal? PromotionPrice { get; set; } [StringLength(10)] public string QuantityLeft { get; set; } public int? CategoryID { get; set; } public int? BrandID { get; set; } public DateTime? CreatedDate { get; set; } public DateTime? ModifiedDate { get; set; } [StringLength(50)] public string CreatedBy { get; set; } [StringLength(50)] public string ModifiedBy { get; set; } public bool? Status { get; set; } public bool? PromotedItem { get; set; } public bool? HotItem { get; set; } [StringLength(200)] public string MetaTitle { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<BillDetail> BillDetails { get; set; } public virtual Brand Brand { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<Image> Images { get; set; } public virtual ProductCategory ProductCategory { get; set; } } } <file_sep>namespace ElectricCity.Entities { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.Spatial; [Table("Image")] public partial class Image { public int ID { get; set; } [StringLength(100)] public string ImageLink { get; set; } public bool? Status { get; set; } public int? ProductID { get; set; } public virtual Product Product { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace ElectricCity.Common { public static class Result { public enum LoginResult { DangNhapThanhCong, TaiKhoanKhongTonTai, TaiKhoanBiKhoa, MatKhauSai, KhongCoQuyen, } public enum InsertResult { ThemThanhCong, TaiKhoanTonTai, MatKhauKhongKhop, } } }<file_sep>namespace ElectricCity.Entities { using System; using System.Data.Entity; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; public partial class ElectricCityOnlineDBContext : DbContext { public ElectricCityOnlineDBContext() : base("name=ElectricCityOnlineDBContext1") { } public virtual DbSet<Bill> Bills { get; set; } public virtual DbSet<BillDetail> BillDetails { get; set; } public virtual DbSet<Brand> Brands { get; set; } public virtual DbSet<Contact> Contacts { get; set; } public virtual DbSet<FeedBack> FeedBacks { get; set; } public virtual DbSet<Image> Images { get; set; } public virtual DbSet<Permisssion> Permisssions { get; set; } public virtual DbSet<Product> Products { get; set; } public virtual DbSet<ProductCategory> ProductCategories { get; set; } public virtual DbSet<SystemConfig> SystemConfigs { get; set; } public virtual DbSet<User> Users { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity<Bill>() .Property(e => e.CustomerEmail) .IsUnicode(false); modelBuilder.Entity<Bill>() .Property(e => e.CustomerPhone) .IsUnicode(false); modelBuilder.Entity<Bill>() .Property(e => e.PaymentType) .IsUnicode(false); modelBuilder.Entity<Bill>() .HasMany(e => e.BillDetails) .WithRequired(e => e.Bill) .HasForeignKey(e => e.IDBill) .WillCascadeOnDelete(false); modelBuilder.Entity<Brand>() .Property(e => e.ImageLink) .IsUnicode(false); modelBuilder.Entity<Brand>() .Property(e => e.CreatedBy) .IsUnicode(false); modelBuilder.Entity<Brand>() .Property(e => e.ModifiedBy) .IsUnicode(false); modelBuilder.Entity<Brand>() .Property(e => e.MetaTitle) .IsUnicode(false); modelBuilder.Entity<Contact>() .Property(e => e.Contents) .IsFixedLength(); modelBuilder.Entity<FeedBack>() .Property(e => e.PhoneNumber) .IsUnicode(false); modelBuilder.Entity<FeedBack>() .Property(e => e.Email) .IsUnicode(false); modelBuilder.Entity<Image>() .Property(e => e.ImageLink) .IsUnicode(false); modelBuilder.Entity<Permisssion>() .Property(e => e.PermissionName) .IsUnicode(false); modelBuilder.Entity<Permisssion>() .HasMany(e => e.Users) .WithOptional(e => e.Permisssion) .HasForeignKey(e => e.Permission); modelBuilder.Entity<Product>() .Property(e => e.ImageLink) .IsUnicode(false); modelBuilder.Entity<Product>() .Property(e => e.Price) .HasPrecision(18, 0); modelBuilder.Entity<Product>() .Property(e => e.PromotionPrice) .HasPrecision(18, 0); modelBuilder.Entity<Product>() .Property(e => e.QuantityLeft) .IsFixedLength(); modelBuilder.Entity<Product>() .Property(e => e.CreatedBy) .IsUnicode(false); modelBuilder.Entity<Product>() .Property(e => e.ModifiedBy) .IsUnicode(false); modelBuilder.Entity<Product>() .Property(e => e.MetaTitle) .IsUnicode(false); modelBuilder.Entity<Product>() .HasMany(e => e.BillDetails) .WithRequired(e => e.Product) .HasForeignKey(e => e.IDProduct) .WillCascadeOnDelete(false); modelBuilder.Entity<ProductCategory>() .Property(e => e.CreatedBy) .IsUnicode(false); modelBuilder.Entity<ProductCategory>() .Property(e => e.ModifiedBy) .IsUnicode(false); modelBuilder.Entity<ProductCategory>() .Property(e => e.MetaTitle) .IsUnicode(false); modelBuilder.Entity<ProductCategory>() .HasMany(e => e.Products) .WithOptional(e => e.ProductCategory) .HasForeignKey(e => e.CategoryID); modelBuilder.Entity<SystemConfig>() .Property(e => e.Type) .IsUnicode(false); modelBuilder.Entity<User>() .Property(e => e.UserName) .IsUnicode(false); modelBuilder.Entity<User>() .Property(e => e.Password) .IsUnicode(false); modelBuilder.Entity<User>() .Property(e => e.Email) .IsUnicode(false); modelBuilder.Entity<User>() .Property(e => e.PhoneNumber) .IsUnicode(false); } } } <file_sep>namespace ElectricCity.Entities { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.Spatial; [Table("BillDetail")] public partial class BillDetail { [Key] [Column(Order = 0)] [DatabaseGenerated(DatabaseGeneratedOption.None)] public int IDProduct { get; set; } [Key] [Column(Order = 1)] [DatabaseGenerated(DatabaseGeneratedOption.None)] public long IDBill { get; set; } public int? Quantity { get; set; } public bool? Status { get; set; } public virtual Bill Bill { get; set; } public virtual Product Product { get; set; } } } <file_sep>using ElectricCity.Entities; using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace ElectricCity.Dao { public class CategoryDao { ElectricCityOnlineDBContext db = null; public CategoryDao() { db = new ElectricCityOnlineDBContext(); } public List<ProductCategory> GetAllCategory() { List<ProductCategory> lst = db.ProductCategories.Where(x=>x.Status==true).ToList(); return lst; } } }<file_sep>using ElectricCity.Areas.Admin.Models; using ElectricCity.Common; using ElectricCity.Dao; using ElectricCity.Entities; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace ElectricCity.Areas.Admin.Controllers { public class AuthenticationController : Controller { // GET: Admin/Authentication public ActionResult Index() { return View(); } [HttpPost] public ActionResult Login(LoginModel model) { if (ModelState.IsValid) //Nếu đã vượt qua mức valid Form không rỗng { var usDao = new UserDao(); var result = usDao.Login(model.UserName, Encryptor.MD5Hash(model.Password)); if (result == Result.LoginResult.DangNhapThanhCong) { var user = usDao.GetUser(model.UserName); var userSession = new UserLogin(); userSession.UserName = user.UserName; userSession.UserID = user.ID; Session.Add(CommonConstants.USER_SESSION, userSession); return RedirectToAction("Index", "Home"); } else if (result == Result.LoginResult.MatKhauSai) { ModelState.AddModelError("", "Mật khẩu sai!!!"); } else if (result == Result.LoginResult.TaiKhoanBiKhoa) { ModelState.AddModelError("", "Tài khoản hiện giờ đang bị khóa! :("); } else if (result == Result.LoginResult.TaiKhoanKhongTonTai) { ModelState.AddModelError("", "Tài khoản không tồn tại!"); }else if (result == Result.LoginResult.KhongCoQuyen) { ModelState.AddModelError("", "Tài khoản Khong co quyen vao Admin! :("); } } return View("Index"); } [HttpGet] public ActionResult Create() { return View(); } [HttpPost] public ActionResult Create(User user) { if (ModelState.IsValid) { var usDao = new UserDao(); user.Password = <PASSWORD>(user.Password); Result.InsertResult res = usDao.InsertUser(user); if (res == Result.InsertResult.ThemThanhCong) { return RedirectToAction("Index", "User"); } if (res == Result.InsertResult.TaiKhoanTonTai) { ModelState.AddModelError("", "Username đã tồn tại!"); } } return View("Create"); } } }<file_sep>namespace ElectricCity.Entities { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.Spatial; [Table("User")] public partial class User { public int ID { get; set; } [StringLength(50)] [Display(Name ="Tên tài khoản")] [Required(ErrorMessage = "Nhập nội dung trước!.")] public string UserName { get; set; } [StringLength(50)] [Display(Name = "Mật khẩu")] [Required(ErrorMessage = "Mật khẩu không trống!.")] public string Password { get; set; } [StringLength(100)] [Display(Name = "Tên Hiển thị")] public string NameDisplay { get; set; } [Display(Name = "Ngày sinh")] public DateTime? DoB { get; set; } [StringLength(100)] public string Email { get; set; } [StringLength(200)] [Display(Name = "Địa chỉ")] public string Address { get; set; } [StringLength(20)] [Display(Name = "Số điện thoại")] public string PhoneNumber { get; set; } public bool? Status { get; set; } public int? Permission { get; set; } public virtual Permisssion Permisssion { get; set; } } }
0cfd438ae6773eb46869912bfbbc903a15888aa1
[ "C#" ]
14
C#
quoctv1202/ElectricCity
167295d53cb94111f754df7cb27a4d7467eb3ec3
86eb26a5f6659b02ba3e15da7f3490dd525f31a7
refs/heads/master
<file_sep>from django.db import models from django.contrib.auth.models import AbstractUser from .validators import validate_no_special_characters from django.core.validators import MinValueValidator # Create your models here. class User(AbstractUser): nickname = models.CharField(max_length=15, unique=True, null=True, validators=[validate_no_special_characters], error_messages={'unique':"이미 사용중인 닉네임입니다."}) kakao_id = models.CharField(max_length=20, null=True, validators=[validate_no_special_characters]) address = models.CharField(max_length=40, null=True, validators=[validate_no_special_characters]) def __str__(self): return self.email class Post(models.Model): title = models.CharField(max_length=60) item_price = models.IntegerField(validators=[MinValueValidator(1)]) ITEM_CONDITION_CHOICE = [('새제품', '새제품'), ('최상', '최상'), ('상', '상'), ('중', '중'), ('하', '하')] item_condition = models.CharField(choices=ITEM_CONDITION_CHOICE, max_length=5) item_details = models.TextField(blank=True) image1 = models.ImageField(upload_to='item_pics') image2 = models.ImageField(upload_to='item_pics', blank=True) image3 = models.ImageField(upload_to='item_pics', blank=True) author = models.ForeignKey(User, on_delete=models.CASCADE) dt_created = models.DateField(auto_now_add=True) dt_updated = models.DateField(auto_now=True) def __str__(self): return self.title<file_sep>from django.shortcuts import render from allauth.account.views import PasswordChangeView from django.urls import reverse # Create your views here. def index(request): return render(request, 'podomarket/index.html') class CustomPasswordChangeView(PasswordChangeView): def get_success_url(self): return reverse("index")
53f9f0ca8dbc82e4a4f728e7d012501d5c101c6d
[ "Python" ]
2
Python
lmj00/podomarket
202e1c7740ccb0c89ea50e8e89d0952d29c071e4
a77cbb30e7861a5662da456f2f08a555e88da7ec
refs/heads/master
<file_sep>package hypervisor import ( "os" "path/filepath" "strings" "syscall" "time" "github.com/golang/glog" "github.com/hyperhq/runv/hypervisor/pod" ) func CreateContainer(userPod *pod.UserPod, sharedDir string, hub chan VmEvent) (string, error) { return "", nil } func UmountOverlayContainer(shareDir, image string, index int, hub chan VmEvent) { glog.Warningf("Non support") } func UmountAufsContainer(shareDir, image string, index int, hub chan VmEvent) { glog.Warningf("Non support") } func UmountVfsContainer(shareDir, image string, index int, hub chan VmEvent) { mount := filepath.Join(shareDir, image) success := true for i := 0; i < 10; i++ { time.Sleep(3 * time.Second / 1000) err := syscall.Unlink(mount) if err != nil { if !strings.Contains(strings.ToLower(err.Error()), "device or resource busy") { success = true break } glog.Warningf("Cannot umount vfs %s: %s", mount, err.Error()) success = false } else { success = true break } } hub <- &ContainerUnmounted{Index: index, Success: success} } func UmountVolume(shareDir, volPath string, name string, hub chan VmEvent) { mount := filepath.Join(shareDir, volPath) success := true if err := syscall.Unlink(mount); err != nil { success = false } if success == true { os.Remove(mount) } // After umount that device, we need to delete it hub <- &VolumeUnmounted{Name: name, Success: success} } func UmountDMDevice(deviceFullPath, name string, hub chan VmEvent) { // After umount that device, we need to delete it hub <- &BlockdevRemovedEvent{Name: name, Success: true} } func supportAufs() bool { return false } func supportOverlay() bool { return false } <file_sep>package main import ( "fmt" "os" "strconv" "strings" "syscall" "github.com/codegangsta/cli" "github.com/hyperhq/runv/lib/linuxsignal" ) var linuxSignalMap = map[string]syscall.Signal{ "ABRT": linuxsignal.SIGABRT, "ALRM": linuxsignal.SIGALRM, "BUS": linuxsignal.SIGBUS, "CHLD": linuxsignal.SIGCHLD, "CLD": linuxsignal.SIGCLD, "CONT": linuxsignal.SIGCONT, "FPE": linuxsignal.SIGFPE, "HUP": linuxsignal.SIGHUP, "ILL": linuxsignal.SIGILL, "INT": linuxsignal.SIGINT, "IO": linuxsignal.SIGIO, "IOT": linuxsignal.SIGIOT, "KILL": linuxsignal.SIGKILL, "PIPE": linuxsignal.SIGPIPE, "POLL": linuxsignal.SIGPOLL, "PROF": linuxsignal.SIGPROF, "PWR": linuxsignal.SIGPWR, "QUIT": linuxsignal.SIGQUIT, "SEGV": linuxsignal.SIGSEGV, "STKFLT": linuxsignal.SIGSTKFLT, "STOP": linuxsignal.SIGSTOP, "SYS": linuxsignal.SIGSYS, "TERM": linuxsignal.SIGTERM, "TRAP": linuxsignal.SIGTRAP, "TSTP": linuxsignal.SIGTSTP, "TTIN": linuxsignal.SIGTTIN, "TTOU": linuxsignal.SIGTTOU, "UNUSED": linuxsignal.SIGUNUSED, "URG": linuxsignal.SIGURG, "USR1": linuxsignal.SIGUSR1, "USR2": linuxsignal.SIGUSR2, "VTALRM": linuxsignal.SIGVTALRM, "WINCH": linuxsignal.SIGWINCH, "XCPU": linuxsignal.SIGXCPU, "XFSZ": linuxsignal.SIGXFSZ, } type killContainerCmd struct { Name string Root string Signal syscall.Signal } var killCommand = cli.Command{ Name: "kill", Usage: "kill sends the specified signal (default: SIGTERM) to the container's init process", Action: func(context *cli.Context) { root := context.GlobalString("root") container := context.GlobalString("id") sigstr := context.Args().First() if sigstr == "" { sigstr = "SIGTERM" } signal, err := parseSignal(sigstr) if err != nil { fmt.Printf("kill container failed %v\n", err) os.Exit(-1) } killCmd := &killContainerCmd{Name: container, Root: root, Signal: signal} conn, err := runvRequest(root, container, RUNV_KILLCONTAINER, killCmd) if err != nil { fmt.Printf("kill container failed %v\n", err) os.Exit(-1) } conn.Close() }, } func parseSignal(rawSignal string) (syscall.Signal, error) { s, err := strconv.Atoi(rawSignal) if err == nil { return syscall.Signal(s), nil } signal, ok := linuxSignalMap[strings.TrimPrefix(strings.ToUpper(rawSignal), "SIG")] if !ok { return -1, fmt.Errorf("unknown signal %q", rawSignal) } return signal, nil } <file_sep>package daemon import ( "encoding/base64" "encoding/json" "errors" "fmt" "io" "os" "path" "path/filepath" "strings" "time" dockertypes "github.com/docker/docker/api/types" "github.com/docker/docker/daemon/logger" "github.com/docker/docker/daemon/logger/jsonfilelog" "github.com/golang/glog" "github.com/hyperhq/hyper/engine" "github.com/hyperhq/hyper/servicediscovery" "github.com/hyperhq/hyper/storage" "github.com/hyperhq/hyper/utils" "github.com/hyperhq/runv/hypervisor" "github.com/hyperhq/runv/hypervisor/pod" "github.com/hyperhq/runv/hypervisor/types" ) func (daemon *Daemon) CmdPodCreate(job *engine.Job) error { // we can only support 1024 Pods if daemon.GetRunningPodNum() >= 1024 { return fmt.Errorf("Pod full, the maximum Pod is 1024!") } podArgs := job.Args[0] autoRemove := false if job.Args[1] == "yes" || job.Args[1] == "true" { autoRemove = true } podId := fmt.Sprintf("pod-%s", pod.RandStr(10, "alpha")) daemon.PodList.Lock() glog.V(2).Infof("lock PodList") defer glog.V(2).Infof("unlock PodList") defer daemon.PodList.Unlock() err := daemon.CreatePod(podId, podArgs, autoRemove) if err != nil { return err } // Prepare the VM status to client v := &engine.Env{} v.Set("ID", podId) v.SetInt("Code", 0) v.Set("Cause", "") if _, err := v.WriteTo(job.Stdout); err != nil { return err } return nil } // CmdPodLabels updates labels of the specified pod func (daemon *Daemon) CmdPodLabels(job *engine.Job) error { override := false if job.Args[1] == "true" || job.Args[1] == "yes" { override = true } labels := make(map[string]string) if len(job.Args[2]) == 0 { return fmt.Errorf("labels can't be null") } if err := json.Unmarshal([]byte(job.Args[2]), &labels); err != nil { return err } daemon.PodList.RLock() glog.V(2).Infof("lock read of PodList") defer daemon.PodList.RUnlock() defer glog.V(2).Infof("unlock read of PodList") var ( pod *Pod ok bool ) if strings.Contains(job.Args[0], "pod-") { podId := job.Args[0] pod, ok = daemon.PodList.Get(podId) if !ok { return fmt.Errorf("Can not get Pod info with pod ID(%s)", podId) } } else { pod = daemon.PodList.GetByName(job.Args[0]) if pod == nil { return fmt.Errorf("Can not get Pod info with pod name(%s)", job.Args[0]) } } if pod.spec.Labels == nil { pod.spec.Labels = make(map[string]string) } for k := range labels { if _, ok := pod.spec.Labels[k]; ok && !override { return fmt.Errorf("Can't update label %s without override", k) } } for k, v := range labels { pod.spec.Labels[k] = v } spec, err := json.Marshal(pod.spec) if err != nil { return err } if err := daemon.WritePodToDB(pod.id, spec); err != nil { return err } // Prepare the VM status to client v := &engine.Env{} v.Set("ID", pod.id) v.SetInt("Code", 0) v.Set("Cause", "") if _, err := v.WriteTo(job.Stdout); err != nil { return err } return nil } func (daemon *Daemon) CmdPodStart(job *engine.Job) error { // we can only support 1024 Pods if daemon.GetRunningPodNum() >= 1024 { return fmt.Errorf("Pod full, the maximum Pod is 1024!") } var ( tag string = "" ttys []*hypervisor.TtyIO = []*hypervisor.TtyIO{} ttyCallback chan *types.VmResponse ) podId := job.Args[0] vmId := job.Args[1] if len(job.Args) > 2 { tag = job.Args[2] } if tag != "" { glog.V(1).Info("Pod Run with client terminal tag: ", tag) ttyCallback = make(chan *types.VmResponse, 1) ttys = append(ttys, &hypervisor.TtyIO{ Stdin: job.Stdin, Stdout: job.Stdout, ClientTag: tag, Callback: ttyCallback, }) } glog.Infof("pod:%s, vm:%s", podId, vmId) // Do the status check for the given pod daemon.PodList.Lock() glog.V(2).Infof("lock PodList") if _, ok := daemon.PodList.Get(podId); !ok { glog.V(2).Infof("unlock PodList") daemon.PodList.Unlock() return fmt.Errorf("The pod(%s) can not be found, please create it first", podId) } var lazy bool = hypervisor.HDriver.SupportLazyMode() && vmId == "" code, cause, err := daemon.StartPod(podId, "", vmId, nil, lazy, false, types.VM_KEEP_NONE, ttys) if err != nil { glog.Error(err.Error()) glog.V(2).Infof("unlock PodList") daemon.PodList.Unlock() return err } if len(ttys) > 0 { glog.V(2).Infof("unlock PodList") daemon.PodList.Unlock() daemon.GetExitCode(podId, tag, ttyCallback) return nil } defer glog.V(2).Infof("unlock PodList") defer daemon.PodList.Unlock() // Prepare the VM status to client v := &engine.Env{} v.Set("ID", vmId) v.SetInt("Code", code) v.Set("Cause", cause) if _, err := v.WriteTo(job.Stdout); err != nil { return err } return nil } // I'd like to move the remain part of this file to another file. type Pod struct { id string status *hypervisor.PodStatus spec *pod.UserPod vm *hypervisor.Vm containers []*hypervisor.ContainerInfo volumes []*hypervisor.VolumeInfo } func (p *Pod) GetVM(daemon *Daemon, id string, lazy bool, keep int) (err error) { if p == nil || p.spec == nil { return errors.New("Pod: unable to create VM without resource info.") } p.vm, err = daemon.GetVM(id, &p.spec.Resource, lazy, keep) return } func (p *Pod) SetVM(id string, vm *hypervisor.Vm) { p.status.Vm = id p.vm = vm } func (p *Pod) KillVM(daemon *Daemon) { if p.vm != nil { daemon.KillVm(p.vm.Id) p.vm = nil } } func (p *Pod) Status() *hypervisor.PodStatus { return p.status } func CreatePod(daemon *Daemon, dclient DockerInterface, podId, podArgs string, autoremove bool) (*Pod, error) { glog.V(1).Infof("podArgs: %s", podArgs) resPath := filepath.Join(DefaultResourcePath, podId) if err := os.MkdirAll(resPath, os.FileMode(0755)); err != nil { glog.Error("cannot create resource dir ", resPath) return nil, err } spec, err := ProcessPodBytes([]byte(podArgs), podId) if err != nil { glog.V(1).Infof("Process POD file error: %s", err.Error()) return nil, err } if err = spec.Validate(); err != nil { return nil, err } status := hypervisor.NewPod(podId, spec) status.Handler.Handle = hyperHandlePodEvent status.Autoremove = autoremove status.ResourcePath = resPath pod := &Pod{ id: podId, status: status, spec: spec, } if err = pod.InitContainers(daemon, dclient); err != nil { return nil, err } return pod, nil } func (p *Pod) InitContainers(daemon *Daemon, dclient DockerInterface) (err error) { type cinfo struct { id string name string image string } var ( containers map[string]*cinfo = make(map[string]*cinfo) created []string = []string{} ) // trying load existing containers from db if ids, _ := daemon.GetPodContainersByName(p.id); ids != nil { for _, id := range ids { if jsonResponse, err := daemon.DockerCli.GetContainerInfo(id); err == nil { n := strings.TrimLeft(jsonResponse.Name, "/") containers[n] = &cinfo{ id: id, name: jsonResponse.Name, image: jsonResponse.Config.Image, } glog.V(1).Infof("Found exist container %s (%s), image: %s", n, id, jsonResponse.Config.Image) } } } defer func() { if err != nil { for _, cid := range created { dclient.SendCmdDelete(cid) } } }() glog.V(1).Info("Process the Containers section in POD SPEC") for _, c := range p.spec.Containers { glog.V(1).Info("trying to init container ", c.Name) if info, ok := containers[c.Name]; ok { p.status.AddContainer(info.id, info.name, info.image, []string{}, types.S_POD_CREATED) continue } var ( cId []byte rsp *dockertypes.ContainerJSON ) cId, _, err = dclient.SendCmdCreate(c.Name, c.Image, []string{}, nil) if err != nil { glog.Error(err.Error()) return } created = append(created, string(cId)) if rsp, err = dclient.GetContainerInfo(string(cId)); err != nil { return } p.status.AddContainer(string(cId), rsp.Name, rsp.Config.Image, []string{}, types.S_POD_CREATED) } return nil } //FIXME: there was a `config` argument passed by docker/builder, but we never processed it. func (daemon *Daemon) CreatePod(podId, podArgs string, autoremove bool) error { pod, err := CreatePod(daemon, daemon.DockerCli, podId, podArgs, autoremove) if err != nil { return err } return daemon.AddPod(pod, podArgs) } func (p *Pod) PrepareContainers(sd Storage, dclient DockerInterface) (err error) { err = nil p.containers = []*hypervisor.ContainerInfo{} var ( sharedDir = path.Join(hypervisor.BaseDir, p.vm.Id, hypervisor.ShareDirTag) ) files := make(map[string](pod.UserFile)) for _, f := range p.spec.Files { files[f.Name] = f } for i, c := range p.status.Containers { var ( info *dockertypes.ContainerJSON ci *hypervisor.ContainerInfo ) info, err = getContinerInfo(dclient, c) ci, err = sd.PrepareContainer(c.Id, sharedDir) if err != nil { return err } ci.Workdir = info.Config.WorkingDir ci.Entrypoint = info.Config.Entrypoint.Slice() ci.Cmd = info.Config.Cmd.Slice() env := make(map[string]string) for _, v := range info.Config.Env { env[v[:strings.Index(v, "=")]] = v[strings.Index(v, "=")+1:] } for _, e := range p.spec.Containers[i].Envs { env[e.Env] = e.Value } ci.Envs = env processImageVolumes(info, c.Id, p.spec, &p.spec.Containers[i]) err = processInjectFiles(&p.spec.Containers[i], files, sd, c.Id, sd.RootPath(), sharedDir) if err != nil { return err } p.containers = append(p.containers, ci) glog.V(1).Infof("Container Info is \n%v", ci) } return nil } func getContinerInfo(dclient DockerInterface, container *hypervisor.Container) (info *dockertypes.ContainerJSON, err error) { info, err = dclient.GetContainerInfo(container.Id) if err != nil { glog.Error("got error when get container Info ", err.Error()) return nil, err } if container.Name == "" { container.Name = info.Name } if container.Image == "" { container.Image = info.Config.Image } return } func processInjectFiles(container *pod.UserContainer, files map[string]pod.UserFile, sd Storage, id, rootPath, sharedDir string) error { for _, f := range container.Files { targetPath := f.Path if strings.HasSuffix(targetPath, "/") { targetPath = targetPath + f.Filename } file, ok := files[f.Filename] if !ok { continue } var src io.Reader if file.Uri != "" { urisrc, err := utils.UriReader(file.Uri) if err != nil { return err } defer urisrc.Close() src = urisrc } else { src = strings.NewReader(file.Contents) } switch file.Encoding { case "base64": src = base64.NewDecoder(base64.StdEncoding, src) default: } err := sd.InjectFile(src, id, targetPath, sharedDir, utils.PermInt(f.Perm), utils.UidInt(f.User), utils.UidInt(f.Group)) if err != nil { glog.Error("got error when inject files ", err.Error()) return err } } return nil } func processImageVolumes(config *dockertypes.ContainerJSON, id string, userPod *pod.UserPod, container *pod.UserContainer) { if config.Config.Volumes == nil { return } for tgt := range config.Config.Volumes { n := id + strings.Replace(tgt, "/", "_", -1) v := pod.UserVolume{ Name: n, Source: "", } r := pod.UserVolumeReference{ Volume: n, Path: tgt, ReadOnly: false, } userPod.Volumes = append(userPod.Volumes, v) container.Volumes = append(container.Volumes, r) } } func (p *Pod) PrepareServices() error { err := servicediscovery.PrepareServices(p.spec, p.id) if err != nil { glog.Errorf("PrepareServices failed %s", err.Error()) } return err } /*** PrepareDNS() Set the resolv.conf of host to each container, except the following cases: - if the pod has a `dns` field with values, the pod will follow the dns setup, and daemon won't insert resolv.conf file into any containers - if the pod has a `file` which source is uri "file:///etc/resolv.conf", this mean the user will handle this file by himself/herself, daemon won't touch the dns setting even if the file is not referenced by any containers. This could be a method to prevent the daemon from unwanted setting the dns configuration - if a container has a file config in the pod spec with `/etc/resolv.conf` as target `path`, then this container won't be set as the file from hosts. Then a user can specify the content of the file. */ func (p *Pod) PrepareDNS() (err error) { err = nil var ( resolvconf = "/etc/resolv.conf" fileId = p.id + "-resolvconf" ) if p.spec == nil { estr := "No Spec available for insert a DNS configuration" glog.V(1).Info(estr) err = fmt.Errorf(estr) return } if len(p.spec.Dns) > 0 { glog.V(1).Info("Already has DNS config, bypass DNS insert") return } if stat, e := os.Stat(resolvconf); e != nil || !stat.Mode().IsRegular() { glog.V(1).Info("Host resolv.conf is not exist or not a regular file, do not insert DNS conf") return } for _, src := range p.spec.Files { if src.Uri == "file:///etc/resolv.conf" { glog.V(1).Info("Already has resolv.conf configured, bypass DNS insert") return } } p.spec.Files = append(p.spec.Files, pod.UserFile{ Name: fileId, Encoding: "raw", Uri: "file://" + resolvconf, }) for idx, c := range p.spec.Containers { insert := true for _, f := range c.Files { if f.Path == resolvconf { insert = false break } } if !insert { continue } p.spec.Containers[idx].Files = append(c.Files, pod.UserFileReference{ Path: resolvconf, Filename: fileId, Perm: "0644", }) } return } func (p *Pod) PrepareVolume(daemon *Daemon, sd Storage) (err error) { err = nil p.volumes = []*hypervisor.VolumeInfo{} var ( sharedDir = path.Join(hypervisor.BaseDir, p.vm.Id, hypervisor.ShareDirTag) ) for _, v := range p.spec.Volumes { var vol *hypervisor.VolumeInfo if v.Source == "" { vol, err = sd.CreateVolume(daemon, p.id, v.Name) if err != nil { return } v.Source = vol.Filepath if sd.Type() != "devicemapper" { v.Driver = "vfs" vol.Filepath, err = storage.MountVFSVolume(v.Source, sharedDir) if err != nil { return } glog.V(1).Infof("dir %s is bound to %s", v.Source, vol.Filepath) } else { // type other than doesn't need to be mounted v.Driver = "raw" } } else { vol, err = ProbeExistingVolume(&v, sharedDir) if err != nil { return } } p.volumes = append(p.volumes, vol) } return nil } func (p *Pod) Prepare(daemon *Daemon) (err error) { if err = p.PrepareServices(); err != nil { return } if err = p.PrepareDNS(); err != nil { glog.Warning("Fail to prepare DNS for %s: %v", p.id, err) return } if err = p.PrepareContainers(daemon.Storage, daemon.DockerCli); err != nil { return } if err = p.PrepareVolume(daemon, daemon.Storage); err != nil { return } return nil } func stopLogger(mypod *hypervisor.PodStatus) { for _, c := range mypod.Containers { if c.Logs.Driver == nil { continue } c.Logs.Driver.Close() } } func (p *Pod) getLogger(daemon *Daemon) (err error) { if p.spec.LogConfig.Type == "" { p.spec.LogConfig.Type = daemon.DefaultLog.Type p.spec.LogConfig.Config = daemon.DefaultLog.Config } if p.spec.LogConfig.Type == "none" { return nil } var ( needLogger []int = []int{} creator logger.Creator ) for i, c := range p.status.Containers { if c.Logs.Driver == nil { needLogger = append(needLogger, i) } } if len(needLogger) == 0 && p.status.Status == types.S_POD_RUNNING { return nil } if err = logger.ValidateLogOpts(p.spec.LogConfig.Type, p.spec.LogConfig.Config); err != nil { return } creator, err = logger.GetLogDriver(p.spec.LogConfig.Type) if err != nil { return } glog.V(1).Infof("configuring log driver [%s] for %s", p.spec.LogConfig.Type, p.id) for i, c := range p.status.Containers { ctx := logger.Context{ Config: p.spec.LogConfig.Config, ContainerID: c.Id, ContainerName: c.Name, ContainerImageName: p.spec.Containers[i].Image, ContainerCreated: time.Now(), //FIXME: should record creation time in PodStatus } if p.containers != nil && len(p.containers) > i { ctx.ContainerEntrypoint = p.containers[i].Workdir ctx.ContainerArgs = p.containers[i].Cmd ctx.ContainerImageID = p.containers[i].Image } if p.spec.LogConfig.Type == jsonfilelog.Name { ctx.LogPath = filepath.Join(p.status.ResourcePath, fmt.Sprintf("%s-json.log", c.Id)) glog.V(1).Info("configure container log to ", ctx.LogPath) } if c.Logs.Driver, err = creator(ctx); err != nil { return } glog.V(1).Infof("configured logger for %s/%s (%s)", p.id, c.Id, c.Name) } return nil } func (p *Pod) startLogging(daemon *Daemon) (err error) { err = nil if err = p.getLogger(daemon); err != nil { return } if p.spec.LogConfig.Type == "none" { return nil } for _, c := range p.status.Containers { var stdout, stderr io.Reader tag := "log-" + utils.RandStr(8, "alphanum") if stdout, stderr, err = p.vm.GetLogOutput(c.Id, tag, nil); err != nil { return } c.Logs.Copier = logger.NewCopier(c.Id, map[string]io.Reader{"stdout": stdout, "stderr": stderr}, c.Logs.Driver) c.Logs.Copier.Run() if jl, ok := c.Logs.Driver.(*jsonfilelog.JSONFileLogger); ok { c.Logs.LogPath = jl.LogPath() } } return nil } func (p *Pod) AttachTtys(streams []*hypervisor.TtyIO) (err error) { ttyContainers := p.containers if p.spec.Type == "service-discovery" { ttyContainers = p.containers[1:] } for idx, str := range streams { if idx >= len(ttyContainers) { break } err = p.vm.Attach(str.Stdin, str.Stdout, str.ClientTag, ttyContainers[idx].Id, str.Callback, nil) if err != nil { glog.Errorf("Failed to attach client %s before start pod", str.ClientTag) return } glog.V(1).Infof("Attach client %s before start pod", str.ClientTag) } return nil } func (p *Pod) Start(daemon *Daemon, vmId string, lazy, autoremove bool, keep int, streams []*hypervisor.TtyIO) (*types.VmResponse, error) { var err error = nil if err = p.GetVM(daemon, vmId, lazy, keep); err != nil { return nil, err } defer func() { if err != nil && vmId == "" { p.KillVM(daemon) } }() if err = p.Prepare(daemon); err != nil { return nil, err } defer func() { if err != nil { stopLogger(p.status) } }() if err = p.startLogging(daemon); err != nil { return nil, err } if err = p.AttachTtys(streams); err != nil { return nil, err } vmResponse := p.vm.StartPod(p.status, p.spec, p.containers, p.volumes) if vmResponse.Data == nil { err = fmt.Errorf("VM response data is nil") return vmResponse, err } err = daemon.UpdateVmData(p.vm.Id, vmResponse.Data.([]byte)) if err != nil { glog.Error(err.Error()) return nil, err } // add or update the Vm info for POD err = daemon.UpdateVmByPod(p.id, p.vm.Id) if err != nil { glog.Error(err.Error()) return nil, err } return vmResponse, nil } func (daemon *Daemon) GetExitCode(podId, tag string, callback chan *types.VmResponse) error { var ( pod *Pod ok bool ) daemon.PodList.Lock() if pod, ok = daemon.PodList.Get(podId); !ok { daemon.PodList.Unlock() return fmt.Errorf("Can not find the POD instance of %s", podId) } if pod.vm == nil { daemon.PodList.Unlock() return fmt.Errorf("pod %s is already stopped", podId) } daemon.PodList.Unlock() return pod.vm.GetExitCode(tag, callback) } func (daemon *Daemon) StartPod(podId, podArgs, vmId string, config interface{}, lazy, autoremove bool, keep int, streams []*hypervisor.TtyIO) (int, string, error) { glog.V(1).Infof("podArgs: %s", podArgs) var ( err error p *Pod ) p, err = daemon.GetPod(podId, podArgs, autoremove) if err != nil { return -1, "", err } if p.vm != nil { return -1, "", fmt.Errorf("pod %s is already running", podId) } vmResponse, err := p.Start(daemon, vmId, lazy, autoremove, keep, streams) if err != nil { return -1, "", err } return vmResponse.Code, vmResponse.Cause, nil } // The caller must make sure that the restart policy and the status is right to restart func (daemon *Daemon) RestartPod(mypod *hypervisor.PodStatus) error { // Remove the pod // The pod is stopped, the vm is gone for _, c := range mypod.Containers { glog.V(1).Infof("Ready to rm container: %s", c.Id) if _, _, err := daemon.DockerCli.SendCmdDelete(c.Id); err != nil { glog.V(1).Infof("Error to rm container: %s", err.Error()) } } daemon.RemovePod(mypod.Id) daemon.DeletePodContainerFromDB(mypod.Id) daemon.DeleteVolumeId(mypod.Id) podData, err := daemon.GetPodByName(mypod.Id) if err != nil { return err } var lazy bool = hypervisor.HDriver.SupportLazyMode() // Start the pod _, _, err = daemon.StartPod(mypod.Id, string(podData), "", nil, lazy, false, types.VM_KEEP_NONE, []*hypervisor.TtyIO{}) if err != nil { glog.Error(err.Error()) return err } if err := daemon.WritePodAndContainers(mypod.Id); err != nil { glog.Error("Found an error while saving the Containers info") return err } return nil } func hyperHandlePodEvent(vmResponse *types.VmResponse, data interface{}, mypod *hypervisor.PodStatus, vm *hypervisor.Vm) bool { daemon := data.(*Daemon) if vmResponse.Code == types.E_POD_FINISHED { if vm.Keep != types.VM_KEEP_NONE { vm.Status = types.S_VM_IDLE return false } stopLogger(mypod) mypod.SetPodContainerStatus(vmResponse.Data.([]uint32)) vm.Status = types.S_VM_IDLE if mypod.Autoremove == true { daemon.CleanPod(mypod.Id) return false } } else if vmResponse.Code == types.E_VM_SHUTDOWN { if mypod.Status == types.S_POD_RUNNING { stopLogger(mypod) mypod.Status = types.S_POD_SUCCEEDED mypod.SetContainerStatus(types.S_POD_SUCCEEDED) } mypod.Vm = "" daemon.PodStopped(mypod.Id) if mypod.Type == "kubernetes" { switch mypod.Status { case types.S_POD_SUCCEEDED: if mypod.RestartPolicy == "always" { daemon.RestartPod(mypod) break } daemon.DeletePodFromDB(mypod.Id) for _, c := range mypod.Containers { glog.V(1).Infof("Ready to rm container: %s", c.Id) if _, _, err := daemon.DockerCli.SendCmdDelete(c.Id); err != nil { glog.V(1).Infof("Error to rm container: %s", err.Error()) } } daemon.DeletePodContainerFromDB(mypod.Id) daemon.DeleteVolumeId(mypod.Id) break case types.S_POD_FAILED: if mypod.RestartPolicy != "never" { daemon.RestartPod(mypod) break } daemon.DeletePodFromDB(mypod.Id) for _, c := range mypod.Containers { glog.V(1).Infof("Ready to rm container: %s", c.Id) if _, _, err := daemon.DockerCli.SendCmdDelete(c.Id); err != nil { glog.V(1).Infof("Error to rm container: %s", err.Error()) } } daemon.DeletePodContainerFromDB(mypod.Id) daemon.DeleteVolumeId(mypod.Id) break default: break } } return true } return false } <file_sep>// +build !linux,!darwin package network func InitNetwork(bIface, bIP string, disableIptables bool) error { return nil } func Allocate(vmId, requestedIP string, addrOnly bool, maps []pod.UserContainerPort) (*Settings, error) { return nil, nil } func Configure(vmId, requestedIP string, addrOnly bool, maps []pod.UserContainerPort, config pod.UserInterface) (*Settings, error) { return nil, fmt.Errorf("Generial Network driver is unsupported on this os") } func Release(vmId, releasedIP string, maps []pod.UserContainerPort, file *os.File) error { return nil } <file_sep>package main import ( "encoding/json" "fmt" "io/ioutil" "os" "runtime" "github.com/codegangsta/cli" "github.com/opencontainers/runtime-spec/specs-go" ) var specCommand = cli.Command{ Name: "spec", Usage: "create a new specification file", Flags: []cli.Flag{ cli.StringFlag{ Name: "bundle, b", Usage: "path to the root of the bundle directory", }, }, Action: func(context *cli.Context) { spec := specs.Spec{ Version: specs.Version, Platform: specs.Platform{ OS: runtime.GOOS, Arch: runtime.GOARCH, }, Root: specs.Root{ Path: "rootfs", Readonly: true, }, Process: specs.Process{ Terminal: true, User: specs.User{}, Args: []string{ "sh", }, Env: []string{ "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", "TERM=xterm", }, }, Hostname: "shell", Linux: specs.Linux{ Resources: &specs.Resources{}, }, } checkNoFile := func(name string) error { _, err := os.Stat(name) if err == nil { return fmt.Errorf("File %s exists. Remove it first", name) } if !os.IsNotExist(err) { return err } return nil } bundle := context.String("bundle") if bundle != "" { if err := os.Chdir(bundle); err != nil { fmt.Printf("Failed to chdir to bundle dir:%s\nerror:%v\n", bundle, err) return } } if err := checkNoFile(specConfig); err != nil { fmt.Printf("%s\n", err.Error()) return } data, err := json.MarshalIndent(&spec, "", "\t") if err != nil { fmt.Printf("%s\n", err.Error()) return } if err := ioutil.WriteFile(specConfig, data, 0666); err != nil { fmt.Printf("%s\n", err.Error()) return } }, } func loadSpec(ocffile string) (*specs.Spec, error) { var spec specs.Spec if _, err := os.Stat(ocffile); os.IsNotExist(err) { return nil, fmt.Errorf("Please make sure bundle directory contains config.json: %v\n", err.Error()) } ocfData, err := ioutil.ReadFile(ocffile) if err != nil { return nil, err } if err := json.Unmarshal(ocfData, &spec); err != nil { return nil, err } return &spec, nil } <file_sep>package hypervisor import ( "bufio" "fmt" "os" "os/exec" "path/filepath" "strings" "syscall" "time" "github.com/golang/glog" "github.com/hyperhq/runv/hypervisor/pod" ) func CreateContainer(userPod *pod.UserPod, sharedDir string, hub chan VmEvent) (string, error) { return "", nil } func UmountOverlayContainer(shareDir, image string, index int, hub chan VmEvent) { mount := filepath.Join(shareDir, image) success := true for i := 0; i < 10; i++ { time.Sleep(3 * time.Second / 1000) err := syscall.Unmount(mount, 0) if err != nil { if !strings.Contains(strings.ToLower(err.Error()), "device or resource busy") { success = true break } glog.Warningf("Cannot umount overlay %s: %s", mount, err.Error()) success = false } else { success = true break } } hub <- &ContainerUnmounted{Index: index, Success: success} } func aufsUnmount(target string) error { glog.V(1).Infof("Ready to unmount the target : %s", target) if _, err := os.Stat(target); err != nil && os.IsNotExist(err) { return nil } cmdString := fmt.Sprintf("auplink %s flush", target) cmd := exec.Command("/bin/sh", "-c", cmdString) if err := cmd.Run(); err != nil { glog.Warningf("Couldn't run auplink command : %s\n%s", err.Error()) } if err := syscall.Unmount(target, 0); err != nil { return err } return nil } func UmountAufsContainer(shareDir, image string, index int, hub chan VmEvent) { mount := filepath.Join(shareDir, image) success := true for i := 0; i < 10; i++ { time.Sleep(3 * time.Second / 1000) err := aufsUnmount(mount) if err != nil { if !strings.Contains(strings.ToLower(err.Error()), "device or resource busy") { success = true break } glog.Warningf("Cannot umount aufs %s: %s", mount, err.Error()) success = false } else { success = true break } } hub <- &ContainerUnmounted{Index: index, Success: success} } func UmountVolume(shareDir, volPath string, name string, hub chan VmEvent) { mount := filepath.Join(shareDir, volPath) success := true err := syscall.Unmount(mount, 0) if err != nil { glog.Warningf("Cannot umount volume %s: %s", mount, err.Error()) err = syscall.Unmount(mount, syscall.MNT_DETACH) if err != nil { glog.Warningf("Cannot lazy umount volume %s: %s", mount, err.Error()) success = false } else { success = true } } if success == true { os.Remove(mount) } // After umount that device, we need to delete it hub <- &VolumeUnmounted{Name: name, Success: success} } func UmountDMDevice(deviceFullPath, name string, hub chan VmEvent) { args := fmt.Sprintf("dmsetup remove -f %s", deviceFullPath) cmd := exec.Command("/bin/sh", "-c", args) success := true if output, err := cmd.CombinedOutput(); err != nil { glog.Warningf("Cannot umount device %s: %s, %s", deviceFullPath, err.Error(), output) // retry cmd := exec.Command("/bin/sh", "-c", args) if err := cmd.Run(); err != nil { success = false } } else { // Command was successful success = true } // After umount that device, we need to delete it hub <- &BlockdevRemovedEvent{Name: name, Success: success} } func UmountRbdDevice(deviceFullPath, name string, hub chan VmEvent) { args := fmt.Sprintf("rbd unmap %s",deviceFullPath) cmd := exec.Command("/bin/sh","-c",args) success := true if output,err := cmd.CombinedOutput(); err != nil { glog.Warningf("Cannot umount device %s: %s, %s",deviceFullPath,err.Error(),output) // retry cmd := exec.Command("/bin/sh","-c",args) if err := cmd.Run(); err != nil { success = false } } else { // Command was successful success = true } // After umount that device, we need to delete it hub <- &BlockdevRemovedEvent{Name: name,Success: success} } func supportAufs() bool { f, err := os.Open("/proc/filesystems") if err != nil { return false } defer f.Close() s := bufio.NewScanner(f) for s.Scan() { if strings.Contains(s.Text(), "aufs") { return true } } return false } func supportOverlay() bool { f, err := os.Open("/proc/filesystems") if err != nil { return false } defer f.Close() s := bufio.NewScanner(f) for s.Scan() { if strings.Contains(s.Text(), "overlay") { return true } } return false } <file_sep>#!/bin/bash set -o errexit set -o nounset set -o pipefail # The root of the build/dist directory HYPER_ROOT=$(readlink -f $(dirname "${BASH_SOURCE}")/../..) HYPER_OUTPUT_BINPATH="${HYPER_ROOT}" source "${HYPER_ROOT}/hack/lib/util.sh" source "${HYPER_ROOT}/hack/lib/logging.sh" hyper::log::install_errexit source "${HYPER_ROOT}/hack/lib/version.sh" source "${HYPER_ROOT}/hack/lib/test.sh" source "${HYPER_ROOT}/hack/lib/hyperstart.sh" HYPER_OUTPUT_HOSTBIN="${HYPER_OUTPUT_BINPATH}" <file_sep>package supervisor import ( "fmt" "os" "strings" "sync" "time" "github.com/golang/glog" "github.com/hyperhq/runv/factory" "github.com/opencontainers/runtime-spec/specs-go" ) type Supervisor struct { StateDir string Factory factory.Factory Events SvEvents sync.RWMutex // Protects Supervisor.Containers, HyperPod.Containers, HyperPod.Processes, Container.Processes Containers map[string]*Container } func New(stateDir, eventLogDir string, f factory.Factory) (*Supervisor, error) { if err := os.MkdirAll(stateDir, 0755); err != nil { return nil, err } if err := os.MkdirAll(eventLogDir, 0755); err != nil { return nil, err } sv := &Supervisor{ StateDir: stateDir, Factory: f, Containers: make(map[string]*Container), } sv.Events.subscribers = make(map[chan Event]struct{}) go sv.reaper() return sv, sv.Events.setupEventLog(eventLogDir) } func (sv *Supervisor) CreateContainer(container, bundlePath, stdin, stdout, stderr string, spec *specs.Spec) (*Container, *Process, error) { sv.Lock() defer sv.Unlock() hp, err := sv.getHyperPod(container, spec) if err != nil { return nil, nil, err } c, err := hp.createContainer(container, bundlePath, stdin, stdout, stderr, spec) if err != nil { return nil, nil, err } sv.Containers[container] = c glog.Infof("Supervisor.CreateContainer() return: c:%v p:%v", c, c.Processes["init"]) return c, c.Processes["init"], nil } func (sv *Supervisor) AddProcess(container, processId, stdin, stdout, stderr string, spec *specs.Process) (*Process, error) { sv.Lock() defer sv.Unlock() if c, ok := sv.Containers[container]; ok { return c.addProcess(processId, stdin, stdout, stderr, spec) } return nil, fmt.Errorf("container %s is not found for AddProcess()", container) } func (sv *Supervisor) TtyResize(container, processId string, width, height int) error { sv.RLock() defer sv.RUnlock() p := sv.getProcess(container, processId) if p != nil { return p.ttyResize(width, height) } return fmt.Errorf("The container %s or the process %s is not found", container, processId) } func (sv *Supervisor) CloseStdin(container, processId string) error { sv.RLock() defer sv.RUnlock() p := sv.getProcess(container, processId) if p != nil { return p.closeStdin() } return fmt.Errorf("The container %s or the process %s is not found", container, processId) } func (sv *Supervisor) Signal(container, processId string, sig int) error { sv.RLock() defer sv.RUnlock() p := sv.getProcess(container, processId) if p != nil { return p.signal(sig) } return fmt.Errorf("The container %s or the process %s is not found", container, processId) } func (sv *Supervisor) getProcess(container, processId string) *Process { if c, ok := sv.Containers[container]; ok { if p, ok := c.Processes[processId]; ok { return p } } return nil } func (sv *Supervisor) reaper() { events := sv.Events.Events(time.Time{}) for e := range events { if e.Type == EventExit { go sv.reap(e.ID, e.PID) } } } func (sv *Supervisor) reap(container, processId string) { glog.Infof("reap container %s processId %s", container, processId) sv.Lock() defer sv.Unlock() if c, ok := sv.Containers[container]; ok { if p, ok := c.Processes[processId]; ok { go p.reap() delete(c.ownerPod.Processes, processId) delete(c.Processes, processId) if p.init { // TODO: kill all the other existing processes in the same container } if len(c.Processes) == 0 { go c.reap() delete(c.ownerPod.Containers, container) delete(sv.Containers, container) } if len(c.ownerPod.Containers) == 0 { go c.ownerPod.reap() } } } } // find shared pod or create a new one func (sv *Supervisor) getHyperPod(container string, spec *specs.Spec) (hp *HyperPod, err error) { if _, ok := sv.Containers[container]; ok { return nil, fmt.Errorf("The container %s is already existing", container) } for _, ns := range spec.Linux.Namespaces { if ns.Path != "" { if strings.Contains(ns.Path, "/") { return nil, fmt.Errorf("Runv doesn't support path to namespace file, it supports containers name as shared namespaces only") } if ns.Type == "mount" { // TODO support it! return nil, fmt.Errorf("Runv doesn't support shared mount namespace currently") } shared := ns.Path cnt, ok := sv.Containers[shared] if !ok { return nil, fmt.Errorf("The container %s is not existing to share with", shared) } if hp == nil { hp = cnt.ownerPod } else if cnt.ownerPod != hp { return nil, fmt.Errorf("conflict share") } } } if hp == nil { sv.Unlock() hp, err = createHyperPod(sv.Factory, spec) sv.Lock() glog.Infof("createHyperPod() returns") if err != nil { return nil, err } hp.sv = sv // recheck existed if _, ok := sv.Containers[container]; ok { go hp.reap() return nil, fmt.Errorf("The container %s is already existing", container) } } return hp, nil } <file_sep>package hypervisor const ( BaseDir = "/var/run/hyper" HyperSockName = "hyper.sock" TtySockName = "tty.sock" ConsoleSockName = "console.sock" ShareDirTag = "share_dir" DefaultKernel = "/var/lib/hyper/kernel" DefaultInitrd = "/var/lib/hyper/hyper-initrd.img" DetachKeys = "ctrl-p,ctrl-q" // cpu/mem hotplug constants DefaultMaxCpus = 8 // CONFIG_NR_CPUS hyperstart.git/build/kernel_config DefaultMaxMem = 32768 // size in MiB ) var InterfaceCount int = 1 var PciAddrFrom int = 0x05 const ( EVENT_VM_START_FAILED = iota EVENT_VM_EXIT EVENT_VM_KILL EVENT_VM_TIMEOUT EVENT_POD_FINISH EVENT_INIT_CONNECTED EVENT_CONTAINER_ADD EVENT_CONTAINER_DELETE EVENT_VOLUME_ADD EVENT_VOLUME_DELETE EVENT_BLOCK_INSERTED EVENT_DEV_SKIP EVENT_BLOCK_EJECTED EVENT_INTERFACE_ADD EVENT_INTERFACE_DELETE EVENT_INTERFACE_INSERTED EVENT_INTERFACE_EJECTED EVENT_SERIAL_ADD EVENT_SERIAL_DELETE EVENT_TTY_OPEN EVENT_TTY_CLOSE EVENT_PAUSE_RESULT COMMAND_GET_POD_IP COMMAND_RUN_POD COMMAND_REPLACE_POD COMMAND_STOP_POD COMMAND_SHUTDOWN COMMAND_RELEASE COMMAND_NEWCONTAINER COMMAND_EXEC COMMAND_KILL COMMAND_ONLINECPUMEM COMMAND_WRITEFILE COMMAND_READFILE COMMAND_ATTACH COMMAND_DETACH COMMAND_WINDOWSIZE COMMAND_ACK COMMAND_GET_POD_STATS COMMAND_PAUSEVM GENERIC_OPERATION ERROR_INIT_FAIL ERROR_QMP_FAIL ERROR_INTERRUPTED ERROR_CMD_FAIL ) const ( INIT_RESERVED = iota INIT_STARTPOD INIT_GETPOD INIT_STOPPOD INIT_DESTROYPOD INIT_RESTARTCONTAINER INIT_EXECCMD INIT_FINISHCMD INIT_READY INIT_ACK INIT_ERROR INIT_WINSIZE INIT_PING INIT_FINISHPOD INIT_NEXT INIT_WRITEFILE INIT_READFILE INIT_NEWCONTAINER INIT_KILLCONTAINER INIT_ONLINECPUMEM ) func EventString(ev int) string { switch ev { case EVENT_VM_START_FAILED: return "EVENT_VM_START_FAILED" case EVENT_VM_EXIT: return "EVENT_VM_EXIT" case EVENT_VM_KILL: return "EVENT_VM_KILL" case EVENT_VM_TIMEOUT: return "EVENT_VM_TIMEOUT" case COMMAND_PAUSEVM: return "COMMAND_PAUSEVM" case EVENT_PAUSE_RESULT: return "EVENT_PAUSE_RESULT" case EVENT_POD_FINISH: return "EVENT_POD_FINISH" case EVENT_INIT_CONNECTED: return "EVENT_INIT_CONNECTED" case EVENT_CONTAINER_ADD: return "EVENT_CONTAINER_ADD" case EVENT_CONTAINER_DELETE: return "EVENT_CONTAINER_DELETE" case EVENT_VOLUME_ADD: return "EVENT_VOLUME_ADD" case EVENT_VOLUME_DELETE: return "EVENT_VOLUME_DELETE" case EVENT_DEV_SKIP: return "EVENT_DEV_SKIP" case EVENT_BLOCK_INSERTED: return "EVENT_BLOCK_INSERTED" case EVENT_BLOCK_EJECTED: return "EVENT_BLOCK_EJECTED" case EVENT_INTERFACE_ADD: return "EVENT_INTERFACE_ADD" case EVENT_INTERFACE_DELETE: return "EVENT_INTERFACE_DELETE" case EVENT_INTERFACE_INSERTED: return "EVENT_INTERFACE_INSERTED" case EVENT_INTERFACE_EJECTED: return "EVENT_INTERFACE_EJECTED" case EVENT_SERIAL_ADD: return "EVENT_SERIAL_ADD" case EVENT_SERIAL_DELETE: return "EVENT_SERIAL_DELETE" case EVENT_TTY_OPEN: return "EVENT_TTY_OPEN" case EVENT_TTY_CLOSE: return "EVENT_TTY_CLOSE" case COMMAND_GET_POD_IP: return "COMMAND_GET_POD_IP" case COMMAND_RUN_POD: return "COMMAND_RUN_POD" case COMMAND_REPLACE_POD: return "COMMAND_REPLACE_POD" case COMMAND_STOP_POD: return "COMMAND_STOP_POD" case COMMAND_SHUTDOWN: return "COMMAND_SHUTDOWN" case COMMAND_RELEASE: return "COMMAND_RELEASE" case COMMAND_NEWCONTAINER: return "COMMAND_NEWCONTAINER" case COMMAND_EXEC: return "COMMAND_EXEC" case COMMAND_WRITEFILE: return "COMMAND_WRITEFILE" case COMMAND_READFILE: return "COMMAND_READFILE" case COMMAND_ATTACH: return "COMMAND_ATTACH" case COMMAND_DETACH: return "COMMAND_DETACH" case COMMAND_WINDOWSIZE: return "COMMAND_WINDOWSIZE" case COMMAND_ACK: return "COMMAND_ACK" case COMMAND_GET_POD_STATS: return "COMMAND_GET_POD_STATS" case COMMAND_ONLINECPUMEM: return "COMMAND_ONLINECPUMEM" case GENERIC_OPERATION: return "GENERIC_OPERATION" case ERROR_INIT_FAIL: return "ERROR_INIT_FAIL" case ERROR_QMP_FAIL: return "ERROR_QMP_FAIL" case ERROR_INTERRUPTED: return "ERROR_INTERRUPTED" case ERROR_CMD_FAIL: return "ERROR_CMD_FAIL" } return "UNKNOWN" } <file_sep>package utils //#include <stdio.h> //#include <stdlib.h> //#include <unistd.h> //#include <signal.h> //#include <sys/types.h> //#include <sys/stat.h> //#include <sys/wait.h> //#include <sys/time.h> //#include <sys/resource.h> //#include <fcntl.h> /* int daemonize(char *cmd, char *argv[], int pipe, int fds[], int num) { int status = 0, fd, pid, i; struct sigaction sa; pid = fork(); if (pid < 0) { return -1; } else if (pid > 0) { if (waitpid(pid, &status, 0) < 0) return -1; return WEXITSTATUS(status); } //Become a session leader to lose controlling TTY setsid(); //Ensure future opens won't allocate controlling TTYs sa.sa_handler = SIG_IGN; sigemptyset(&sa.sa_mask); sa.sa_flags = 0; if (sigaction(SIGHUP, &sa, NULL) < 0) { _exit(-1); } pid = fork(); if (pid < 0) { _exit(-1); } else if (pid > 0) { _exit(0); } if (pipe > 0) { char buf[4]; int ret; pid = getpid(); buf[0] = pid >> 24; buf[1] = pid >> 16; buf[2] = pid >> 8; buf[3] = pid; ret = write(pipe, buf, 4); if (ret != 4) _exit(-1); } //Clear file creation mask umask(0); //Change the current working directory to the root so we won't prevent file system from being unmounted if (chdir("/") < 0) _exit(-1); //Close all open file descriptors // for (i = 0; i < num; i++) { // if (fds[i] == 0 || fds[i] == 1 || fds[i] == 2) // continue; // printf("\n\nI didnt close any file descriptor\n\n"); // close(fds[i]); // } //Attach file descriptors 0, 1, and 2 to /dev/null fd = open("/dev/null", O_RDWR); dup2(fd, 0); dup2(fd, 1); dup2(fd, 2); close(fd); if (execvp(cmd, argv) < 0) _exit(-1); return -1; } */ import "C" import ( "encoding/binary" "fmt" "io/ioutil" "strconv" "syscall" "unsafe" ) func ExecInDaemon(cmd string, argv []string) (pid uint32, err error) { // convert the args to the C style args // +1 for the list of arguments must be terminated by a null pointer cargs := make([]*C.char, len(argv)+1) for idx, a := range argv { cargs[idx] = C.CString(a) } // collect all the opened fds and close them when exec the daemon fds := (*C.int)(nil) num := C.int(0) fdlist := listFd() if len(fdlist) != 0 { fds = (*C.int)(unsafe.Pointer(&fdlist[0])) num = C.int(len(fdlist)) } // create pipe for geting the daemon pid pipe := make([]int, 2) err = syscall.Pipe(pipe) if err != nil { return 0, fmt.Errorf("fail to create pipe: %v", err) } // do the job! ret, err := C.daemonize(C.CString(cmd), (**C.char)(unsafe.Pointer(&cargs[0])), C.int(pipe[1]), fds, num) if err != nil || ret < 0 { return 0, fmt.Errorf("fail to start %s in daemon mode: %v", argv[0], err) } // get the daemon pid buf := make([]byte, 4) nr, err := syscall.Read(pipe[0], buf) if err != nil || nr != 4 { return 0, fmt.Errorf("fail to start %s in daemon mode or fail to get pid: %v", argv[0], err) } syscall.Close(pipe[1]) syscall.Close(pipe[0]) pid = binary.BigEndian.Uint32(buf[:nr]) return pid, nil } func listFd() []int { files, err := ioutil.ReadDir("/proc/self/fd/") if err != nil { return []int{} } result := []int{} for _, file := range files { f, err := strconv.Atoi(file.Name()) if err != nil { continue } result = append(result, f) } return result } <file_sep>package main import ( "encoding/json" "fmt" "io/ioutil" "os" "runtime" "github.com/codegangsta/cli" "github.com/opencontainers/specs" ) var specCommand = cli.Command{ Name: "spec", Usage: "create a new specification file", Flags: []cli.Flag{ cli.StringFlag{ Name: "config-file, c", Value: "config.json", Usage: "path to spec config file for writing", }, cli.StringFlag{ Name: "runtime-file, r", Value: "runtime.json", Usage: "path to runtime config file for writing", }, }, Action: func(context *cli.Context) { spec := specs.Spec{ Version: specs.Version, Platform: specs.Platform{ OS: runtime.GOOS, Arch: runtime.GOARCH, }, Root: specs.Root{ Path: "rootfs", Readonly: true, }, Process: specs.Process{ Terminal: true, User: specs.User{}, Args: []string{ "sh", }, Env: []string{ "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", "TERM=xterm", }, }, Hostname: "shell", } rspec := specs.LinuxRuntimeSpec{ Linux: specs.LinuxRuntime{ Resources: &specs.Resources{}, }, } checkNoFile := func(name string) error { _, err := os.Stat(name) if err == nil { return fmt.Errorf("File %s exists. Remove it first", name) } if !os.IsNotExist(err) { return err } return nil } cName := context.String("config-file") rName := context.String("runtime-file") if err := checkNoFile(cName); err != nil { fmt.Printf("%s", err.Error()) return } if err := checkNoFile(rName); err != nil { fmt.Printf("%s", err.Error()) return } data, err := json.MarshalIndent(&spec, "", "\t") if err != nil { fmt.Printf("%s", err.Error()) return } if err := ioutil.WriteFile(cName, data, 0666); err != nil { fmt.Printf("%s", err.Error()) return } rdata, err := json.MarshalIndent(&rspec, "", "\t") if err != nil { fmt.Printf("%s", err.Error()) return } if err := ioutil.WriteFile(rName, rdata, 0666); err != nil { fmt.Printf("%s", err.Error()) return } }, } <file_sep>package daemon import ( "fmt" "github.com/golang/glog" "github.com/hyperhq/hyper/engine" ) func (daemon *Daemon) CmdExitCode(job *engine.Job) (err error) { if len(job.Args) == 0 { return fmt.Errorf("Can not execute 'exitstatus' command without container id!") } if len(job.Args) == 1 { return fmt.Errorf("Can not execute 'exitstatus' command without tag!") } var ( container = job.Args[0] tag = job.Args[1] code = -1 vmId string podId string ) glog.V(1).Infof("Get container id is %s", container) podId, err = daemon.GetPodByContainer(container) if err != nil { return } vmId, err = daemon.GetVmByPodId(podId) if err != nil { return err } vm, ok := daemon.VmList[vmId] if !ok { return fmt.Errorf("Can not find VM whose Id is %s!", vmId) } if _, ok := vm.ExitCodes[tag]; ok { code = int(vm.ExitCodes[tag]) } v := &engine.Env{} v.Set("ExitCode", fmt.Sprintf("%d", code)) if _, err := v.WriteTo(job.Stdout); err != nil { return err } return nil } func (daemon *Daemon) CmdExec(job *engine.Job) (err error) { if len(job.Args) == 0 { return fmt.Errorf("Can not execute 'exec' command without any container ID!") } if len(job.Args) == 1 { return fmt.Errorf("Can not execute 'exec' command without any command!") } var ( typeKey = job.Args[0] typeVal = job.Args[1] cmd = job.Args[2] tag = job.Args[3] vmId string podId string container string ) // We need find the vm id which running POD, and stop it if typeKey == "pod" { vmId = typeVal container = "" } else { container = typeVal glog.V(1).Infof("Get container id is %s", container) podId, err = daemon.GetPodByContainer(container) if err != nil { return } vmId, err = daemon.GetVmByPodId(podId) } if err != nil { return err } vm, ok := daemon.VmList[vmId] if !ok { return fmt.Errorf("Can not find VM whose Id is %s!", vmId) } err = vm.Exec(job.Stdin, job.Stdout, cmd, tag, container) if err != nil { return err } defer func() { glog.V(2).Info("Defer function for exec!") }() return nil } <file_sep>#!/bin/bash su makerpm -c "rpmbuild -ba hyper.spec" su makerpm -c "rpmbuild -ba hyperstart.spec" <file_sep>package pod import "fmt" type KPod struct { Kind string `json:"kind"` Meta *KMeta `json:"metadata"` Spec *KSpec `json:"spec"` } type KSpec struct { Containers []*KContainer `json:"containers"` Volumes []*KVolume `json:"volumes"` RestartPolicy string `json:"restartPolicy"` DNSPolicy []string } type KMeta struct { Name string `json:"name"` Labels map[string]string `json:"labels,omitempty"` } type KContainer struct { Name string `json:"name"` Image string `json:"image"` Command []string `json:"command"` Args []string `json:"args"` WorkingDir string `json:"workingDir"` Resources map[string]interface{} `json:"resources"` CPU int Memory int64 Volumes []*KVolumeReference `json:"volumeMounts"` Ports []*KPort `json:"ports"` Env []*KEnv `json:"env"` } type KVolumeReference struct { Name string `json:"name"` MountPath string `json:"mountPath"` ReadOnly bool `json:"readOnly"` } type KPort struct { Name string `json:"name"` ContainerPort int `json:"containerPort"` HostPort int `json:"hostPort"` Protocol string `json:"protocol"` } type KEnv struct { Name string `json:"name"` Value string `json:"value"` } type KVolume struct { Name string `json:"name"` Source *KVolumeSource `json:"source"` } type KVolumeSource struct { EmptyDir *KEmptyDir `json:"emptyDir"` HostDir *KHostDir `json:"hostDir"` GCEPersistentDisk *KGCEPersistentDisk } type KEmptyDir struct{} type KHostDir struct { Path string `json:"path"` } type KGCEPersistentDisk struct{} func (kp *KPod) Convert() (*UserPod, error) { name := "default" if kp.Meta != nil && kp.Meta.Name != "" { name = kp.Meta.Name } if kp.Kind != "Pod" { return nil, fmt.Errorf("kind of the json is not Pod: %s", kp.Kind) } if kp.Spec == nil { return nil, fmt.Errorf("No spec in the file") } rpolicy := "never" switch kp.Spec.RestartPolicy { case "Never": rpolicy = "never" case "Always": rpolicy = "always" case "OnFailure": rpolicy = "onFailure" default: } var memory int64 = 0 containers := make([]UserContainer, len(kp.Spec.Containers)) for i, kc := range kp.Spec.Containers { memory += kc.Memory ports := make([]UserContainerPort, len(kc.Ports)) for j, p := range kc.Ports { ports[j] = UserContainerPort{ HostPort: p.HostPort, ContainerPort: p.ContainerPort, Protocol: p.Protocol, } } envs := make([]UserEnvironmentVar, len(kc.Env)) for j, e := range kc.Env { envs[j] = UserEnvironmentVar{ Env: e.Name, Value: e.Value, } } vols := make([]UserVolumeReference, len(kc.Volumes)) for j, v := range kc.Volumes { vols[j] = UserVolumeReference{ Path: v.MountPath, Volume: v.Name, ReadOnly: v.ReadOnly, } } containers[i] = UserContainer{ Name: kc.Name, Image: kc.Image, Entrypoint: kc.Command, Command: kc.Args, Workdir: kc.WorkingDir, Ports: ports, Envs: envs, Volumes: vols, Files: []UserFileReference{}, RestartPolicy: "never", } } volumes := make([]UserVolume, len(kp.Spec.Volumes)) for i, vol := range kp.Spec.Volumes { volumes[i].Name = vol.Name if vol.Source.HostDir != nil && vol.Source.HostDir.Path != "" { volumes[i].Source = vol.Source.HostDir.Path volumes[i].Driver = "vfs" } else { volumes[i].Source = "" volumes[i].Driver = "" } } return &UserPod{ Name: name, Containers: containers, Labels: kp.Meta.Labels, Resource: UserResource{ Vcpu: 1, Memory: int(memory / 1024 / 1024), }, Volumes: volumes, Tty: true, Type: "kubernetes", RestartPolicy: rpolicy, }, nil } <file_sep>package supervisor import ( "encoding/json" "io" "os" "path/filepath" "sync" "time" "github.com/golang/glog" ) const ( EventExit = "exit" EventContainerStart = "start-container" EventProcessStart = "start-process" ) var ( defaultEventsBufferSize = 128 ) type Event struct { ID string `json:"id"` Type string `json:"type"` Timestamp time.Time `json:"timestamp"` PID string `json:"pid,omitempty"` Status int `json:"status,omitempty"` } // TODO: copied code, including two bugs // eventLog is not protected // Events() might be deadlocked type SvEvents struct { sync.RWMutex subscribers map[chan Event]struct{} eventLog []Event } func (se *SvEvents) setupEventLog(logDir string) error { if err := se.readEventLog(logDir); err != nil { return err } events := se.Events(time.Time{}) f, err := os.OpenFile(filepath.Join(logDir, "events.log"), os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0755) if err != nil { return err } enc := json.NewEncoder(f) go func() { for e := range events { glog.Infof("write event log: %v", e) se.eventLog = append(se.eventLog, e) if err := enc.Encode(e); err != nil { glog.Infof("containerd: fail to write event to journal") } } }() return nil } func (se *SvEvents) readEventLog(logDir string) error { f, err := os.Open(filepath.Join(logDir, "events.log")) if err != nil { if os.IsNotExist(err) { return nil } return err } defer f.Close() dec := json.NewDecoder(f) for { var e Event if err := dec.Decode(&e); err != nil { if err == io.EOF { break } return err } se.eventLog = append(se.eventLog, e) } return nil } // Events returns an event channel that external consumers can use to receive updates // on container events func (se *SvEvents) Events(from time.Time) chan Event { se.Lock() defer se.Unlock() c := make(chan Event, defaultEventsBufferSize) se.subscribers[c] = struct{}{} if !from.IsZero() { // replay old event for _, e := range se.eventLog { if e.Timestamp.After(from) { c <- e } } // Notify the client that from now on it's live events c <- Event{ Type: "live", Timestamp: time.Now(), } } return c } // Unsubscribe removes the provided channel from receiving any more events func (se *SvEvents) Unsubscribe(sub chan Event) { se.Lock() defer se.Unlock() delete(se.subscribers, sub) close(sub) } // notifySubscribers will send the provided event to the external subscribers // of the events channel func (se *SvEvents) notifySubscribers(e Event) { glog.Infof("notifySubscribers: %v", e) se.RLock() defer se.RUnlock() for sub := range se.subscribers { // do a non-blocking send for the channel select { case sub <- e: default: glog.Infof("containerd: event not sent to subscriber") } } } <file_sep>package vbox import ( "fmt" "net" "os" "strings" "github.com/golang/glog" "github.com/hyperhq/runv/hypervisor/network" "github.com/hyperhq/runv/hypervisor/pod" "github.com/hyperhq/runv/lib/govbox" ) func (vd *VBoxDriver) BuildinNetwork() bool { return true } func (vd *VBoxDriver) InitNetwork(bIface, bIP string, disableIptables bool) error { var i = 0 if bIP == "" { network.BridgeIP = network.DefaultBridgeIP } else { network.BridgeIP = bIP } bip, ipnet, err := net.ParseCIDR(network.BridgeIP) if err != nil { glog.Errorf(err.Error()) return err } gateway := bip.Mask(ipnet.Mask) inc(gateway, 2) if !ipnet.Contains(gateway) { glog.Errorf(err.Error()) return fmt.Errorf("get Gateway from BridgeIP %s failed", network.BridgeIP) } prefixSize, _ := ipnet.Mask.Size() _, network.BridgeIPv4Net, err = net.ParseCIDR(gateway.String() + fmt.Sprintf("/%d", prefixSize)) if err != nil { glog.Errorf(err.Error()) return err } network.BridgeIPv4Net.IP = gateway glog.Warningf(network.BridgeIPv4Net.String()) /* * Filter the IPs which can not be used for VMs */ bip = bip.Mask(ipnet.Mask) for inc(bip, 1); ipnet.Contains(bip) && i < 2; inc(bip, 1) { i++ glog.V(3).Infof("Try %s", bip.String()) _, err = network.IpAllocator.RequestIP(network.BridgeIPv4Net, bip) if err != nil { glog.Errorf(err.Error()) return err } } return nil } func SetupPortMaps(vmId string, containerip string, maps []pod.UserContainerPort) error { if len(maps) == 0 { return nil } for _, m := range maps { var proto string if strings.EqualFold(m.Protocol, "udp") { proto = "udp" } else { proto = "tcp" } rule := virtualbox.PFRule{} rule.Proto = virtualbox.PFProto(proto) rule.HostIP = nil rule.HostPort = uint16(m.HostPort) rule.GuestIP = net.ParseIP(containerip) rule.GuestPort = uint16(m.ContainerPort) err := virtualbox.SetNATPF(vmId, 1, vmId, rule) if err != nil { return err } err = network.PortMapper.AllocateMap(m.Protocol, m.HostPort, containerip, m.ContainerPort) if err != nil { return err } } /* forbid to map ports twice */ return nil } func ReleasePortMaps(vmId string, containerip string, maps []pod.UserContainerPort) error { if len(maps) == 0 { return nil } for _, m := range maps { glog.V(1).Infof("release port map %d", m.HostPort) err := network.PortMapper.ReleaseMap(m.Protocol, m.HostPort) if err != nil { continue } } /* forbid to map ports twice */ return nil } func (vc *VBoxContext) AllocateNetwork(vmId, requestedIP string, maps []pod.UserContainerPort) (*network.Settings, error) { ip, err := network.IpAllocator.RequestIP(network.BridgeIPv4Net, net.ParseIP(requestedIP)) if err != nil { return nil, err } maskSize, _ := network.BridgeIPv4Net.Mask.Size() err = SetupPortMaps(vmId, ip.String(), maps) if err != nil { glog.Errorf("Setup Port Map failed %s", err) return nil, err } return &network.Settings{ Mac: "", IPAddress: ip.String(), Gateway: network.BridgeIPv4Net.IP.String(), Bridge: "", IPPrefixLen: maskSize, Device: "", File: nil, }, nil } func (vc *VBoxContext) ConfigureNetwork(vmId, requestedIP string, maps []pod.UserContainerPort, config pod.UserInterface) (*network.Settings, error) { ip, ipnet, err := net.ParseCIDR(config.Ip) if err != nil { glog.Errorf("Parse interface IP failed %s", err) return nil, err } maskSize, _ := ipnet.Mask.Size() err = SetupPortMaps(vmId, ip.String(), maps) if err != nil { glog.Errorf("Setup Port Map failed %s", err) return nil, err } return &network.Settings{ Mac: config.Mac, IPAddress: ip.String(), Gateway: config.Gw, Bridge: "", IPPrefixLen: maskSize, Device: "", File: nil, }, nil } // Release an interface for a select ip func (vc *VBoxContext) ReleaseNetwork(vmId, releasedIP string, maps []pod.UserContainerPort, file *os.File) error { if err := network.IpAllocator.ReleaseIP(network.BridgeIPv4Net, net.ParseIP(releasedIP)); err != nil { return err } if err := ReleasePortMaps(vmId, releasedIP, maps); err != nil { glog.Errorf("fail to release port map %s", err) return err } return nil } func inc(ip net.IP, count int) { for j := len(ip) - 1; j >= 0; j-- { for i := 0; i < count; i++ { ip[j]++ } if ip[j] > 0 { break } } } <file_sep>package daemon import ( "fmt" "io" "os" "path" "strconv" "strings" "github.com/Unknwon/goconfig" dockertypes "github.com/docker/docker/api/types" "github.com/docker/docker/daemon/logger/jsonfilelog" "github.com/docker/docker/graph" "github.com/golang/glog" "github.com/hyperhq/hyper/engine" "github.com/hyperhq/hyper/lib/portallocator" apiserver "github.com/hyperhq/hyper/server" "github.com/hyperhq/hyper/utils" "github.com/hyperhq/runv/hypervisor" "github.com/hyperhq/runv/hypervisor/pod" "github.com/hyperhq/runv/hypervisor/types" "github.com/syndtr/goleveldb/leveldb" "github.com/syndtr/goleveldb/leveldb/util" ) var ( DefaultResourcePath string = "/var/run/hyper/Pods" ) type DockerInterface interface { SendCmdCreate(name, image string, cmds []string, config interface{}) ([]byte, int, error) SendCmdRestore(name, image, cid string, cmds []string, config interface{}) ([]byte, int, error) SendCmdDelete(arg ...string) ([]byte, int, error) SendCmdInfo(args ...string) (*dockertypes.Info, error) SendCmdImages(all string) ([]*dockertypes.Image, error) GetContainerInfo(args ...string) (*dockertypes.ContainerJSON, error) SendCmdPull(image string, config *graph.ImagePullConfig) ([]byte, int, error) SendCmdAuth(body io.ReadCloser) (string, error) SendCmdPush(remote string, ipconfig *graph.ImagePushConfig) error SendImageDelete(args ...string) ([]dockertypes.ImageDelete, error) SendImageBuild(image string, size int, context io.ReadCloser) ([]byte, int, error) SendContainerCommit(args ...string) ([]byte, int, error) SendContainerRename(oName, nName string) error Shutdown() error Setup() error } type Daemon struct { ID string db *leveldb.DB eng *engine.Engine DockerCli DockerInterface PodList *PodList VmList map[string]*hypervisor.Vm Kernel string Initrd string Bios string Cbfs string VboxImage string BridgeIface string BridgeIP string Host string Storage Storage Hypervisor string DefaultLog *pod.PodLogConfig } // Install installs daemon capabilities to eng. func (daemon *Daemon) Install(eng *engine.Engine) error { // Now, we just install a command 'info' to set/get the information of the docker and Hyper daemon for name, method := range map[string]engine.Handler{ "auth": daemon.CmdAuth, "info": daemon.CmdInfo, "version": daemon.CmdVersion, "create": daemon.CmdCreate, "pull": daemon.CmdPull, "build": daemon.CmdBuild, "commit": daemon.CmdCommit, "rename": daemon.CmdRename, "push": daemon.CmdPush, "podCreate": daemon.CmdPodCreate, "podStart": daemon.CmdPodStart, "podInfo": daemon.CmdPodInfo, "podStats": daemon.CmdPodStats, "podLabels": daemon.CmdPodLabels, "containerInfo": daemon.CmdContainerInfo, "containerLogs": daemon.CmdLogs, "podRm": daemon.CmdPodRm, "podStop": daemon.CmdPodStop, "podMigrate": daemon.CmdPodMigrate, "podListen": daemon.CmdPodListen, "vmCreate": daemon.CmdVmCreate, "vmKill": daemon.CmdVmKill, "list": daemon.CmdList, "exec": daemon.CmdExec, "exitcode": daemon.CmdExitCode, "attach": daemon.CmdAttach, "tty": daemon.CmdTty, "serviceAdd": daemon.AddService, "serviceList": daemon.GetServices, "serviceUpdate": daemon.UpdateService, "serviceDelete": daemon.DeleteService, "serveapi": apiserver.ServeApi, "acceptconnections": apiserver.AcceptConnections, "images": daemon.CmdImages, "imagesremove": daemon.CmdImagesRemove, } { glog.V(3).Infof("Engine Register: name= %s", name) if err := eng.Register(name, method); err != nil { return err } } return nil } func (daemon *Daemon) Restore() error { if daemon.GetPodNum() == 0 { return nil } podList := map[string]string{} iter := daemon.db.NewIterator(util.BytesPrefix([]byte("pod-")), nil) for iter.Next() { key := iter.Key() value := iter.Value() if strings.Contains(string(key), "pod-container-") { glog.V(1).Infof(string(value)) continue } glog.V(1).Infof("Get the pod item, pod is %s!", key) err := daemon.db.Delete(key, nil) if err != nil { return err } podList[string(key)[4:]] = string(value) } iter.Release() err := iter.Error() if err != nil { return err } daemon.PodList.Lock() glog.V(2).Infof("lock PodList") defer glog.V(2).Infof("unlock PodList") defer daemon.PodList.Unlock() for k, v := range podList { err = daemon.CreatePod(k, v, false) if err != nil { glog.Warningf("Got a unexpected error, %s", err.Error()) continue } vmId, err := daemon.DbGetVmByPod(k) if err != nil { glog.V(1).Info(err.Error(), " for ", k) continue } p, _ := daemon.PodList.Get(k) if err := p.AssociateVm(daemon, string(vmId)); err != nil { glog.V(1).Info("Some problem during associate vm %s to pod %s, %v", string(vmId), k, err) // continue to next } } return nil } func NewDaemon(eng *engine.Engine) (*Daemon, error) { daemon, err := NewDaemonFromDirectory(eng) if err != nil { return nil, err } return daemon, nil } func NewDaemonFromDirectory(eng *engine.Engine) (*Daemon, error) { // register portallocator release on shutdown eng.OnShutdown(func() { if err := portallocator.ReleaseAll(); err != nil { glog.Errorf("portallocator.ReleaseAll(): %s", err.Error()) } }) if os.Geteuid() != 0 { return nil, fmt.Errorf("The Hyper daemon needs to be run as root") } if err := checkKernel(); err != nil { return nil, err } cfg, err := goconfig.LoadConfigFile(eng.Config) if err != nil { glog.Errorf("Read config file (%s) failed, %s", eng.Config, err.Error()) return nil, err } kernel, _ := cfg.GetValue(goconfig.DEFAULT_SECTION, "Kernel") initrd, _ := cfg.GetValue(goconfig.DEFAULT_SECTION, "Initrd") glog.V(0).Infof("The config: kernel=%s, initrd=%s", kernel, initrd) vboxImage, _ := cfg.GetValue(goconfig.DEFAULT_SECTION, "Vbox") glog.V(0).Infof("The config: vbox image=%s", vboxImage) biface, _ := cfg.GetValue(goconfig.DEFAULT_SECTION, "Bridge") bridgeip, _ := cfg.GetValue(goconfig.DEFAULT_SECTION, "BridgeIP") glog.V(0).Infof("The config: bridge=%s, ip=%s", biface, bridgeip) bios, _ := cfg.GetValue(goconfig.DEFAULT_SECTION, "Bios") cbfs, _ := cfg.GetValue(goconfig.DEFAULT_SECTION, "Cbfs") glog.V(0).Infof("The config: bios=%s, cbfs=%s", bios, cbfs) host, _ := cfg.GetValue(goconfig.DEFAULT_SECTION, "Host") var tempdir = path.Join(utils.HYPER_ROOT, "run") os.Setenv("TMPDIR", tempdir) if err := os.MkdirAll(tempdir, 0755); err != nil && !os.IsExist(err) { return nil, err } var realRoot = path.Join(utils.HYPER_ROOT, "lib") // Create the root directory if it doesn't exists if err := os.MkdirAll(realRoot, 0755); err != nil && !os.IsExist(err) { return nil, err } var ( db_file = fmt.Sprintf("%s/hyper.db", realRoot) ) db, err := leveldb.OpenFile(db_file, nil) if err != nil { glog.Errorf("open leveldb file failed, %s", err.Error()) return nil, err } dockerCli, err1 := NewDocker() if err1 != nil { glog.Errorf(err1.Error()) return nil, err1 } vList := map[string]*hypervisor.Vm{} daemon := &Daemon{ ID: fmt.Sprintf("%d", os.Getpid()), db: db, eng: eng, Kernel: kernel, Initrd: initrd, Bios: bios, Cbfs: cbfs, VboxImage: vboxImage, DockerCli: dockerCli, PodList: NewPodList(), VmList: vList, Host: host, BridgeIP: bridgeip, BridgeIface: biface, } // Get the docker daemon info sysinfo, err := dockerCli.SendCmdInfo() if err != nil { return nil, err } stor, err := StorageFactory(sysinfo) if err != nil { return nil, err } daemon.Storage = stor daemon.Storage.Init() eng.OnShutdown(func() { if err := daemon.shutdown(); err != nil { glog.Errorf("Error during daemon.shutdown(): %v", err) } }) return daemon, nil } func (daemon *Daemon) DefaultLogCfg(driver string, cfg map[string]string) { if driver == "" { driver = jsonfilelog.Name } daemon.DefaultLog = &pod.PodLogConfig{ Type: driver, Config: cfg, } } func (daemon *Daemon) GetPodNum() int64 { iter := daemon.db.NewIterator(util.BytesPrefix([]byte("pod-")), nil) var i int64 = 0 for iter.Next() { key := iter.Key() if strings.Contains(string(key), "pod-container-") { continue } i++ } iter.Release() err := iter.Error() if err != nil { return 0 } return i } func (daemon *Daemon) GetRunningPodNum() int64 { return daemon.PodList.CountRunning() } func (daemon *Daemon) WritePodToDB(podName string, podData []byte) error { key := fmt.Sprintf("pod-%s", podName) _, err := daemon.db.Get([]byte(key), nil) if err != nil { err = daemon.db.Put([]byte(key), podData, nil) if err != nil { return err } } else { err = daemon.db.Delete([]byte(key), nil) if err != nil { return err } err = daemon.db.Put([]byte(key), podData, nil) if err != nil { return err } } return nil } func (daemon *Daemon) GetPod(podId, podArgs string, autoremove bool) (*Pod, error) { var ( pod *Pod ok bool ) if podArgs == "" { if pod, ok = daemon.PodList.Get(podId); !ok { return nil, fmt.Errorf("Can not find the POD instance of %s", podId) } return pod, nil } pod, err := CreatePod(daemon, daemon.DockerCli, podId, podArgs, autoremove) if err != nil { return nil, err } if err = daemon.AddPod(pod, podArgs); err != nil { return nil, err } return pod, nil } func (daemon *Daemon) GetPodByName(podName string) ([]byte, error) { key := fmt.Sprintf("pod-%s", podName) data, err := daemon.db.Get([]byte(key), nil) if err != nil { return []byte(""), err } return data, nil } func (daemon *Daemon) DeletePodFromDB(podName string) error { key := fmt.Sprintf("pod-%s", podName) err := daemon.db.Delete([]byte(key), nil) if err != nil { return err } return nil } func (daemon *Daemon) SetVolumeId(podId, volName, dev_id string) error { key := fmt.Sprintf("vol-%s-%s", podId, dev_id) err := daemon.db.Put([]byte(key), []byte(fmt.Sprintf("%s:%s", volName, dev_id)), nil) if err != nil { return err } return nil } func (daemon *Daemon) GetVolumeId(podId, volName string) (int, error) { dev_id := 0 key := fmt.Sprintf("vol-%s", podId) iter := daemon.db.NewIterator(util.BytesPrefix([]byte(key)), nil) for iter.Next() { value := iter.Value() fields := strings.Split(string(value), ":") if fields[0] == volName { dev_id, _ = strconv.Atoi(fields[1]) } } iter.Release() err := iter.Error() if err != nil { return -1, err } return dev_id, nil } func (daemon *Daemon) DeleteVolumeId(podId string) error { key := fmt.Sprintf("vol-%s", podId) iter := daemon.db.NewIterator(util.BytesPrefix([]byte(key)), nil) for iter.Next() { value := iter.Key() daemon.Storage.RemoveVolume(podId, iter.Value()) err := daemon.db.Delete(value, nil) if err != nil { return err } } iter.Release() err := iter.Error() if err != nil { return err } return nil } func (daemon *Daemon) WritePodAndContainers(podId string) error { key := fmt.Sprintf("pod-container-%s", podId) value := "" p, ok := daemon.PodList.Get(podId) if !ok { return fmt.Errorf("Cannot find Pod %s to write", podId) } for _, c := range p.status.Containers { if value == "" { value = c.Id } else { value = value + ":" + c.Id } } err := daemon.db.Put([]byte(key), []byte(value), nil) if err != nil { return err } return nil } func (daemon *Daemon) GetPodContainersByName(podName string) ([]string, error) { key := fmt.Sprintf("pod-container-%s", podName) data, err := daemon.db.Get([]byte(key), nil) if err != nil { return nil, err } containers := strings.Split(string(data), ":") return containers, nil } func (daemon *Daemon) DeletePodContainerFromDB(podName string) error { key := fmt.Sprintf("pod-container-%s", podName) err := daemon.db.Delete([]byte(key), nil) if err != nil { return err } return nil } func (daemon *Daemon) DbGetVmByPod(podId string) (string, error) { key := fmt.Sprintf("vm-%s", podId) data, err := daemon.db.Get([]byte(key), nil) if err != nil { return "", err } return string(data), nil } func (daemon *Daemon) UpdateVmByPod(podId, vmId string) error { glog.V(1).Infof("Add or Update the VM info for pod(%s)", podId) key := fmt.Sprintf("vm-%s", podId) _, err := daemon.db.Get([]byte(key), nil) if err == nil { err = daemon.db.Delete([]byte(key), nil) if err != nil { return err } err = daemon.db.Put([]byte(key), []byte(vmId), nil) if err != nil { return err } } else { err = daemon.db.Put([]byte(key), []byte(vmId), nil) if err != nil { return err } } glog.V(1).Infof("success to add or update the VM info for pod(%s)", podId) return nil } func (daemon *Daemon) DeleteVmByPod(podId string) error { key := fmt.Sprintf("vm-%s", podId) vmId, err := daemon.db.Get([]byte(key), nil) if err != nil { return err } err = daemon.db.Delete([]byte(key), nil) if err != nil { return err } if err = daemon.DeleteVmData(string(vmId)); err != nil { return err } glog.V(1).Infof("success to delete the VM info for pod(%s)", podId) return nil } func (daemon *Daemon) GetVmByPodId(podId string) (string, error) { daemon.PodList.RLock() glog.V(2).Infof("lock read of PodList") defer glog.V(2).Infof("unlock read of PodList") defer daemon.PodList.RUnlock() pod, ok := daemon.PodList.Get(podId) if !ok { return "", fmt.Errorf("Not found Pod %s", podId) } return pod.status.Vm, nil } func (daemon *Daemon) GetPodByContainer(containerId string) (string, error) { daemon.PodList.RLock() glog.V(2).Infof("lock read of PodList") defer glog.V(2).Infof("unlock read of PodList") defer daemon.PodList.RUnlock() pod := daemon.PodList.Find(func(p *Pod) bool { for _, c := range p.status.Containers { if c.Id == containerId { return true } } return false }) if pod == nil { return "", fmt.Errorf("Can not find that container!") } return pod.id, nil } func (daemon *Daemon) GetPodByContainerIdOrName(name string) (pod *Pod, idx int, err error) { daemon.PodList.RLock() glog.V(2).Infof("lock read of PodList") defer glog.V(2).Infof("unlock read of PodList") defer daemon.PodList.RUnlock() err = nil wslash := name if name[0] != '/' { wslash = "/" + name } var c *hypervisor.Container pod = daemon.PodList.Find(func(p *Pod) bool { for idx, c = range p.status.Containers { if c.Name == wslash || c.Id == name { return true } } return false }) if pod == nil { err = fmt.Errorf("cannot found container %s", name) return } return } func (daemon *Daemon) AddPod(pod *Pod, podArgs string) (err error) { // store the UserPod into the db if err = daemon.WritePodToDB(pod.id, []byte(podArgs)); err != nil { glog.V(1).Info("Found an error while saveing the POD file") return } defer func() { if err != nil { daemon.DeletePodFromDB(pod.id) } }() daemon.PodList.Put(pod) defer func() { if err != nil { daemon.RemovePod(pod.id) } }() if err = daemon.WritePodAndContainers(pod.id); err != nil { glog.V(1).Info("Found an error while saveing the Containers info") return } pod.status.Handler.Data = daemon return nil } func (daemon *Daemon) RemovePod(podId string) { daemon.PodList.Delete(podId) } func (daemon *Daemon) AddVm(vm *hypervisor.Vm) { daemon.VmList[vm.Id] = vm glog.V(1).Infof("add new vm : %s", vm.Id) } func (daemon *Daemon) RemoveVm(vmId string) { delete(daemon.VmList, vmId) } func (daemon *Daemon) UpdateVmData(vmId string, data []byte) error { key := fmt.Sprintf("vmdata-%s", vmId) _, err := daemon.db.Get([]byte(key), nil) if err == nil { err = daemon.db.Delete([]byte(key), nil) if err != nil { return err } err = daemon.db.Put([]byte(key), data, nil) if err != nil { return err } } if err != nil && strings.Contains(err.Error(), "not found") { err = daemon.db.Put([]byte(key), data, nil) if err != nil { return err } } return err } func (daemon *Daemon) GetVmData(vmId string) ([]byte, error) { key := fmt.Sprintf("vmdata-%s", vmId) data, err := daemon.db.Get([]byte(key), nil) if err != nil { return []byte(""), err } return data, nil } func (daemon *Daemon) DeleteVmData(vmId string) error { key := fmt.Sprintf("vmdata-%s", vmId) err := daemon.db.Delete([]byte(key), nil) if err != nil { return err } return nil } func (daemon *Daemon) DestroyAllVm() error { glog.V(0).Info("The daemon will stop all pod") daemon.PodList.Lock() glog.V(2).Infof("lock PodList") daemon.PodList.Foreach(func(p *Pod) error { if _, _, err := daemon.StopPod(p.id, "yes"); err != nil { glog.V(1).Infof("fail to stop %s: %v", p.id, err) } return nil }) daemon.PodList.Unlock() glog.V(2).Infof("unlock PodList") iter := daemon.db.NewIterator(util.BytesPrefix([]byte("vm-")), nil) for iter.Next() { key := iter.Key() daemon.db.Delete(key, nil) } iter.Release() err := iter.Error() return err } func (daemon *Daemon) DestroyAndKeepVm() error { for i := 0; i < 3; i++ { code, err := daemon.ReleaseAllVms() if err != nil && code == types.E_BUSY { continue } else { return err } } return nil } func (daemon *Daemon) shutdown() error { glog.V(0).Info("The daemon will be shutdown") glog.V(0).Info("Shutdown all VMs") for vm := range daemon.VmList { daemon.KillVm(vm) } daemon.db.Close() glog.Flush() return nil } func NewDocker() (DockerInterface, error) { return NewDockerImpl() } var NewDockerImpl = func() (DockerInterface, error) { return nil, fmt.Errorf("no docker create function") } // Now, the daemon can be ran for any linux kernel func checkKernel() error { return nil } <file_sep>// Package daemon exposes the functions that occur on the host server // that the Docker daemon is running. // // In implementing the various functions of the daemon, there is often // a method-specific struct for configuring the runtime behavior. package daemon import ( "errors" "fmt" "io" "io/ioutil" "os" "path" "path/filepath" "regexp" "strings" "sync" "time" "github.com/Sirupsen/logrus" "github.com/docker/docker/api" "github.com/docker/docker/api/types" "github.com/docker/docker/cliconfig" "github.com/docker/docker/daemon/events" "github.com/docker/docker/daemon/execdriver" "github.com/docker/docker/daemon/network" "github.com/docker/docker/graph" "github.com/docker/docker/image" "github.com/docker/docker/pkg/archive" "github.com/docker/docker/pkg/broadcaster" "github.com/docker/docker/pkg/discovery" "github.com/docker/docker/pkg/fileutils" "github.com/docker/docker/pkg/graphdb" "github.com/docker/docker/pkg/idtools" "github.com/docker/docker/pkg/ioutils" "github.com/docker/docker/pkg/jsonmessage" "github.com/docker/docker/pkg/mount" "github.com/docker/docker/pkg/namesgenerator" "github.com/docker/docker/pkg/nat" "github.com/docker/docker/pkg/parsers/filters" "github.com/docker/docker/pkg/signal" "github.com/docker/docker/pkg/stringid" "github.com/docker/docker/pkg/stringutils" "github.com/docker/docker/pkg/sysinfo" "github.com/docker/docker/pkg/system" "github.com/docker/docker/pkg/truncindex" "github.com/docker/docker/registry" "github.com/docker/docker/runconfig" "github.com/docker/docker/utils" "github.com/docker/docker/volume/drivers" "github.com/docker/docker/volume/local" "github.com/docker/docker/volume/store" "github.com/docker/libnetwork" lntypes "github.com/docker/libnetwork/types" "github.com/golang/glog" "github.com/hyperhq/hyper/lib/docker/daemon/graphdriver" _ "github.com/hyperhq/hyper/lib/docker/daemon/graphdriver/vfs" "github.com/opencontainers/runc/libcontainer" ) var ( validContainerNameChars = `[a-zA-Z0-9][a-zA-Z0-9_.-]` validContainerNamePattern = regexp.MustCompile(`^/?` + validContainerNameChars + `+$`) ) type contStore struct { s map[string]*Container sync.Mutex } func (c *contStore) Add(id string, cont *Container) { c.Lock() c.s[id] = cont c.Unlock() } func (c *contStore) Get(id string) *Container { c.Lock() res := c.s[id] c.Unlock() return res } func (c *contStore) Delete(id string) { c.Lock() delete(c.s, id) c.Unlock() } func (c *contStore) List() []*Container { containers := new(History) c.Lock() for _, cont := range c.s { containers.Add(cont) } c.Unlock() containers.Sort() return *containers } // Daemon holds information about the Docker daemon. type Daemon struct { ID string repository string sysInitPath string containers *contStore graph *graph.Graph repositories *graph.TagStore idIndex *truncindex.TruncIndex configStore *Config sysInfo *sysinfo.SysInfo containerGraphDB *graphdb.Database driver graphdriver.Driver execDriver execdriver.Driver defaultLogConfig runconfig.LogConfig RegistryService *registry.Service EventsService *events.Events netController libnetwork.NetworkController volumes *store.VolumeStore discoveryWatcher discovery.Watcher root string shutdown bool uidMaps []idtools.IDMap gidMaps []idtools.IDMap } // Get looks for a container using the provided information, which could be // one of the following inputs from the caller: // - A full container ID, which will exact match a container in daemon's list // - A container name, which will only exact match via the GetByName() function // - A partial container ID prefix (e.g. short ID) of any length that is // unique enough to only return a single container object // If none of these searches succeed, an error is returned func (daemon *Daemon) Get(prefixOrName string) (*Container, error) { if containerByID := daemon.containers.Get(prefixOrName); containerByID != nil { // prefix is an exact match to a full container ID return containerByID, nil } // GetByName will match only an exact name provided; we ignore errors containerByName, _ := daemon.GetByName(prefixOrName) containerId, indexError := daemon.idIndex.Get(prefixOrName) if containerByName != nil { // prefix is an exact match to a full container Name return containerByName, nil } if containerId != "" { // prefix is a fuzzy match to a container ID return daemon.containers.Get(containerId), nil } return nil, indexError } // Exists returns a true if a container of the specified ID or name exists, // false otherwise. func (daemon *Daemon) Exists(id string) bool { c, _ := daemon.Get(id) return c != nil } func (daemon *Daemon) containerRoot(id string) string { return path.Join(daemon.repository, id) } // Load reads the contents of a container from disk // This is typically done at startup. func (daemon *Daemon) load(id string) (*Container, error) { container := &Container{ CommonContainer: CommonContainer{ State: NewState(), root: daemon.containerRoot(id), }, } if err := container.fromDisk(); err != nil { return nil, err } if container.ID != id { return container, fmt.Errorf("Container %s is stored at %s", container.ID, id) } return container, nil } // Register makes a container object usable by the daemon as <container.ID> // This is a wrapper for register func (daemon *Daemon) Register(container *Container) error { if container.daemon != nil || daemon.Exists(container.ID) { return fmt.Errorf("Container is already loaded") } if err := validateID(container.ID); err != nil { return err } if err := daemon.ensureName(container); err != nil { return err } if daemon == nil { glog.Error("daemon can not be nil") return fmt.Errorf("daemon can not be nil") } container.daemon = daemon // Attach to stdout and stderr container.stderr = new(broadcaster.Unbuffered) container.stdout = new(broadcaster.Unbuffered) // Attach to stdin if container.Config.OpenStdin { container.stdin, container.stdinPipe = io.Pipe() } else { container.stdinPipe = ioutils.NopWriteCloser(ioutil.Discard) // Silently drop stdin } // done daemon.containers.Add(container.ID, container) // don't update the Suffixarray if we're starting up // we'll waste time if we update it for every container daemon.idIndex.Add(container.ID) if container.IsRunning() { glog.Infof("killing old running container %s", container.ID) // Set exit code to 128 + SIGKILL (9) to properly represent unsuccessful exit container.setStoppedLocking(&execdriver.ExitStatus{ExitCode: 137}) if daemon.execDriver != nil { // use the current driver and ensure that the container is dead x.x cmd := &execdriver.Command{ CommonCommand: execdriver.CommonCommand{ ID: container.ID, }, } daemon.execDriver.Terminate(cmd) } container.unmountIpcMounts(mount.Unmount) if err := daemon.Unmount(container); err != nil { logrus.Debugf("unmount error %s", err) } if err := container.toDiskLocking(); err != nil { logrus.Errorf("Error saving stopped state to disk: %v", err) } } if err := daemon.prepareMountPoints(container); err != nil { return err } return nil } func (daemon *Daemon) ensureName(container *Container) error { if container.Name == "" { name, err := daemon.generateNewName(container.ID) if err != nil { return err } container.Name = name if err := container.toDisk(); err != nil { glog.V(1).Infof("Error saving container name %s", err) } } return nil } func (daemon *Daemon) Restore() error { return daemon.restore() } func (daemon *Daemon) restore() error { type cr struct { container *Container registered bool } var ( currentDriver = daemon.driver.String() containers = make(map[string]*cr) ) dir, err := ioutil.ReadDir(daemon.repository) if err != nil { return err } for _, v := range dir { id := v.Name() container, err := daemon.load(id) if err != nil { glog.Errorf("Failed to load container %v: %v", id, err) continue } // Ignore the container if it does not support the current driver being used by the graph if (container.Driver == "" && currentDriver == "aufs") || container.Driver == currentDriver { glog.V(1).Infof("Loaded container %v", container.ID) containers[container.ID] = &cr{container: container} } else { glog.V(1).Infof("Cannot load container %s because it was created with another graph driver.", container.ID) } } if entities := daemon.containerGraph().List("/", -1); entities != nil { for _, p := range entities.Paths() { e := entities[p] if c, ok := containers[e.ID()]; ok { c.registered = true } } } group := sync.WaitGroup{} for _, c := range containers { group.Add(1) go func(container *Container, registered bool) { defer group.Done() if !registered { // Try to set the default name for a container if it exists prior to links container.Name, err = daemon.generateNewName(container.ID) if err != nil { glog.V(1).Infof("Setting default id - %s", err) } } if err := daemon.Register(container); err != nil { glog.V(1).Infof("Failed to register container %s: %s", container.ID, err) } // check the restart policy on the containers and restart any container with // the restart policy of "always" if daemon.configStore.AutoRestart && container.shouldRestart() { glog.V(1).Infof("Starting container %s", container.ID) if err := daemon.containerStart(container); err != nil { glog.V(1).Infof("Failed to start container %s: %s", container.ID, err) } } }(c.container, c.registered) } group.Wait() glog.Info("Loading containers: done.") return nil } func (daemon *Daemon) mergeAndVerifyConfig(config *runconfig.Config, img *image.Image) error { if img != nil && img.Config != nil { if err := runconfig.Merge(config, img.Config); err != nil { return err } } if config.Entrypoint.Len() == 0 && config.Cmd.Len() == 0 { return fmt.Errorf("No command specified") } return nil } func (daemon *Daemon) generateIdAndName(name string) (string, string, error) { var ( err error id = stringid.GenerateRandomID() ) if name == "" { if name, err = daemon.generateNewName(id); err != nil { return "", "", err } return id, name, nil } if name, err = daemon.reserveName(id, name); err != nil { return "", "", err } return id, name, nil } func (daemon *Daemon) reserveName(id, name string) (string, error) { if !validContainerNamePattern.MatchString(name) { return "", fmt.Errorf("Invalid container name (%s), only %s are allowed", name, validContainerNameChars) } if name[0] != '/' { name = "/" + name } if _, err := daemon.containerGraph().Set(name, id); err != nil { if !graphdb.IsNonUniqueNameError(err) { return "", err } conflictingContainer, err := daemon.GetByName(name) if err != nil { if strings.Contains(err.Error(), "Could not find entity") { return "", err } // Remove name and continue starting the container if err := daemon.containerGraph().Delete(name); err != nil { return "", err } } else { nameAsKnownByUser := strings.TrimPrefix(name, "/") return "", fmt.Errorf( "Conflict. The name %q is already in use by container %s. You have to delete (or rename) that container to be able to reuse that name.", nameAsKnownByUser, stringid.TruncateID(conflictingContainer.ID)) } } return name, nil } func (daemon *Daemon) generateNewName(id string) (string, error) { var name string for i := 0; i < 6; i++ { name = namesgenerator.GetRandomName(i) if name[0] != '/' { name = "/" + name } if _, err := daemon.containerGraph().Set(name, id); err != nil { if !graphdb.IsNonUniqueNameError(err) { return "", err } continue } return name, nil } name = "/" + stringid.TruncateID(id) if _, err := daemon.containerGraph().Set(name, id); err != nil { return "", err } return name, nil } func (daemon *Daemon) generateHostname(id string, config *runconfig.Config) { // Generate default hostname // FIXME: the lxc template no longer needs to set a default hostname if config.Hostname == "" { config.Hostname = id[:12] } } func (daemon *Daemon) getEntrypointAndArgs(configEntrypoint *stringutils.StrSlice, configCmd *stringutils.StrSlice) (string, []string) { var ( entrypoint string args []string ) cmdSlice := configCmd.Slice() if configEntrypoint.Len() != 0 { eSlice := configEntrypoint.Slice() entrypoint = eSlice[0] args = append(eSlice[1:], cmdSlice...) } else { entrypoint = cmdSlice[0] args = cmdSlice[1:] } return entrypoint, args } func (daemon *Daemon) newContainer(name string, config *runconfig.Config, imgID string) (*Container, error) { var ( id string err error ) id, name, err = daemon.generateIdAndName(name) if err != nil { return nil, err } daemon.generateHostname(id, config) entrypoint, args := daemon.getEntrypointAndArgs(config.Entrypoint, config.Cmd) container := &Container{ CommonContainer: CommonContainer{ ID: id, // FIXME: we should generate the ID here instead of receiving it as an argument Created: time.Now().UTC(), Path: entrypoint, Args: args, //FIXME: de-duplicate from config Config: config, hostConfig: &runconfig.HostConfig{}, ImageID: imgID, NetworkSettings: &network.Settings{}, Name: name, Driver: daemon.driver.String(), State: NewState(), }, } container.root = daemon.containerRoot(container.ID) return container, err } func (daemon *Daemon) restoreNewContainer(name string, config *runconfig.Config, imgID string, id string) (*Container, error) { var ( err error ) /*id, name, err = daemon.generateIdAndName(name) if err != nil { return nil, err }*/ daemon.generateHostname(id, config) entrypoint, args := daemon.getEntrypointAndArgs(config.Entrypoint, config.Cmd) container := &Container{ CommonContainer: CommonContainer{ ID: id, // FIXME: we should generate the ID here instead of receiving it as an argument Created: time.Now().UTC(), Path: entrypoint, Args: args, //FIXME: de-duplicate from config Config: config, hostConfig: &runconfig.HostConfig{}, ImageID: imgID, NetworkSettings: &network.Settings{}, Name: name, Driver: daemon.driver.String(), State: NewState(), }, } container.root = daemon.containerRoot(container.ID) return container, err } func (daemon *Daemon) createRootfs(container *Container) error { // Step 1: create the container directory. // This doubles as a barrier to avoid race conditions. // Step 1: create the container directory. // This doubles as a barrier to avoid race conditions. rootUID, rootGID, err := idtools.GetRootUIDGID(daemon.uidMaps, daemon.gidMaps) if err != nil { return err } if err := idtools.MkdirAs(container.root, 0700, rootUID, rootGID); err != nil { return err } initID := fmt.Sprintf("%s-init", container.ID) if err := daemon.driver.Create(initID, container.ImageID, container.getMountLabel()); err != nil { return err } initPath, err := daemon.driver.Get(initID, "") if err != nil { return err } if err := setupInitLayer(initPath, rootUID, rootGID); err != nil { if err := daemon.driver.Put(initID); err != nil { logrus.Errorf("Failed to Put init layer: %v", err) } return err } // We want to unmount init layer before we take snapshot of it // for the actual container. if err := daemon.driver.Put(initID); err != nil { return err } if err := daemon.driver.Create(container.ID, initID, ""); err != nil { return err } return nil } func GetFullContainerName(name string) (string, error) { if name == "" { return "", fmt.Errorf("Container name cannot be empty") } if name[0] != '/' { name = "/" + name } return name, nil } func (daemon *Daemon) GetByName(name string) (*Container, error) { fullName, err := GetFullContainerName(name) if err != nil { return nil, err } entity := daemon.containerGraph().Get(fullName) if entity == nil { return nil, fmt.Errorf("Could not find entity for %s", name) } e := daemon.containers.Get(entity.ID()) if e == nil { return nil, fmt.Errorf("Could not find container for entity id %s", entity.ID()) } return e, nil } // GetEventFilter returns a filters.Filter for a set of filters func (daemon *Daemon) GetEventFilter(filter filters.Args) *events.Filter { // incoming container filter can be name, id or partial id, convert to // a full container id for i, cn := range filter["container"] { c, err := daemon.Get(cn) if err != nil { filter["container"][i] = "" } else { filter["container"][i] = c.ID } } return events.NewFilter(filter, daemon.GetLabels) } // SubscribeToEvents returns the currently record of events, a channel to stream new events from, and a function to cancel the stream of events. func (daemon *Daemon) SubscribeToEvents() ([]*jsonmessage.JSONMessage, chan interface{}, func()) { return daemon.EventsService.Subscribe() } // GetLabels for a container or image id func (daemon *Daemon) GetLabels(id string) map[string]string { // TODO: TestCase container := daemon.containers.Get(id) if container != nil { return container.Config.Labels } img, err := daemon.repositories.LookupImage(id) if err == nil { return img.ContainerConfig.Labels } return nil } func (daemon *Daemon) children(name string) (map[string]*Container, error) { name, err := GetFullContainerName(name) if err != nil { return nil, err } children := make(map[string]*Container) err = daemon.containerGraph().Walk(name, func(p string, e *graphdb.Entity) error { c, err := daemon.Get(e.ID()) if err != nil { return err } children[p] = c return nil }, 0) if err != nil { return nil, err } return children, nil } func (daemon *Daemon) parents(name string) ([]string, error) { name, err := GetFullContainerName(name) if err != nil { return nil, err } return daemon.containerGraph().Parents(name) } func (daemon *Daemon) registerLink(parent, child *Container, alias string) error { fullName := path.Join(parent.Name, alias) if !daemon.containerGraph().Exists(fullName) { _, err := daemon.containerGraph().Set(fullName, child.ID) return err } return nil } func NewDaemon(config *Config, registryService *registry.Service) (daemon *Daemon, err error) { uidMaps, gidMaps, err := setupRemappedRoot(config) if err != nil { return nil, err } rootUID, rootGID, err := idtools.GetRootUIDGID(uidMaps, gidMaps) if err != nil { return nil, err } // get the canonical path to the Docker root directory var realRoot string if _, err := os.Stat(config.Root); err != nil && os.IsNotExist(err) { realRoot = config.Root } else { realRoot, err = fileutils.ReadSymlinkedDirectory(config.Root) if err != nil { return nil, fmt.Errorf("Unable to get the full path to root (%s): %s", config.Root, err) } } if err = setupDaemonRoot(config, realRoot, rootUID, rootGID); err != nil { return nil, err } // set up the tmpDir to use a canonical path tmp, err := tempDir(config.Root, rootUID, rootGID) if err != nil { return nil, fmt.Errorf("Unable to get the TempDir under %s: %s", config.Root, err) } realTmp, err := fileutils.ReadSymlinkedDirectory(tmp) if err != nil { return nil, fmt.Errorf("Unable to get the full path to the TempDir (%s): %s", tmp, err) } os.Setenv("TMPDIR", realTmp) // Load storage driver driver, err := graphdriver.New(config.Root, config.GraphOptions, uidMaps, gidMaps) if err != nil { return nil, fmt.Errorf("error initializing graphdriver: %v", err) } glog.V(1).Infof("Using graph driver %s", driver) d := &Daemon{} d.driver = driver defer func() { if err != nil { if err := d.Shutdown(); err != nil { glog.Error(err) } } }() daemonRepo := path.Join(config.Root, "containers") if err := os.MkdirAll(daemonRepo, 0700); err != nil && !os.IsExist(err) { glog.Error(err.Error()) return nil, err } glog.Info("Creating images graph") g, err := graph.NewGraph(filepath.Join(config.Root, "graph"), d.driver, uidMaps, gidMaps) if err != nil { glog.Error(err.Error()) return nil, err } // Configure the volumes driver volStore, err := configureVolumes(config, rootUID, rootGID) if err != nil { return nil, err } trustKey, err := api.LoadOrCreateTrustKey(config.TrustKeyPath) if err != nil { glog.Error(err.Error()) return nil, err } trustDir := path.Join(config.Root, "trust") if err := os.MkdirAll(trustDir, 0700); err != nil && !os.IsExist(err) { glog.Error(err.Error()) return nil, err } eventsService := events.New() glog.Info("Creating repository list") tagCfg := &graph.TagStoreConfig{ Graph: g, Key: trustKey, Registry: registryService, Events: eventsService, } repositories, err := graph.NewTagStore(path.Join(config.Root, "repositories-"+d.driver.String()), tagCfg) if err != nil { glog.Error(err.Error()) return nil, fmt.Errorf("Couldn't create Tag store: %s", err) } graphdbPath := path.Join(config.Root, "linkgraph.db") graph, err := graphdb.NewSqliteConn(graphdbPath) if err != nil { glog.Error(err.Error()) return nil, err } d.containerGraphDB = graph sysInfo := sysinfo.New(false) d.ID = trustKey.PublicKey().KeyID() d.repository = daemonRepo d.containers = &contStore{s: make(map[string]*Container)} d.graph = g d.repositories = repositories d.idIndex = truncindex.NewTruncIndex([]string{}) d.sysInfo = sysInfo d.configStore = config d.sysInitPath = "" d.defaultLogConfig = config.LogConfig d.RegistryService = registryService d.EventsService = eventsService d.root = config.Root d.volumes = volStore if err := d.restore(); err != nil { return nil, err } return d, nil } func (daemon *Daemon) shutdownContainer(c *Container) error { // TODO(windows): Handle docker restart with paused containers if c.isPaused() { // To terminate a process in freezer cgroup, we should send // SIGTERM to this process then unfreeze it, and the process will // force to terminate immediately. logrus.Debugf("Found container %s is paused, sending SIGTERM before unpause it", c.ID) sig, ok := signal.SignalMap["TERM"] if !ok { return fmt.Errorf("System doesn not support SIGTERM") } if err := daemon.kill(c, int(sig)); err != nil { return fmt.Errorf("sending SIGTERM to container %s with error: %v", c.ID, err) } if err := daemon.containerUnpause(c); err != nil { return fmt.Errorf("Failed to unpause container %s with error: %v", c.ID, err) } if _, err := c.WaitStop(10 * time.Second); err != nil { logrus.Debugf("container %s failed to exit in 10 second of SIGTERM, sending SIGKILL to force", c.ID) sig, ok := signal.SignalMap["KILL"] if !ok { return fmt.Errorf("System does not support SIGKILL") } if err := daemon.kill(c, int(sig)); err != nil { logrus.Errorf("Failed to SIGKILL container %s", c.ID) } c.WaitStop(-1 * time.Second) return err } } // If container failed to exit in 10 seconds of SIGTERM, then using the force if err := daemon.containerStop(c, 10); err != nil { return fmt.Errorf("Stop container %s with error: %v", c.ID, err) } c.WaitStop(-1 * time.Second) return nil } func (daemon *Daemon) Shutdown() error { if daemon.containerGraphDB != nil { if err := daemon.containerGraph().Close(); err != nil { glog.Errorf("Error during container graph.Close(): %v", err) } } if daemon.driver != nil { if err := daemon.driver.Cleanup(); err != nil { glog.Errorf("Error during graph storage driver.Cleanup(): %v", err) } } if daemon.containers != nil { group := sync.WaitGroup{} glog.V(1).Info("starting clean shutdown of all containers...") for _, container := range daemon.List() { c := container if c.IsRunning() { glog.V(1).Infof("stopping %s", c.ID) group.Add(1) go func() { defer group.Done() // If container failed to exit in 10 seconds of SIGTERM, then using the force if err := c.Stop(10); err != nil { glog.Errorf("Stop container %s with error: %v", c.ID, err) } c.WaitStop(-1 * time.Second) glog.V(1).Infof("container stopped %s", c.ID) }() } } group.Wait() } return nil } func (daemon *Daemon) Mount(container *Container) error { dir, err := daemon.driver.Get(container.ID, container.getMountLabel()) if err != nil { return fmt.Errorf("Error getting container %s from driver %s: %s", container.ID, daemon.driver, err) } if container.basefs == "" { container.basefs = dir } else if container.basefs != dir { daemon.driver.Put(container.ID) return fmt.Errorf("Error: driver %s is returning inconsistent paths for container %s ('%s' then '%s')", daemon.driver, container.ID, container.basefs, dir) } return nil } func (daemon *Daemon) Unmount(container *Container) error { daemon.driver.Put(container.ID) return nil } func (daemon *Daemon) changes(container *Container) ([]archive.Change, error) { initID := fmt.Sprintf("%s-init", container.ID) return daemon.driver.Changes(container.ID, initID) } func (daemon *Daemon) diff(container *Container) (archive.Archive, error) { glog.V(2).Infof("container address %p, daemon address %p", container, daemon) initID := fmt.Sprintf("%s-init", container.ID) driver := daemon.driver return driver.Diff(container.ID, initID) } // FIXME: this is a convenience function for integration tests // which need direct access to daemon.graph. // Once the tests switch to using engine and jobs, this method // can go away. func (daemon *Daemon) Graph() *graph.Graph { return daemon.graph } // TagImage creates a tag in the repository reponame, pointing to the image named // imageName. If force is true, an existing tag with the same name may be // overwritten. func (daemon *Daemon) TagImage(repoName, tag, imageName string, force bool) error { if err := daemon.repositories.Tag(repoName, tag, imageName, force); err != nil { return err } daemon.EventsService.Log("tag", utils.ImageReference(repoName, tag), "") return nil } // PullImage initiates a pull operation. image is the repository name to pull, and // tag may be either empty, or indicate a specific tag to pull. func (daemon *Daemon) PullImage(image string, tag string, imagePullConfig *graph.ImagePullConfig) error { return daemon.repositories.Pull(image, tag, imagePullConfig) } // ImportImage imports an image, getting the archived layer data either from // inConfig (if src is "-"), or from a URI specified in src. Progress output is // written to outStream. Repository and tag names can optionally be given in // the repo and tag arguments, respectively. func (daemon *Daemon) ImportImage(src, repo, tag, msg string, inConfig io.ReadCloser, outStream io.Writer, containerConfig *runconfig.Config) error { return daemon.repositories.Import(src, repo, tag, msg, inConfig, outStream, containerConfig) } // ExportImage exports a list of images to the given output stream. The // exported images are archived into a tar when written to the output // stream. All images with the given tag and all versions containing // the same tag are exported. names is the set of tags to export, and // outStream is the writer which the images are written to. func (daemon *Daemon) ExportImage(names []string, outStream io.Writer) error { return daemon.repositories.ImageExport(names, outStream) } // PushImage initiates a push operation on the repository named localName. func (daemon *Daemon) PushImage(localName string, imagePushConfig *graph.ImagePushConfig) error { return daemon.repositories.Push(localName, imagePushConfig) } // LookupImage looks up an image by name and returns it as an ImageInspect // structure. func (daemon *Daemon) LookupImage(name string) (*types.ImageInspect, error) { return daemon.repositories.Lookup(name) } // LoadImage uploads a set of images into the repository. This is the // complement of ImageExport. The input stream is an uncompressed tar // ball containing images and metadata. func (daemon *Daemon) LoadImage(inTar io.ReadCloser, outStream io.Writer) error { return daemon.repositories.Load(inTar, outStream) } // ListImages returns a filtered list of images. filterArgs is a JSON-encoded set // of filter arguments which will be interpreted by pkg/parsers/filters. // filter is a shell glob string applied to repository names. The argument // named all controls whether all images in the graph are filtered, or just // the heads. func (daemon *Daemon) ListImages(filterArgs, filter string, all bool) ([]*types.Image, error) { return daemon.repositories.Images(filterArgs, filter, all) } // ImageHistory returns a slice of ImageHistory structures for the specified image // name by walking the image lineage. func (daemon *Daemon) ImageHistory(name string) ([]*types.ImageHistory, error) { return daemon.repositories.History(name) } // GetImage returns pointer to an Image struct corresponding to the given // name. The name can include an optional tag; otherwise the default tag will // be used. func (daemon *Daemon) GetImage(name string) (*image.Image, error) { return daemon.repositories.LookupImage(name) } func (daemon *Daemon) Repositories() *graph.TagStore { return daemon.repositories } func (daemon *Daemon) Config() *Config { return daemon.configStore } func (daemon *Daemon) SystemConfig() *sysinfo.SysInfo { return daemon.sysInfo } func (daemon *Daemon) SystemInitPath() string { return daemon.sysInitPath } func (daemon *Daemon) GraphDriver() graphdriver.Driver { return daemon.driver } func (daemon *Daemon) ContainerGraph() *graphdb.Database { return daemon.containerGraphDB } // ExecutionDriver returns the currently used driver for creating and // starting execs in a container. func (daemon *Daemon) ExecutionDriver() execdriver.Driver { return daemon.execDriver } func (daemon *Daemon) containerGraph() *graphdb.Database { return daemon.containerGraphDB } // GetUIDGIDMaps returns the current daemon's user namespace settings // for the full uid and gid maps which will be applied to containers // started in this instance. func (daemon *Daemon) GetUIDGIDMaps() ([]idtools.IDMap, []idtools.IDMap) { return daemon.uidMaps, daemon.gidMaps } // GetRemappedUIDGID returns the current daemon's uid and gid values // if user namespaces are in use for this daemon instance. If not // this function will return "real" root values of 0, 0. func (daemon *Daemon) GetRemappedUIDGID() (int, int) { uid, gid, _ := idtools.GetRootUIDGID(daemon.uidMaps, daemon.gidMaps) return uid, gid } func (daemon *Daemon) ImageGetCached(imgID string, config *runconfig.Config) (*image.Image, error) { // for now just exit if imgID has no children. // maybe parentRefs in graph could be used to store // the Image obj children for faster lookup below but this can // be quite memory hungry. if !daemon.Graph().HasChildren(imgID) { return nil, nil } // Retrieve all images images := daemon.Graph().Map() // Store the tree in a map of map (map[parentId][childId]) imageMap := make(map[string]map[string]struct{}) for _, img := range images { if _, exists := imageMap[img.Parent]; !exists { imageMap[img.Parent] = make(map[string]struct{}) } imageMap[img.Parent][img.ID] = struct{}{} } // Loop on the children of the given image and check the config var match *image.Image for elem := range imageMap[imgID] { img, ok := images[elem] if !ok { return nil, fmt.Errorf("unable to find image %q", elem) } if runconfig.Compare(&img.ContainerConfig, config) { if match == nil || match.Created.Before(img.Created) { match = img } } } return match, nil } // tempDir returns the default directory to use for temporary files. func tempDir(rootDir string, rootUID, rootGID int) (string, error) { var tmpDir string if tmpDir = os.Getenv("DOCKER_TMPDIR"); tmpDir == "" { tmpDir = filepath.Join(rootDir, "tmp") } return tmpDir, idtools.MkdirAllAs(tmpDir, 0700, rootUID, rootGID) } func (daemon *Daemon) setHostConfig(container *Container, hostConfig *runconfig.HostConfig) error { // Do not lock while creating volumes since this could be calling out to external plugins // Don't want to block other actions, like `docker ps` because we're waiting on an external plugin if err := daemon.registerMountPoints(container, hostConfig); err != nil { return err } container.Lock() defer container.Unlock() // Register any links from the host config before starting the container if err := daemon.registerLinks(container, hostConfig); err != nil { return err } container.hostConfig = hostConfig container.toDisk() return nil } func setDefaultMtu(config *Config) { // do nothing if the config does not have the default 0 value. if config.Mtu != 0 { return } config.Mtu = defaultNetworkMtu if routeMtu, err := getDefaultRouteMtu(); err == nil { config.Mtu = routeMtu } } var errNoDefaultRoute = errors.New("no default route was found") // verifyContainerSettings performs validation of the hostconfig and config // structures. func (daemon *Daemon) verifyContainerSettings(hostConfig *runconfig.HostConfig, config *runconfig.Config) ([]string, error) { // First perform verification of settings common across all platforms. if config != nil { if config.WorkingDir != "" { config.WorkingDir = filepath.FromSlash(config.WorkingDir) // Ensure in platform semantics if !system.IsAbs(config.WorkingDir) { return nil, fmt.Errorf("The working directory '%s' is invalid. It needs to be an absolute path.", config.WorkingDir) } } if len(config.StopSignal) > 0 { _, err := signal.ParseSignal(config.StopSignal) if err != nil { return nil, err } } } if hostConfig == nil { return nil, nil } for port := range hostConfig.PortBindings { _, portStr := nat.SplitProtoPort(string(port)) if _, err := nat.ParsePort(portStr); err != nil { return nil, fmt.Errorf("Invalid port specification: %q", portStr) } for _, pb := range hostConfig.PortBindings[port] { _, err := nat.NewPort(nat.SplitProtoPort(pb.HostPort)) if err != nil { return nil, fmt.Errorf("Invalid port specification: %q", pb.HostPort) } } } // Now do platform-specific verification return verifyPlatformContainerSettings(daemon, hostConfig, config) } func (daemon *Daemon) kill(c *Container, sig int) error { if daemon.execDriver != nil { return daemon.execDriver.Kill(c.command, sig) } else { return nil } } func configureVolumes(config *Config, rootUID, rootGID int) (*store.VolumeStore, error) { volumesDriver, err := local.New(config.Root, rootUID, rootGID) if err != nil { return nil, err } volumedrivers.Register(volumesDriver, volumesDriver.Name()) s := store.New() s.AddAll(volumesDriver.List()) return s, nil } // AuthenticateToRegistry checks the validity of credentials in authConfig func (daemon *Daemon) AuthenticateToRegistry(authConfig *cliconfig.AuthConfig) (string, error) { return daemon.RegistryService.Auth(authConfig) } // SearchRegistryForImages queries the registry for images matching // term. authConfig is used to login. func (daemon *Daemon) SearchRegistryForImages(term string, authConfig *cliconfig.AuthConfig, headers map[string][]string) (*registry.SearchResults, error) { return daemon.RegistryService.Search(term, authConfig, headers) } // IsShuttingDown tells whether the daemon is shutting down or not func (daemon *Daemon) IsShuttingDown() bool { return daemon.shutdown } // GetContainerStats collects all the stats published by a container func (daemon *Daemon) GetContainerStats(container *Container) (*execdriver.ResourceStats, error) { return nil, nil } func (daemon *Daemon) getNetworkStats(c *Container) ([]*libcontainer.NetworkInterface, error) { return nil, nil } // newBaseContainer creates a new container with its initial // configuration based on the root storage from the daemon. func (daemon *Daemon) newBaseContainer(id string) *Container { return newBaseContainer(id, daemon.containerRoot(id)) } func convertLnNetworkStats(name string, stats *lntypes.InterfaceStatistics) *libcontainer.NetworkInterface { return nil } func (daemon *Daemon) Setup() error { if err := daemon.driver.Setup(); err != nil { return err } return nil } <file_sep>package main import ( "flag" "net" "os" "os/signal" "syscall" "github.com/codegangsta/cli" "github.com/docker/containerd/api/grpc/types" "github.com/docker/containerd/osutils" "github.com/golang/glog" "github.com/hyperhq/runv/containerd/api/grpc/server" "github.com/hyperhq/runv/driverloader" "github.com/hyperhq/runv/factory" "github.com/hyperhq/runv/hypervisor" "github.com/hyperhq/runv/supervisor" "google.golang.org/grpc" ) const ( usage = `High performance hypervisor based container daemon` defaultStateDir = "/run/runv-containerd" defaultListenType = "unix" defaultGRPCEndpoint = "/run/runv-containerd/containerd.sock" ) var daemonFlags = []cli.Flag{ cli.BoolFlag{ Name: "debug", Usage: "enable debug output in the logs", }, cli.StringFlag{ Name: "log_dir", Value: "/var/log/hyper", Usage: "the directory for the logging (glog style)", }, cli.StringFlag{ Name: "state-dir", Value: defaultStateDir, Usage: "runtime state directory", }, cli.DurationFlag{ Name: "metrics-interval", Usage: "[ignore] interval for flushing metrics to the store", }, cli.StringFlag{ Name: "listen,l", Value: defaultGRPCEndpoint, Usage: "Address on which GRPC API will listen", }, cli.StringFlag{ Name: "runtime,r", Value: "runv", Usage: "[ignore] name of the OCI compliant runtime to use when executing containers", }, cli.StringSliceFlag{ Name: "runtime-args", Usage: "[ignore] specify additional runtime args", }, cli.StringFlag{ Name: "pprof-address", Usage: "[ignore] http address to listen for pprof events", }, cli.DurationFlag{ Name: "start-timeout", Usage: "[ignore] timeout duration for waiting on a container to start before it is killed", }, cli.StringFlag{ Name: "kernel", Usage: "kernel for the container", }, cli.StringFlag{ Name: "initrd", Usage: "runv-compatible initrd for the container", }, cli.StringFlag{ Name: "driver", Value: "qemu", Usage: "hypervisor driver", }, } func main() { app := cli.NewApp() app.Name = "runv-containerd" app.Version = "0.01" app.Usage = usage app.Flags = daemonFlags app.Action = func(context *cli.Context) { if context.Bool("debug") { flag.CommandLine.Parse([]string{"-v", "3", "--log_dir", context.String("log_dir"), "--alsologtostderr"}) } else { flag.CommandLine.Parse([]string{"-v", "1", "--log_dir", context.String("log_dir")}) } if context.String("kernel") == "" || context.String("initrd") == "" { glog.Infof("argument kernel and initrd must be set") os.Exit(1) } hypervisor.InterfaceCount = 0 var err error if hypervisor.HDriver, err = driverloader.Probe(context.String("driver")); err != nil { glog.V(1).Infof("%s\n", err.Error()) os.Exit(1) } if err = daemon( context.String("listen"), context.String("state-dir"), context.String("kernel"), context.String("initrd"), ); err != nil { glog.Infof("%v", err) os.Exit(1) } } if err := app.Run(os.Args); err != nil { glog.Infof("%v", err) os.Exit(1) } } func daemon(address, stateDir, kernel, initrd string) error { // setup a standard reaper so that we don't leave any zombies if we are still alive // this is just good practice because we are spawning new processes s := make(chan os.Signal, 2048) signal.Notify(s, syscall.SIGCHLD, syscall.SIGTERM, syscall.SIGINT) f := factory.NewFromConfigs(kernel, initrd, nil) sv, err := supervisor.New(stateDir, stateDir, f) if err != nil { return err } server, err := startServer(address, sv) if err != nil { return err } for ss := range s { switch ss { case syscall.SIGCHLD: if _, err := osutils.Reap(); err != nil { glog.Infof("containerd: reap child processes") } default: glog.Infof("stopping containerd after receiving %s", ss) server.Stop() os.Exit(0) } } return nil } func startServer(address string, sv *supervisor.Supervisor) (*grpc.Server, error) { if err := os.RemoveAll(address); err != nil { return nil, err } l, err := net.Listen(defaultListenType, address) if err != nil { return nil, err } s := grpc.NewServer() types.RegisterAPIServer(s, server.NewServer(sv)) go func() { glog.Infof("containerd: grpc api on %s", address) if err := s.Serve(l); err != nil { glog.Infof("containerd: serve grpc error") } }() return s, nil } <file_sep>package daemon import ( "encoding/json" "errors" "fmt" "io" "io/ioutil" "os" "path/filepath" "strings" "sync" "syscall" "time" "github.com/Sirupsen/logrus" "github.com/docker/docker/daemon/execdriver" "github.com/docker/docker/daemon/logger" "github.com/docker/docker/daemon/logger/jsonfilelog" "github.com/docker/docker/daemon/network" derr "github.com/docker/docker/errors" "github.com/docker/docker/image" "github.com/docker/docker/pkg/archive" "github.com/docker/docker/pkg/broadcaster" "github.com/docker/docker/pkg/ioutils" "github.com/docker/docker/pkg/nat" "github.com/docker/docker/pkg/promise" "github.com/docker/docker/pkg/signal" "github.com/docker/docker/pkg/symlink" "github.com/docker/docker/runconfig" "github.com/docker/docker/volume" "github.com/golang/glog" "github.com/opencontainers/runc/libcontainer/label" ) var ( ErrNotATTY = errors.New("The PTY is not a file") ErrNoTTY = errors.New("No PTY found") ErrContainerStart = errors.New("The container failed to start. Unknown error") ErrContainerStartTimeout = errors.New("The container failed to start due to timed out.") ) type streamConfig struct { stdout *broadcaster.Unbuffered stderr *broadcaster.Unbuffered stdin io.ReadCloser stdinPipe io.WriteCloser } // CommonContainer holds the settings for a container which are applicable // across all platforms supported by the daemon. type CommonContainer struct { streamConfig // embed for Container to support states directly. *State `json:"State"` // Needed for remote api version <= 1.11 root string // Path to the "home" of the container, including metadata. basefs string // Path to the graphdriver mountpoint ID string Created time.Time Path string Args []string Config *runconfig.Config ImageID string `json:"Image"` NetworkSettings *network.Settings ResolvConfPath string HostnamePath string HostsPath string LogPath string Name string Driver string ExecDriver string MountLabel, ProcessLabel string RestartCount int HasBeenStartedBefore bool HasBeenManuallyStopped bool // used for unless-stopped restart policy UpdateDns bool MountPoints map[string]*volume.MountPoint hostConfig *runconfig.HostConfig command *execdriver.Command daemon *Daemon } // newBaseContainer creates a new container with its // basic configuration. func newBaseContainer(id, root string) *Container { return &Container{ CommonContainer: CommonContainer{ ID: id, State: NewState(), root: root, MountPoints: make(map[string]*volume.MountPoint), }, } } func (container *Container) fromDisk() error { pth, err := container.jsonPath() if err != nil { return err } jsonSource, err := os.Open(pth) if err != nil { return err } defer jsonSource.Close() dec := json.NewDecoder(jsonSource) // Load container settings // udp broke compat of docker.PortMapping, but it's not used when loading a container, we can skip it if err := dec.Decode(container); err != nil && !strings.Contains(err.Error(), "docker.PortMapping") { return err } if err := label.ReserveLabel(container.ProcessLabel); err != nil { return err } return container.readHostConfig() } func (container *Container) toDisk() error { data, err := json.Marshal(container) if err != nil { return err } pth, err := container.jsonPath() if err != nil { return err } if err := ioutil.WriteFile(pth, data, 0666); err != nil { return err } return container.writeHostConfig() } func (container *Container) toDiskLocking() error { container.Lock() err := container.toDisk() container.Unlock() return err } func (container *Container) readHostConfig() error { container.hostConfig = &runconfig.HostConfig{} // If the hostconfig file does not exist, do not read it. // (We still have to initialize container.hostConfig, // but that's OK, since we just did that above.) pth, err := container.hostConfigPath() if err != nil { return err } _, err = os.Stat(pth) if os.IsNotExist(err) { return nil } f, err := os.Open(pth) if err != nil { return err } defer f.Close() return json.NewDecoder(f).Decode(&container.hostConfig) } func (container *Container) writeHostConfig() error { pth, err := container.hostConfigPath() if err != nil { return err } f, err := os.Create(pth) if err != nil { return err } defer f.Close() return json.NewEncoder(f).Encode(&container.hostConfig) } // GetResourcePath evaluates `path` in the scope of the container's basefs, with proper path // sanitisation. Symlinks are all scoped to the basefs of the container, as // though the container's basefs was `/`. // // The basefs of a container is the host-facing path which is bind-mounted as // `/` inside the container. This method is essentially used to access a // particular path inside the container as though you were a process in that // container. // // NOTE: The returned path is *only* safely scoped inside the container's basefs // if no component of the returned path changes (such as a component // symlinking to a different path) between using this method and using the // path. See symlink.FollowSymlinkInScope for more details. func (container *Container) GetResourcePath(path string) (string, error) { // IMPORTANT - These are paths on the OS where the daemon is running, hence // any filepath operations must be done in an OS agnostic way. cleanPath := filepath.Join(string(os.PathSeparator), path) r, e := symlink.FollowSymlinkInScope(filepath.Join(container.basefs, cleanPath), container.basefs) return r, e } // Evaluates `path` in the scope of the container's root, with proper path // sanitisation. Symlinks are all scoped to the root of the container, as // though the container's root was `/`. // // The root of a container is the host-facing configuration metadata directory. // Only use this method to safely access the container's `container.json` or // other metadata files. If in doubt, use container.GetResourcePath. // // NOTE: The returned path is *only* safely scoped inside the container's root // if no component of the returned path changes (such as a component // symlinking to a different path) between using this method and using the // path. See symlink.FollowSymlinkInScope for more details. func (container *Container) getRootResourcePath(path string) (string, error) { // IMPORTANT - These are paths on the OS where the daemon is running, hence // any filepath operations must be done in an OS agnostic way. cleanPath := filepath.Join(string(os.PathSeparator), path) return symlink.FollowSymlinkInScope(filepath.Join(container.root, cleanPath), container.root) } // StreamConfig.StdinPipe returns a WriteCloser which can be used to feed data // to the standard input of the container's active process. // Container.StdoutPipe and Container.StderrPipe each return a ReadCloser // which can be used to retrieve the standard output (and error) generated // by the container's active process. The output (and error) are actually // copied and delivered to all StdoutPipe and StderrPipe consumers, using // a kind of "broadcaster". func (streamConfig *streamConfig) StdinPipe() io.WriteCloser { return streamConfig.stdinPipe } func (streamConfig *streamConfig) StdoutPipe() io.ReadCloser { bytesPipe := ioutils.NewBytesPipe(nil) streamConfig.stdout.Add(bytesPipe) return bytesPipe } func (streamConfig *streamConfig) StderrPipe() io.ReadCloser { bytesPipe := ioutils.NewBytesPipe(nil) streamConfig.stderr.Add(bytesPipe) return bytesPipe } // ExitOnNext signals to the monitor that it should not restart the container // after we send the kill signal. func (container *Container) ExitOnNext() { } func (container *Container) KillSig(sig int) error { glog.V(1).Infof("Sending %d to %s", sig, container.ID) container.Lock() defer container.Unlock() // We could unpause the container for them rather than returning this error if container.Paused { return fmt.Errorf("Container %s is paused. Unpause the container before stopping", container.ID) } if !container.Running { return nil } // if the container is currently restarting we do not need to send the signal // to the process. Telling the monitor that it should exit on it's next event // loop is enough if container.Restarting { return nil } return nil } // Wrapper aroung KillSig() suppressing "no such process" error. func (container *Container) killPossiblyDeadProcess(sig int) error { err := container.KillSig(sig) if err == syscall.ESRCH { glog.V(1).Infof("Cannot kill process (pid=%d) with signal %d: no such process.", container.GetPID(), sig) return nil } return err } func (container *Container) Kill() error { if !container.IsRunning() { return nil } // 1. Send SIGKILL if err := container.killPossiblyDeadProcess(9); err != nil { // While normally we might "return err" here we're not going to // because if we can't stop the container by this point then // its probably because its already stopped. Meaning, between // the time of the IsRunning() call above and now it stopped. // Also, since the err return will be exec driver specific we can't // look for any particular (common) error that would indicate // that the process is already dead vs something else going wrong. // So, instead we'll give it up to 2 more seconds to complete and if // by that time the container is still running, then the error // we got is probably valid and so we return it to the caller. if container.IsRunning() { container.WaitStop(2 * time.Second) if container.IsRunning() { return err } } } // 2. Wait for the process to die, in last resort, try to kill the process directly if err := killProcessDirectly(container); err != nil { return err } container.WaitStop(-1 * time.Second) return nil } func (container *Container) Stop(seconds int) error { if !container.IsRunning() { return nil } // 1. Send a SIGTERM if err := container.killPossiblyDeadProcess(15); err != nil { glog.Infof("Failed to send SIGTERM to the process, force killing") if err := container.killPossiblyDeadProcess(9); err != nil { return err } } // 2. Wait for the process to exit on its own if _, err := container.WaitStop(time.Duration(seconds) * time.Second); err != nil { glog.Infof("Container %v failed to exit within %d seconds of SIGTERM - using the force", container.ID, seconds) // 3. If it doesn't, then send SIGKILL if err := container.Kill(); err != nil { container.WaitStop(-1 * time.Second) return err } } return nil } func (container *Container) Resize(h, w int) error { if !container.IsRunning() { return fmt.Errorf("Cannot resize container %s, container is not running", container.ID) } return nil } func (container *Container) Export() (archive.Archive, error) { if err := container.Mount(); err != nil { return nil, err } archive, err := archive.Tar(container.basefs, archive.Uncompressed) if err != nil { container.Unmount() return nil, err } arch := ioutils.NewReadCloserWrapper(archive, func() error { err := archive.Close() container.Unmount() return err }) return arch, err } func (container *Container) Mount() error { return container.daemon.Mount(container) } func (container *Container) changes() ([]archive.Change, error) { return container.daemon.changes(container) } func (container *Container) Changes() ([]archive.Change, error) { container.Lock() defer container.Unlock() return container.changes() } func (container *Container) GetImage() (*image.Image, error) { if container.daemon == nil { return nil, fmt.Errorf("Can't get image of unregistered container") } return container.daemon.graph.Get(container.ImageID) } func (container *Container) Unmount() error { return container.daemon.Unmount(container) } func (container *Container) hostConfigPath() (string, error) { return container.getRootResourcePath("hostconfig.json") } func (container *Container) jsonPath() (string, error) { return container.getRootResourcePath("config.json") } // This method must be exported to be used from the lxc template // This directory is only usable when the container is running func (container *Container) rootfsPath() string { return container.basefs } func validateID(id string) error { if id == "" { return fmt.Errorf("Invalid empty id") } return nil } // Returns true if the container exposes a certain port func (container *Container) exposes(p nat.Port) bool { _, exists := container.Config.ExposedPorts[p] return exists } func (container *Container) getLogConfig(defaultConfig runconfig.LogConfig) runconfig.LogConfig { cfg := container.hostConfig.LogConfig if cfg.Type != "" || len(cfg.Config) > 0 { // container has log driver configured if cfg.Type == "" { cfg.Type = jsonfilelog.Name } return cfg } // Use daemon's default log config for containers return defaultConfig } // StartLogger starts a new logger driver for the container. func (container *Container) StartLogger(cfg runconfig.LogConfig) (logger.Logger, error) { c, err := logger.GetLogDriver(cfg.Type) if err != nil { return nil, derr.ErrorCodeLoggingFactory.WithArgs(err) } ctx := logger.Context{ Config: cfg.Config, ContainerID: container.ID, ContainerName: container.Name, ContainerEntrypoint: container.Path, ContainerArgs: container.Args, ContainerImageID: container.ImageID, ContainerImageName: container.Config.Image, ContainerCreated: container.Created, ContainerEnv: container.Config.Env, ContainerLabels: container.Config.Labels, } // Set logging file for "json-logger" if cfg.Type == jsonfilelog.Name { ctx.LogPath, err = container.getRootResourcePath(fmt.Sprintf("%s-json.log", container.ID)) if err != nil { return nil, err } } return c(ctx) } func (container *Container) getProcessLabel() string { // even if we have a process label return "" if we are running // in privileged mode if container.hostConfig.Privileged { return "" } return container.ProcessLabel } func (container *Container) getMountLabel() string { if container.hostConfig.Privileged { return "" } return container.MountLabel } func (container *Container) getExecIDs() []string { return nil } // Attach connects to the container's TTY, delegating to standard // streams or websockets depending on the configuration. func (container *Container) Attach(stdin io.ReadCloser, stdout io.Writer, stderr io.Writer) chan error { return attach(&container.streamConfig, container.Config.OpenStdin, container.Config.StdinOnce, container.Config.Tty, stdin, stdout, stderr) } func attach(streamConfig *streamConfig, openStdin, stdinOnce, tty bool, stdin io.ReadCloser, stdout io.Writer, stderr io.Writer) chan error { var ( cStdout, cStderr io.ReadCloser cStdin io.WriteCloser wg sync.WaitGroup errors = make(chan error, 3) ) if stdin != nil && openStdin { cStdin = streamConfig.StdinPipe() wg.Add(1) } if stdout != nil { cStdout = streamConfig.StdoutPipe() wg.Add(1) } if stderr != nil { cStderr = streamConfig.StderrPipe() wg.Add(1) } // Connect stdin of container to the http conn. go func() { if stdin == nil || !openStdin { return } logrus.Debugf("attach: stdin: begin") defer func() { if stdinOnce && !tty { cStdin.Close() } else { // No matter what, when stdin is closed (io.Copy unblock), close stdout and stderr if cStdout != nil { cStdout.Close() } if cStderr != nil { cStderr.Close() } } wg.Done() logrus.Debugf("attach: stdin: end") }() var err error if tty { _, err = copyEscapable(cStdin, stdin) } else { _, err = io.Copy(cStdin, stdin) } if err == io.ErrClosedPipe { err = nil } if err != nil { logrus.Errorf("attach: stdin: %s", err) errors <- err return } }() attachStream := func(name string, stream io.Writer, streamPipe io.ReadCloser) { if stream == nil { return } defer func() { // Make sure stdin gets closed if stdin != nil { stdin.Close() } streamPipe.Close() wg.Done() logrus.Debugf("attach: %s: end", name) }() logrus.Debugf("attach: %s: begin", name) _, err := io.Copy(stream, streamPipe) if err == io.ErrClosedPipe { err = nil } if err != nil { logrus.Errorf("attach: %s: %v", name, err) errors <- err } } go attachStream("stdout", stdout, cStdout) go attachStream("stderr", stderr, cStderr) return promise.Go(func() error { wg.Wait() close(errors) for err := range errors { if err != nil { return err } } return nil }) } func (container *Container) Copy(resource string) (io.ReadCloser, error) { container.Lock() defer container.Unlock() var err error if err := container.Mount(); err != nil { return nil, err } defer func() { if err != nil { // unmount the container's rootfs container.Unmount() } }() basePath, err := container.GetResourcePath(resource) if err != nil { return nil, err } stat, err := os.Stat(basePath) if err != nil { return nil, err } var filter []string if !stat.IsDir() { d, f := filepath.Split(basePath) basePath = d filter = []string{f} } else { filter = []string{filepath.Base(basePath)} basePath = filepath.Dir(basePath) } archive, err := archive.TarWithOptions(basePath, &archive.TarOptions{ Compression: archive.Uncompressed, IncludeFiles: filter, }) if err != nil { return nil, err } reader := ioutils.NewReadCloserWrapper(archive, func() error { err := archive.Close() container.Unmount() return err }) return reader, nil } // Returns true if the container exposes a certain port func (container *Container) Exposes(p nat.Port) bool { _, exists := container.Config.ExposedPorts[p] return exists } func (container *Container) HostConfig() *runconfig.HostConfig { return container.hostConfig } func (container *Container) SetHostConfig(hostConfig *runconfig.HostConfig) { container.hostConfig = hostConfig } func (container *Container) waitForStart() error { return nil } func (c *Container) LogDriverType() string { c.Lock() defer c.Unlock() if c.hostConfig.LogConfig.Type == "" { return c.daemon.defaultLogConfig.Type } return c.hostConfig.LogConfig.Type } // Code c/c from io.Copy() modified to handle escape sequence func copyEscapable(dst io.Writer, src io.ReadCloser) (written int64, err error) { buf := make([]byte, 32*1024) for { nr, er := src.Read(buf) if nr > 0 { // ---- Docker addition // char 16 is C-p if nr == 1 && buf[0] == 16 { nr, er = src.Read(buf) // char 17 is C-q if nr == 1 && buf[0] == 17 { if err := src.Close(); err != nil { return 0, err } return 0, nil } } // ---- End of docker nw, ew := dst.Write(buf[0:nr]) if nw > 0 { written += int64(nw) } if ew != nil { err = ew break } if nr != nw { err = io.ErrShortWrite break } } if er == io.EOF { break } if er != nil { err = er break } } return written, err } func (container *Container) shouldRestart() bool { return container.hostConfig.RestartPolicy.Name == "always" || (container.hostConfig.RestartPolicy.Name == "on-failure" && container.ExitCode != 0) } func (container *Container) addBindMountPoint(name, source, destination string, rw bool) { container.MountPoints[destination] = &volume.MountPoint{ Name: name, Source: source, Destination: destination, RW: rw, } } func (container *Container) addLocalMountPoint(name, destination string, rw bool) { container.MountPoints[destination] = &volume.MountPoint{ Name: name, Driver: volume.DefaultDriverName, Destination: destination, RW: rw, } } func (container *Container) addMountPointWithVolume(destination string, vol volume.Volume, rw bool) { container.MountPoints[destination] = &volume.MountPoint{ Name: vol.Name(), Driver: vol.DriverName(), Destination: destination, RW: rw, Volume: vol, } } func (container *Container) isDestinationMounted(destination string) bool { return container.MountPoints[destination] != nil } func (container *Container) stopSignal() int { var stopSignal syscall.Signal if container.Config.StopSignal != "" { stopSignal, _ = signal.ParseSignal(container.Config.StopSignal) } if int(stopSignal) == 0 { stopSignal, _ = signal.ParseSignal(signal.DefaultStopSignal) } return int(stopSignal) } func (container *Container) GetDaemon() *Daemon { return container.daemon } func (container *Container) SetDaemon(daemon *Daemon) { container.daemon = daemon } <file_sep>package hypervisor import ( "encoding/binary" "fmt" "net" "time" "github.com/golang/glog" "github.com/hyperhq/runv/lib/telnet" "github.com/hyperhq/runv/lib/utils" ) // Message type DecodedMessage struct { Code uint32 Message []byte Event VmEvent } func waitConsoleOutput(ctx *VmContext) { conn, err := utils.UnixSocketConnect(ctx.ConsoleSockName) if err != nil { glog.Error("failed to connected to ", ctx.ConsoleSockName, " ", err.Error()) return } glog.V(1).Info("connected to ", ctx.ConsoleSockName) tc, err := telnet.NewConn(conn) if err != nil { glog.Error("fail to init telnet connection to ", ctx.ConsoleSockName, ": ", err.Error()) return } glog.V(1).Infof("connected %s as telnet mode.", ctx.ConsoleSockName) cout := make(chan string, 128) go TtyLiner(tc, cout) for { line, ok := <-cout if ok { glog.V(1).Info("[console] ", line) } else { glog.Info("console output end") break } } } func NewVmMessage(m *DecodedMessage) []byte { length := len(m.Message) + 8 msg := make([]byte, length) binary.BigEndian.PutUint32(msg[:], uint32(m.Code)) binary.BigEndian.PutUint32(msg[4:], uint32(length)) copy(msg[8:], m.Message) return msg } func ReadVmMessage(conn *net.UnixConn) (*DecodedMessage, error) { needRead := 8 length := 0 read := 0 buf := make([]byte, 512) res := []byte{} for read < needRead { want := needRead - read if want > 512 { want = 512 } glog.V(1).Infof("trying to read %d bytes", want) nr, err := conn.Read(buf[:want]) if err != nil { glog.Error("read init data failed") return nil, err } res = append(res, buf[:nr]...) read = read + nr glog.V(1).Infof("read %d/%d [length = %d]", read, needRead, length) if length == 0 && read >= 8 { length = int(binary.BigEndian.Uint32(res[4:8])) glog.V(1).Infof("data length is %d", length) if length > 8 { needRead = length } } } return &DecodedMessage{ Code: binary.BigEndian.Uint32(res[:4]), Message: res[8:], }, nil } func waitInitReady(ctx *VmContext) { conn, err := utils.UnixSocketConnect(ctx.HyperSockName) if err != nil { glog.Error("Cannot connect to hyper socket ", err.Error()) ctx.Hub <- &InitFailedEvent{ Reason: "Cannot connect to hyper socket " + err.Error(), } return } glog.Info("Wating for init messages...") msg, err := ReadVmMessage(conn.(*net.UnixConn)) if err != nil { glog.Error("read init message failed... ", err.Error()) ctx.Hub <- &InitFailedEvent{ Reason: "read init message failed... " + err.Error(), } conn.Close() } else if msg.Code == INIT_READY { glog.Info("Get init ready message") ctx.Hub <- &InitConnectedEvent{conn: conn.(*net.UnixConn)} go waitCmdToInit(ctx, conn.(*net.UnixConn)) } else { glog.Warningf("Get init message %d", msg.Code) ctx.Hub <- &InitFailedEvent{ Reason: fmt.Sprintf("Get init message %d", msg.Code), } conn.Close() } } func connectToInit(ctx *VmContext) { conn, err := utils.UnixSocketConnect(ctx.HyperSockName) if err != nil { glog.Error("Cannot re-connect to hyper socket ", err.Error()) ctx.Hub <- &InitFailedEvent{ Reason: "Cannot re-connect to hyper socket " + err.Error(), } return } go waitCmdToInit(ctx, conn.(*net.UnixConn)) } func waitCmdToInit(ctx *VmContext, init *net.UnixConn) { looping := true cmds := []*DecodedMessage{} var data []byte var timeout bool = false var index int = 0 var got int = 0 var pingTimer *time.Timer = nil var pongTimer *time.Timer = nil go waitInitAck(ctx, init) for looping { cmd, ok := <-ctx.vm if !ok { glog.Info("vm channel closed, quit") break } glog.Infof("got cmd:%d", cmd.Code) if cmd.Code == INIT_ACK || cmd.Code == INIT_ERROR { if len(cmds) > 0 { if cmds[0].Code == INIT_DESTROYPOD { glog.Info("got response of shutdown command, last round of command to init") looping = false } if cmd.Code == INIT_ACK { if cmds[0].Code != INIT_PING { ctx.Hub <- &CommandAck{ reply: cmds[0], msg: cmd.Message, } } } else { ctx.Hub <- &CommandError{ reply: cmds[0], msg: cmd.Message, } } cmds = cmds[1:] if pongTimer != nil { glog.V(1).Info("ack got, clear pong timer") pongTimer.Stop() pongTimer = nil } if pingTimer == nil { pingTimer = time.AfterFunc(30*time.Second, func() { defer func() { recover() }() glog.V(1).Info("Send ping message to init") ctx.vm <- &DecodedMessage{ Code: INIT_PING, Message: []byte{}, } pingTimer = nil }) } else { pingTimer.Reset(30 * time.Second) } } else { glog.Error("got ack but no command in queue") } } else if cmd.Code == INIT_FINISHPOD { num := len(cmd.Message) / 4 results := make([]uint32, num) for i := 0; i < num; i++ { results[i] = binary.BigEndian.Uint32(cmd.Message[i*4 : i*4+4]) } for _, c := range cmds { if c.Code == INIT_DESTROYPOD { glog.Info("got pod finish message after having send destroy message") looping = false ctx.Hub <- &CommandAck{ reply: c, } break } } glog.V(1).Infof("Pod finished, returned %d values", num) ctx.Hub <- &PodFinished{ result: results, } } else { if cmd.Code == INIT_NEXT { glog.V(1).Infof("get command NEXT") got += int(binary.BigEndian.Uint32(cmd.Message[0:4])) glog.V(1).Infof("send %d, receive %d", index, got) timeout = false if index == got { /* received the sent out message */ tmp := data[index:] data = tmp index = 0 got = 0 } } else { glog.V(1).Infof("send command %d to init, payload: '%s'.", cmd.Code, string(cmd.Message)) cmds = append(cmds, cmd) data = append(data, NewVmMessage(cmd)...) timeout = true } if index == 0 && len(data) != 0 { var end int = len(data) if end > 512 { end = 512 } wrote, _ := init.Write(data[:end]) glog.V(1).Infof("write %d to init, payload: '%s'.", wrote, data[:end]) index += wrote } if timeout && pongTimer == nil { glog.V(1).Info("message sent, set pong timer") pongTimer = time.AfterFunc(30*time.Second, func() { if !ctx.Paused { ctx.Hub <- &Interrupted{Reason: "init not reply ping mesg"} } }) } } } if pingTimer != nil { pingTimer.Stop() } if pongTimer != nil { pongTimer.Stop() } } func waitInitAck(ctx *VmContext, init *net.UnixConn) { for { res, err := ReadVmMessage(init) if err != nil { ctx.Hub <- &Interrupted{Reason: "init socket failed " + err.Error()} return } else if res.Code == INIT_ACK || res.Code == INIT_NEXT || res.Code == INIT_ERROR || res.Code == INIT_FINISHPOD { ctx.vm <- res } } } <file_sep>package daemon import ( "fmt" "net" "github.com/golang/glog" "github.com/hyperhq/runv/hypervisor/types" "github.com/hyperhq/runv/hypervisor" "github.com/hyperhq/hyper/engine" ) func (daemon *Daemon) CmdPodMigrate(job *engine.Job) error { if len(job.Args) == 0 { return fmt.Errorf("Can not execute 'migrate' command without any pod name!") } podId := job.Args[0] ip := job.Args[1] port := job.Args[2] daemon.PodList.Lock() glog.V(2).Infof("lock PodList") defer glog.V(2).Infof("unlock PodList") defer daemon.PodList.Unlock() code, cause, err := daemon.MigratePod(podId, ip, port) if err != nil { return err } // Prepare the VM status to client v := &engine.Env{} v.Set("ID",podId) v.SetInt("Code",code) v.Set("Cause",cause) if _,err := v.WriteTo(job.Stdout); err != nil { return err } return nil } func (daemon *Daemon) CmdPodListen(job *engine.Job) error { if len(job.Args) == 0 { return fmt.Errorf("Can not execute 'listen' command without any pod name!") } var ( tag string = "" ttys []*hypervisor.TtyIO = []*hypervisor.TtyIO{} ttyCallback chan *types.VmResponse ) vmId := "" ip := job.Args[0] port := job.Args[1] if len(job.Args) > 2 { tag = job.Args[1] } if tag != "" { glog.V(1).Info("Pod Run with client terminal tag: ",tag) ttyCallback = make(chan *types.VmResponse, 1) ttys = append(ttys,&hypervisor.TtyIO{ Stdin: job.Stdin, Stdout: job.Stdout, ClientTag: tag, Callback: ttyCallback, }) } /* daemon.PodList.Lock() glog.V(2).Infof("lock PodList") if _,ok := daemon.PodList.Get(podId); !ok { glog.V(2).Infof("unlock PodList") daemon.PodList.Unlock() return fmt.Errorf("The pod(%s) can not be found, please create it first", podId) }*/ var lazy bool = hypervisor.HDriver.SupportLazyMode() && vmId == "" _, _, err := daemon.ListenPod(ip, port, vmId, nil, lazy, false, types.VM_KEEP_NONE, ttys) if err != nil { glog.Errorf(err.Error()) return err } /* if len(ttys) >0 { // glog.V(2).Infof("unlock PodList") // daemon.PodList.Unlock() daemon.GetExitCode(podId,tag,ttyCallback) }*/ // Prepare the VM status to client /* v := &engine.Env{} v.Set("ID",podId) v.SetInt("Code",code) v.Set("Cause",cause) if _,err := v.WriteTo(job.Stdout); err != nil { return err }*/ return nil } func (daemon *Daemon) ListenPod(ip, port, vmId string, config interface{}, lazy, autoremove bool, keep int, streams []*hypervisor.TtyIO) (int, string, error) { glog.V(1).Infof("Listening ip is %s, port is %s", ip, port) var ( err error p *Pod ) // listen for the mata data addr := fmt.Sprintf("%s:%s", ip, port) listener, err := net.Listen("tcp", addr) defer listener.Close() if err != nil { glog.Errorf("Create mata data listener error") } conn,_ := listener.Accept() pId := getMata(conn) glog.V(1).Infof("Listen Pod get pod Id %s",string(pId)) conn,_ = listener.Accept() pArgs := getMata(conn) glog.V(1).Infof("Listen Pod get pod Args %s",string(pArgs)) conn,_ = listener.Accept() cId := getMata(conn) glog.V(1).Infof("Listen Pod get containers ids %s",string(cId)) spec, err := ProcessPodBytes(pArgs, string(pId)) if err != nil { glog.Errorf("Process Pod(%s) Args error", string(pId)) } cName := spec.Containers[0].Name cImage := spec.Containers[0].Image glog.V(1).Infof("Listen Pod get containers name %s", cName) glog.V(1).Infof("Listen Pod get containers image %s", cImage) podId := string(pId) podArgs := string(pArgs) if _,ok := daemon.PodList.Get(podId); ok { glog.V(1).Infof("The listening get an existing pod") return -1,"",fmt.Errorf("The pos has existed(%s)", podId) } if cInfo,_ := daemon.DockerCli.GetContainerInfo(string(cId)); cInfo == nil { if _, _, err := daemon.DockerCli.SendCmdRestore(cName, cImage, string(cId), []string{}, nil); err != nil { return -1, "", fmt.Errorf("Restore Container(%s) error", string(cId)) } } // put the container ids into db key := fmt.Sprintf("pod-container-%s",podId) daemon.db.Put([]byte(key), []byte(cId),nil) p,err = daemon.GetPod(podId, podArgs, autoremove) if err != nil { return -1, "", err } //vmResponse, err := p.Listen(daemon, vmId, lazy, autoremove, keep, streams) _, err = p.Listen(daemon, ip, port, vmId, lazy, autoremove, keep, streams) if err != nil { return -1, "", err } //return vmResponse.Code, vmResponse.Cause, nil return 0, "", nil } func getMata(conn net.Conn) []byte { buf := make([]byte, 1024) defer conn.Close() arg := []byte{} for { n,err := conn.Read(buf) if err != nil { return arg } arg = append(arg, buf[:n]...) } } func (daemon *Daemon) MigratePod(podId , ip, port string) (int,string,error) { var ( code = 0 cause = "" err error ) glog.V(1).Infof("Prepare to migrate the POD: %s",podId) pod, ok := daemon.PodList.Get(podId) if !ok { glog.Errorf("Can not find pod(%s)",podId) return -1, "", fmt.Errorf("Can not find pod(%s)",podId) } glog.V(1).Infof("Migrate Pod , pod id %s",string(podId)) podArgs,_ := daemon.GetPodByName(podId) glog.V(1).Infof("Migrate Pod , pod Args %s",string(podArgs)) key := fmt.Sprintf("pod-container-%s", podId) cIds, err := daemon.db.Get([]byte(key), nil) glog.V(1).Infof("Migrate Pod , containers Id %s",string(cIds)) if err != nil { glog.Errorf("can not find containers of pod(%s)",podId) } sendMata([]byte(podId), ip, port) sendMata(podArgs, ip, port) sendMata(cIds, ip, port) if pod.vm == nil { return types.E_VM_SHUTDOWN, "", nil } vmId := pod.vm.Id vmResponse := pod.vm.MigratePod(pod.status, ip, port) if vmResponse != nil { glog.V(1).Infof("Migrate Pod succeed, now plan to move the Pod") daemon.DeleteVmByPod(podId) daemon.RemoveVm(vmId) code, cause, err = daemon.CleanPod(podId) } return code, cause, nil } func sendMata(arg []byte, ip, port string) error { addr := fmt.Sprintf("%s:%s", ip, port) conn, err := net.Dial("tcp",addr) if err != nil { return err } defer conn.Close() send := 0 length := len(arg) for send<length { n,err := conn.Write(arg[send:]) if err != nil { glog.Errorf("send Mata data error", err.Error()) return err } send = send + n } return nil } func (p *Pod) Listen(daemon *Daemon, ip, port, vmId string, lazy, autoremove bool, keep int, streams []*hypervisor.TtyIO) (*types.VmResponse, error) { var err error = nil if err = p.GetVM(daemon, vmId, lazy, keep); err != nil { return nil, err } defer func() { if err != nil && vmId == "" { p.KillVM(daemon) } }() if err = p.Prepare(daemon); err != nil { return nil, err } defer func() { if err != nil { stopLogger(p.status) } }() if err = p.startLogging(daemon); err != nil { return nil, err } if err = p.AttachTtys(streams); err != nil { return nil, err } //vmResponse := p.vm.ListenPod(p.status, p.spec, p.containers, p.volumes) p.vm.ListenPod(ip, port, p.status, p.spec, p.containers, p.volumes) /* if vmResponse.Data == nil { err = fmt.Errorf("VM response data is nil") return vmResponse, err }*/ //err = daemon.UpdateVmData(p.vm.Id, vmResponse.Data.([]byte)) err = daemon.UpdateVmData(p.vm.Id, []byte{}) if err != nil { glog.Error(err.Error()) return nil, err } // add or update the Vm info for POD err = daemon.UpdateVmByPod(p.id, p.vm.Id) if err != nil { glog.Error(err.Error()) return nil, err } //return vmResponse, nil return nil,nil } <file_sep>// +build linux,with_libvirt package libvirt import ( "os" "github.com/hyperhq/runv/hypervisor/network" "github.com/hyperhq/runv/hypervisor/pod" ) func (ld *LibvirtDriver) BuildinNetwork() bool { return true } func (ld *LibvirtDriver) InitNetwork(bIface, bIP string, disableIptables bool) error { return network.InitNetwork(bIface, bIP, disableIptables) } func (lc *LibvirtContext) ConfigureNetwork(vmId, requestedIP string, maps []pod.UserContainerPort, config pod.UserInterface) (*network.Settings, error) { return network.Configure(vmId, requestedIP, true, maps, config) } func (lc *LibvirtContext) AllocateNetwork(vmId, requestedIP string, maps []pod.UserContainerPort) (*network.Settings, error) { return network.Allocate(vmId, requestedIP, true, maps) } func (lc *LibvirtContext) ReleaseNetwork(vmId, releasedIP string, maps []pod.UserContainerPort, file *os.File) error { return network.Release(vmId, releasedIP, maps, nil) } <file_sep>package daemon import ( "sync" "github.com/hyperhq/runv/hypervisor" "github.com/hyperhq/runv/hypervisor/types" ) type PodList struct { pods map[string]*Pod sync.RWMutex } func NewPodList() *PodList { return &PodList{ pods: make(map[string]*Pod), } } func (pl *PodList) Get(id string) (*Pod, bool) { if pl.pods == nil { return nil, false } p, ok := pl.pods[id] return p, ok } func (pl *PodList) Put(p *Pod) { if pl.pods == nil { pl.pods = make(map[string]*Pod) } pl.pods[p.id] = p } func (pl *PodList) Delete(id string) { delete(pl.pods, id) } func (pl *PodList) GetByName(name string) *Pod { return pl.Find(func(p *Pod) bool { if p.status.Name == name { return true } return false }) } func (pl *PodList) GetStatus(id string) (*hypervisor.PodStatus, bool) { p, ok := pl.Get(id) if !ok { return nil, false } return p.status, true } func (pl *PodList) CountRunning() int64 { return pl.CountStatus(types.S_POD_RUNNING) } func (pl *PodList) CountStatus(status uint) (num int64) { num = 0 pl.RLock() defer pl.RUnlock() if pl.pods == nil { return } for _, pod := range pl.pods { if pod.status.Status == status { num++ } } return } func (pl *PodList) CountContainers() (num int64) { num = 0 pl.RLock() defer pl.RUnlock() if pl.pods == nil { return } for _, pod := range pl.pods { num += int64(len(pod.status.Containers)) } return } type PodOp func(*Pod) error type PodFilterOp func(*Pod) bool func (pl *PodList) Foreach(fn PodOp) error { for _, p := range pl.pods { if err := fn(p); err != nil { return err } } return nil } func (pl *PodList) Find(fn PodFilterOp) *Pod { for _, p := range pl.pods { if fn(p) { return p } } return nil } <file_sep>package docker import ( "github.com/docker/docker/pkg/stringutils" "github.com/docker/docker/runconfig" "github.com/hyperhq/hyper/lib/docker/daemon" ) func (cli Docker) SendCmdCreate(name, image string, cmds []string, userConfig interface{}) ([]byte, int, error) { config := &runconfig.Config{ Image: image, Cmd: stringutils.NewStrSlice(cmds...), } if userConfig != nil { config = userConfig.(*runconfig.Config) } hostConfig := &runconfig.HostConfig{} containerResp, err := cli.daemon.ContainerCreate(&daemon.ContainerCreateConfig{ Name: name, Config: config, HostConfig: hostConfig, AdjustCPUShares: false, }) if err != nil { return nil, 500, err } return []byte(containerResp.ID), 200, nil } func (cli Docker) SendCmdRestore(name, image, cid string, cmds []string, userConfig interface{}) ([]byte, int, error) { config := &runconfig.Config{ Image: image, Cmd: stringutils.NewStrSlice(cmds...), } if userConfig != nil { config = userConfig.(*runconfig.Config) } hostConfig := &runconfig.HostConfig{} containerResp, err := cli.daemon.ContainerRestore(&daemon.ContainerCreateConfig{ Name: name, Config: config, HostConfig: hostConfig, AdjustCPUShares: false, },cid) if err != nil { return nil, 500, err } return []byte(containerResp.ID), 200, nil } <file_sep>package main import ( "encoding/json" "fmt" "io/ioutil" "os" "path/filepath" "strings" "github.com/codegangsta/cli" "github.com/hyperhq/runv/lib/utils" "github.com/kardianos/osext" "github.com/opencontainers/specs" ) type startConfig struct { Name string BundlePath string Root string Driver string Kernel string Initrd string Vbox string specs.LinuxSpec `json:"config"` specs.LinuxRuntimeSpec `json:"runtime"` } func loadStartConfig(context *cli.Context) (*startConfig, error) { config := &startConfig{ Name: context.GlobalString("id"), Root: context.GlobalString("root"), Driver: context.GlobalString("driver"), Kernel: context.GlobalString("kernel"), Initrd: context.GlobalString("initrd"), Vbox: context.GlobalString("vbox"), BundlePath: context.String("bundle"), } var err error if config.Name == "" { return nil, fmt.Errorf("Please specify container ID") } // If config.BundlePath is "", this code sets it to the current work directory if !filepath.IsAbs(config.BundlePath) { config.BundlePath, err = filepath.Abs(config.BundlePath) if err != nil { fmt.Printf("Cannot get abs path for bundle path: %s\n", err.Error()) return nil, err } } ocffile := filepath.Join(config.BundlePath, specConfig) runtimefile := filepath.Join(config.BundlePath, runtimeConfig) if _, err = os.Stat(ocffile); os.IsNotExist(err) { fmt.Printf("Please make sure bundle directory contains config.json\n") return nil, err } ocfData, err := ioutil.ReadFile(ocffile) if err != nil { fmt.Printf("%s\n", err.Error()) return nil, err } var runtimeData []byte = nil _, err = os.Stat(runtimefile) if err != nil { if !os.IsNotExist(err) { fmt.Printf("Fail to stat %s, %s\n", runtimefile, err.Error()) return nil, err } } else { runtimeData, err = ioutil.ReadFile(runtimefile) if err != nil { fmt.Printf("Fail to readfile %s, %s\n", runtimefile, err.Error()) return nil, err } } if err := json.Unmarshal(ocfData, &config.LinuxSpec); err != nil { return nil, err } if err := json.Unmarshal(runtimeData, &config.LinuxRuntimeSpec); err != nil { return nil, err } return config, nil } func firstExistingFile(candidates []string) string { for _, file := range candidates { if _, err := os.Stat(file); err == nil { return file } } return "" } var startCommand = cli.Command{ Name: "start", Usage: "create and run a container", Flags: []cli.Flag{ cli.StringFlag{ Name: "bundle, b", Usage: "path to the root of the bundle directory", }, cli.StringFlag{ Name: "verbose, v", Value: "0", Usage: "logging verbosity", }, cli.StringFlag{ Name: "log_dir", Value: "/var/log/hyper", Usage: "the directory for the logging (glog style)", }, }, Action: func(context *cli.Context) { config, err := loadStartConfig(context) if err != nil { fmt.Printf("load config failed %v\n", err) os.Exit(-1) } if os.Geteuid() != 0 { fmt.Printf("runv should be run as root\n") os.Exit(-1) } _, err = os.Stat(filepath.Join(config.Root, config.Name)) if err == nil { fmt.Printf("Container %s exists\n", config.Name) os.Exit(-1) } var sharedContainer string for _, ns := range config.LinuxRuntimeSpec.Linux.Namespaces { if ns.Path != "" { if strings.Contains(ns.Path, "/") { fmt.Printf("Runv doesn't support path to namespace file, it supports containers name as shared namespaces only\n") os.Exit(-1) } if ns.Type == "mount" { // TODO support it! fmt.Printf("Runv doesn't support shared mount namespace currently\n") os.Exit(-1) } sharedContainer = ns.Path _, err = os.Stat(filepath.Join(config.Root, sharedContainer, "state.json")) if err != nil { fmt.Printf("The container %s is not existing or not ready\n", sharedContainer) os.Exit(-1) } _, err = os.Stat(filepath.Join(config.Root, sharedContainer, "runv.sock")) if err != nil { fmt.Printf("The container %s is not ready\n", sharedContainer) os.Exit(-1) } } } // only set the default Kernel/Initrd/Vbox when it is the first container(sharedContainer == "") if config.Kernel == "" && sharedContainer == "" && config.Driver != "vbox" { config.Kernel = firstExistingFile([]string{ filepath.Join(config.BundlePath, config.LinuxSpec.Spec.Root.Path, "boot/vmlinuz"), filepath.Join(config.BundlePath, "boot/vmlinuz"), filepath.Join(config.BundlePath, "vmlinuz"), "/var/lib/hyper/kernel", }) } if config.Initrd == "" && sharedContainer == "" && config.Driver != "vbox" { config.Initrd = firstExistingFile([]string{ filepath.Join(config.BundlePath, config.LinuxSpec.Spec.Root.Path, "boot/initrd.img"), filepath.Join(config.BundlePath, "boot/initrd.img"), filepath.Join(config.BundlePath, "initrd.img"), "/var/lib/hyper/hyper-initrd.img", }) } if config.Vbox == "" && sharedContainer == "" && config.Driver == "vbox" { config.Vbox = firstExistingFile([]string{ filepath.Join(config.BundlePath, "vbox.iso"), "/opt/hyper/static/iso/hyper-vbox-boot.iso", }) } // convert the paths to abs if config.Kernel != "" && !filepath.IsAbs(config.Kernel) { config.Kernel, err = filepath.Abs(config.Kernel) if err != nil { fmt.Printf("Cannot get abs path for kernel: %s\n", err.Error()) os.Exit(-1) } } if config.Initrd != "" && !filepath.IsAbs(config.Initrd) { config.Initrd, err = filepath.Abs(config.Initrd) if err != nil { fmt.Printf("Cannot get abs path for initrd: %s\n", err.Error()) os.Exit(-1) } } if config.Vbox != "" && !filepath.IsAbs(config.Vbox) { config.Vbox, err = filepath.Abs(config.Vbox) if err != nil { fmt.Printf("Cannot get abs path for vbox: %s\n", err.Error()) os.Exit(-1) } } if sharedContainer != "" { if context.IsSet("verbose") || context.IsSet("log_dir") { fmt.Printf("The logging flags --verbose and --log_dir are only valid for starting the first container, we ignore them here") } initCmd := &initContainerCmd{Name: config.Name, Root: config.Root} conn, err := runvRequest(config.Root, sharedContainer, RUNV_INITCONTAINER, initCmd) if err != nil { os.Exit(-1) } conn.Close() } else { path, err := osext.Executable() if err != nil { fmt.Printf("cannot find self executable path for %s: %v\n", os.Args[0], err) os.Exit(-1) } os.MkdirAll(context.String("log_dir"), 0755) args := []string{ "runv-ns-daemon", "--root", config.Root, "--id", config.Name, "-v", context.String("verbose"), "--log_dir", context.String("log_dir"), } _, err = utils.ExecInDaemon(path, args) if err != nil { fmt.Printf("failed to launch runv daemon, error:%v\n", err) os.Exit(-1) } } status, err := startContainer(config) if err != nil { fmt.Printf("start container failed: %v", err) } os.Exit(status) }, } type initContainerCmd struct { Name string Root string } // Shared namespaces multiple containers suppurt // The runv supports pod-style shared namespaces currently. // (More fine grain shared namespaces style (docker/runc style) is under implementation) // // Pod-style shared namespaces: // * if two containers share at least one type of namespace, they share all kinds of namespaces except the mount namespace // * mount namespace can't be shared, each container has its own mount namespace // // Implementation detail: // * Shared namespaces is configured in LinuxRuntimeSpec.Linux.Namespaces, the namespace Path should be existing container name. // * In runv, shared namespaces multiple containers are located in the same VM which is managed by a runv-daemon. // * Any running container can exit in any arbitrary order, the runv-daemon and the VM are existed until the last container of the VM is existed func startContainer(config *startConfig) (int, error) { conn, err := runvRequest(config.Root, config.Name, RUNV_STARTCONTAINER, config) if err != nil { return -1, err } return containerTtySplice(config.Root, config.Name, conn, true) } <file_sep>package network import ( "testing" ) func TestInitNetwork(t *testing.T) { if err := InitNetwork("hyper-test", "192.168.138.1/24"); err != nil { t.Error("create hyper-test bridge failed") } if err := DeleteBridge("hyper-test"); err != nil { t.Error("delete hyper-test bridge failed") } t.Log("bridge check finished.") } func TestAllocate(t *testing.T) { if err := InitNetwork("hyper-test", "192.168.138.1/24"); err != nil { t.Error("create hyper-test bridge failed") } if setting, err := Allocate("192.168.138.2"); err != nil { t.Error("allocate tap device and ip failed") } else { t.Log("alocate tap device finished. bridge %s, device %s, ip %s, gateway %s", setting.Bridge, setting.Device, setting.IPAddress, setting.Gateway) if err := Release("192.168.138.2", setting.File); err != nil { t.Error("release ip failed") } } if err := DeleteBridge("hyper-test"); err != nil { t.Error("delete hyper-test bridge failed") } t.Log("allocate finished") } <file_sep>package hypervisor import ( "fmt" "net" "os" "strings" "github.com/golang/glog" "github.com/hyperhq/runv/hypervisor/network" "github.com/hyperhq/runv/hypervisor/pod" ) type deviceMap struct { imageMap map[string]*imageInfo volumeMap map[string]*volumeInfo networkMap map[int]*InterfaceCreated } type BlockDescriptor struct { Name string Filename string Format string Fstype string DeviceName string ScsiId int Options map[string]string } type imageInfo struct { info *BlockDescriptor pos int } type volumeInfo struct { info *BlockDescriptor pos volumePosition readOnly map[int]bool } type volumePosition map[int]string //containerIdx -> mpoint type processingList struct { adding *processingMap deleting *processingMap finished *processingMap } type processingMap struct { containers map[int]bool volumes map[string]bool blockdevs map[string]bool networks map[int]bool ttys map[int]bool serialPorts map[int]bool } func newProcessingMap() *processingMap { return &processingMap{ containers: make(map[int]bool), //to be create, and get images, volumes: make(map[string]bool), //to be create, and get volume blockdevs: make(map[string]bool), //to be insert to VM, both volume and images networks: make(map[int]bool), } } func newProcessingList() *processingList { return &processingList{ adding: newProcessingMap(), deleting: newProcessingMap(), finished: newProcessingMap(), } } func newDeviceMap() *deviceMap { return &deviceMap{ imageMap: make(map[string]*imageInfo), volumeMap: make(map[string]*volumeInfo), networkMap: make(map[int]*InterfaceCreated), } } func (pm *processingMap) isEmpty() bool { return len(pm.containers) == 0 && len(pm.volumes) == 0 && len(pm.blockdevs) == 0 && len(pm.networks) == 0 } func (ctx *VmContext) deviceReady() bool { ready := ctx.progress.adding.isEmpty() && ctx.progress.deleting.isEmpty() if ready && ctx.wait { glog.V(1).Info("All resource being released, someone is waiting for us...") ctx.wg.Done() ctx.wait = false } return ready } func (ctx *VmContext) initContainerInfo(index int, target *VmContainer, spec *pod.UserContainer) { vols := []VmVolumeDescriptor{} fsmap := []VmFsmapDescriptor{} for _, v := range spec.Volumes { ctx.devices.volumeMap[v.Volume].pos[index] = v.Path ctx.devices.volumeMap[v.Volume].readOnly[index] = v.ReadOnly } envs := make([]VmEnvironmentVar, len(spec.Envs)) for j, e := range spec.Envs { envs[j] = VmEnvironmentVar{Env: e.Env, Value: e.Value} } restart := "never" if len(spec.RestartPolicy) > 0 { restart = spec.RestartPolicy } *target = VmContainer{ Id: "", Rootfs: "rootfs", Fstype: "", Image: "", Volumes: vols, Fsmap: fsmap, Tty: 0, Stderr: 0, Workdir: spec.Workdir, Entrypoint: spec.Entrypoint, Cmd: spec.Command, Envs: envs, RestartPolicy: restart, } } func (ctx *VmContext) setContainerInfo(index int, container *VmContainer, info *ContainerInfo) { container.Id = info.Id container.Rootfs = info.Rootfs cmd := container.Entrypoint if len(container.Entrypoint) == 0 && len(info.Entrypoint) > 0 { cmd = info.Entrypoint } if len(container.Cmd) > 0 { cmd = append(cmd, container.Cmd...) } else if len(info.Cmd) > 0 { cmd = append(cmd, info.Cmd...) } container.Cmd = cmd container.Entrypoint = []string{} if container.Workdir == "" { if info.Workdir != "" { container.Workdir = info.Workdir } else { container.Workdir = "/" } } for _, e := range container.Envs { if _, ok := info.Envs[e.Env]; ok { delete(info.Envs, e.Env) } } for e, v := range info.Envs { container.Envs = append(container.Envs, VmEnvironmentVar{Env: e, Value: v}) } if info.Fstype == "dir" { container.Image = info.Image container.Fstype = "" } else { container.Fstype = info.Fstype ctx.devices.imageMap[info.Image] = &imageInfo{ info: &BlockDescriptor{ Name: info.Image, Filename: info.Image, Format: "raw", Fstype: info.Fstype, DeviceName: ""}, pos: index, } ctx.progress.adding.blockdevs[info.Image] = true } } func (ctx *VmContext) initVolumeMap(spec *pod.UserPod) { //classify volumes, and generate device info and progress info for _, vol := range spec.Volumes { if vol.Source == "" || vol.Driver == "" { ctx.devices.volumeMap[vol.Name] = &volumeInfo{ info: &BlockDescriptor{Name: vol.Name, Filename: "", Format: "", Fstype: "", DeviceName: ""}, pos: make(map[int]string), readOnly: make(map[int]bool), } } else if vol.Driver == "raw" || vol.Driver == "qcow2" || vol.Driver == "vdi" { ctx.devices.volumeMap[vol.Name] = &volumeInfo{ info: &BlockDescriptor{ Name: vol.Name, Filename: vol.Source, Format: vol.Driver, Fstype: "ext4", DeviceName: ""}, pos: make(map[int]string), readOnly: make(map[int]bool), } ctx.progress.adding.blockdevs[vol.Name] = true } else if vol.Driver == "vfs" { ctx.devices.volumeMap[vol.Name] = &volumeInfo{ info: &BlockDescriptor{ Name: vol.Name, Filename: vol.Source, Format: vol.Driver, Fstype: "dir", DeviceName: ""}, pos: make(map[int]string), readOnly: make(map[int]bool), } } else if vol.Driver == "rbd" { ctx.devices.volumeMap[vol.Name] = &volumeInfo{ info: &BlockDescriptor{ Name: vol.Name, Filename: vol.Source, Format: vol.Driver, Fstype: "ext4", DeviceName: "", Options: map[string]string{ "user": vol.Option.User, "keyring": vol.Option.Keyring, "monitors": strings.Join(vol.Option.Monitors, ";"), }, }, pos: make(map[int]string), readOnly: make(map[int]bool), } ctx.progress.adding.blockdevs[vol.Name] = true } } } func (ctx *VmContext) setVolumeInfo(info *VolumeInfo) { vol, ok := ctx.devices.volumeMap[info.Name] if !ok { return } vol.info.Filename = info.Filepath vol.info.Format = info.Format if info.Fstype != "dir" { vol.info.Fstype = info.Fstype ctx.progress.adding.blockdevs[info.Name] = true } else { vol.info.Fstype = "" for i, mount := range vol.pos { glog.V(1).Infof("insert volume %s to %s on %d", info.Name, mount, i) ctx.vmSpec.Containers[i].Fsmap = append(ctx.vmSpec.Containers[i].Fsmap, VmFsmapDescriptor{ Source: info.Filepath, Path: mount, ReadOnly: vol.readOnly[i], }) } } } func (ctx *VmContext) allocateNetworks() { for i := range ctx.progress.adding.networks { name := fmt.Sprintf("eth%d", i) addr := ctx.nextPciAddr() if len(ctx.userSpec.Interfaces) > 0 { go ctx.ConfigureInterface(i, addr, name, ctx.userSpec.Interfaces[i]) } else { go ctx.CreateInterface(i, addr, name) } } for _, srv := range ctx.userSpec.Services { inf := VmNetworkInf{ Device: "lo", IpAddress: srv.ServiceIP, NetMask: "255.255.255.255", } ctx.vmSpec.Interfaces = append(ctx.vmSpec.Interfaces, inf) } } func (ctx *VmContext) addBlockDevices() { for blk := range ctx.progress.adding.blockdevs { if info, ok := ctx.devices.volumeMap[blk]; ok { sid := ctx.nextScsiId() info.info.ScsiId = sid ctx.DCtx.AddDisk(ctx, "volume", info.info) } else if info, ok := ctx.devices.imageMap[blk]; ok { sid := ctx.nextScsiId() info.info.ScsiId = sid ctx.DCtx.AddDisk(ctx, "image", info.info) } else { continue } } } func (ctx *VmContext) allocateDevices() { if len(ctx.progress.adding.networks) == 0 && len(ctx.progress.adding.blockdevs) == 0 { ctx.Hub <- &DevSkipEvent{} return } ctx.allocateNetworks() ctx.addBlockDevices() } func (ctx *VmContext) blockdevInserted(info *BlockdevInsertedEvent) { ctx.lock.Lock() defer ctx.lock.Unlock() if info.SourceType == "image" { image := ctx.devices.imageMap[info.Name] image.info.DeviceName = info.DeviceName image.info.ScsiId = info.ScsiId ctx.vmSpec.Containers[image.pos].Image = info.DeviceName ctx.vmSpec.Containers[image.pos].Addr = info.ScsiAddr } else if info.SourceType == "volume" { volume := ctx.devices.volumeMap[info.Name] volume.info.DeviceName = info.DeviceName volume.info.ScsiId = info.ScsiId for c, vol := range volume.pos { ctx.vmSpec.Containers[c].Volumes = append(ctx.vmSpec.Containers[c].Volumes, VmVolumeDescriptor{ Device: info.DeviceName, Addr: info.ScsiAddr, Mount: vol, Fstype: volume.info.Fstype, ReadOnly: volume.readOnly[c], }) } } ctx.progress.finished.blockdevs[info.Name] = true if _, ok := ctx.progress.adding.blockdevs[info.Name]; ok { delete(ctx.progress.adding.blockdevs, info.Name) } } func (ctx *VmContext) interfaceCreated(info *InterfaceCreated) { ctx.lock.Lock() defer ctx.lock.Unlock() ctx.devices.networkMap[info.Index] = info } func (ctx *VmContext) netdevInserted(info *NetDevInsertedEvent) { ctx.lock.Lock() defer ctx.lock.Unlock() ctx.progress.finished.networks[info.Index] = true if _, ok := ctx.progress.adding.networks[info.Index]; ok { delete(ctx.progress.adding.networks, info.Index) } if len(ctx.progress.adding.networks) == 0 { count := len(ctx.devices.networkMap) for i := 0; i < count; i++ { inf := VmNetworkInf{ Device: ctx.devices.networkMap[i].DeviceName, IpAddress: ctx.devices.networkMap[i].IpAddr, NetMask: ctx.devices.networkMap[i].NetMask, } ctx.vmSpec.Interfaces = append(ctx.vmSpec.Interfaces, inf) for _, rl := range ctx.devices.networkMap[i].RouteTable { dev := "" if rl.ViaThis { dev = inf.Device } ctx.vmSpec.Routes = append(ctx.vmSpec.Routes, VmRoute{ Dest: rl.Destination, Gateway: rl.Gateway, Device: dev, }) } } } } func (ctx *VmContext) onContainerRemoved(c *ContainerUnmounted) bool { ctx.lock.Lock() defer ctx.lock.Unlock() if _, ok := ctx.progress.deleting.containers[c.Index]; ok { glog.V(1).Infof("container %d umounted", c.Index) delete(ctx.progress.deleting.containers, c.Index) } if ctx.vmSpec.Containers[c.Index].Fstype != "" { for name, image := range ctx.devices.imageMap { if image.pos == c.Index { glog.V(1).Info("need remove image dm file", image.info.Filename) ctx.progress.deleting.blockdevs[name] = true go UmountDMDevice(image.info.Filename, name, ctx.Hub) } } } return c.Success } func (ctx *VmContext) onInterfaceRemoved(nic *InterfaceReleased) bool { if _, ok := ctx.progress.deleting.networks[nic.Index]; ok { glog.V(1).Infof("interface %d released", nic.Index) delete(ctx.progress.deleting.networks, nic.Index) } return nic.Success } func (ctx *VmContext) onVolumeRemoved(v *VolumeUnmounted) bool { if _, ok := ctx.progress.deleting.volumes[v.Name]; ok { glog.V(1).Infof("volume %s umounted", v.Name) delete(ctx.progress.deleting.volumes, v.Name) } vol := ctx.devices.volumeMap[v.Name] if vol.info.Fstype != "" { glog.V(1).Info("need remove dm file ", vol.info.Filename) ctx.progress.deleting.blockdevs[vol.info.Name] = true go UmountDMDevice(vol.info.Filename, vol.info.Name, ctx.Hub) } return v.Success } func (ctx *VmContext) onBlockReleased(v *BlockdevRemovedEvent) bool { if _, ok := ctx.progress.deleting.blockdevs[v.Name]; ok { glog.V(1).Infof("blockdev %s deleted", v.Name) delete(ctx.progress.deleting.blockdevs, v.Name) } return v.Success } func (ctx *VmContext) releaseVolumeDir() { for name, vol := range ctx.devices.volumeMap { if vol.info.Fstype == "" { glog.V(1).Info("need umount dir ", vol.info.Filename) ctx.progress.deleting.volumes[name] = true go UmountVolume(ctx.ShareDir, vol.info.Filename, name, ctx.Hub) } } } func (ctx *VmContext) removeDMDevice() { for name, container := range ctx.devices.imageMap { if container.info.Fstype != "dir" { // remove device mapper device if strings.HasPrefix(container.info.Filename,"/dev/mapper/") { glog.V(1).Info("need remove dm file", container.info.Filename) ctx.progress.deleting.blockdevs[name] = true go UmountDMDevice(container.info.Filename, name, ctx.Hub) } // remove rbd device if strings.HasPrefix(container.info.Filename,"/dev/rbd/rbd/") { glog.V(1).Info("need remove rbd file",container.info.Filename) ctx.progress.deleting.blockdevs[name] = true go UmountRbdDevice(container.info.Filename,name,ctx.Hub) } } } for name, vol := range ctx.devices.volumeMap { if vol.info.Fstype != "" { // remove device mapper device if strings.HasPrefix(vol.info.Filename,"/dev/mapper/") { glog.V(1).Info("need remove dm file ", vol.info.Filename) ctx.progress.deleting.blockdevs[name] = true go UmountDMDevice(vol.info.Filename, name, ctx.Hub) } // remove rbd device if strings.HasPrefix(vol.info.Filename,"/dev/rbd/rbd/") { glog.V(1).Info("need remove rbd file",vol.info.Filename) ctx.progress.deleting.blockdevs[name] = true go UmountRbdDevice(vol.info.Filename,name,ctx.Hub) } } } } func (ctx *VmContext) releaseOverlayDir() { if !supportOverlay() { return } for idx, container := range ctx.vmSpec.Containers { if container.Fstype == "" { glog.V(1).Info("need unmount overlay dir ", container.Image) ctx.progress.deleting.containers[idx] = true go UmountOverlayContainer(ctx.ShareDir, container.Image, idx, ctx.Hub) } } } func (ctx *VmContext) releaseAufsDir() { if !supportAufs() { return } for idx, container := range ctx.vmSpec.Containers { if container.Fstype == "" { glog.V(1).Info("need unmount aufs ", container.Image) ctx.progress.deleting.containers[idx] = true go UmountAufsContainer(ctx.ShareDir, container.Image, idx, ctx.Hub) } } } func (ctx *VmContext) removeVolumeDrive() { for name, vol := range ctx.devices.volumeMap { if vol.info.Format == "raw" || vol.info.Format == "qcow2" || vol.info.Format == "vdi" || vol.info.Format == "rbd" { glog.V(1).Infof("need detach volume %s (%s) ", name, vol.info.DeviceName) ctx.DCtx.RemoveDisk(ctx, vol.info, &VolumeUnmounted{Name: name, Success: true}) ctx.progress.deleting.volumes[name] = true } } } func (ctx *VmContext) removeImageDrive() { for _, image := range ctx.devices.imageMap { if image.info.Fstype != "dir" { glog.V(1).Infof("need eject no.%d image block device: %s", image.pos, image.info.DeviceName) ctx.progress.deleting.containers[image.pos] = true ctx.DCtx.RemoveDisk(ctx, image.info, &ContainerUnmounted{Index: image.pos, Success: true}) } } } func (ctx *VmContext) releaseNetwork() { var maps []pod.UserContainerPort for _, c := range ctx.userSpec.Containers { for _, m := range c.Ports { maps = append(maps, m) } } for idx, nic := range ctx.devices.networkMap { glog.V(1).Infof("remove network card %d: %s", idx, nic.IpAddr) ctx.progress.deleting.networks[idx] = true go ctx.ReleaseInterface(idx, nic.IpAddr, nic.Fd, maps) maps = nil } } func (ctx *VmContext) removeInterface() { var maps []pod.UserContainerPort for _, c := range ctx.userSpec.Containers { for _, m := range c.Ports { maps = append(maps, m) } } for idx, nic := range ctx.devices.networkMap { glog.V(1).Infof("remove network card %d: %s", idx, nic.IpAddr) ctx.progress.deleting.networks[idx] = true ctx.DCtx.RemoveNic(ctx, nic, &NetDevRemovedEvent{Index: idx}) maps = nil } } func (ctx *VmContext) allocateInterface(index int, pciAddr int, name string) (*InterfaceCreated, error) { var err error var inf *network.Settings var maps []pod.UserContainerPort if index == 0 { for _, c := range ctx.userSpec.Containers { for _, m := range c.Ports { maps = append(maps, m) } } } if HDriver.BuildinNetwork() { inf, err = ctx.DCtx.AllocateNetwork(ctx.Id, "", maps) } else { inf, err = network.Allocate(ctx.Id, "", false, maps) } if err != nil { glog.Error("interface creating failed: ", err.Error()) return &InterfaceCreated{Index: index, PCIAddr: pciAddr, DeviceName: name}, err } return interfaceGot(index, pciAddr, name, inf) } func (ctx *VmContext) ConfigureInterface(index int, pciAddr int, name string, config pod.UserInterface) { var err error var inf *network.Settings var maps []pod.UserContainerPort if index == 0 { for _, c := range ctx.userSpec.Containers { for _, m := range c.Ports { maps = append(maps, m) } } } if HDriver.BuildinNetwork() { /* VBox doesn't support join to bridge */ inf, err = ctx.DCtx.ConfigureNetwork(ctx.Id, "", maps, config) } else { inf, err = network.Configure(ctx.Id, "", false, maps, config) } if err != nil { glog.Error("interface creating failed: ", err.Error()) session := &InterfaceCreated{Index: index, PCIAddr: pciAddr, DeviceName: name} ctx.Hub <- &DeviceFailed{Session: session} return } session, err := interfaceGot(index, pciAddr, name, inf) if err != nil { ctx.Hub <- &DeviceFailed{Session: session} return } ctx.Hub <- session } func (ctx *VmContext) CreateInterface(index int, pciAddr int, name string) { session, err := ctx.allocateInterface(index, pciAddr, name) if err != nil { ctx.Hub <- &DeviceFailed{Session: session} return } ctx.Hub <- session } func (ctx *VmContext) ReleaseInterface(index int, ipAddr string, file *os.File, maps []pod.UserContainerPort) { var err error success := true if HDriver.BuildinNetwork() { err = ctx.DCtx.ReleaseNetwork(ctx.Id, ipAddr, maps, file) } else { err = network.Release(ctx.Id, ipAddr, maps, file) } if err != nil { glog.Warning("Unable to release network interface, address: ", ipAddr, err) success = false } ctx.Hub <- &InterfaceReleased{Index: index, Success: success} } func interfaceGot(index int, pciAddr int, name string, inf *network.Settings) (*InterfaceCreated, error) { ip, nw, err := net.ParseCIDR(fmt.Sprintf("%s/%d", inf.IPAddress, inf.IPPrefixLen)) if err != nil { glog.Error("can not parse cidr") return &InterfaceCreated{Index: index, PCIAddr: pciAddr, DeviceName: name}, err } var tmp []byte = nw.Mask var mask net.IP = tmp rt := []*RouteRule{} /* Route rule is generated automaticly on first interface, * or generated on the gateway configured interface. */ if (index == 0 && inf.Automatic) || (!inf.Automatic && inf.Gateway != "") { rt = append(rt, &RouteRule{ Destination: "0.0.0.0/0", Gateway: inf.Gateway, ViaThis: true, }) } return &InterfaceCreated{ Index: index, PCIAddr: pciAddr, Bridge: inf.Bridge, HostDevice: inf.Device, DeviceName: name, Fd: inf.File, MacAddr: inf.Mac, IpAddr: ip.String(), NetMask: mask.String(), RouteTable: rt, }, nil } <file_sep>package daemon import ( _ "github.com/hyperhq/hyper/lib/docker/daemon/graphdriver/rbd" )<file_sep>export GOPATH:=$(abs_top_srcdir)/Godeps/_workspace:$(GOPATH) if WITH_XEN XEN_BUILD_TAG=with_xen else XEN_BUILD_TAG= endif if WITH_LIBVIRT LIBVIRT_BUILD_TAG=with_libvirt else LIBVIRT_BUILD_TAG= endif HYPER_BULD_TAGS=$(XEN_BUILD_TAG) $(LIBVIRT_BUILD_TAG) all-local: build-runv build-containerd clean-local: -rm -f runv install-exec-local: $(INSTALL_PROGRAM) runv $(bindir) build-runv: go build -tags "static_build $(HYPER_BULD_TAGS)" -o runv . build-containerd: go build -tags "static_build $(HYPER_BULD_TAGS)" -o runv-containerd ./containerd/ <file_sep>// +build linux,with_xen package xen import ( "os" "github.com/hyperhq/runv/hypervisor/network" "github.com/hyperhq/runv/hypervisor/pod" ) func (xd *XenDriver) BuildinNetwork() bool { return false } func (xd *XenDriver) InitNetwork(bIface, bIP string, disableIptables bool) error { return nil } func (xc *XenContext) ConfigureNetwork(vmId, requestedIP string, maps []pod.UserContainerPort, config pod.UserInterface) (*network.Settings, error) { return nil, nil } func (xc *XenContext) AllocateNetwork(vmId, requestedIP string, maps []pod.UserContainerPort) (*network.Settings, error) { return nil, nil } func (xc *XenContext) ReleaseNetwork(vmId, releasedIP string, maps []pod.UserContainerPort, file *os.File) error { return nil } <file_sep>package docker import ( "github.com/docker/docker/api/types" "github.com/golang/glog" ) func (cli *Docker) GetContainerInfo(args ...string) (*types.ContainerJSON, error) { containerId := args[0] glog.V(1).Infof("ready to get the container(%s) info", containerId) containerJSON, err := cli.daemon.ContainerInspect(containerId, false) if err != nil { return nil, err } return containerJSON, nil } func (cli Docker) SendContainerRename(oldName, newName string) error { return cli.daemon.ContainerRename(oldName, newName) } <file_sep>// +build linux package rbd import ( "fmt" "os/exec" "encoding/json" ) type RbdMappingInfo struct { Pool string `json:"pool"` Name string `json:"name"` Snapshot string `json:"snap"` Device string `json:"device"` } // For rbd, we do not need to mount the container to sharedDir. // All of we need to provide the block device name of container. func MountContainerToSharedDir(containerId, sharedDir, devPrefix string) (string, error) { devFullName := fmt.Sprintf("/dev/rbd/rbd/%s_%s",devPrefix,containerId) return devFullName,nil } func MapImageToRbdDevice(containerId, devPrefix, poolName string) error { imageName := fmt.Sprintf("%s_%s",devPrefix,containerId) _,err := exec.Command("rbd","--pool",poolName,"map",imageName).Output() if err != nil { return err } v,_ := imageIsMapped(imageName,poolName) if v == true { return nil } else { return fmt.Errorf("Unable map image %s",imageName) } } func imageIsMapped(imageName, poolName string) (bool, error) { out,err := exec.Command("rbd","showmapped","--format","json").Output() if err != nil { fmt.Errorf("Rbd run rbd showmapped failed: %v",err) return false,err } mappingInfos := map[string]*RbdMappingInfo{} json.Unmarshal(out,&mappingInfos) for _,info := range mappingInfos { if info.Pool == poolName && info.Name == imageName { return true,nil } } return false,nil } <file_sep>package qemu import ( "encoding/json" "github.com/hyperhq/runv/hypervisor" "net" "testing" "time" ) func TestMessageParse(t *testing.T) { rsp := &QmpResponse{} msg := []byte(`{"return": {}}`) err := json.Unmarshal(msg, rsp) if err != nil || rsp.msg.MessageType() != QMP_RESULT { t.Error("normal return parsing failed") } msg_str := []byte(`{"return": "OK\r\n"}`) err = json.Unmarshal(msg_str, rsp) if err != nil || rsp.msg.MessageType() != QMP_RESULT { t.Error("normal return parsing failed") } msg_event := []byte(`{"timestamp": {"seconds": 1429545058, "microseconds": 283331}, "event": "NIC_RX_FILTER_CHANGED", "data": {"path": "/machine/peripheral-anon/device[1]/virtio-backend"}}`) err = json.Unmarshal(msg_event, rsp) if err != nil || rsp.msg.MessageType() != QMP_EVENT { t.Error("normal return parsing failed") } msg_error := []byte(`{"error": {"class": "GenericError", "desc": "QMP input object member 'server' is unexpected"}}`) err = json.Unmarshal(msg_error, rsp) if err != nil || rsp.msg.MessageType() != QMP_ERROR { t.Error("normal return parsing failed") } } func testQmpInitHelper(t *testing.T, ctx *QemuContext) (*net.UnixListener, net.Conn) { t.Log("setup ", ctx.qmpSockName) ss, err := net.ListenUnix("unix", &net.UnixAddr{ctx.qmpSockName, "unix"}) if err != nil { t.Error("fail to setup connect to qmp socket", err.Error()) } c, err := ss.Accept() if err != nil { t.Error("cannot accept qmp socket", err.Error()) } t.Log("connected") banner := `{"QMP": {"version": {"qemu": {"micro": 0,"minor": 0,"major": 2},"package": ""},"capabilities": []}}` t.Log("Writting", banner) nr, err := c.Write([]byte(banner)) if err != nil { t.Error("write banner fail ", err.Error()) } t.Log("wrote hello ", nr) buf := make([]byte, 1024) nr, err = c.Read(buf) if err != nil { t.Error("fail to get init message") } t.Log("received message", string(buf[:nr])) var msg interface{} err = json.Unmarshal(buf[:nr], &msg) if err != nil { t.Error("can not read init message to json ", string(buf[:nr])) } hello := msg.(map[string]interface{}) if hello["execute"].(string) != "qmp_capabilities" { t.Error("message wrong", string(buf[:nr])) } c.Write([]byte(`{ "return": {}}`)) return ss, c } func testQmpEnvironment() (*hypervisor.VmContext, *QemuContext) { b := &hypervisor.BootConfig{ CPU: 1, Memory: 128, Kernel: hypervisor.DefaultKernel, Initrd: hypervisor.DefaultInitrd, } qemuChan := make(chan hypervisor.VmEvent, 128) dr := &QemuDriver{} dr.Initialize() ctx, _ := hypervisor.InitContext(dr, "vmid", qemuChan, nil, nil, b) return ctx, ctx.DCtx.(*QemuContext) } func TestQmpHello(t *testing.T) { ctx, qc := testQmpEnvironment() go qmpHandler(ctx) s, c := testQmpInitHelper(t, qc) defer s.Close() defer c.Close() c.Write([]byte(`{ "event": "SHUTDOWN", "timestamp": { "seconds": 1265044230, "microseconds": 450486 } }`)) ev := <-ctx.Hub if ev.Event() != hypervisor.EVENT_VM_EXIT { t.Error("should got an exit event") } t.Log("qmp finished") } func TestInitFail(t *testing.T) { ctx, qc := testQmpEnvironment() go qmpHandler(ctx) t.Log("setup ", qc.qmpSockName) ss, err := net.ListenUnix("unix", &net.UnixAddr{qc.qmpSockName, "unix"}) if err != nil { t.Error("fail to setup connect to qmp socket", err.Error()) } c, err := ss.Accept() if err != nil { t.Error("cannot accept qmp socket", err.Error()) } defer ss.Close() defer c.Close() t.Log("connected") banner := `{"QMP": {"version": {"qemu": {"micro": 0,"minor": 0,"major": 2},"package": ""},"capabilities": []}}` t.Log("Writting", banner) nr, err := c.Write([]byte(banner)) if err != nil { t.Error("write banner fail ", err.Error()) } t.Log("wrote hello ", nr) buf := make([]byte, 1024) nr, err = c.Read(buf) if err != nil { t.Error("fail to get init message") } t.Log("received message", string(buf[:nr])) var msg interface{} err = json.Unmarshal(buf[:nr], &msg) if err != nil { t.Error("can not read init message to json ", string(buf[:nr])) } hello := msg.(map[string]interface{}) if hello["execute"].(string) != "qmp_capabilities" { t.Error("message wrong", string(buf[:nr])) } c.Write([]byte(`{ "error": {}}`)) ev := <-ctx.Hub if ev.Event() != hypervisor.ERROR_INIT_FAIL { t.Error("should got an event") } t.Log("qmp init failed") } func TestQmpConnTimeout(t *testing.T) { ctx, _ := testQmpEnvironment() go qmpHandler(ctx) time.Sleep(6 * time.Second) ev := <-ctx.Hub if ev.Event() != hypervisor.ERROR_INIT_FAIL { t.Error("should got an fail event") } t.Log("finished timeout test") } func TestQmpInitTimeout(t *testing.T) { ctx, qc := testQmpEnvironment() go qmpHandler(ctx) t.Log("connecting to ", qc.qmpSockName) ss, err := net.ListenUnix("unix", &net.UnixAddr{qc.qmpSockName, "unix"}) if err != nil { t.Error("fail to setup connect to qmp socket", err.Error()) } c, err := ss.Accept() if err != nil { t.Error("cannot accept qmp socket", err.Error()) } defer ss.Close() defer c.Close() t.Log("connected") time.Sleep(11 * time.Second) ev := <-ctx.Hub if ev.Event() != hypervisor.ERROR_INIT_FAIL { t.Error("should got an fail event") } t.Log("finished timeout test") } func TestQmpDiskSession(t *testing.T) { ctx, qc := testQmpEnvironment() go qmpHandler(ctx) s, c := testQmpInitHelper(t, qc) defer s.Close() defer c.Close() newDiskAddSession(qc, "vol1", "volume", "/dev/dm7", "raw", 5) buf := make([]byte, 1024) nr, err := c.Read(buf) if err != nil { t.Error("cannot read command 0 in session", err.Error()) } t.Log("received ", string(buf[:nr])) c.Write([]byte(`{ "return": "success"}`)) nr, err = c.Read(buf) if err != nil { t.Error("cannot read command 1 in session", err.Error()) } t.Log("received ", string(buf[:nr])) c.Write([]byte(`{ "return": {}}`)) msg := <-ctx.Hub if msg.Event() != hypervisor.EVENT_BLOCK_INSERTED { t.Error("wrong type of message", msg.Event()) } info := msg.(*hypervisor.BlockdevInsertedEvent) t.Log("got block device", info.Name, info.SourceType, info.DeviceName) } func TestQmpFailOnce(t *testing.T) { ctx, qc := testQmpEnvironment() go qmpHandler(ctx) s, c := testQmpInitHelper(t, qc) defer s.Close() defer c.Close() newDiskAddSession(qc, "vol1", "volume", "/dev/dm7", "raw", 5) buf := make([]byte, 1024) nr, err := c.Read(buf) if err != nil { t.Error("cannot read command 0 in session", err.Error()) } t.Log("received ", string(buf[:nr])) c.Write([]byte(`{"error": {"class": "GenericError", "desc": "QMP input object member 'server' is unexpected"}}`)) nr, err = c.Read(buf) if err != nil { t.Error("cannot read repeated command 1 in session", err.Error()) } t.Log("received ", string(buf[:nr])) c.Write([]byte(`{ "return": {}}`)) nr, err = c.Read(buf) if err != nil { t.Error("cannot read command 1 in session", err.Error()) } t.Log("received ", string(buf[:nr])) c.Write([]byte(`{ "return": {}}`)) msg := <-ctx.Hub if msg.Event() != hypervisor.EVENT_BLOCK_INSERTED { t.Error("wrong type of message", msg.Event()) } info := msg.(*hypervisor.BlockdevInsertedEvent) t.Log("got block device", info.Name, info.SourceType, info.DeviceName) } func TestQmpKeepFail(t *testing.T) { ctx, qc := testQmpEnvironment() go qmpHandler(ctx) s, c := testQmpInitHelper(t, qc) defer s.Close() defer c.Close() newDiskAddSession(qc, "vol1", "volume", "/dev/dm7", "raw", 5) buf := make([]byte, 1024) nr, err := c.Read(buf) if err != nil { t.Error("cannot read command 0 in session", err.Error()) } t.Log("received ", string(buf[:nr])) c.Write([]byte(`{"error": {"class": "GenericError", "desc": "QMP input object member 'server' is unexpected"}}`)) nr, err = c.Read(buf) if err != nil { t.Error("cannot read repeated command 1 in session", err.Error()) } t.Log("received ", string(buf[:nr])) c.Write([]byte(`{"error": {"class": "GenericError", "desc": "QMP input object member 'server' is unexpected"}}`)) nr, err = c.Read(buf) if err != nil { t.Error("cannot read repeated command 1 again in session", err.Error()) } t.Log("received ", string(buf[:nr])) c.Write([]byte(`{"error": {"class": "GenericError", "desc": "QMP input object member 'server' is unexpected"}}`)) msg := <-ctx.Hub if msg.Event() != hypervisor.ERROR_QMP_FAIL { t.Error("wrong type of message", msg.Event()) } info := msg.(*hypervisor.DeviceFailed) t.Log("got block device", hypervisor.EventString(info.Session.Event())) } func TestQmpNetSession(t *testing.T) { ctx, qc := testQmpEnvironment() go qmpHandler(ctx) s, c := testQmpInitHelper(t, qc) defer s.Close() defer c.Close() newNetworkAddSession(qc, 12, "eth0", "mac", 0, 3) buf := make([]byte, 1024) nr, err := c.Read(buf) if err != nil { t.Error("cannot read command 0 in session", err.Error()) } t.Log("received ", string(buf[:nr])) c.Write([]byte(`{ "return": {}}`)) nr, err = c.Read(buf) if err != nil { t.Error("cannot read command 1 in session", err.Error()) } t.Log("received ", string(buf[:nr])) c.Write([]byte(`{ "return": {}}`)) nr, err = c.Read(buf) if err != nil { t.Error("cannot read command 2 in session", err.Error()) } t.Log("received ", string(buf[:nr])) c.Write([]byte(`{ "return": {}}`)) msg := <-ctx.Hub if msg.Event() != hypervisor.EVENT_INTERFACE_INSERTED { t.Error("wrong type of message", msg.Event()) } info := msg.(*hypervisor.NetDevInsertedEvent) t.Log("got net device", info.Address, info.Index, info.DeviceName) } func TestSessionQueue(t *testing.T) { ctx, qc := testQmpEnvironment() go qmpHandler(ctx) s, c := testQmpInitHelper(t, qc) defer s.Close() defer c.Close() newNetworkAddSession(qc, 12, "eth0", "mac", 0, 3) newNetworkAddSession(qc, 13, "eth1", "mac", 1, 4) buf := make([]byte, 1024) nr, err := c.Read(buf) if err != nil { t.Error("cannot read command 0 in session", err.Error()) } t.Log("received ", string(buf[:nr])) c.Write([]byte(`{ "return": {}}`)) nr, err = c.Read(buf) if err != nil { t.Error("cannot read command 1 in session", err.Error()) } t.Log("received ", string(buf[:nr])) c.Write([]byte(`{ "return": {}}`)) nr, err = c.Read(buf) if err != nil { t.Error("cannot read command 2 in session", err.Error()) } t.Log("received ", string(buf[:nr])) c.Write([]byte(`{ "return": {}}`)) msg := <-ctx.Hub if msg.Event() != hypervisor.EVENT_INTERFACE_INSERTED { t.Error("wrong type of message", msg.Event()) } info := msg.(*hypervisor.NetDevInsertedEvent) t.Log("got block device", info.Address, info.Index, info.DeviceName) if info.Address != 0x03 || info.Index != 0 || info.DeviceName != "eth0" { t.Error("net dev 0 creation failed") } nr, err = c.Read(buf) if err != nil { t.Error("cannot read command 0 in session", err.Error()) } t.Log("received ", string(buf[:nr])) c.Write([]byte(`{ "return": {}}`)) nr, err = c.Read(buf) if err != nil { t.Error("cannot read command 1 in session", err.Error()) } t.Log("received ", string(buf[:nr])) c.Write([]byte(`{ "return": {}}`)) nr, err = c.Read(buf) if err != nil { t.Error("cannot read command 2 in session", err.Error()) } t.Log("received ", string(buf[:nr])) c.Write([]byte(`{ "return": {}}`)) msg = <-ctx.Hub if msg.Event() != hypervisor.EVENT_INTERFACE_INSERTED { t.Error("wrong type of message", msg.Event()) } info = msg.(*hypervisor.NetDevInsertedEvent) t.Log("got network device", info.Address, info.Index, info.DeviceName) if info.Address != 0x04 || info.Index != 1 || info.DeviceName != "eth1" { t.Error("net dev 1 creation failed") } } <file_sep>package main import ( "fmt" "os" "path/filepath" "runtime" "github.com/codegangsta/cli" "github.com/opencontainers/specs" ) const ( version = "0.4.0" specConfig = "config.json" runtimeConfig = "runtime.json" usage = `Open Container Initiative hypervisor-based runtime runv is a command line client for running applications packaged according to the Open Container Format (OCF) and is a compliant implementation of the Open Container Initiative specification. However, due to the difference between hypervisors and containers, the following sections of OCF don't apply to runV: Namespace Capability Device "linux" and "mount" fields in OCI specs are ignored The current release of "runV" supports the following hypervisors: KVM (QEMU 2.0 or later) Xen (4.5 or later) VirtualBox (Mac OS X) After creating a spec for your root filesystem, you can execute a container in your shell by running: # cd /mycontainer # runv start start [ -b bundle ] If not specified, the default value for the 'bundle' is the current directory. 'Bundle' is the directory where '` + specConfig + `' and '` + runtimeConfig + `' must be located.` ) func main() { if os.Args[0] == "runv-ns-daemon" { runvNamespaceDaemon() os.Exit(0) } app := cli.NewApp() app.Name = "runv" app.Usage = usage app.Version = version app.Flags = []cli.Flag{ cli.StringFlag{ Name: "id", Value: getDefaultID(), Usage: "specify the ID to be used for the container", }, cli.StringFlag{ Name: "root", Value: specs.LinuxStateDirectory, Usage: "root directory for storage of container state (this should be located in tmpfs)", }, cli.StringFlag{ Name: "driver", Value: getDefaultDriver(), Usage: "hypervisor driver (supports: kvm xen vbox)", }, cli.StringFlag{ Name: "kernel", Usage: "kernel for the container", }, cli.StringFlag{ Name: "initrd", Usage: "runv-compatible initrd for the container", }, cli.StringFlag{ Name: "vbox", Usage: "runv-compatible boot ISO for the container for vbox driver", }, } app.Commands = []cli.Command{ startCommand, specCommand, execCommand, killCommand, } if err := app.Run(os.Args); err != nil { fmt.Printf("%s\n", err.Error()) } } func getDefaultID() string { cwd, err := os.Getwd() if err != nil { panic(err) } return filepath.Base(cwd) } func getDefaultDriver() string { if runtime.GOOS == "linux" { return "qemu" } if runtime.GOOS == "darwin" { return "vbox" } return "" } <file_sep>package hypervisor import ( "encoding/json" "fmt" "github.com/golang/glog" "github.com/hyperhq/runv/hypervisor/pod" "github.com/hyperhq/runv/hypervisor/types" "time" ) // states const ( StateInit = "INIT" StatePreparing = "PREPARING" StateStarting = "STARTING" StateRunning = "RUNNING" StatePodStopping = "STOPPING" StateCleaning = "CLEANING" StateTerminating = "TERMINATING" StateDestroying = "DESTROYING" StateNone = "NONE" ) func (ctx *VmContext) timedKill(seconds int) { ctx.timer = time.AfterFunc(time.Duration(seconds)*time.Second, func() { if ctx != nil && ctx.handler != nil { ctx.DCtx.Kill(ctx) } }) } func (ctx *VmContext) onVmExit(reclaim bool) bool { glog.V(1).Info("VM has exit...") ctx.reportVmShutdown() ctx.setTimeout(60) if reclaim { ctx.reclaimDevice() } return ctx.tryClose() } func (ctx *VmContext) reclaimDevice() { ctx.releaseVolumeDir() ctx.releaseOverlayDir() ctx.releaseAufsDir() ctx.removeDMDevice() ctx.releaseNetwork() } func (ctx *VmContext) detachDevice() { ctx.releaseVolumeDir() ctx.releaseOverlayDir() ctx.releaseAufsDir() ctx.removeVolumeDrive() ctx.removeImageDrive() ctx.removeInterface() } func (ctx *VmContext) prepareDevice(cmd *RunPodCommand) bool { if len(cmd.Spec.Containers) != len(cmd.Containers) { ctx.reportBadRequest("Spec and Container Info mismatch") return false } ctx.InitDeviceContext(cmd.Spec, cmd.Wg, cmd.Containers, cmd.Volumes) if glog.V(2) { res, _ := json.MarshalIndent(*ctx.vmSpec, " ", " ") glog.Info("initial vm spec: ", string(res)) } pendings := ctx.ptys.pendingTtys ctx.ptys.pendingTtys = []*AttachCommand{} for _, acmd := range pendings { idx := ctx.Lookup(acmd.Container) if idx >= 0 { glog.Infof("attach pending client %s for %s", acmd.Streams.ClientTag, acmd.Container) ctx.attachTty2Container(&ctx.vmSpec.Containers[idx].Process, acmd) } else { glog.Infof("not attach %s for %s", acmd.Streams.ClientTag, acmd.Container) ctx.ptys.pendingTtys = append(ctx.ptys.pendingTtys, acmd) } } ctx.allocateDevices() return true } func (ctx *VmContext) prepareContainer(cmd *NewContainerCommand) *VmContainer { ctx.lock.Lock() idx := len(ctx.vmSpec.Containers) vmContainer := &VmContainer{} ctx.initContainerInfo(idx, vmContainer, cmd.container) ctx.setContainerInfo(idx, vmContainer, cmd.info) vmContainer.Sysctl = cmd.container.Sysctl vmContainer.Process.Stdio = ctx.ptys.attachId ctx.ptys.attachId++ if !cmd.container.Tty { vmContainer.Process.Stderr = ctx.ptys.attachId ctx.ptys.attachId++ } ctx.userSpec.Containers = append(ctx.userSpec.Containers, *cmd.container) ctx.vmSpec.Containers = append(ctx.vmSpec.Containers, *vmContainer) ctx.lock.Unlock() pendings := ctx.ptys.pendingTtys ctx.ptys.pendingTtys = []*AttachCommand{} for _, acmd := range pendings { if idx == ctx.Lookup(acmd.Container) { glog.Infof("attach pending client %s for %s", acmd.Streams.ClientTag, acmd.Container) ctx.attachTty2Container(&ctx.vmSpec.Containers[idx].Process, acmd) } else { glog.Infof("not attach %s for %s", acmd.Streams.ClientTag, acmd.Container) ctx.ptys.pendingTtys = append(ctx.ptys.pendingTtys, acmd) } } return vmContainer } func (ctx *VmContext) newContainer(cmd *NewContainerCommand) { c := ctx.prepareContainer(cmd) jsonCmd, err := json.Marshal(*c) if err != nil { ctx.Hub <- &InitFailedEvent{ Reason: "Generated wrong run profile " + err.Error(), } glog.Infof("INIT_NEWCONTAINER marshal failed") return } glog.Infof("start sending INIT_NEWCONTAINER") ctx.vm <- &DecodedMessage{ Code: INIT_NEWCONTAINER, Message: jsonCmd, } glog.Infof("sent INIT_NEWCONTAINER") } func (ctx *VmContext) pauseVm(cmd *PauseCommand) { /* FIXME: only support pause whole vm now */ ctx.DCtx.Pause(ctx, cmd) } func (ctx *VmContext) handlePauseResult(ev *PauseResult) { if ev.Cause == "" { ctx.Paused = ev.Reply.Pause if ctx.Paused { glog.V(1).Info("vm is paused") } else { glog.V(1).Info("vm is resumed") } } ctx.reportPauseResult(ev) } func (ctx *VmContext) setWindowSize(tag string, size *WindowSize) { if session, ok := ctx.ptys.ttySessions[tag]; ok { if !ctx.ptys.isTty(session) { ctx.reportBadRequest(fmt.Sprintf("the session is not a tty, doesn't support resize.")) } cmd := map[string]interface{}{ "seq": session, "row": size.Row, "column": size.Column, } msg, err := json.Marshal(cmd) if err != nil { ctx.reportBadRequest(fmt.Sprintf("command window size parse failed")) return } ctx.vm <- &DecodedMessage{ Code: INIT_WINSIZE, Message: msg, } } else { msg := fmt.Sprintf("cannot resolve client tag %s", tag) ctx.reportBadRequest(msg) glog.Error(msg) } } func (ctx *VmContext) writeFile(cmd *WriteFileCommand) { writeCmd, err := json.Marshal(*cmd) if err != nil { ctx.Hub <- &InitFailedEvent{ Reason: "Generated wrong run profile " + err.Error(), } return } writeCmd = append(writeCmd, cmd.Data[:]...) ctx.vm <- &DecodedMessage{ Code: INIT_WRITEFILE, Message: writeCmd, Event: cmd, } } func (ctx *VmContext) readFile(cmd *ReadFileCommand) { readCmd, err := json.Marshal(*cmd) if err != nil { ctx.Hub <- &InitFailedEvent{ Reason: "Generated wrong run profile " + err.Error(), } return } ctx.vm <- &DecodedMessage{ Code: INIT_READFILE, Message: readCmd, Event: cmd, } } func (ctx *VmContext) onlineCpuMem(cmd *OnlineCpuMemCommand) { ctx.vm <- &DecodedMessage{ Code: INIT_ONLINECPUMEM, Message: []byte{}, } } func (ctx *VmContext) execCmd(cmd *ExecCommand) { cmd.Process.Stdio = ctx.ptys.nextAttachId() if !cmd.Process.Terminal { cmd.Process.Stderr = ctx.ptys.nextAttachId() } pkg, err := json.Marshal(*cmd) if err != nil { cmd.Callback <- &types.VmResponse{ VmId: ctx.Id, Code: types.E_JSON_PARSE_FAIL, Cause: fmt.Sprintf("command %s parse failed", cmd.Process.Args), Data: cmd.Process.Stdio, } return } ctx.ptys.ptyConnect(false, cmd.Process.Terminal, cmd.Process.Stdio, cmd.TtyIO) ctx.ptys.clientReg(cmd.ClientTag, cmd.Process.Stdio) if !cmd.Process.Terminal { stderrIO := &TtyIO{ Stdin: nil, Stdout: cmd.TtyIO.Stdout, ClientTag: cmd.TtyIO.ClientTag, Callback: nil, } ctx.ptys.ptyConnect(false, cmd.Process.Terminal, cmd.Process.Stderr, stderrIO) } ctx.vm <- &DecodedMessage{ Code: INIT_EXECCMD, Message: pkg, Event: cmd, } } func (ctx *VmContext) killCmd(cmd *KillCommand) { killCmd, err := json.Marshal(*cmd) if err != nil { ctx.Hub <- &InitFailedEvent{ Reason: "Generated wrong kill profile " + err.Error(), } return } ctx.vm <- &DecodedMessage{ Code: INIT_KILLCONTAINER, Message: killCmd, Event: cmd, } } func (ctx *VmContext) attachCmd(cmd *AttachCommand) { idx := ctx.Lookup(cmd.Container) if cmd.Container != "" && idx < 0 { ctx.ptys.pendingTtys = append(ctx.ptys.pendingTtys, cmd) glog.V(1).Infof("attachment %s is pending", cmd.Streams.ClientTag) return } else if idx < 0 || idx > len(ctx.vmSpec.Containers) || ctx.vmSpec.Containers[idx].Process.Stdio == 0 { cause := fmt.Sprintf("tty is not configured for %s", cmd.Container) ctx.reportBadRequest(cause) cmd.Streams.Callback <- &types.VmResponse{ VmId: ctx.Id, Code: types.E_NO_TTY, Cause: cause, Data: uint64(0), } return } ctx.attachTty2Container(&ctx.vmSpec.Containers[idx].Process, cmd) if cmd.Size != nil { ctx.setWindowSize(cmd.Streams.ClientTag, cmd.Size) } } func (ctx *VmContext) attachTty2Container(process *VmProcess, cmd *AttachCommand) { session := process.Stdio ctx.ptys.ptyConnect(true, process.Terminal, session, cmd.Streams) ctx.ptys.clientReg(cmd.Streams.ClientTag, session) glog.V(1).Infof("Connecting tty for %s on session %d", cmd.Container, session) //new stderr session session = process.Stderr if session > 0 { stderrIO := cmd.Stderr if stderrIO == nil { stderrIO = &TtyIO{ Stdin: nil, Stdout: cmd.Streams.Stdout, ClientTag: cmd.Streams.ClientTag, Callback: nil, } } ctx.ptys.ptyConnect(true, process.Terminal, session, stderrIO) } } func (ctx *VmContext) startPod() { pod, err := json.Marshal(*ctx.vmSpec) if err != nil { ctx.Hub <- &InitFailedEvent{ Reason: "Generated wrong run profile " + err.Error(), } return } ctx.vm <- &DecodedMessage{ Code: INIT_STARTPOD, Message: pod, } } func (ctx *VmContext) stopPod() { ctx.setTimeout(30) ctx.vm <- &DecodedMessage{ Code: INIT_STOPPOD, Message: []byte{}, } } func (ctx *VmContext) exitVM(err bool, msg string, hasPod bool, wait bool) { ctx.wait = wait if hasPod { ctx.shutdownVM(err, msg) ctx.Become(stateTerminating, StateTerminating) } else { ctx.poweroffVM(err, msg) ctx.Become(stateDestroying, StateDestroying) } } func (ctx *VmContext) shutdownVM(err bool, msg string) { if err { ctx.reportVmFault(msg) glog.Error("Shutting down because of an exception: ", msg) } ctx.setTimeout(10) ctx.vm <- &DecodedMessage{Code: INIT_DESTROYPOD, Message: []byte{}} } func (ctx *VmContext) poweroffVM(err bool, msg string) { if err { ctx.reportVmFault(msg) glog.Error("Shutting down because of an exception: ", msg) } ctx.DCtx.Shutdown(ctx) ctx.timedKill(10) } func (ctx *VmContext) handleGenericOperation(goe *GenericOperation) { for _, allowd := range goe.State { if ctx.current == allowd { glog.V(3).Infof("handle GenericOperation(%s) on state(%s)", goe.OpName, ctx.current) goe.OpFunc(ctx, goe.Result) return } } glog.V(3).Infof("GenericOperation(%s) is unsupported on state(%s)", goe.OpName, ctx.current) goe.Result <- fmt.Errorf("GenericOperation(%s) is unsupported on state(%s)", goe.OpName, ctx.current) } // state machine func commonStateHandler(ctx *VmContext, ev VmEvent, hasPod bool) bool { processed := true switch ev.Event() { case EVENT_VM_EXIT: glog.Info("Got VM shutdown event, go to cleaning up") ctx.unsetTimeout() if closed := ctx.onVmExit(hasPod); !closed { ctx.Become(stateDestroying, StateDestroying) } case ERROR_INTERRUPTED: glog.Info("Connection interrupted, quit...") ctx.exitVM(true, "connection to VM broken", false, false) ctx.onVmExit(hasPod) case COMMAND_SHUTDOWN: glog.Info("got shutdown command, shutting down") ctx.exitVM(false, "", hasPod, ev.(*ShutdownCommand).Wait) case GENERIC_OPERATION: ctx.handleGenericOperation(ev.(*GenericOperation)) default: processed = false } return processed } func deviceInitHandler(ctx *VmContext, ev VmEvent) bool { processed := true switch ev.Event() { case EVENT_BLOCK_INSERTED: info := ev.(*BlockdevInsertedEvent) ctx.blockdevInserted(info) case EVENT_DEV_SKIP: case EVENT_INTERFACE_ADD: info := ev.(*InterfaceCreated) ctx.interfaceCreated(info) h := &HostNicInfo{ Fd: uint64(info.Fd.Fd()), Device: info.HostDevice, Mac: info.MacAddr, Bridge: info.Bridge, Gateway: info.Bridge, } g := &GuestNicInfo{ Device: info.DeviceName, Ipaddr: info.IpAddr, Index: info.Index, Busaddr: info.PCIAddr, } ctx.DCtx.AddNic(ctx, h, g) case EVENT_INTERFACE_INSERTED: info := ev.(*NetDevInsertedEvent) ctx.netdevInserted(info) default: processed = false } return processed } func deviceRemoveHandler(ctx *VmContext, ev VmEvent) (bool, bool) { processed := true success := true switch ev.Event() { case EVENT_CONTAINER_DELETE: success = ctx.onContainerRemoved(ev.(*ContainerUnmounted)) glog.V(1).Info("Unplug container return with ", success) case EVENT_INTERFACE_DELETE: success = ctx.onInterfaceRemoved(ev.(*InterfaceReleased)) glog.V(1).Info("Unplug interface return with ", success) case EVENT_BLOCK_EJECTED: success = ctx.onVolumeRemoved(ev.(*VolumeUnmounted)) glog.V(1).Info("Unplug block device return with ", success) case EVENT_VOLUME_DELETE: success = ctx.onBlockReleased(ev.(*BlockdevRemovedEvent)) glog.V(1).Info("release volume return with ", success) case EVENT_INTERFACE_EJECTED: n := ev.(*NetDevRemovedEvent) nic := ctx.devices.networkMap[n.Index] var maps []pod.UserContainerPort for _, c := range ctx.userSpec.Containers { for _, m := range c.Ports { maps = append(maps, m) } } glog.V(1).Infof("release %d interface: %s", n.Index, nic.IpAddr) go ctx.ReleaseInterface(n.Index, nic.IpAddr, nic.Fd, maps) default: processed = false } return processed, success } func unexpectedEventHandler(ctx *VmContext, ev VmEvent, state string) { switch ev.Event() { case COMMAND_RUN_POD, COMMAND_GET_POD_IP, COMMAND_STOP_POD, COMMAND_REPLACE_POD, COMMAND_EXEC, COMMAND_KILL, COMMAND_WRITEFILE, COMMAND_READFILE, COMMAND_SHUTDOWN, COMMAND_RELEASE, COMMAND_PAUSEVM: ctx.reportUnexpectedRequest(ev, state) default: glog.Warning("got unexpected event during ", state) } } func initFailureHandler(ctx *VmContext, ev VmEvent) bool { processed := true switch ev.Event() { case ERROR_INIT_FAIL: // VM connection Failure reason := ev.(*InitFailedEvent).Reason glog.Error(reason) case ERROR_QMP_FAIL: // Device allocate and insert Failure reason := "QMP protocol exception" if ev.(*DeviceFailed).Session != nil { reason = "QMP protocol exception: failed while waiting " + EventString(ev.(*DeviceFailed).Session.Event()) } glog.Error(reason) default: processed = false } return processed } func stateInit(ctx *VmContext, ev VmEvent) { if processed := commonStateHandler(ctx, ev, false); processed { //processed by common } else if processed := initFailureHandler(ctx, ev); processed { ctx.shutdownVM(true, "Fail during init environment") ctx.Become(stateDestroying, StateDestroying) } else { switch ev.Event() { case EVENT_VM_START_FAILED: glog.Error("VM did not start up properly, go to cleaning up") ctx.reportVmFault("VM did not start up properly, go to cleaning up") ctx.Close() case EVENT_INIT_CONNECTED: glog.Info("begin to wait vm commands") ctx.reportVmRun() case COMMAND_RELEASE: glog.Info("no pod on vm, got release, quit.") ctx.shutdownVM(false, "") ctx.Become(stateDestroying, StateDestroying) ctx.reportVmShutdown() case COMMAND_PAUSEVM: ctx.pauseVm(ev.(*PauseCommand)) case EVENT_PAUSE_RESULT: ctx.handlePauseResult(ev.(*PauseResult)) case COMMAND_ATTACH: ctx.attachCmd(ev.(*AttachCommand)) case COMMAND_NEWCONTAINER: ctx.newContainer(ev.(*NewContainerCommand)) case COMMAND_EXEC: ctx.execCmd(ev.(*ExecCommand)) case COMMAND_ONLINECPUMEM: ctx.onlineCpuMem(ev.(*OnlineCpuMemCommand)) case COMMAND_WRITEFILE: ctx.writeFile(ev.(*WriteFileCommand)) case COMMAND_READFILE: ctx.readFile(ev.(*ReadFileCommand)) case COMMAND_WINDOWSIZE: cmd := ev.(*WindowSizeCommand) ctx.setWindowSize(cmd.ClientTag, cmd.Size) case COMMAND_RUN_POD, COMMAND_REPLACE_POD: glog.Info("got spec, prepare devices") if ok := ctx.prepareDevice(ev.(*RunPodCommand)); ok { ctx.setTimeout(60) ctx.Become(stateStarting, StateStarting) } case COMMAND_GET_POD_IP: ctx.reportPodIP(ev) case COMMAND_ACK: ack := ev.(*CommandAck) glog.V(1).Infof("[init] got init ack to %d", ack.reply) if ack.reply.Code == INIT_NEWCONTAINER { glog.Infof("Get ack for new container") // start stdin. TODO: find the correct idx if parallel multi INIT_NEWCONTAINER idx := len(ctx.vmSpec.Containers) - 1 c := ctx.vmSpec.Containers[idx] ctx.ptys.startStdin(c.Process.Stdio, c.Process.Terminal) } default: unexpectedEventHandler(ctx, ev, "pod initiating") } } } func stateStarting(ctx *VmContext, ev VmEvent) { if processed := commonStateHandler(ctx, ev, true); processed { //processed by common } else if processed := deviceInitHandler(ctx, ev); processed { if ctx.deviceReady() { glog.V(1).Info("device ready, could run pod.") ctx.startPod() } } else if processed := initFailureHandler(ctx, ev); processed { ctx.shutdownVM(true, "Fail during init pod running environment") ctx.Become(stateTerminating, StateTerminating) } else { switch ev.Event() { case EVENT_VM_START_FAILED: glog.Info("VM did not start up properly, go to cleaning up") if closed := ctx.onVmExit(true); !closed { ctx.Become(stateDestroying, StateDestroying) } case EVENT_INIT_CONNECTED: glog.Info("begin to wait vm commands") ctx.reportVmRun() case COMMAND_RELEASE: glog.Info("pod starting, got release, please wait") ctx.reportBusy("") case COMMAND_ATTACH: ctx.attachCmd(ev.(*AttachCommand)) case COMMAND_WINDOWSIZE: cmd := ev.(*WindowSizeCommand) ctx.setWindowSize(cmd.ClientTag, cmd.Size) case COMMAND_ACK: ack := ev.(*CommandAck) glog.V(1).Infof("[starting] got init ack to %d", ack.reply) if ack.reply.Code == INIT_STARTPOD { ctx.unsetTimeout() var pinfo []byte = []byte{} persist, err := ctx.dump() if err == nil { buf, err := persist.serialize() if err == nil { pinfo = buf } } for _, c := range ctx.vmSpec.Containers { ctx.ptys.startStdin(c.Process.Stdio, c.Process.Terminal) } ctx.reportSuccess("Start POD success", pinfo) ctx.Become(stateRunning, StateRunning) glog.Info("pod start success ", string(ack.msg)) } case ERROR_CMD_FAIL: ack := ev.(*CommandError) if ack.reply.Code == INIT_STARTPOD { reason := "Start POD failed" ctx.shutdownVM(true, reason) ctx.Become(stateTerminating, StateTerminating) glog.Error(reason) } case EVENT_VM_TIMEOUT: reason := "Start POD timeout" ctx.shutdownVM(true, reason) ctx.Become(stateTerminating, StateTerminating) glog.Error(reason) default: unexpectedEventHandler(ctx, ev, "pod initiating") } } } func stateRunning(ctx *VmContext, ev VmEvent) { if processed := commonStateHandler(ctx, ev, true); processed { } else if processed := initFailureHandler(ctx, ev); processed { ctx.shutdownVM(true, "Fail during reconnect to a running pod") ctx.Become(stateTerminating, StateTerminating) } else { switch ev.Event() { case COMMAND_STOP_POD: ctx.stopPod() ctx.Become(statePodStopping, StatePodStopping) case COMMAND_RELEASE: glog.Info("pod is running, got release command, let VM fly") ctx.Become(nil, StateNone) ctx.reportSuccess("", nil) case COMMAND_EXEC: ctx.execCmd(ev.(*ExecCommand)) case COMMAND_KILL: ctx.killCmd(ev.(*KillCommand)) case COMMAND_ATTACH: ctx.attachCmd(ev.(*AttachCommand)) case COMMAND_PAUSEVM: ctx.pauseVm(ev.(*PauseCommand)) case EVENT_PAUSE_RESULT: ctx.handlePauseResult(ev.(*PauseResult)) case COMMAND_NEWCONTAINER: ctx.newContainer(ev.(*NewContainerCommand)) case COMMAND_WINDOWSIZE: cmd := ev.(*WindowSizeCommand) ctx.setWindowSize(cmd.ClientTag, cmd.Size) case COMMAND_WRITEFILE: ctx.writeFile(ev.(*WriteFileCommand)) case COMMAND_READFILE: ctx.readFile(ev.(*ReadFileCommand)) case EVENT_POD_FINISH: result := ev.(*PodFinished) ctx.reportPodFinished(result) ctx.exitVM(false, "", true, false) case COMMAND_ACK: ack := ev.(*CommandAck) glog.V(1).Infof("[running] got init ack to %d", ack.reply) if ack.reply.Code == INIT_EXECCMD { cmd := ack.reply.Event.(*ExecCommand) ctx.ptys.startStdin(cmd.Process.Stdio, true) ctx.reportExec(ack.reply.Event, false) glog.Infof("Get ack for exec cmd") } else if ack.reply.Code == INIT_READFILE { ctx.reportFile(ack.reply.Event, INIT_READFILE, ack.msg, false) glog.Infof("Get ack for read data: %s", string(ack.msg)) } else if ack.reply.Code == INIT_WRITEFILE { ctx.reportFile(ack.reply.Event, INIT_WRITEFILE, ack.msg, false) glog.Infof("Get ack for write data: %s", string(ack.msg)) } else if ack.reply.Code == INIT_NEWCONTAINER { glog.Infof("Get ack for new container") // start stdin. TODO: find the correct idx if parallel multi INIT_NEWCONTAINER idx := len(ctx.vmSpec.Containers) - 1 c := ctx.vmSpec.Containers[idx] ctx.ptys.startStdin(c.Process.Stdio, c.Process.Terminal) } else if ack.reply.Code == INIT_KILLCONTAINER { glog.Infof("Get ack for kill container") ctx.reportKill(ack.reply.Event, true) } case ERROR_CMD_FAIL: ack := ev.(*CommandError) if ack.reply.Code == INIT_EXECCMD { cmd := ack.reply.Event.(*ExecCommand) ctx.ptys.Close(cmd.Process.Stdio, 255) ctx.reportExec(ack.reply.Event, true) glog.V(0).Infof("Exec command %v on session %d failed", cmd.Process.Args, cmd.Process.Stdio) } else if ack.reply.Code == INIT_READFILE { ctx.reportFile(ack.reply.Event, INIT_READFILE, ack.msg, true) glog.Infof("Get error for read data: %s", string(ack.msg)) } else if ack.reply.Code == INIT_WRITEFILE { ctx.reportFile(ack.reply.Event, INIT_WRITEFILE, ack.msg, true) glog.Infof("Get error for write data: %s", string(ack.msg)) } else if ack.reply.Code == INIT_KILLCONTAINER { glog.Infof("Get ack for kill container") ctx.reportKill(ack.reply.Event, false) } case COMMAND_GET_POD_IP: ctx.reportPodIP(ev) case COMMAND_GET_POD_STATS: ctx.reportPodStats(ev) default: unexpectedEventHandler(ctx, ev, "pod running") } } } func statePodStopping(ctx *VmContext, ev VmEvent) { if processed := commonStateHandler(ctx, ev, true); processed { } else { switch ev.Event() { case COMMAND_RELEASE: glog.Info("pod stopping, got release, quit.") ctx.unsetTimeout() ctx.shutdownVM(false, "got release, quit") ctx.Become(stateTerminating, StateTerminating) ctx.reportVmShutdown() case EVENT_POD_FINISH: glog.Info("POD stopped") ctx.detachDevice() ctx.Become(stateCleaning, StateCleaning) case COMMAND_ACK: ack := ev.(*CommandAck) glog.V(1).Infof("[Stopping] got init ack to %d", ack.reply.Code) if ack.reply.Code == INIT_STOPPOD { glog.Info("POD stopped ", string(ack.msg)) ctx.detachDevice() ctx.Become(stateCleaning, StateCleaning) } case ERROR_CMD_FAIL: ack := ev.(*CommandError) if ack.reply.Code == INIT_STOPPOD { ctx.unsetTimeout() ctx.shutdownVM(true, "Stop pod failed as init report") ctx.Become(stateTerminating, StateTerminating) glog.Error("Stop pod failed as init report") } case EVENT_VM_TIMEOUT: reason := "stopping POD timeout" ctx.shutdownVM(true, reason) ctx.Become(stateTerminating, StateTerminating) glog.Error(reason) default: unexpectedEventHandler(ctx, ev, "pod stopping") } } } func stateTerminating(ctx *VmContext, ev VmEvent) { switch ev.Event() { case EVENT_VM_EXIT: glog.Info("Got VM shutdown event while terminating, go to cleaning up") ctx.unsetTimeout() if closed := ctx.onVmExit(true); !closed { ctx.Become(stateDestroying, StateDestroying) } case EVENT_VM_KILL: glog.Info("Got VM force killed message, go to cleaning up") ctx.unsetTimeout() if closed := ctx.onVmExit(true); !closed { ctx.Become(stateDestroying, StateDestroying) } case COMMAND_RELEASE: glog.Info("vm terminating, got release") ctx.reportVmShutdown() case COMMAND_ACK: ack := ev.(*CommandAck) glog.V(1).Infof("[Terminating] Got reply to %d: '%s'", ack.reply, string(ack.msg)) if ack.reply.Code == INIT_DESTROYPOD { glog.Info("POD destroyed ", string(ack.msg)) ctx.poweroffVM(false, "") } case ERROR_CMD_FAIL: ack := ev.(*CommandError) if ack.reply.Code == INIT_DESTROYPOD { glog.Warning("Destroy pod failed") ctx.poweroffVM(true, "Destroy pod failed") } case EVENT_VM_TIMEOUT: glog.Warning("VM did not exit in time, try to stop it") ctx.poweroffVM(true, "vm terminating timeout") case ERROR_INTERRUPTED: glog.V(1).Info("Connection interrupted while terminating") case GENERIC_OPERATION: ctx.handleGenericOperation(ev.(*GenericOperation)) default: unexpectedEventHandler(ctx, ev, "terminating") } } func stateCleaning(ctx *VmContext, ev VmEvent) { if processed := commonStateHandler(ctx, ev, false); processed { } else if processed, success := deviceRemoveHandler(ctx, ev); processed { if !success { glog.Warning("fail to unplug devices for stop") ctx.poweroffVM(true, "fail to unplug devices") ctx.Become(stateDestroying, StateDestroying) } else if ctx.deviceReady() { // ctx.reset() // ctx.unsetTimeout() // ctx.reportPodStopped() // glog.V(1).Info("device ready, could run pod.") // ctx.Become(stateInit, StateInit) ctx.vm <- &DecodedMessage{ Code: INIT_READY, Message: []byte{}, } glog.V(1).Info("device ready, could run pod.") } } else if processed := initFailureHandler(ctx, ev); processed { ctx.poweroffVM(true, "fail to unplug devices") ctx.Become(stateDestroying, StateDestroying) } else { switch ev.Event() { case COMMAND_RELEASE: glog.Info("vm cleaning to idle, got release, quit") ctx.reportVmShutdown() ctx.Become(stateDestroying, StateDestroying) case EVENT_VM_TIMEOUT: glog.Warning("VM did not exit in time, try to stop it") ctx.poweroffVM(true, "pod stopp/unplug timeout") ctx.Become(stateDestroying, StateDestroying) case COMMAND_ACK: ack := ev.(*CommandAck) glog.V(1).Infof("[cleaning] Got reply to %d: '%s'", ack.reply.Code, string(ack.msg)) if ack.reply.Code == INIT_READY { ctx.reset() ctx.unsetTimeout() ctx.reportPodStopped() glog.Info("init has been acknowledged, could run pod.") ctx.Become(stateInit, StateInit) } default: unexpectedEventHandler(ctx, ev, "cleaning") } } } func stateDestroying(ctx *VmContext, ev VmEvent) { if processed, _ := deviceRemoveHandler(ctx, ev); processed { if closed := ctx.tryClose(); closed { glog.Info("resources reclaimed, quit...") } } else { switch ev.Event() { case EVENT_VM_EXIT: glog.Info("Got VM shutdown event") ctx.unsetTimeout() if closed := ctx.onVmExit(false); closed { glog.Info("VM Context closed.") } case EVENT_VM_KILL: glog.Info("Got VM force killed message") ctx.unsetTimeout() if closed := ctx.onVmExit(true); closed { glog.Info("VM Context closed.") } case ERROR_INTERRUPTED: glog.V(1).Info("Connection interrupted while destroying") case COMMAND_RELEASE: glog.Info("vm destroying, got release") ctx.reportVmShutdown() case EVENT_VM_TIMEOUT: glog.Info("Device removing timeout") ctx.Close() case GENERIC_OPERATION: ctx.handleGenericOperation(ev.(*GenericOperation)) default: unexpectedEventHandler(ctx, ev, "vm cleaning up") } } } <file_sep>package pod import ( "fmt" "strings" "github.com/opencontainers/specs" ) func ConvertOCF2UserContainer(s *specs.LinuxSpec, r *specs.LinuxRuntimeSpec) *UserContainer { container := &UserContainer{ Command: s.Spec.Process.Args, Workdir: s.Spec.Process.Cwd, Tty: s.Spec.Process.Terminal, Image: s.Spec.Root.Path, Sysctl: r.Linux.Sysctl, RestartPolicy: "never", } for _, value := range s.Spec.Process.Env { fmt.Printf("env: %s\n", value) values := strings.Split(value, "=") tmp := UserEnvironmentVar{ Env: values[0], Value: values[1], } container.Envs = append(container.Envs, tmp) } return container } func ConvertOCF2PureUserPod(s *specs.LinuxSpec, r *specs.LinuxRuntimeSpec) *UserPod { return &UserPod{ Name: s.Spec.Hostname, Resource: UserResource{ Memory: int(r.Linux.Resources.Memory.Limit >> 20), Vcpu: 0, }, Tty: s.Spec.Process.Terminal, Type: "OCF", RestartPolicy: "never", } } <file_sep>#!/bin/bash # This command checks that the built commands can function together for # simple scenarios. It does not require Docker so it can run in travis. set -o errexit set -o nounset set -o pipefail # TODO directly test runv here ########################### # test runv from hyper function cancel_and_exit() { echo $1 exit 0 # don't fail in preparing hyper } cd ${GOPATH}/src/github.com/hyperhq/hyperd || cancel_and_exit "failed to find hyper" ./autogen.sh || cancel_and_exit "failed to autogen hyper" ./configure || cancel_and_exit "failed to configure hyper" make || cancel_and_exit "failed to compile hyper" hack/test-cmd.sh <file_sep>package main import ( "fmt" "os" "runtime" "github.com/codegangsta/cli" ) const ( version = "0.4.0" specConfig = "config.json" stateJson = "state.json" usage = `Open Container Initiative hypervisor-based runtime runv is a command line client for running applications packaged according to the Open Container Format (OCF) and is a compliant implementation of the Open Container Initiative specification. However, due to the difference between hypervisors and containers, the following sections of OCF don't apply to runV: Namespace Capability Device "linux" and "mount" fields in OCI specs are ignored The current release of "runV" supports the following hypervisors: KVM (QEMU 2.0 or later) Xen (4.5 or later) VirtualBox (Mac OS X) After creating a spec for your root filesystem, you can execute a container in your shell by running: # cd /mycontainer # runv start start [ -b bundle ] <container-id> If not specified, the default value for the 'bundle' is the current directory. 'Bundle' is the directory where '` + specConfig + `' must be located.` ) func main() { if os.Args[0] == "runv-ns-daemon" { runvNamespaceDaemon() os.Exit(0) } app := cli.NewApp() app.Name = "runv" app.Usage = usage app.Version = version app.Flags = []cli.Flag{ cli.BoolFlag{ Name: "debug", Usage: "enable debug output for logging, saved on the dir specified by log_dir via glog style", }, cli.StringFlag{ Name: "log_dir", Value: "/var/log/hyper", Usage: "the directory for the logging (glog style)", }, cli.StringFlag{ Name: "log", Usage: "[ignored on runv] set the log file path where internal debug information is written", }, cli.StringFlag{ Name: "log-format", Usage: "[ignored on runv] set the format used by logs ('text' (default), or 'json')", }, cli.StringFlag{ Name: "root", Value: "/run/runv", Usage: "root directory for storage of container state (this should be located in tmpfs)", }, cli.StringFlag{ Name: "driver", Value: getDefaultDriver(), Usage: "hypervisor driver (supports: kvm xen vbox)", }, cli.StringFlag{ Name: "kernel", Usage: "kernel for the container", }, cli.StringFlag{ Name: "initrd", Usage: "runv-compatible initrd for the container", }, cli.StringFlag{ Name: "vbox", Usage: "runv-compatible boot ISO for the container for vbox driver", }, } app.Commands = []cli.Command{ startCommand, specCommand, execCommand, killCommand, listCommand, stateCommand, } if err := app.Run(os.Args); err != nil { fmt.Printf("%s\n", err.Error()) } } func getDefaultDriver() string { if runtime.GOOS == "linux" { return "qemu" } if runtime.GOOS == "darwin" { return "vbox" } return "" } <file_sep>package hypervisor import ( "encoding/json" "errors" "github.com/golang/glog" "github.com/hyperhq/runv/hypervisor/pod" "github.com/hyperhq/runv/hypervisor/types" "sync" ) type PersistVolumeInfo struct { Name string Filename string Format string Fstype string DeviceName string ScsiId int Containers []int MontPoints []string } type PersistNetworkInfo struct { Index int PciAddr int DeviceName string IpAddr string } type PersistInfo struct { Id string DriverInfo map[string]interface{} UserSpec *pod.UserPod VmSpec *VmPod HwStat *VmHwStatus VolumeList []*PersistVolumeInfo NetworkList []*PersistNetworkInfo } func (ctx *VmContext) dump() (*PersistInfo, error) { dr, err := ctx.DCtx.Dump() if err != nil { return nil, err } info := &PersistInfo{ Id: ctx.Id, DriverInfo: dr, UserSpec: ctx.userSpec, VmSpec: ctx.vmSpec, HwStat: ctx.dumpHwInfo(), VolumeList: make([]*PersistVolumeInfo, len(ctx.devices.imageMap)+len(ctx.devices.volumeMap)), NetworkList: make([]*PersistNetworkInfo, len(ctx.devices.networkMap)), } vid := 0 for _, image := range ctx.devices.imageMap { info.VolumeList[vid] = image.info.dump() info.VolumeList[vid].Containers = []int{image.pos} info.VolumeList[vid].MontPoints = []string{"/"} vid++ } for _, vol := range ctx.devices.volumeMap { info.VolumeList[vid] = vol.info.dump() mps := len(vol.pos) info.VolumeList[vid].Containers = make([]int, mps) info.VolumeList[vid].MontPoints = make([]string, mps) i := 0 for idx, mp := range vol.pos { info.VolumeList[vid].Containers[i] = idx info.VolumeList[vid].MontPoints[i] = mp i++ } vid++ } nid := 0 for _, nic := range ctx.devices.networkMap { info.NetworkList[nid] = &PersistNetworkInfo{ Index: nic.Index, PciAddr: nic.PCIAddr, DeviceName: nic.DeviceName, IpAddr: nic.IpAddr, } nid++ } return info, nil } func (ctx *VmContext) dumpHwInfo() *VmHwStatus { return &VmHwStatus{ PciAddr: ctx.pciAddr, ScsiId: ctx.scsiId, AttachId: ctx.attachId, } } func (ctx *VmContext) loadHwStatus(pinfo *PersistInfo) { ctx.pciAddr = pinfo.HwStat.PciAddr ctx.scsiId = pinfo.HwStat.ScsiId ctx.attachId = pinfo.HwStat.AttachId } func (blk *BlockDescriptor) dump() *PersistVolumeInfo { return &PersistVolumeInfo{ Name: blk.Name, Filename: blk.Filename, Format: blk.Format, Fstype: blk.Fstype, DeviceName: blk.DeviceName, ScsiId: blk.ScsiId, } } func (vol *PersistVolumeInfo) blockInfo() *BlockDescriptor { return &BlockDescriptor{ Name: vol.Name, Filename: vol.Filename, Format: vol.Format, Fstype: vol.Fstype, DeviceName: vol.DeviceName, ScsiId: vol.ScsiId, } } func (cr *VmContainer) roLookup(mpoint string) bool { if v := cr.volLookup(mpoint); v != nil { return v.ReadOnly } else if m := cr.mapLookup(mpoint); m != nil { return m.ReadOnly } return false } func (cr *VmContainer) mapLookup(mpoint string) *VmFsmapDescriptor { for _, fs := range cr.Fsmap { if fs.Path == mpoint { return &fs } } return nil } func (cr *VmContainer) volLookup(mpoint string) *VmVolumeDescriptor { for _, vol := range cr.Volumes { if vol.Mount == mpoint { return &vol } } return nil } func vmDeserialize(s []byte) (*PersistInfo, error) { info := &PersistInfo{} err := json.Unmarshal(s, info) return info, err } func (pinfo *PersistInfo) serialize() ([]byte, error) { return json.Marshal(pinfo) } func (pinfo *PersistInfo) vmContext(hub chan VmEvent, client chan *types.VmResponse, wg *sync.WaitGroup) (*VmContext, error) { dc, err := HDriver.LoadContext(pinfo.DriverInfo) if err != nil { glog.Error("cannot load driver context: ", err.Error()) return nil, err } ctx, err := InitContext(pinfo.Id, hub, client, dc, &BootConfig{}, types.VM_KEEP_NONE) if err != nil { return nil, err } ctx.vmSpec = pinfo.VmSpec ctx.userSpec = pinfo.UserSpec ctx.wg = wg ctx.loadHwStatus(pinfo) for idx, container := range ctx.vmSpec.Containers { ctx.ptys.ttys[container.Tty] = newAttachments(idx, true) if container.Stderr > 0 { ctx.ptys.ttys[container.Stderr] = newAttachments(idx, true) } } for _, vol := range pinfo.VolumeList { binfo := vol.blockInfo() if len(vol.Containers) != len(vol.MontPoints) { return nil, errors.New("persistent data corrupt, volume info mismatch") } if len(vol.MontPoints) == 1 && vol.MontPoints[0] == "/" { img := &imageInfo{ info: binfo, pos: vol.Containers[0], } ctx.devices.imageMap[vol.Name] = img } else { v := &volumeInfo{ info: binfo, pos: make(map[int]string), readOnly: make(map[int]bool), } for i := 0; i < len(vol.Containers); i++ { idx := vol.Containers[i] v.pos[idx] = vol.MontPoints[i] v.readOnly[idx] = ctx.vmSpec.Containers[idx].roLookup(vol.MontPoints[i]) } } } for _, nic := range pinfo.NetworkList { ctx.devices.networkMap[nic.Index] = &InterfaceCreated{ Index: nic.Index, PCIAddr: nic.PciAddr, DeviceName: nic.DeviceName, IpAddr: nic.IpAddr, } } return ctx, nil } <file_sep>package daemon import ( "fmt" "github.com/golang/glog" "github.com/hyperhq/hyper/engine" "github.com/hyperhq/runv/hypervisor/types" ) func (daemon *Daemon) CmdPodStop(job *engine.Job) error { if len(job.Args) == 0 { return fmt.Errorf("Can not execute 'stop' command without any pod name!") } podId := job.Args[0] stopVm := job.Args[1] daemon.PodList.Lock() glog.V(2).Infof("lock PodList") defer glog.V(2).Infof("unlock PodList") defer daemon.PodList.Unlock() code, cause, err := daemon.StopPod(podId, stopVm) if err != nil { return err } // Prepare the VM status to client v := &engine.Env{} v.Set("ID", podId) v.SetInt("Code", code) v.Set("Cause", cause) if _, err := v.WriteTo(job.Stdout); err != nil { return err } return nil } func (daemon *Daemon) PodStopped(podId string) { // find the vm id which running POD, and stop it pod, ok := daemon.PodList.Get(podId) if !ok { glog.Errorf("Can not find pod(%s)", podId) return } if pod.vm == nil { return } daemon.DeleteVmByPod(podId) daemon.RemoveVm(pod.vm.Id) if pod.status.Autoremove == true { daemon.CleanPod(podId) } pod.vm = nil } func (daemon *Daemon) StopPod(podId, stopVm string) (int, string, error) { glog.V(1).Infof("Prepare to stop the POD: %s", podId) // find the vm id which running POD, and stop it pod, ok := daemon.PodList.Get(podId) if !ok { glog.Errorf("Can not find pod(%s)", podId) return -1, "", fmt.Errorf("Can not find pod(%s)", podId) } // we need to set the 'RestartPolicy' of the pod to 'never' if stop command is invoked // for kubernetes if pod.status.Type == "kubernetes" { pod.status.RestartPolicy = "never" } if pod.vm == nil { return types.E_VM_SHUTDOWN, "", nil } vmId := pod.vm.Id vmResponse := pod.vm.StopPod(pod.status, stopVm) // Delete the Vm info for POD daemon.DeleteVmByPod(podId) if vmResponse.Code == types.E_VM_SHUTDOWN { daemon.RemoveVm(vmId) } if pod.status.Autoremove == true { daemon.CleanPod(podId) } pod.vm = nil return vmResponse.Code, vmResponse.Cause, nil } <file_sep>package qemu import ( "errors" "fmt" "os" "os/exec" "strconv" "strings" "github.com/golang/glog" "github.com/hyperhq/runv/hypervisor" "github.com/hyperhq/runv/hypervisor/types" ) //implement the hypervisor.HypervisorDriver interface type QemuDriver struct { executable string } //implement the hypervisor.DriverContext interface type QemuContext struct { driver *QemuDriver qmp chan QmpInteraction waitQmp chan int wdt chan string qmpSockName string cpus int process *os.Process interfaces []qemuNicConfig images []qemuImageConfig callbacks []hypervisor.VmEvent } //qemu nic configuration type qemuNicConfig struct { fd uint64 deviceName string macAddr string pciAddr int } //qemu image configuration type qemuImageConfig struct { deviceName string sourceType string format string scsiId int } func qemuContext(ctx *hypervisor.VmContext) *QemuContext { return ctx.DCtx.(*QemuContext) } func InitDriver() *QemuDriver { cmd, err := exec.LookPath("qemu-system-x86_64") if err != nil { return nil } return &QemuDriver{ executable: cmd, } } func (qd *QemuDriver) InitContext(homeDir string) hypervisor.DriverContext { return &QemuContext{ driver: qd, qmp: make(chan QmpInteraction, 128), wdt: make(chan string, 16), qmpSockName: homeDir + QmpSockName, process: nil, } } func (qd *QemuDriver) LoadContext(persisted map[string]interface{}) (hypervisor.DriverContext, error) { if t, ok := persisted["hypervisor"]; !ok || t != "qemu" { return nil, errors.New("wrong driver type in persist info") } var sock string var proc *os.Process = nil var err error s, ok := persisted["qmpSock"] if !ok { return nil, errors.New("cannot read the qmp socket info from persist info") } else { switch s.(type) { case string: sock = s.(string) default: return nil, errors.New("wrong sock name type in persist info") } } p, ok := persisted["pid"] if !ok { return nil, errors.New("cannot read the pid info from persist info") } else { switch p.(type) { case float64: proc, err = os.FindProcess(int(p.(float64))) if err != nil { return nil, err } default: return nil, errors.New("wrong pid field type in persist info") } } return &QemuContext{ driver: qd, qmp: make(chan QmpInteraction, 128), wdt: make(chan string, 16), waitQmp: make(chan int, 1), qmpSockName: sock, process: proc, }, nil } func (qc *QemuContext) Launch(ctx *hypervisor.VmContext) { go launchQemu(qc, ctx) go qmpHandler(ctx) } func (qc *QemuContext) Associate(ctx *hypervisor.VmContext) { go associateQemu(ctx) go qmpHandler(ctx) } func (qc *QemuContext) Dump() (map[string]interface{}, error) { if qc.process == nil { return nil, errors.New("can not serialize qemu context: no process running") } return map[string]interface{}{ "hypervisor": "qemu", "qmpSock": qc.qmpSockName, "pid": qc.process.Pid, }, nil } func (qc *QemuContext) Shutdown(ctx *hypervisor.VmContext) { qmpQemuQuit(ctx, qc) } func (qc *QemuContext) Kill(ctx *hypervisor.VmContext) { defer func() { err := recover() if glog.V(1) && err != nil { glog.Info("kill qemu, but channel has already been closed") } }() qc.wdt <- "kill" } func (qc *QemuContext) Stats(ctx *hypervisor.VmContext) (*types.PodStats, error) { return nil, nil } func (qc *QemuContext) Close() { qc.wdt <- "quit" _ = <-qc.waitQmp close(qc.waitQmp) close(qc.qmp) close(qc.wdt) } func (qc *QemuContext) Pause(ctx *hypervisor.VmContext, cmd *hypervisor.PauseCommand) { commands := make([]*QmpCommand, 1) if cmd.Pause { commands[0] = &QmpCommand{ Execute: "stop", } } else { commands[0] = &QmpCommand{ Execute: "cont", } } qc.qmp <- &QmpSession{ commands: commands, respond: func(err error) { cause := "" if err != nil { cause = err.Error() } ctx.Hub <- &hypervisor.PauseResult{Cause: cause, Reply: cmd} }, } } func (qc *QemuContext) AddDisk(ctx *hypervisor.VmContext, sourceType string, blockInfo *hypervisor.BlockDescriptor) { name := blockInfo.Name filename := blockInfo.Filename format := blockInfo.Format id := blockInfo.ScsiId if format == "rbd" { if blockInfo.Options != nil { keyring := blockInfo.Options["keyring"] user := blockInfo.Options["user"] if keyring != "" && user != "" { filename += ":id=" + user + ":key=" + keyring } monitors := blockInfo.Options["monitors"] for i, m := range strings.Split(monitors, ";") { monitor := strings.Replace(m, ":", "\\:", -1) if i == 0 { filename += ":mon_host=" + monitor continue } filename += ";" + monitor } } } newDiskAddSession(ctx, qc, name, sourceType, filename, format, id) } func (qc *QemuContext) RemoveDisk(ctx *hypervisor.VmContext, blockInfo *hypervisor.BlockDescriptor, callback hypervisor.VmEvent) { id := blockInfo.ScsiId newDiskDelSession(ctx, qc, id, callback) } func (qc *QemuContext) AddNic(ctx *hypervisor.VmContext, host *hypervisor.HostNicInfo, guest *hypervisor.GuestNicInfo) { newNetworkAddSession(ctx, qc, host.Fd, guest.Device, host.Mac, guest.Index, guest.Busaddr) } func (qc *QemuContext) RemoveNic(ctx *hypervisor.VmContext, n *hypervisor.InterfaceCreated, callback hypervisor.VmEvent) { newNetworkDelSession(ctx, qc, n.DeviceName, callback) } func (qc *QemuContext) SetCpus(ctx *hypervisor.VmContext, cpus int, result chan<- error) { currcpus := qc.cpus if cpus < currcpus { result <- fmt.Errorf("can't reduce cpus number from %d to %d", currcpus, cpus) return } else if cpus == currcpus { result <- nil return } commands := make([]*QmpCommand, cpus-currcpus) for id := currcpus; id < cpus; id++ { commands[id-currcpus] = &QmpCommand{ Execute: "cpu-add", Arguments: map[string]interface{}{ "id": id, }, } } qc.qmp <- &QmpSession{ commands: commands, respond: func(err error) { if err == nil { qc.cpus = cpus } result <- err }, } } func (qc *QemuContext) AddMem(ctx *hypervisor.VmContext, slot, size int, result chan<- error) { commands := make([]*QmpCommand, 2) commands[0] = &QmpCommand{ Execute: "object-add", Arguments: map[string]interface{}{ "qom-type": "memory-backend-ram", "id": "mem" + strconv.Itoa(slot), "props": map[string]interface{}{"size": int64(size) << 20}, }, } commands[1] = &QmpCommand{ Execute: "device_add", Arguments: map[string]interface{}{ "driver": "pc-dimm", "id": "dimm" + strconv.Itoa(slot), "memdev": "mem" + strconv.Itoa(slot), }, } qc.qmp <- &QmpSession{ commands: commands, respond: func(err error) { result <- err }, } } func (qc *QemuContext) Save(ctx *hypervisor.VmContext, path string, result chan<- error) { commands := make([]*QmpCommand, 1) commands[0] = &QmpCommand{ Execute: "migrate", Arguments: map[string]interface{}{ "uri": fmt.Sprintf("exec:cat>%s", path), }, } // TODO: use query-migrate to query until completed qc.qmp <- &QmpSession{ commands: commands, respond: func(err error) { result <- err }, } } func (qc *QemuDriver) SupportLazyMode() bool { return true } func (qc *QemuContext) arguments(ctx *hypervisor.VmContext) []string { if ctx.Boot == nil { ctx.Boot = &hypervisor.BootConfig{ CPU: 1, Memory: 128, Kernel: hypervisor.DefaultKernel, Initrd: hypervisor.DefaultInitrd, } } boot := ctx.Boot qc.cpus = boot.CPU var machineClass, memParams, cpuParams string if ctx.Boot.HotAddCpuMem { machineClass = "pc-i440fx-2.1" memParams = fmt.Sprintf("size=%d,slots=1,maxmem=%dM", ctx.Boot.Memory, hypervisor.DefaultMaxMem) // TODO set maxmem to the total memory of the system cpuParams = fmt.Sprintf("cpus=%d,maxcpus=%d", ctx.Boot.CPU, hypervisor.DefaultMaxCpus) // TODO set it to the cpus of the system } else { machineClass = "pc-i440fx-2.0" memParams = strconv.Itoa(ctx.Boot.Memory) cpuParams = strconv.Itoa(ctx.Boot.CPU) } params := []string{ "-machine", machineClass + ",accel=kvm,usb=off", "-global", "kvm-pit.lost_tick_policy=discard", "-cpu", "host"} if _, err := os.Stat("/dev/kvm"); os.IsNotExist(err) { glog.V(1).Info("kvm not exist change to no kvm mode") params = []string{"-machine", machineClass + ",usb=off", "-cpu", "core2duo"} } if boot.Bios != "" && boot.Cbfs != "" { params = append(params, "-drive", fmt.Sprintf("if=pflash,file=%s,readonly=on", boot.Bios), "-drive", fmt.Sprintf("if=pflash,file=%s,readonly=on", boot.Cbfs)) } else if boot.Bios != "" { params = append(params, "-bios", boot.Bios, "-kernel", boot.Kernel, "-initrd", boot.Initrd, "-append", "\"console=ttyS0 panic=1 no_timer_check\"") } else if boot.Cbfs != "" { params = append(params, "-drive", fmt.Sprintf("if=pflash,file=%s,readonly=on", boot.Cbfs)) } else { params = append(params, "-kernel", boot.Kernel, "-initrd", boot.Initrd, "-append", "\"console=ttyS0 panic=1 no_timer_check\"") } params = append(params, "-realtime", "mlock=off", "-no-user-config", "-nodefaults", "-no-hpet", "-rtc", "base=utc,driftfix=slew", "-no-reboot", "-display", "none", "-boot", "strict=on", "-m", memParams, "-smp", cpuParams, "-qmp", fmt.Sprintf("unix:%s,server,nowait", qc.qmpSockName), "-serial", fmt.Sprintf("unix:%s,server,nowait", ctx.ConsoleSockName), "-device", "virtio-serial-pci,id=virtio-serial0,bus=pci.0,addr=0x2", "-device", "virtio-scsi-pci,id=scsi0,bus=pci.0,addr=0x3", "-chardev", fmt.Sprintf("socket,id=charch0,path=%s,server,nowait", ctx.HyperSockName), "-device", "virtserialport,bus=virtio-serial0.0,nr=1,chardev=charch0,id=channel0,name=sh.hyper.channel.0", "-chardev", fmt.Sprintf("socket,id=charch1,path=%s,server,nowait", ctx.TtySockName), "-device", "virtserialport,bus=virtio-serial0.0,nr=2,chardev=charch1,id=channel1,name=sh.hyper.channel.1", "-fsdev", fmt.Sprintf("local,id=virtio9p,path=%s,security_model=none", ctx.ShareDir), "-device", fmt.Sprintf("virtio-9p-pci,fsdev=virtio9p,mount_tag=%s", hypervisor.ShareDirTag), ) for i, info := range qc.interfaces { params = append(params, "-netdev", fmt.Sprintf("tap,fd=%d,id=%s", info.fd, info.deviceName), "-device", fmt.Sprintf("virtio-net-pci,netdev=%s,id=netchan%d,mac=%s,bus=pci.0,addr=0x%d", info.deviceName, i, info.macAddr, info.pciAddr), ) } for _, image := range qc.images { params = append(params, "-drive", fmt.Sprintf("file=%s,if=none,id=drive%d,format=%s,cache=writeback", image.deviceName, image.scsiId, image.format), "-device", fmt.Sprintf("scsi-hd,bus=scsi0.0,drive=drive%d,id=scsi-disk%d,scsi-id=%d", image.scsiId, image.scsiId, image.scsiId), ) } return params } func (qc *QemuContext) LazyAddNic(ctx *hypervisor.VmContext, host *hypervisor.HostNicInfo, guest *hypervisor.GuestNicInfo) { callback := &hypervisor.NetDevInsertedEvent{ Index: guest.Index, DeviceName: guest.Device, Address: guest.Busaddr, } qc.callbacks = append(qc.callbacks, callback) info := qemuNicConfig{ fd: host.Fd, deviceName: guest.Device, macAddr: host.Mac, pciAddr: guest.Busaddr, } qc.interfaces = append(qc.interfaces, info) } func (qc *QemuContext) LazyAddDisk(ctx *hypervisor.VmContext, name, sourceType, filename, format string, id int) { devName := scsiId2Name(id) callback := &hypervisor.BlockdevInsertedEvent{ Name: name, SourceType: sourceType, DeviceName: devName, ScsiId: id, } qc.callbacks = append(qc.callbacks, callback) image := qemuImageConfig{ deviceName: filename, sourceType: sourceType, format: format, scsiId: id, } qc.images = append(qc.images, image) } func (qc *QemuContext) InitVM(ctx *hypervisor.VmContext) error { return nil } func (qc *QemuContext) LazyLaunch(ctx *hypervisor.VmContext) { go launchQemu(qc, ctx) go qmpHandler(ctx) } <file_sep>package hypervisor import ( "encoding/binary" "io" "net" "strings" "sync" "github.com/golang/glog" "github.com/hyperhq/runv/hypervisor/types" "github.com/hyperhq/runv/lib/utils" ) type WindowSize struct { Row uint16 `json:"row"` Column uint16 `json:"column"` } type TtyIO struct { Stdin io.ReadCloser Stdout io.WriteCloser ClientTag string Callback chan *types.VmResponse liner StreamTansformer } type ttyAttachments struct { container int persistent bool closed bool attachments []*TtyIO } type pseudoTtys struct { channel chan *ttyMessage ttys map[uint64]*ttyAttachments lock *sync.Mutex } type ttyMessage struct { session uint64 message []byte } func (tm *ttyMessage) toBuffer() []byte { length := len(tm.message) + 12 buf := make([]byte, length) binary.BigEndian.PutUint64(buf[:8], tm.session) binary.BigEndian.PutUint32(buf[8:12], uint32(length)) copy(buf[12:], tm.message) return buf } func newPts() *pseudoTtys { return &pseudoTtys{ channel: make(chan *ttyMessage, 256), ttys: make(map[uint64]*ttyAttachments), lock: &sync.Mutex{}, } } func readTtyMessage(conn *net.UnixConn) (*ttyMessage, error) { needRead := 12 length := 0 read := 0 buf := make([]byte, 512) res := []byte{} for read < needRead { want := needRead - read if want > 512 { want = 512 } glog.V(1).Infof("tty: trying to read %d bytes", want) nr, err := conn.Read(buf[:want]) if err != nil { glog.Error("read tty data failed") return nil, err } res = append(res, buf[:nr]...) read = read + nr if nr<want && read<needRead { return readTtyMessage(conn) } glog.V(1).Infof("tty: read %d/%d [length = %d]", read, needRead, length) if length == 0 && read >= 12 { length = int(binary.BigEndian.Uint32(res[8:12])) glog.V(1).Infof("data length is %d", length) if length > 12 { needRead = length } } } return &ttyMessage{ session: binary.BigEndian.Uint64(res[:8]), message: res[12:], }, nil } func waitTtyMessage(ctx *VmContext, conn *net.UnixConn) { for { msg, ok := <-ctx.ptys.channel if !ok { glog.V(1).Info("tty chan closed, quit sent goroutine") break } glog.V(3).Infof("trying to write to session %d", msg.session) if _, ok := ctx.ptys.ttys[msg.session]; ok { _, err := conn.Write(msg.toBuffer()) if err != nil { glog.V(1).Info("Cannot write to tty socket: ", err.Error()) return } } } } func waitPts(ctx *VmContext) { conn, err := utils.UnixSocketConnect(ctx.TtySockName) if err != nil { glog.Error("Cannot connect to tty socket ", err.Error()) ctx.Hub <- &InitFailedEvent{ Reason: "Cannot connect to tty socket " + err.Error(), } return } glog.V(1).Info("tty socket connected") go waitTtyMessage(ctx, conn.(*net.UnixConn)) for { res, err := readTtyMessage(conn.(*net.UnixConn)) if err != nil { glog.V(1).Info("tty socket closed, quit the reading goroutine ", err.Error()) ctx.Hub <- &Interrupted{Reason: "tty socket failed " + err.Error()} close(ctx.ptys.channel) return } if ta, ok := ctx.ptys.ttys[res.session]; ok { if len(res.message) == 0 { glog.V(1).Infof("session %d closed by peer, close pty", res.session) ta.closed = true } else if ta.closed { var code uint8 = 255 if len(res.message) == 1 { code = uint8(res.message[0]) } glog.V(1).Infof("session %d, exit code", res.session, code) ctx.ptys.Close(ctx, res.session, code) } else { for _, tty := range ta.attachments { if tty.Stdout != nil && tty.liner == nil { _, err = tty.Stdout.Write(res.message) } else if tty.Stdout != nil { m := tty.liner.Transform(res.message) if len(m) > 0 { _, err = tty.Stdout.Write(m) } } if err != nil { glog.V(1).Infof("fail to write session %d, close pty attachment", res.session) ctx.ptys.Detach(ctx, res.session, tty) } } } } } } func newAttachments(idx int, persist bool) *ttyAttachments { return &ttyAttachments{ container: idx, persistent: persist, attachments: []*TtyIO{}, } } func newAttachmentsWithTty(idx int, persist bool, tty *TtyIO) *ttyAttachments { return &ttyAttachments{ container: idx, persistent: persist, attachments: []*TtyIO{tty}, } } func (ta *ttyAttachments) attach(tty *TtyIO) { ta.attachments = append(ta.attachments, tty) } func (ta *ttyAttachments) detach(tty *TtyIO) { at := []*TtyIO{} detached := false for _, t := range ta.attachments { if tty.ClientTag != t.ClientTag { at = append(at, t) } else { detached = true } } if detached { ta.attachments = at } } func (ta *ttyAttachments) close(code uint8) []string { tags := []string{} for _, t := range ta.attachments { tags = append(tags, t.Close(code)) } ta.attachments = []*TtyIO{} return tags } func (ta *ttyAttachments) empty() bool { return len(ta.attachments) == 0 } func (tty *TtyIO) Close(code uint8) string { glog.V(1).Info("Close tty ", tty.ClientTag) if tty.Stdin != nil { tty.Stdin.Close() } if tty.Stdout != nil { tty.Stdout.Close() } if tty.Callback != nil { tty.Callback <- &types.VmResponse{ Code: types.E_EXEC_FINISH, Cause: "Command finished", Data: code, } } return tty.ClientTag } func (pts *pseudoTtys) Detach(ctx *VmContext, session uint64, tty *TtyIO) { if ta, ok := ctx.ptys.ttys[session]; ok { ctx.ptys.lock.Lock() ta.detach(tty) ctx.ptys.lock.Unlock() if !ta.persistent && ta.empty() { ctx.ptys.Close(ctx, session, 0) } ctx.clientDereg(tty.Close(0)) } } func (pts *pseudoTtys) Close(ctx *VmContext, session uint64, code uint8) { if ta, ok := pts.ttys[session]; ok { pts.lock.Lock() tags := ta.close(code) delete(pts.ttys, session) pts.lock.Unlock() for _, t := range tags { ctx.clientDereg(t) } } } func (pts *pseudoTtys) ptyConnect(ctx *VmContext, container int, session uint64, tty *TtyIO) { pts.lock.Lock() if ta, ok := pts.ttys[session]; ok { ta.attach(tty) } else { pts.ttys[session] = newAttachmentsWithTty(container, false, tty) } pts.lock.Unlock() if tty.Stdin != nil { go func() { buf := make([]byte, 32) defer pts.Detach(ctx, session, tty) defer func() { recover() }() for { nr, err := tty.Stdin.Read(buf) if err != nil { glog.Info("a stdin closed, ", err.Error()) return } else if nr == 1 && buf[0] == ExitChar { glog.Info("got stdin detach char, exit term") return } glog.V(3).Infof("trying to input char: %d and %d chars", buf[0], nr) mbuf := make([]byte, nr) copy(mbuf, buf[:nr]) pts.channel <- &ttyMessage{ session: session, message: mbuf[:nr], } } }() } return } type StreamTansformer interface { Transform(input []byte) []byte } type linerTransformer struct { cr bool } func (lt *linerTransformer) Transform(input []byte) []byte { output := []byte{} for len(input) > 0 { // process remain \n of \r\n if lt.cr { lt.cr = false if input[0] == '\n' { input = input[1:] continue } } // find \r\n or \r pos := strings.IndexByte(string(input), '\r') if pos > 0 { output = append(output, input[:pos]...) output = append(output, '\r', '\n') input = input[pos+1:] lt.cr = true continue } // find \n pos = strings.IndexByte(string(input), '\n') if pos > 0 { output = append(output, input[:pos]...) output = append(output, '\r', '\n') input = input[pos+1:] //do not set lt.cr here continue } //no \n or \r output = append(output, input...) break } return output } func TtyLiner(conn io.Reader, output chan string) { buf := make([]byte, 1) line := []byte{} cr := false emit := false for { nr, err := conn.Read(buf) if err != nil || nr < 1 { glog.V(1).Info("Input byte chan closed, close the output string chan") close(output) return } switch buf[0] { case '\n': emit = !cr cr = false case '\r': emit = true cr = true default: cr = false line = append(line, buf[0]) } if emit { output <- string(line) line = []byte{} emit = false } } } func (vm *Vm) Attach(Stdin io.ReadCloser, Stdout io.WriteCloser, tag, container string, callback chan *types.VmResponse, size *WindowSize) error { ttyIO := &TtyIO{ Stdin: Stdin, Stdout: Stdout, ClientTag: tag, Callback: callback, } var attachCommand = &AttachCommand{ Streams: ttyIO, Size: size, Container: container, } VmEvent, err := vm.GetRequestChan() if err != nil { return err } defer vm.ReleaseRequestChan(VmEvent) VmEvent <- attachCommand return nil } func (vm *Vm) GetLogOutput(container, tag string, callback chan *types.VmResponse) (io.ReadCloser, io.ReadCloser, error) { stdout, stdoutStub := io.Pipe() stderr, stderrStub := io.Pipe() outIO := &TtyIO{ Stdin: nil, Stdout: stdoutStub, ClientTag: tag, Callback: callback, } errIO := &TtyIO{ Stdin: nil, Stdout: stderrStub, ClientTag: tag, Callback: nil, } cmd := &AttachCommand{ Streams: outIO, Stderr: errIO, Container: container, } VmEvent, err := vm.GetRequestChan() if err != nil { return nil, nil, err } defer vm.ReleaseRequestChan(VmEvent) VmEvent <- cmd return stdout, stderr, nil } <file_sep>package hypervisor import ( "errors" "fmt" "os" "strings" "syscall" "time" "encoding/json" "github.com/golang/glog" "github.com/hyperhq/runv/hypervisor/pod" "github.com/hyperhq/runv/hypervisor/types" ) type Vm struct { Id string Pod *PodStatus Status uint Cpu int Mem int Lazy bool Hub chan VmEvent clients *Fanout } func (vm *Vm) GetResponseChan() (chan *types.VmResponse, error) { if vm.clients != nil { return vm.clients.Acquire() } return nil, errors.New("No channels available") } func (vm *Vm) ReleaseResponseChan(ch chan *types.VmResponse) { if vm.clients != nil { vm.clients.Release(ch) } } func (vm *Vm) Launch(b *BootConfig) (err error) { var ( PodEvent = make(chan VmEvent, 128) Status = make(chan *types.VmResponse, 128) ) if vm.Lazy { go LazyVmLoop(vm.Id, PodEvent, Status, b) } else { go VmLoop(vm.Id, PodEvent, Status, b) } vm.Hub = PodEvent vm.clients = CreateFanout(Status, 128, false) return nil } func (vm *Vm) Kill() (int, string, error) { Status, err := vm.GetResponseChan() if err != nil { return -1, "", err } var Response *types.VmResponse shutdownPodEvent := &ShutdownCommand{Wait: false} vm.Hub <- shutdownPodEvent // wait for the VM response stop := false for !stop { var ok bool Response, ok = <-Status if !ok || Response == nil || Response.Code == types.E_VM_SHUTDOWN { vm.ReleaseResponseChan(Status) vm.clients.Close() vm.clients = nil stop = true } if Response != nil { glog.V(1).Infof("Got response: %d: %s", Response.Code, Response.Cause) } else { glog.V(1).Infof("Nil response from status chan") } } if Response == nil { return types.E_VM_SHUTDOWN, "", nil } return Response.Code, Response.Cause, nil } // This function will only be invoked during daemon start func (vm *Vm) AssociateVm(mypod *PodStatus, data []byte) error { glog.V(1).Infof("Associate the POD(%s) with VM(%s)", mypod.Id, mypod.Vm) var ( PodEvent = make(chan VmEvent, 128) Status = make(chan *types.VmResponse, 128) ) VmAssociate(mypod.Vm, PodEvent, Status, mypod.Wg, data) go vm.handlePodEvent(mypod) ass := <-Status if ass.Code != types.E_OK { glog.Errorf("cannot associate with vm: %s, error status %d (%s)", mypod.Vm, ass.Code, ass.Cause) return errors.New("load vm status failed") } vm.Hub = PodEvent vm.clients = CreateFanout(Status, 128, false) mypod.Status = types.S_POD_RUNNING mypod.StartedAt = time.Now().Format("2006-01-02T15:04:05Z") mypod.SetContainerStatus(types.S_POD_RUNNING) vm.Status = types.S_VM_ASSOCIATED vm.Pod = mypod return nil } func (vm *Vm) ReleaseVm() (int, error) { var Response *types.VmResponse Status, err := vm.GetResponseChan() if err != nil { return -1, err } defer vm.ReleaseResponseChan(Status) if vm.Status == types.S_VM_IDLE { shutdownPodEvent := &ShutdownCommand{Wait: false} vm.Hub <- shutdownPodEvent for { Response = <-Status if Response.Code == types.E_VM_SHUTDOWN { break } } } else { releasePodEvent := &ReleaseVMCommand{} vm.Hub <- releasePodEvent for { Response = <-Status if Response.Code == types.E_VM_SHUTDOWN || Response.Code == types.E_OK { break } if Response.Code == types.E_BUSY { return types.E_BUSY, fmt.Errorf("VM busy") } } } return types.E_OK, nil } func defaultHandlePodEvent(Response *types.VmResponse, data interface{}, mypod *PodStatus, vm *Vm) bool { if Response.Code == types.E_POD_FINISHED { mypod.SetPodContainerStatus(Response.Data.([]uint32)) mypod.Vm = "" vm.Status = types.S_VM_IDLE } else if Response.Code == types.E_VM_SHUTDOWN { if mypod.Status == types.S_POD_RUNNING { mypod.Status = types.S_POD_SUCCEEDED mypod.SetContainerStatus(types.S_POD_SUCCEEDED) } mypod.Vm = "" return true } return false } func (vm *Vm) handlePodEvent(mypod *PodStatus) { glog.V(1).Infof("hyperHandlePodEvent pod %s, vm %s", mypod.Id, vm.Id) Status, err := vm.GetResponseChan() if err != nil { return } defer vm.ReleaseResponseChan(Status) for { Response, ok := <-Status if !ok { break } exit := mypod.Handler.Handle(Response, mypod.Handler.Data, mypod, vm) if exit { vm.clients.Close() vm.clients = nil break } } } func (vm *Vm) StartPod(mypod *PodStatus, userPod *pod.UserPod, cList []*ContainerInfo, vList map[string]*VolumeInfo) *types.VmResponse { mypod.Vm = vm.Id var ok bool = false vm.Pod = mypod vm.Status = types.S_VM_ASSOCIATED var response *types.VmResponse if mypod.Status == types.S_POD_RUNNING { err := fmt.Errorf("The pod(%s) is running, can not start it", mypod.Id) response = &types.VmResponse{ Code: -1, Cause: err.Error(), Data: nil, } return response } if mypod.Type == "kubernetes" && mypod.Status != types.S_POD_CREATED { err := fmt.Errorf("The pod(%s) is finished with kubernetes type, can not start it again", mypod.Id) response = &types.VmResponse{ Code: -1, Cause: err.Error(), Data: nil, } return response } Status, err := vm.GetResponseChan() if err != nil { return errorResponse(err.Error()) } defer vm.ReleaseResponseChan(Status) go vm.handlePodEvent(mypod) runPodEvent := &RunPodCommand{ Spec: userPod, Containers: cList, Volumes: vList, Wg: mypod.Wg, } vm.Hub <- runPodEvent // wait for the VM response for { response, ok = <-Status if !ok { response = &types.VmResponse{ Code: -1, Cause: "Start pod failed", Data: nil, } glog.V(1).Infof("return response %v", response) break } glog.V(1).Infof("Get the response from VM, VM id is %s!", response.VmId) if response.Code == types.E_VM_RUNNING { continue } if response.VmId == vm.Id { break } } if response.Data != nil { mypod.Status = types.S_POD_RUNNING mypod.StartedAt = time.Now().Format("2006-01-02T15:04:05Z") // Set the container status to online mypod.SetContainerStatus(types.S_POD_RUNNING) } return response } func (vm *Vm) StopPod(mypod *PodStatus, stopVm string) *types.VmResponse { var Response *types.VmResponse Status, err := vm.GetResponseChan() if err != nil { return errorResponse(err.Error()) } defer vm.ReleaseResponseChan(Status) if mypod.Status != types.S_POD_RUNNING { return errorResponse("The POD has already stoppod") } if stopVm == "yes" { mypod.Wg.Add(1) shutdownPodEvent := &ShutdownCommand{Wait: true} vm.Hub <- shutdownPodEvent // wait for the VM response for { Response = <-Status glog.V(1).Infof("Got response: %d: %s", Response.Code, Response.Cause) if Response.Code == types.E_VM_SHUTDOWN { mypod.Vm = "" break } } // wait for goroutines exit mypod.Wg.Wait() } else { stopPodEvent := &StopPodCommand{} vm.Hub <- stopPodEvent // wait for the VM response for { Response = <-Status glog.V(1).Infof("Got response: %d: %s", Response.Code, Response.Cause) if Response.Code == types.E_POD_STOPPED || Response.Code == types.E_BAD_REQUEST || Response.Code == types.E_FAILED { mypod.Vm = "" vm.Status = types.S_VM_IDLE break } } } mypod.Status = types.S_POD_FAILED mypod.SetContainerStatus(types.S_POD_FAILED) return Response } func (vm *Vm) WriteFile(container, target string, data []byte) error { if target == "" { return fmt.Errorf("'write' without file") } Status, err := vm.GetResponseChan() if err != nil { return nil } defer vm.ReleaseResponseChan(Status) writeEvent := &WriteFileCommand{ Container: container, File: target, Data: []byte{}, } writeEvent.Data = append(writeEvent.Data, data[:]...) vm.Hub <- writeEvent cause := "get response failed" for { Response, ok := <-Status if !ok { break } glog.V(1).Infof("Got response: %d: %s", Response.Code, Response.Cause) if Response.Reply == writeEvent { if Response.Cause == "" { return nil } cause = Response.Cause break } } return fmt.Errorf("Write container %s file %s failed: %s", container, target, cause) } func (vm *Vm) ReadFile(container, target string) ([]byte, error) { if target == "" { return nil, fmt.Errorf("'read' without file") } Status, err := vm.GetResponseChan() if err != nil { return nil, err } defer vm.ReleaseResponseChan(Status) readEvent := &ReadFileCommand{ Container: container, File: target, } vm.Hub <- readEvent cause := "get response failed" for { Response, ok := <-Status if !ok { break } glog.V(1).Infof("Got response: %d: %s", Response.Code, Response.Cause) if Response.Reply == readEvent { if Response.Cause == "" { return Response.Data.([]byte), nil } cause = Response.Cause break } } return nil, fmt.Errorf("Read container %s file %s failed: %s", container, target, cause) } func (vm *Vm) KillContainer(container string, signal syscall.Signal) error { killCmd := &KillCommand{ Container: container, Signal: signal, } Status, err := vm.GetResponseChan() if err != nil { return nil } defer vm.ReleaseResponseChan(Status) vm.Hub <- killCmd for { Response, ok := <-Status if !ok { return fmt.Errorf("kill container %v failed: get response failed", container) } glog.V(1).Infof("Got response: %d: %s", Response.Code, Response.Cause) if Response.Reply == killCmd { if Response.Code != types.E_OK { return fmt.Errorf("kill container %v failed: %s", container, Response.Cause) } break } } return nil } // TODO: deprecated api, it will be removed after the hyper.git updated func (vm *Vm) AddCpu(totalCpu int) error { return vm.SetCpus(totalCpu) } func (vm *Vm) SetCpus(cpus int) error { if vm.Cpu >= cpus { return nil } res := vm.SendGenericOperation("SetCpus", func(ctx *VmContext, result chan<- error) { ctx.DCtx.SetCpus(ctx, cpus, result) }, StateInit) err := <-res if err == nil { vm.Cpu = cpus } return err } func (vm *Vm) AddMem(totalMem int) error { if vm.Mem >= totalMem { return nil } size := totalMem - vm.Mem res := vm.SendGenericOperation("AddMem", func(ctx *VmContext, result chan<- error) { ctx.DCtx.AddMem(ctx, 1, size, result) }, StateInit) err := <-res if err == nil { vm.Mem = totalMem } return err } func (vm *Vm) OnlineCpuMem() error { onlineCmd := &OnlineCpuMemCommand{} Status, err := vm.GetResponseChan() if err != nil { return nil } defer vm.ReleaseResponseChan(Status) vm.Hub <- onlineCmd return nil } func (vm *Vm) Exec(container, cmd string, terminal bool, tty *TtyIO) error { var command []string if cmd == "" { return fmt.Errorf("'exec' without command") } if err := json.Unmarshal([]byte(cmd), &command); err != nil { return err } return vm.AddProcess(container, terminal, command, []string{}, "/", tty) } func (vm *Vm) AddProcess(container string, terminal bool, args []string, env []string, workdir string, tty *TtyIO) error { envs := []VmEnvironmentVar{} for _, v := range env { if eqlIndex := strings.Index(v, "="); eqlIndex > 0 { envs = append(envs, VmEnvironmentVar{ Env: v[:eqlIndex], Value: v[eqlIndex+1:], }) } } execCmd := &ExecCommand{ TtyIO: tty, Container: container, Process: VmProcess{ Terminal: terminal, Args: args, Envs: envs, Workdir: workdir, }, } Status, err := vm.GetResponseChan() if err != nil { return nil } defer vm.ReleaseResponseChan(Status) vm.Hub <- execCmd for { Response, ok := <-Status if !ok { return fmt.Errorf("exec command %v failed: get response failed", args) } glog.V(1).Infof("Got response: %d: %s", Response.Code, Response.Cause) if Response.Reply == execCmd { if Response.Cause != "" { return fmt.Errorf("exec command %v failed: %s", args, Response.Cause) } break } } return execCmd.WaitForFinish() } func (vm *Vm) NewContainer(c *pod.UserContainer, info *ContainerInfo) error { newContainerCommand := &NewContainerCommand{ container: c, info: info, } vm.Hub <- newContainerCommand return nil } func (vm *Vm) Tty(tag string, row, column int) error { var ttySizeCommand = &WindowSizeCommand{ ClientTag: tag, Size: &WindowSize{Row: uint16(row), Column: uint16(column)}, } vm.Hub <- ttySizeCommand return nil } func (vm *Vm) Stats() *types.VmResponse { var response *types.VmResponse if nil == vm.Pod || vm.Pod.Status != types.S_POD_RUNNING { return errorResponse("The pod is not running, can not get stats for it") } Status, err := vm.GetResponseChan() if err != nil { return errorResponse(err.Error()) } defer vm.ReleaseResponseChan(Status) getPodStatsEvent := &GetPodStatsCommand{ Id: vm.Id, } vm.Hub <- getPodStatsEvent // wait for the VM response for { response = <-Status glog.V(1).Infof("Got response, Code %d, VM id %s!", response.Code, response.VmId) if response.Reply != getPodStatsEvent { continue } if response.VmId == vm.Id { break } } return response } func (vm *Vm) Pause(pause bool) error { pauseCmd := &PauseCommand{Pause: pause} command := "pause" if !pause { command = "unpause" } Status, err := vm.GetResponseChan() if err != nil { return nil } defer vm.ReleaseResponseChan(Status) vm.Hub <- pauseCmd for { Response, ok := <-Status if !ok { return fmt.Errorf("%s failed: get response failed", command) } glog.V(1).Infof("Got response: %d: %s", Response.Code, Response.Cause) if Response.Reply == pauseCmd { if Response.Cause != "" { return fmt.Errorf("%s failed: %s", command, Response.Cause) } break } } return nil } func (vm *Vm) Save(path string) error { res := vm.SendGenericOperation("Save", func(ctx *VmContext, result chan<- error) { if ctx.Paused { ctx.DCtx.Save(ctx, path, result) } else { result <- fmt.Errorf("the vm should paused on non-live Save()") } }, StateInit, StateRunning) err := <-res return err } func (vm *Vm) SendGenericOperation(name string, op func(ctx *VmContext, result chan<- error), states ...string) <-chan error { result := make(chan error, 1) goe := &GenericOperation{ OpName: name, State: states, OpFunc: op, Result: result, } vm.Hub <- goe return result } func errorResponse(cause string) *types.VmResponse { return &types.VmResponse{ Code: -1, Cause: cause, Data: nil, } } func NewVm(vmId string, cpu, memory int, lazy bool) *Vm { return &Vm{ Id: vmId, Pod: nil, Lazy: lazy, Status: types.S_VM_IDLE, Cpu: cpu, Mem: memory, } } func GetVm(vmId string, b *BootConfig, waitStarted, lazy bool) (vm *Vm, err error) { id := vmId if id == "" { for { id = fmt.Sprintf("vm-%s", pod.RandStr(10, "alpha")) if _, err = os.Stat(BaseDir + "/" + id); os.IsNotExist(err) { break } } } vm = NewVm(id, b.CPU, b.Memory, lazy) if err = vm.Launch(b); err != nil { return nil, err } if waitStarted { // wait init connected Status, err := vm.GetResponseChan() if err != nil { vm.Kill() return nil, err } defer vm.ReleaseResponseChan(Status) for { vmResponse, ok := <-Status if !ok || vmResponse.Code == types.E_VM_RUNNING { break } } } return vm, nil } <file_sep>package hypervisor import ( "github.com/golang/glog" "github.com/hyperhq/runv/hypervisor/network" "github.com/hyperhq/runv/hypervisor/types" "sync" ) func (ctx *VmContext) startSocks() { go waitInitReady(ctx) go waitPts(ctx) if glog.V(1) { go waitConsoleOutput(ctx) } } func (ctx *VmContext) loop() { for ctx.handler != nil { ev, ok := <-ctx.Hub if !ok { glog.Error("hub chan has already been closed") break } else if ev == nil { glog.V(1).Info("got nil event.") continue } glog.V(1).Infof("main event loop got message %d(%s)", ev.Event(), EventString(ev.Event())) ctx.handler(ctx, ev) } } func VmLoop(vmId string, hub chan VmEvent, client chan *types.VmResponse, boot *BootConfig) { context, err := InitContext(vmId, hub, client, nil, boot) if err != nil { client <- &types.VmResponse{ VmId: vmId, Code: types.E_BAD_REQUEST, Cause: err.Error(), } return } //launch routines context.startSocks() context.DCtx.Launch(context) context.loop() } func VmAssociate(vmId string, hub chan VmEvent, client chan *types.VmResponse, wg *sync.WaitGroup, pack []byte) { if glog.V(1) { glog.Infof("VM %s trying to reload with serialized data: %s", vmId, string(pack)) } pinfo, err := vmDeserialize(pack) if err != nil { client <- &types.VmResponse{ VmId: vmId, Code: types.E_BAD_REQUEST, Cause: err.Error(), } return } if pinfo.Id != vmId { client <- &types.VmResponse{ VmId: vmId, Code: types.E_BAD_REQUEST, Cause: "VM ID mismatch", } return } context, err := pinfo.vmContext(hub, client, wg) if err != nil { client <- &types.VmResponse{ VmId: vmId, Code: types.E_BAD_REQUEST, Cause: err.Error(), } return } client <- &types.VmResponse{ VmId: vmId, Code: types.E_OK, } context.DCtx.Associate(context) go waitPts(context) go connectToInit(context) if glog.V(1) { go waitConsoleOutput(context) } context.Become(stateRunning, StateRunning) for _, c := range context.vmSpec.Containers { context.ptys.startStdin(c.Process.Stdio, c.Process.Terminal) } go context.loop() } func InitNetwork(bIface, bIP string, disableIptables bool) error { if HDriver.BuildinNetwork() { return HDriver.InitNetwork(bIface, bIP, disableIptables) } return network.InitNetwork(bIface, bIP, disableIptables) } func SupportLazyMode() bool { return HDriver.SupportLazyMode() } <file_sep>package hypervisor import ( "encoding/json" "github.com/hyperhq/runv/hypervisor/pod" "testing" ) func TestInitContext(t *testing.T) { dr := &EmptyDriver{} dr.Initialize() b := &BootConfig{ CPU: 3, Memory: 202, Kernel: "somekernel", Initrd: "someinitrd", } ctx, _ := InitContext(dr, "vmid", nil, nil, nil, b) if ctx.Id != "vmid" { t.Error("id should be vmid, but is ", ctx.Id) } if ctx.Boot.CPU != 3 { t.Error("cpu should be 3, but is ", string(ctx.Boot.CPU)) } if ctx.Boot.Memory != 202 { t.Error("memory should be 202, but is ", string(ctx.Boot.Memory)) } t.Log("id check finished.") ctx.Close() } func TestParseSpec(t *testing.T) { dr := &EmptyDriver{} dr.Initialize() b := &BootConfig{ CPU: 1, Memory: 128, Kernel: "somekernel", Initrd: "someinitrd", } cs := []*ContainerInfo{ {}, } ctx, _ := InitContext(dr, "vmid", nil, nil, nil, b) spec := pod.UserPod{} err := json.Unmarshal([]byte(testJson("basic")), &spec) if err != nil { t.Error("parse json failed ", err.Error()) } ctx.InitDeviceContext(&spec, cs, nil) if ctx.userSpec != &spec { t.Error("user pod assignment fail") } if len(ctx.vmSpec.Containers) != 1 { t.Error("wrong containers in vm spec") } if ctx.vmSpec.ShareDir != "share_dir" { t.Error("shareDir in vmSpec is ", ctx.vmSpec.ShareDir) } if ctx.vmSpec.Containers[0].RestartPolicy != "never" { t.Error("Default restartPolicy is ", ctx.vmSpec.Containers[0].RestartPolicy) } if ctx.vmSpec.Containers[0].Process.Envs[1].Env != "JAVA_HOME" { t.Error("second environment should not be ", ctx.vmSpec.Containers[0].Process.Envs[1].Env) } res, err := json.MarshalIndent(*ctx.vmSpec, " ", " ") if err != nil { t.Error("vmspec to json failed") } t.Log(string(res)) } func TestParseVolumes(t *testing.T) { dr := &EmptyDriver{} dr.Initialize() b := &BootConfig{ CPU: 1, Memory: 128, Kernel: "somekernel", Initrd: "someinitrd", } ctx, _ := InitContext(dr, "vmid", nil, nil, nil, b) spec := pod.UserPod{} err := json.Unmarshal([]byte(testJson("with_volumes")), &spec) if err != nil { t.Error("parse json failed ", err.Error()) } cs := []*ContainerInfo{ {}, } ctx.InitDeviceContext(&spec, cs, nil) res, err := json.MarshalIndent(*ctx.vmSpec, " ", " ") if err != nil { t.Error("vmspec to json failed") } t.Log(string(res)) vol1 := ctx.devices.volumeMap["vol1"] if vol1.pos[0] != "/var/dir1" { t.Error("vol1 (/var/dir1) path is ", vol1.pos[0]) } if !vol1.readOnly[0] { t.Error("vol1 on container 0 should be read only") } ref1 := BlockDescriptor{Name: "vol1", Filename: "", Format: "", Fstype: "", DeviceName: ""} if *vol1.info != ref1 { t.Errorf("info of vol1: %q %q %q %q %q", vol1.info.Name, vol1.info.Filename, vol1.info.Format, vol1.info.Fstype, vol1.info.DeviceName) } vol2 := ctx.devices.volumeMap["vol2"] if vol2.pos[0] != "/var/dir2" { t.Error("vol1 (/var/dir2) path is ", vol2.pos[0]) } if vol2.readOnly[0] { t.Error("vol2 on container 0 should not be read only") } ref2 := BlockDescriptor{Name: "vol2", Filename: "/home/whatever", Format: "vfs", Fstype: "dir", DeviceName: ""} if *vol2.info != ref2 { t.Errorf("info of vol2: %q %q %q %q %q", vol2.info.Name, vol2.info.Filename, vol2.info.Format, vol2.info.Fstype, vol2.info.DeviceName) } } func testJson(key string) string { jsons := make(map[string]string) jsons["basic"] = `{ "name": "hostname", "containers" : [{ "image": "nginx:latest", "files": [{ "path": "/var/lib/xxx/xxxx", "filename": "filename" }], "envs": [{ "env": "JAVA_OPT", "value": "-XMx=256m" },{ "env": "JAVA_HOME", "value": "/usr/local/java" }] }], "resource": { "vcpu": 1, "memory": 128 }, "files": [{ "name": "filename", "encoding": "raw", "uri": "https://s3.amazonaws/bucket/file.conf", "content": "" }], "volumes": []}` jsons["with_volumes"] = `{ "name": "hostname", "containers" : [{ "image": "nginx:latest", "files": [{ "path": "/var/lib/xxx/xxxx", "filename": "filename" }], "volumes": [{ "path": "/var/dir1", "volume": "vol1", "readOnly": true },{ "path": "/var/dir2", "volume": "vol2", "readOnly": false },{ "path": "/var/dir3", "volume": "vol3", "readOnly": false },{ "path": "/var/dir4", "volume": "vol4", "readOnly": false },{ "path": "/var/dir5", "volume": "vol5", "readOnly": false },{ "path": "/var/dir6", "volume": "vol6", "readOnly": false }] }], "resource": { "vcpu": 1, "memory": 128 }, "files": [], "volumes": [{ "name": "vol1", "source": "", "driver": "" },{ "name": "vol2", "source": "/home/whatever", "driver": "vfs" },{ "name": "vol3", "source": "/home/what/file", "driver": "raw" },{ "name": "vol4", "source": "", "driver": "" },{ "name": "vol5", "source": "/home/what/file2", "driver": "vfs" },{ "name": "vol6", "source": "/home/what/file3", "driver": "qcow2" }] }` return jsons[key] } <file_sep>package supervisor import ( "fmt" "io" "os" "syscall" "github.com/golang/glog" "github.com/hyperhq/runv/hypervisor" "github.com/hyperhq/runv/hypervisor/types" "github.com/opencontainers/runtime-spec/specs-go" ) type Process struct { Id string Stdin string Stdout string Stderr string Spec *specs.Process ProcId int // inerId is Id or container id + "-init" // pass to hypervisor package and HyperPod.Processes inerId string ownerCont *Container init bool stdio *hypervisor.TtyIO stdinCloser io.Closer } func (p *Process) setupIO() error { glog.Infof("process setupIO: stdin %s, stdout %s, stderr %s", p.Stdin, p.Stdout, p.Stderr) // use a new go routine to avoid deadlock when stdin is fifo go func() { if stdinCloser, err := os.OpenFile(p.Stdin, syscall.O_WRONLY, 0); err == nil { p.stdinCloser = stdinCloser } }() stdin, err := os.OpenFile(p.Stdin, syscall.O_RDONLY, 0) if err != nil { return err } stdout, err := os.OpenFile(p.Stdout, syscall.O_RDWR, 0) if err != nil { return err } // TODO: setup stderr if p.Spec.Terminal { } p.stdio = &hypervisor.TtyIO{ ClientTag: p.inerId, Stdin: stdin, Stdout: stdout, Callback: make(chan *types.VmResponse, 1), } glog.Infof("process setupIO() success") return nil } func (p *Process) ttyResize(width, height int) error { return p.ownerCont.ownerPod.vm.Tty(p.inerId, height, width) } func (p *Process) closeStdin() error { var err error if p.stdinCloser != nil { err = p.stdinCloser.Close() p.stdinCloser = nil } return err } func (p *Process) signal(sig int) error { if p.init { // TODO: change vm.KillContainer() return p.ownerCont.ownerPod.vm.KillContainer(p.ownerCont.Id, syscall.Signal(sig)) } else { // TODO support it return fmt.Errorf("Kill to non-init process of container is unsupported") } } func (p *Process) reap() { p.closeStdin() } <file_sep>package hypervisor import ( "encoding/json" "github.com/golang/glog" "github.com/hyperhq/runv/hypervisor/pod" "github.com/hyperhq/runv/hypervisor/types" "os" "sync" "time" ) type VmHwStatus struct { PciAddr int //next available pci addr for pci hotplug ScsiId int //next available scsi id for scsi hotplug AttachId uint64 //next available attachId for attached tty } type VmContext struct { Id string Paused bool Boot *BootConfig // Communication Context Hub chan VmEvent client chan *types.VmResponse vm chan *DecodedMessage DCtx DriverContext HomeDir string HyperSockName string TtySockName string ConsoleSockName string ShareDir string pciAddr int //next available pci addr for pci hotplug scsiId int //next available scsi id for scsi hotplug InterfaceCount int ptys *pseudoTtys // Specification userSpec *pod.UserPod vmSpec *VmPod devices *deviceMap progress *processingList // Internal Helper handler stateHandler current string timer *time.Timer lock *sync.Mutex //protect update of context wg *sync.WaitGroup wait bool } type stateHandler func(ctx *VmContext, event VmEvent) func InitContext(id string, hub chan VmEvent, client chan *types.VmResponse, dc DriverContext, boot *BootConfig) (*VmContext, error) { var err error = nil vmChannel := make(chan *DecodedMessage, 128) //dir and sockets: homeDir := BaseDir + "/" + id + "/" hyperSockName := homeDir + HyperSockName ttySockName := homeDir + TtySockName consoleSockName := homeDir + ConsoleSockName shareDir := homeDir + ShareDirTag if dc == nil { dc = HDriver.InitContext(homeDir) } err = os.MkdirAll(shareDir, 0755) if err != nil { glog.Error("cannot make dir", shareDir, err.Error()) return nil, err } defer func() { if err != nil { os.Remove(homeDir) } }() return &VmContext{ Id: id, Boot: boot, Paused: false, pciAddr: PciAddrFrom, scsiId: 0, Hub: hub, client: client, DCtx: dc, vm: vmChannel, ptys: newPts(), HomeDir: homeDir, HyperSockName: hyperSockName, TtySockName: ttySockName, ConsoleSockName: consoleSockName, ShareDir: shareDir, InterfaceCount: InterfaceCount, timer: nil, handler: stateInit, current: StateInit, userSpec: nil, vmSpec: nil, devices: newDeviceMap(), progress: newProcessingList(), lock: &sync.Mutex{}, wait: false, }, nil } func (ctx *VmContext) setTimeout(seconds int) { if ctx.timer != nil { ctx.unsetTimeout() } ctx.timer = time.AfterFunc(time.Duration(seconds)*time.Second, func() { ctx.Hub <- &VmTimeout{} }) } func (ctx *VmContext) unsetTimeout() { if ctx.timer != nil { ctx.timer.Stop() ctx.timer = nil } } func (ctx *VmContext) reset() { ctx.lock.Lock() ctx.ptys.closePendingTtys() ctx.pciAddr = PciAddrFrom ctx.scsiId = 0 //do not reset attach id here, let it increase ctx.userSpec = nil ctx.vmSpec = nil ctx.devices = newDeviceMap() ctx.progress = newProcessingList() ctx.lock.Unlock() } func (ctx *VmContext) nextScsiId() int { ctx.lock.Lock() id := ctx.scsiId ctx.scsiId++ ctx.lock.Unlock() return id } func (ctx *VmContext) nextPciAddr() int { ctx.lock.Lock() addr := ctx.pciAddr ctx.pciAddr++ ctx.lock.Unlock() return addr } func (ctx *VmContext) Lookup(container string) int { if container == "" || ctx.vmSpec == nil { return -1 } for idx, c := range ctx.vmSpec.Containers { if c.Id == container { glog.V(1).Infof("found container %s at %d", container, idx) return idx } } glog.V(1).Infof("can not found container %s", container) return -1 } func (ctx *VmContext) Close() { ctx.lock.Lock() defer ctx.lock.Unlock() ctx.ptys.closePendingTtys() ctx.unsetTimeout() ctx.DCtx.Close() close(ctx.vm) close(ctx.client) os.Remove(ctx.ShareDir) ctx.handler = nil ctx.current = "None" } func (ctx *VmContext) tryClose() bool { if ctx.deviceReady() { glog.V(1).Info("no more device to release/remove/umount, quit") ctx.Close() return true } return false } func (ctx *VmContext) Become(handler stateHandler, desc string) { orig := ctx.current ctx.lock.Lock() ctx.handler = handler ctx.current = desc ctx.lock.Unlock() glog.V(1).Infof("VM %s: state change from %s to '%s'", ctx.Id, orig, desc) } // InitDeviceContext will init device info in context func (ctx *VmContext) InitDeviceContext(spec *pod.UserPod, wg *sync.WaitGroup, cInfo []*ContainerInfo, vInfo map[string]*VolumeInfo) { ctx.lock.Lock() defer ctx.lock.Unlock() /* Update interface count accourding to user pod */ ret := len(spec.Interfaces) if ret != 0 { ctx.InterfaceCount = ret } for i := 0; i < ctx.InterfaceCount; i++ { ctx.progress.adding.networks[i] = true } if cInfo == nil { cInfo = []*ContainerInfo{} } if vInfo == nil { vInfo = make(map[string]*VolumeInfo) } ctx.initVolumeMap(spec) if glog.V(3) { for i, c := range cInfo { glog.Infof("#%d Container Info:", i) b, err := json.MarshalIndent(c, "...|", " ") if err == nil { glog.Info("\n", string(b)) } } } containers := make([]VmContainer, len(spec.Containers)) for i, container := range spec.Containers { ctx.initContainerInfo(i, &containers[i], &container) ctx.setContainerInfo(i, &containers[i], cInfo[i]) containers[i].Process.Stdio = ctx.ptys.attachId ctx.ptys.attachId++ if !container.Tty { containers[i].Process.Stderr = ctx.ptys.attachId ctx.ptys.attachId++ } } hostname := spec.Hostname if len(hostname) == 0 { hostname = spec.Name } if len(hostname) > 64 { hostname = spec.Name[:64] } ctx.vmSpec = &VmPod{ Hostname: hostname, Containers: containers, Dns: spec.Dns, Interfaces: nil, Routes: nil, ShareDir: ShareDirTag, } for _, vol := range vInfo { ctx.setVolumeInfo(vol) } ctx.userSpec = spec ctx.wg = wg } <file_sep>package client import ( "strings" "fmt" "net/url" "github.com/hyperhq/hyper/engine" gflag "github.com/jessevdk/go-flags" ) func (cli *HyperClient) HyperCmdMigrate(args ...string) error { var opts struct { Ip string `short:"i" long:"ip" default:"127.0.0.1" value-name:"127.0.0.1" description:"destination vm's ip"` Port string `short:"p" long:"port" default:"12345" value-name:"12345" description:"destination vm's port"` } var parser = gflag.NewParser(&opts,gflag.Default) parser.Usage = "migrate [-i 127.0.0.1 -p 12345]| POD_ID \n\nMigrate a 'running' pod" args,err := parser.Parse() if err != nil { if !strings.Contains(err.Error(),"Usage") { return err } else { return nil } } if len(args) == 1 { return fmt.Errorf("\"migrate\" requires a minimum of 1 argument, please provide POD ID.\n") } podId := args[1] ip := opts.Ip port := opts.Port _,_,err = cli.MigratePod(podId, ip, port) if err != nil { return err } fmt.Printf("The POD is: %s! migrate command executed successfully\n",podId) return nil } func (cli *HyperClient) MigratePod(podId string, ip string, port string) (int, string, error) { v := url.Values{} v.Set("podId",podId) v.Set("ip",ip) v.Set("port",port) body,_,err := readBody(cli.call("POST","/pod/migrate?"+v.Encode(),nil,nil)) if err != nil { if strings.Contains(err.Error(),"leveldb: not found") { return -1,"",fmt.Errorf("Can not find that POD ID to migrate, please check your POD ID!") } return -1, "", err } out := engine.NewOutput() remoteInfo,err := out.AddEnv() if err != nil { return -1, "", err } if _, err := out.Write(body); err != nil { return -1, "", err } out.Close() // This 'ID' stands for pod ID // This 'Code' ... // This 'Cause' .. if remoteInfo.Exists("ID") { // TODO ... } return remoteInfo.GetInt("Code"), remoteInfo.Get("Cause"),nil } func (cli *HyperClient) HyperCmdListen(args ...string) error { var opts struct { Ip string `short:"i" long:"ip" default:"0.0.0.0" value-name:"0" description:"destination vm's ip"` Port string `short:"p" long:"port" default:"12345" value-name:"12345" description:"destination vm's port"` } var parser = gflag.NewParser(&opts,gflag.Default) parser.Usage = "migrate [-i 0 -p 12345]| POD_ID \n\nMigrate a 'running' pod" args,err := parser.Parse() if err != nil { if !strings.Contains(err.Error(),"Usage") { return err } else { return nil } } ip := opts.Ip port := opts.Port _,_,err = cli.ListenPod(ip, port) if err != nil { return err } fmt.Printf("Now listening successfully!\n") return nil } func (cli *HyperClient) ListenPod(ip, port string) (int, string, error) { v := url.Values{} v.Set("ip",ip) v.Set("port",port) body,_,err := readBody(cli.call("POST","/pod/listen?"+v.Encode(),nil,nil)) if err != nil { if strings.Contains(err.Error(),"leveldb: not found") { return -1,"",fmt.Errorf("Can not find that POD ID to migrate, please check your POD ID!") } return -1, "", err } out := engine.NewOutput() remoteInfo,err := out.AddEnv() if err != nil { return -1, "", err } if _, err := out.Write(body); err != nil { return -1, "", err } out.Close() // This 'ID' stands for pod ID // This 'Code' ... // This 'Cause' .. if remoteInfo.Exists("ID") { // TODO ... } return remoteInfo.GetInt("Code"), remoteInfo.Get("Cause"),nil }<file_sep>package hypervisor import ( "sync" "time" "github.com/docker/docker/daemon/logger" "github.com/golang/glog" "github.com/hyperhq/runv/hypervisor/pod" "github.com/hyperhq/runv/hypervisor/types" ) //change first letter to uppercase and add json tag (thanks GNU sed): // gsed -ie 's/^ \([a-z]\)\([a-zA-Z]*\)\( \{1,\}[^ ]\{1,\}.*\)$/ \U\1\E\2\3 `json:"\1\2"`/' pod.go type HandleEvent struct { Handle func(*types.VmResponse, interface{}, *PodStatus, *Vm) bool Data interface{} } type PodStatus struct { Id string Name string Vm string Wg *sync.WaitGroup Containers []*Container Status uint Type string RestartPolicy string Autoremove bool Handler HandleEvent StartedAt string FinishedAt string ResourcePath string } type Container struct { Id string Name string PodId string Image string Cmds []string Logs LogStatus Status uint32 ExitCode int } type LogStatus struct { Copier *logger.Copier Driver logger.Logger LogPath string } // Vm DataStructure type VmVolumeDescriptor struct { Device string `json:"device"` Addr string `json:"addr,omitempty"` Mount string `json:"mount"` Fstype string `json:"fstype,omitempty"` ReadOnly bool `json:"readOnly"` DockerVolume bool `json:"dockerVolume"` } type VmFsmapDescriptor struct { Source string `json:"source"` Path string `json:"path"` ReadOnly bool `json:"readOnly"` DockerVolume bool `json:"dockerVolume"` } type VmEnvironmentVar struct { Env string `json:"env"` Value string `json:"value"` } type VmProcess struct { // Terminal creates an interactive terminal for the process. Terminal bool `json:"terminal"` // Sequeue number for stdin and stdout Stdio uint64 `json:"stdio,omitempty"` // sequeue number for stderr if it is not shared with stdout Stderr uint64 `json:"stderr,omitempty"` // Args specifies the binary and arguments for the application to execute. Args []string `json:"args"` // Envs populates the process environment for the process. Envs []VmEnvironmentVar `json:"envs,omitempty"` // Workdir is the current working directory for the process and must be // relative to the container's root. Workdir string `json:"workdir"` } type VmContainer struct { Id string `json:"id"` Rootfs string `json:"rootfs"` Fstype string `json:"fstype,omitempty"` Image string `json:"image"` Addr string `json:"addr,omitempty"` Volumes []VmVolumeDescriptor `json:"volumes,omitempty"` Fsmap []VmFsmapDescriptor `json:"fsmap,omitempty"` Sysctl map[string]string `json:"sysctl,omitempty"` Process VmProcess `json:"process"` Entrypoint []string `json:"-"` RestartPolicy string `json:"restartPolicy"` Initialize bool `json:"initialize"` } type VmNetworkInf struct { Device string `json:"device"` IpAddress string `json:"ipAddress"` NetMask string `json:"netMask"` } type VmRoute struct { Dest string `json:"dest"` Gateway string `json:"gateway,omitempty"` Device string `json:"device,omitempty"` } type VmPod struct { Hostname string `json:"hostname"` Containers []VmContainer `json:"containers"` Interfaces []VmNetworkInf `json:"interfaces,omitempty"` Dns []string `json:"dns,omitempty"` Routes []VmRoute `json:"routes,omitempty"` ShareDir string `json:"shareDir"` } type RunningContainer struct { Id string `json:"id"` } type PreparingItem interface { ItemType() string } func (mypod *PodStatus) SetPodContainerStatus(data []uint32) { failure := 0 for i, c := range mypod.Containers { if data[i] != 0 { failure++ c.Status = types.S_POD_FAILED } else { c.Status = types.S_POD_SUCCEEDED } c.ExitCode = int(data[i]) } if failure == 0 { mypod.Status = types.S_POD_SUCCEEDED } else { mypod.Status = types.S_POD_FAILED } mypod.FinishedAt = time.Now().Format("2006-01-02T15:04:05Z") } func (mypod *PodStatus) SetContainerStatus(status uint32) { for _, c := range mypod.Containers { c.Status = status } } func (mypod *PodStatus) AddContainer(containerId, name, image string, cmds []string, status uint32) { container := &Container{ Id: containerId, Name: name, PodId: mypod.Id, Image: image, Cmds: cmds, Status: status, } mypod.Containers = append(mypod.Containers, container) } func (mypod *PodStatus) GetPodIP(vm *Vm) []string { if mypod.Vm == "" { return nil } var response *types.VmResponse Status, err := vm.GetResponseChan() if err != nil { return nil } defer vm.ReleaseResponseChan(Status) getPodIPEvent := &GetPodIPCommand{ Id: mypod.Vm, } vm.Hub <- getPodIPEvent // wait for the VM response for { response = <-Status glog.V(1).Infof("Got response, Code %d, VM id %s!", response.Code, response.VmId) if response.Reply != getPodIPEvent { continue } if response.VmId == vm.Id { break } } if response.Data == nil { return []string{} } return response.Data.([]string) } func NewPod(podId string, userPod *pod.UserPod) *PodStatus { return &PodStatus{ Id: podId, Name: userPod.Name, Vm: "", Wg: new(sync.WaitGroup), Status: types.S_POD_CREATED, Type: userPod.Type, RestartPolicy: userPod.RestartPolicy, Autoremove: false, Handler: HandleEvent{ Handle: defaultHandlePodEvent, Data: nil, }, } } <file_sep>export GOPATH:=$(abs_top_srcdir)/Godeps/_workspace:$(GOPATH) if WITH_XEN XEN_BUILD_TAG=with_xen else XEN_BUILD_TAG= endif if WITH_LIBVIRT LIBVIRT_BUILD_TAG=with_libvirt else LIBVIRT_BUILD_TAG= endif HYPER_BULD_TAGS=$(XEN_BUILD_TAG) $(LIBVIRT_BUILD_TAG) all-local: build-runv clean-local: -rm -f runv -rm -f Godeps/_workspace/src/github.com/opencontainers/specs/config-linux.go Godeps/_workspace/src/github.com/opencontainers/specs/runtime-config-linux.go install-exec-local: $(INSTALL_PROGRAM) runv $(bindir) # supporting linux container on non-linux platform (copy for catering to go build) if ON_LINUX linux_container: Godeps/_workspace/src/github.com/opencontainers/specs/config_linux.go Godeps/_workspace/src/github.com/opencontainers/specs/runtime_config_linux.go else linux_container: Godeps/_workspace/src/github.com/opencontainers/specs/config-linux.go Godeps/_workspace/src/github.com/opencontainers/specs/runtime-config-linux.go Godeps/_workspace/src/github.com/opencontainers/specs/config-linux.go: cp Godeps/_workspace/src/github.com/opencontainers/specs/config_linux.go Godeps/_workspace/src/github.com/opencontainers/specs/config-linux.go Godeps/_workspace/src/github.com/opencontainers/specs/runtime-config-linux.go: cp Godeps/_workspace/src/github.com/opencontainers/specs/runtime_config_linux.go Godeps/_workspace/src/github.com/opencontainers/specs/runtime-config-linux.go endif build-runv: linux_container go build -tags "static_build $(HYPER_BULD_TAGS)" -o runv . <file_sep>package supervisor import ( "fmt" "os" "path/filepath" "github.com/golang/glog" "github.com/hyperhq/runv/factory" "github.com/hyperhq/runv/hypervisor" "github.com/hyperhq/runv/hypervisor/pod" "github.com/opencontainers/runtime-spec/specs-go" ) type HyperPod struct { Containers map[string]*Container Processes map[string]*Process userPod *pod.UserPod podStatus *hypervisor.PodStatus vm *hypervisor.Vm sv *Supervisor } func (hp *HyperPod) createContainer(container, bundlePath, stdin, stdout, stderr string, spec *specs.Spec) (*Container, error) { inerProcessId := container + "-init" if _, ok := hp.Processes[inerProcessId]; ok { return nil, fmt.Errorf("The process id: %s is in used", inerProcessId) } glog.Infof("createContainer()") c := &Container{ Id: container, BundlePath: bundlePath, Spec: spec, Processes: make(map[string]*Process), ownerPod: hp, } p := &Process{ Id: "init", Stdin: stdin, Stdout: stdout, Stderr: stderr, Spec: &spec.Process, ProcId: -1, inerId: inerProcessId, ownerCont: c, init: true, } err := p.setupIO() if err != nil { return nil, err } glog.Infof("createContainer()") c.Processes["init"] = p c.ownerPod.Processes[inerProcessId] = p c.ownerPod.Containers[container] = c glog.Infof("createContainer() calls c.start(p)") c.start(p) return c, nil } func createHyperPod(f factory.Factory, spec *specs.Spec) (*HyperPod, error) { podId := fmt.Sprintf("pod-%s", pod.RandStr(10, "alpha")) userPod := pod.ConvertOCF2PureUserPod(spec) podStatus := hypervisor.NewPod(podId, userPod) cpu := 1 if userPod.Resource.Vcpu > 0 { cpu = userPod.Resource.Vcpu } mem := 128 if userPod.Resource.Memory > 0 { mem = userPod.Resource.Memory } vm, err := f.GetVm(cpu, mem) if err != nil { glog.V(1).Infof("%s\n", err.Error()) return nil, err } Response := vm.StartPod(podStatus, userPod, nil, nil) if Response.Data == nil { glog.V(1).Infof("StartPod fail: QEMU response data is nil\n") return nil, fmt.Errorf("StartPod fail") } glog.V(1).Infof("result: code %d %s\n", Response.Code, Response.Cause) return &HyperPod{ userPod: userPod, podStatus: podStatus, vm: vm, Containers: make(map[string]*Container), Processes: make(map[string]*Process), }, nil } func (hp *HyperPod) reap() { Response := hp.vm.StopPod(hp.podStatus, "yes") if Response.Data == nil { glog.V(1).Infof("StopPod fail: QEMU response data is nil\n") return } glog.V(1).Infof("result: code %d %s\n", Response.Code, Response.Cause) os.RemoveAll(filepath.Join(hypervisor.BaseDir, hp.vm.Id)) } <file_sep>package hypervisor import ( "encoding/binary" "fmt" "io" "net" "sync" "github.com/golang/glog" "github.com/hyperhq/runv/hypervisor/types" "github.com/hyperhq/runv/lib/term" "github.com/hyperhq/runv/lib/utils" ) type WindowSize struct { Row uint16 `json:"row"` Column uint16 `json:"column"` } type TtyIO struct { Stdin io.ReadCloser Stdout io.WriteCloser ClientTag string Callback chan *types.VmResponse ExitCode uint8 } func (tty *TtyIO) WaitForFinish() error { tty.ExitCode = 255 Response, ok := <-tty.Callback if !ok { return fmt.Errorf("get response failed") } glog.V(1).Infof("Got response: %d: %s", Response.Code, Response.Cause) if Response.Code == types.E_EXEC_FINISH { tty.ExitCode = Response.Data.(uint8) glog.V(1).Infof("Exit code %d", tty.ExitCode) } close(tty.Callback) return nil } type ttyAttachments struct { persistent bool started bool closed bool tty bool attachments []*TtyIO } type pseudoTtys struct { attachId uint64 //next available attachId for attached tty channel chan *ttyMessage ttys map[uint64]*ttyAttachments ttySessions map[string]uint64 pendingTtys []*AttachCommand lock *sync.Mutex } type ttyMessage struct { session uint64 message []byte } func (tm *ttyMessage) toBuffer() []byte { length := len(tm.message) + 12 buf := make([]byte, length) binary.BigEndian.PutUint64(buf[:8], tm.session) binary.BigEndian.PutUint32(buf[8:12], uint32(length)) copy(buf[12:], tm.message) return buf } func newPts() *pseudoTtys { return &pseudoTtys{ attachId: 1, channel: make(chan *ttyMessage, 256), ttys: make(map[uint64]*ttyAttachments), ttySessions: make(map[string]uint64), pendingTtys: []*AttachCommand{}, lock: &sync.Mutex{}, } } func readTtyMessage(conn *net.UnixConn) (*ttyMessage, error) { needRead := 12 length := 0 read := 0 buf := make([]byte, 512) res := []byte{} for read < needRead { want := needRead - read if want > 512 { want = 512 } glog.V(1).Infof("tty: trying to read %d bytes", want) nr, err := conn.Read(buf[:want]) if err != nil { glog.Error("read tty data failed") return nil, err } res = append(res, buf[:nr]...) read = read + nr glog.V(1).Infof("tty: read %d/%d [length = %d]", read, needRead, length) if length == 0 && read >= 12 { length = int(binary.BigEndian.Uint32(res[8:12])) glog.V(1).Infof("data length is %d", length) if length > 12 { needRead = length } } } return &ttyMessage{ session: binary.BigEndian.Uint64(res[:8]), message: res[12:], }, nil } func waitTtyMessage(ctx *VmContext, conn *net.UnixConn) { for { msg, ok := <-ctx.ptys.channel if !ok { glog.V(1).Info("tty chan closed, quit sent goroutine") break } glog.V(3).Infof("trying to write to session %d", msg.session) if _, ok := ctx.ptys.ttys[msg.session]; ok { _, err := conn.Write(msg.toBuffer()) if err != nil { glog.V(1).Info("Cannot write to tty socket: ", err.Error()) return } } } } func waitPts(ctx *VmContext) { conn, err := utils.UnixSocketConnect(ctx.TtySockName) if err != nil { glog.Error("Cannot connect to tty socket ", err.Error()) ctx.Hub <- &InitFailedEvent{ Reason: "Cannot connect to tty socket " + err.Error(), } return } glog.V(1).Info("tty socket connected") go waitTtyMessage(ctx, conn.(*net.UnixConn)) for { res, err := readTtyMessage(conn.(*net.UnixConn)) if err != nil { glog.V(1).Info("tty socket closed, quit the reading goroutine ", err.Error()) ctx.Hub <- &Interrupted{Reason: "tty socket failed " + err.Error()} close(ctx.ptys.channel) return } if ta, ok := ctx.ptys.ttys[res.session]; ok { if len(res.message) == 0 { glog.V(1).Infof("session %d closed by peer, close pty", res.session) ta.closed = true } else if ta.closed { var code uint8 = 255 if len(res.message) == 1 { code = uint8(res.message[0]) } glog.V(1).Infof("session %d, exit code", res.session, code) ctx.ptys.Close(res.session, code) } else { for _, tty := range ta.attachments { if tty.Stdout != nil { _, err := tty.Stdout.Write(res.message) if err != nil { glog.V(1).Infof("fail to write session %d, close pty attachment", res.session) ctx.ptys.Detach(res.session, tty) } } } } } } } func newAttachmentsWithTty(persist, isTty bool, tty *TtyIO) *ttyAttachments { ta := &ttyAttachments{ persistent: persist, tty: isTty, } if tty != nil { ta.attach(tty) } return ta } func (ta *ttyAttachments) attach(tty *TtyIO) { ta.attachments = append(ta.attachments, tty) } func (ta *ttyAttachments) detach(tty *TtyIO) { at := []*TtyIO{} detached := false for _, t := range ta.attachments { if tty.ClientTag != t.ClientTag { at = append(at, t) } else { detached = true } } if detached { ta.attachments = at } } func (ta *ttyAttachments) close(code uint8) []string { tags := []string{} for _, t := range ta.attachments { tags = append(tags, t.Close(code)) } ta.attachments = []*TtyIO{} return tags } func (ta *ttyAttachments) empty() bool { return len(ta.attachments) == 0 } func (ta *ttyAttachments) isTty() bool { return ta.tty } func (tty *TtyIO) Close(code uint8) string { glog.V(1).Info("Close tty ", tty.ClientTag) if tty.Stdin != nil { tty.Stdin.Close() } if tty.Stdout != nil { tty.Stdout.Close() } if tty.Callback != nil { tty.Callback <- &types.VmResponse{ Code: types.E_EXEC_FINISH, Cause: "Command finished", Data: code, } } return tty.ClientTag } func (pts *pseudoTtys) nextAttachId() uint64 { pts.lock.Lock() id := pts.attachId pts.attachId++ pts.lock.Unlock() return id } func (pts *pseudoTtys) isTty(session uint64) bool { if ta, ok := pts.ttys[session]; ok { return ta.isTty() } return false } func (pts *pseudoTtys) clientReg(tag string, session uint64) { pts.lock.Lock() pts.ttySessions[tag] = session pts.lock.Unlock() } func (pts *pseudoTtys) clientDereg(tag string) { if tag == "" { return } pts.lock.Lock() if _, ok := pts.ttySessions[tag]; ok { delete(pts.ttySessions, tag) } pts.lock.Unlock() } func (pts *pseudoTtys) Detach(session uint64, tty *TtyIO) { if ta, ok := pts.ttys[session]; ok { pts.lock.Lock() ta.detach(tty) pts.lock.Unlock() if !ta.persistent && ta.empty() { pts.Close(session, 0) } pts.clientDereg(tty.Close(0)) } } func (pts *pseudoTtys) Close(session uint64, code uint8) { if ta, ok := pts.ttys[session]; ok { pts.lock.Lock() tags := ta.close(code) delete(pts.ttys, session) pts.lock.Unlock() for _, t := range tags { pts.clientDereg(t) } } } func (pts *pseudoTtys) ptyConnect(persist, isTty bool, session uint64, tty *TtyIO) { pts.lock.Lock() if ta, ok := pts.ttys[session]; ok { ta.attach(tty) } else { pts.ttys[session] = newAttachmentsWithTty(persist, isTty, tty) } pts.connectStdin(session, tty) pts.lock.Unlock() } func (pts *pseudoTtys) startStdin(session uint64, isTty bool) { pts.lock.Lock() ta, ok := pts.ttys[session] if ok { if !ta.started { ta.started = true for _, tty := range ta.attachments { pts.connectStdin(session, tty) } } } else { ta = newAttachmentsWithTty(true, isTty, nil) ta.started = true pts.ttys[session] = ta } pts.lock.Unlock() } // we close the stdin of the container when the last attached // stdin closed. we should move this decision to hyper and use // the same policy as docker(stdinOnce) func (pts *pseudoTtys) isLastStdin(session uint64) bool { var count int pts.lock.Lock() if ta, ok := pts.ttys[session]; ok { for _, tty := range ta.attachments { if tty.Stdin != nil { count++ } } } pts.lock.Unlock() return count == 1 } func (pts *pseudoTtys) connectStdin(session uint64, tty *TtyIO) { if ta, ok := pts.ttys[session]; !ok || !ta.started { return } if tty.Stdin != nil { go func() { buf := make([]byte, 32) keys, _ := term.ToBytes(DetachKeys) isTty := pts.isTty(session) defer func() { recover() }() for { nr, err := tty.Stdin.Read(buf) if nr == 1 && isTty { for i, key := range keys { if nr != 1 || buf[0] != key { break } if i == len(keys)-1 { glog.Info("got stdin detach keys, exit term") pts.Detach(session, tty) return } nr, err = tty.Stdin.Read(buf) } } if err != nil { glog.Info("a stdin closed, ", err.Error()) if err == io.EOF && !isTty && pts.isLastStdin(session) { // send eof to hyperstart glog.V(1).Infof("session %d send eof to hyperstart", session) pts.channel <- &ttyMessage{ session: session, message: make([]byte, 0), } // don't detach, we need the last output of the container } else { pts.Detach(session, tty) } return } glog.V(3).Infof("trying to input char: %d and %d chars", buf[0], nr) mbuf := make([]byte, nr) copy(mbuf, buf[:nr]) pts.channel <- &ttyMessage{ session: session, message: mbuf[:nr], } } }() } return } func (pts *pseudoTtys) closePendingTtys() { for _, tty := range pts.pendingTtys { tty.Streams.Close(255) } pts.pendingTtys = []*AttachCommand{} } func TtyLiner(conn io.Reader, output chan string) { buf := make([]byte, 1) line := []byte{} cr := false emit := false for { nr, err := conn.Read(buf) if err != nil || nr < 1 { glog.V(1).Info("Input byte chan closed, close the output string chan") close(output) return } switch buf[0] { case '\n': emit = !cr cr = false case '\r': emit = true cr = true default: cr = false line = append(line, buf[0]) } if emit { output <- string(line) line = []byte{} emit = false } } } func (vm *Vm) Attach(tty *TtyIO, container string, size *WindowSize) error { attachCommand := &AttachCommand{ Streams: tty, Size: size, Container: container, } vm.Hub <- attachCommand return nil } func (vm *Vm) GetLogOutput(container, tag string, callback chan *types.VmResponse) (io.ReadCloser, io.ReadCloser, error) { stdout, stdoutStub := io.Pipe() stderr, stderrStub := io.Pipe() outIO := &TtyIO{ Stdin: nil, Stdout: stdoutStub, ClientTag: tag, Callback: callback, } errIO := &TtyIO{ Stdin: nil, Stdout: stderrStub, ClientTag: tag, Callback: nil, } cmd := &AttachCommand{ Streams: outIO, Stderr: errIO, Container: container, } vm.Hub <- cmd return stdout, stderr, nil } <file_sep>package qemu import ( "os" "github.com/hyperhq/runv/hypervisor/network" "github.com/hyperhq/runv/hypervisor/pod" ) func (qd *QemuDriver) BuildinNetwork() bool { return false } func (qd *QemuDriver) InitNetwork(bIface, bIP string, disableIptables bool) error { return nil } func (qc *QemuContext) ConfigureNetwork(vmId, requestedIP string, maps []pod.UserContainerPort, config pod.UserInterface) (*network.Settings, error) { return nil, nil } func (qc *QemuContext) AllocateNetwork(vmId, requestedIP string, maps []pod.UserContainerPort) (*network.Settings, error) { return nil, nil } func (qc *QemuContext) ReleaseNetwork(vmId, releasedIP string, maps []pod.UserContainerPort, file *os.File) error { return nil } <file_sep>package main import ( "encoding/json" "fmt" "os" "path/filepath" "strconv" "strings" "github.com/codegangsta/cli" "github.com/opencontainers/runtime-spec/specs-go" ) var execCommand = cli.Command{ Name: "exec", Usage: "exec a new program in runv container", ArgsUsage: `<container-id> <container command> Where "<container-id>" is the name for the instance of the container and "<container command>" is the command to be executed in the container. For example, if the container is configured to run the linux ps command the following will output a list of processes running in the container: # runv exec <container-id> ps`, Flags: []cli.Flag{ cli.StringFlag{ Name: "console", Usage: "[reject on runv] specify the pty slave path for use with the container", }, cli.StringFlag{ Name: "cwd", Usage: "[TODO] current working directory in the container", }, cli.StringSliceFlag{ Name: "env, e", Usage: "[TODO] set environment variables", }, cli.BoolFlag{ Name: "tty, t", Usage: "[TODO] allocate a pseudo-TTY", }, cli.StringFlag{ Name: "user, u", Usage: "[TODO] UID (format: <uid>[:<gid>])", }, cli.StringFlag{ Name: "process, p", Usage: "path to the process.json", }, cli.BoolFlag{ Name: "detach,d", Usage: "[TODO] detach from the container's process", }, cli.StringFlag{ Name: "pid-file", Usage: "[TODO] specify the file to write the process id to", }, cli.StringFlag{ Name: "process-label", Usage: "[ignore on runv] set the asm process label for the process commonly used with selinux", }, cli.StringFlag{ Name: "apparmor", Usage: "[ignore on runv] set the apparmor profile for the process", }, cli.BoolFlag{ Name: "no-new-privs", Usage: "[ignore on runv] set the no new privileges value for the process", }, cli.StringSliceFlag{ Name: "cap, c", Usage: "[ignore on runv] add a capability to the bounding set for the process", }, cli.BoolFlag{ Name: "no-subreaper", Usage: "[ignore on runv] disable the use of the subreaper used to reap reparented processes", }, }, Action: func(context *cli.Context) { root := context.GlobalString("root") container := context.Args().First() if context.String("console") != "" { fmt.Printf("--console is unsupported on runv\n") os.Exit(-1) } if container == "" { fmt.Printf("Please specify container ID\n") os.Exit(-1) } if os.Geteuid() != 0 { fmt.Printf("runv should be run as root\n") os.Exit(-1) } // get bundle path from state path := filepath.Join(root, container, stateJson) f, err := os.Open(path) if err != nil { fmt.Printf("open JSON configuration file failed: %v\n", err) os.Exit(-1) } defer f.Close() var s *specs.State if err := json.NewDecoder(f).Decode(&s); err != nil { fmt.Printf("parse JSON configuration file failed: %v\n", err) os.Exit(-1) } bundle := s.BundlePath // get process config, err := getProcess(context, bundle) if err != nil { fmt.Printf("get process config failed %v\n", err) os.Exit(-1) } conn, err := runvRequest(root, container, RUNV_EXECCMD, config.Args) if err != nil { fmt.Printf("exec failed: %v", err) } code, err := containerTtySplice(root, container, conn, false) os.Exit(code) }, } // loadProcessConfig loads the process configuration from the provided path. func loadProcessConfig(path string) (*specs.Process, error) { f, err := os.Open(path) if err != nil { if os.IsNotExist(err) { return nil, fmt.Errorf("JSON configuration file for %s not found", path) } return nil, err } defer f.Close() var s *specs.Process if err := json.NewDecoder(f).Decode(&s); err != nil { return nil, err } return s, nil } func getProcess(context *cli.Context, bundle string) (*specs.Process, error) { if path := context.String("process"); path != "" { return loadProcessConfig(path) } // process via cli flags spec, err := loadSpec(filepath.Join(bundle, specConfig)) if err != nil { return nil, err } p := spec.Process p.Args = context.Args()[1:] // override the cwd, if passed if context.String("cwd") != "" { p.Cwd = context.String("cwd") } // append the passed env variables for _, e := range context.StringSlice("env") { p.Env = append(p.Env, e) } // set the tty if context.IsSet("tty") { p.Terminal = context.Bool("tty") } // override the user, if passed if context.String("user") != "" { u := strings.SplitN(context.String("user"), ":", 2) if len(u) > 1 { gid, err := strconv.Atoi(u[1]) if err != nil { return nil, fmt.Errorf("parsing %s as int for gid failed: %v", u[1], err) } p.User.GID = uint32(gid) } uid, err := strconv.Atoi(u[0]) if err != nil { return nil, fmt.Errorf("parsing %s as int for uid failed: %v", u[0], err) } p.User.UID = uint32(uid) } return &p, nil } <file_sep>package rbd import ( "github.com/hyperhq/hyper/lib/docker/daemon/graphdriver/graphtest" "testing" ) // This avoids creating a new driver for each test if all tests are run // Make sure to put new tests between TestRbdSetup and TestRbdTeardown func TestRbdSetup(t *testing.T) { graphtest.GetDriver(t,"rbd") } func TestRbdCreateEmpty(t *testing.T) { graphtest.DriverTestCreateEmpty(t,"rbd") } func TestRbdCreateBase(t *testing.T) { graphtest.DriverTestCreateBase(t,"rbd") } func TestRbdCreateSnap(t *testing.T) { graphtest.DriverTestCreateSnap(t,"rbd") } func TestRbdTeardown(t *testing.T) { graphtest.PutDriver(t) }<file_sep>#!/bin/bash PROJECT=$(readlink -f $(dirname $0)/../..) CENTOS_DIR=${PROJECT}/package/centos VERSION=0.4 if [ $# -gt 0 ] ; then VERSION=$1 fi #SOURCES cd $PROJECT git archive --format=tar.gz master > ${CENTOS_DIR}/rpm/SOURCES/hyper-${VERSION}.tar.gz cd $PROJECT/../runv git archive --format=tar.gz master > ${CENTOS_DIR}/rpm/SOURCES/runv-${VERSION}.tar.gz cd $PROJECT/../hyperstart git archive --format=tar.gz master > ${CENTOS_DIR}/rpm/SOURCES/hyperstart-${VERSION}.tar.gz cd .. git clone https://github.com/bonzini/qboot.git cd qboot git archive --format=tar.gz master > ${CENTOS_DIR}/rpm/SOURCES/qboot.tar.gz sed -e "s#%PROJECT_ROOT%#${PROJECT}#g" ${CENTOS_DIR}/centos-rpm.pod.in > ${CENTOS_DIR}/centos-rpm.pod sed -e "s#%VERSION%#${VERSION}#g" ${CENTOS_DIR}/rpm/SPECS/hyper.spec.in > ${CENTOS_DIR}/rpm/SPECS/hyper.spec sed -e "s#%VERSION%#${VERSION}#g" ${CENTOS_DIR}/rpm/SPECS/hyperstart.spec.in > ${CENTOS_DIR}/rpm/SPECS/hyperstart.spec <file_sep>package server import ( "encoding/json" "errors" "fmt" "io/ioutil" "path/filepath" "time" "github.com/cloudfoundry/gosigar" "github.com/docker/containerd/api/grpc/types" "github.com/golang/glog" "github.com/hyperhq/runv/supervisor" "github.com/opencontainers/runtime-spec/specs-go" "golang.org/x/net/context" ) type apiServer struct { sv *supervisor.Supervisor } // NewServer returns grpc server instance func NewServer(sv *supervisor.Supervisor) types.APIServer { return &apiServer{ sv: sv, } } func (s *apiServer) CreateContainer(ctx context.Context, r *types.CreateContainerRequest) (*types.CreateContainerResponse, error) { glog.Infof("gRPC handle CreateContainer") if r.BundlePath == "" { return nil, errors.New("empty bundle path") } var spec specs.Spec ocfData, err := ioutil.ReadFile(filepath.Join(r.BundlePath, "config.json")) if err != nil { return nil, err } if err := json.Unmarshal(ocfData, &spec); err != nil { return nil, err } c, p, err := s.sv.CreateContainer(r.Id, r.BundlePath, r.Stdin, r.Stdout, r.Stderr, &spec) if err != nil { return nil, err } glog.Infof("end Supervisor.CreateContainer(), build api Container") apiP := supervisorProcess2ApiProcess(p) apiC := supervisorContainer2ApiContainer(c) addApiProcess2ApiContainer(apiC, apiP) glog.Infof("gRPC respond CreateContainer") return &types.CreateContainerResponse{ Container: apiC, }, nil } func (s *apiServer) Signal(ctx context.Context, r *types.SignalRequest) (*types.SignalResponse, error) { err := s.sv.Signal(r.Id, r.Pid, int(r.Signal)) if err != nil { return nil, err } return &types.SignalResponse{}, nil } func (s *apiServer) AddProcess(ctx context.Context, r *types.AddProcessRequest) (*types.AddProcessResponse, error) { if r.Id == "" { return nil, fmt.Errorf("container id cannot be empty") } if r.Pid == "" { return nil, fmt.Errorf("process id cannot be empty") } if len(r.Args) == 0 { return nil, fmt.Errorf("args cannot be empty") } spec := &specs.Process{ Terminal: r.Terminal, Args: r.Args, Env: r.Env, Cwd: r.Cwd, } _, err := s.sv.AddProcess(r.Id, r.Pid, r.Stdin, r.Stdout, r.Stderr, spec) if err != nil { return nil, err } return &types.AddProcessResponse{}, nil } func (s *apiServer) State(ctx context.Context, r *types.StateRequest) (*types.StateResponse, error) { cpu := sigar.CpuList{} if err := cpu.Get(); err != nil { return nil, err } mem := sigar.Mem{} if err := mem.Get(); err != nil { return nil, err } state := &types.StateResponse{ Machine: &types.Machine{ Cpus: uint32(len(cpu.List)), Memory: uint64(mem.Total / 1024 / 1024), }, } s.sv.RLock() for _, c := range s.sv.Containers { apiC := supervisorContainer2ApiContainer(c) for _, p := range c.Processes { addApiProcess2ApiContainer(apiC, supervisorProcess2ApiProcess(p)) } state.Containers = append(state.Containers, apiC) } s.sv.RUnlock() return state, nil } func (s *apiServer) UpdateContainer(ctx context.Context, r *types.UpdateContainerRequest) (*types.UpdateContainerResponse, error) { return nil, errors.New("UpdateContainer() not implemented yet") } func (s *apiServer) UpdateProcess(ctx context.Context, r *types.UpdateProcessRequest) (*types.UpdateProcessResponse, error) { var err error if r.CloseStdin { err = s.sv.CloseStdin(r.Id, r.Pid) } else { err = s.sv.TtyResize(r.Id, r.Pid, int(r.Width), int(r.Height)) } if err != nil { return nil, err } return &types.UpdateProcessResponse{}, nil } func (s *apiServer) Events(r *types.EventsRequest, stream types.API_EventsServer) error { t := time.Time{} if r.Timestamp != 0 { t = time.Unix(int64(r.Timestamp), 0) } events := s.sv.Events.Events(t) defer s.sv.Events.Unsubscribe(events) for e := range events { if err := stream.Send(&types.Event{ Id: e.ID, Type: e.Type, Timestamp: uint64(e.Timestamp.Unix()), Pid: e.PID, Status: uint32(e.Status), }); err != nil { return err } } return nil } // TODO implement func (s *apiServer) CreateCheckpoint(ctx context.Context, r *types.CreateCheckpointRequest) (*types.CreateCheckpointResponse, error) { return nil, errors.New("CreateCheckpoint() not implemented yet") } // TODO implement func (s *apiServer) DeleteCheckpoint(ctx context.Context, r *types.DeleteCheckpointRequest) (*types.DeleteCheckpointResponse, error) { return nil, errors.New("DeleteCheckpoint() not implemented yet") } // TODO implement func (s *apiServer) ListCheckpoint(ctx context.Context, r *types.ListCheckpointRequest) (*types.ListCheckpointResponse, error) { return nil, errors.New("ListCheckpoint() not implemented yet") } // TODO implement func (s *apiServer) Stats(ctx context.Context, r *types.StatsRequest) (*types.StatsResponse, error) { return nil, errors.New("Stats() not implemented yet") } func supervisorProcess2ApiProcess(p *supervisor.Process) *types.Process { return &types.Process{ Pid: p.Id, SystemPid: uint32(p.ProcId), Terminal: p.Spec.Terminal, Args: p.Spec.Args, Env: p.Spec.Env, Cwd: p.Spec.Cwd, Stdin: p.Stdin, Stdout: p.Stdout, Stderr: p.Stderr, } } func supervisorContainer2ApiContainer(c *supervisor.Container) *types.Container { return &types.Container{ Id: c.Id, BundlePath: c.BundlePath, Status: "running", Runtime: "runv", } } func addApiProcess2ApiContainer(apiC *types.Container, apiP *types.Process) { apiC.Processes = append(apiC.Processes, apiP) apiC.Pids = append(apiC.Pids, apiP.SystemPid) } <file_sep>package client import ( "fmt" "net/http" "net/url" "os" "strings" "time" "github.com/docker/docker/pkg/timeutils" gflag "github.com/jessevdk/go-flags" ) func (cli *HyperClient) HyperCmdLogs(args ...string) error { var opts struct { Follow bool `short:"f" long:"follow" default:"false" default-mask:"-" description:"Follow log output"` Since string `long:"since" value-name:"\"\"" description:"Show logs since timestamp"` Times bool `short:"t" long:"timestamps" default:"false" default-mask:"-" description:"Show timestamps"` Tail string `long:"tail" value-name:"\"all\"" description:"Number of lines to show from the end of the logs"` } var parser = gflag.NewParser(&opts, gflag.Default|gflag.IgnoreUnknown) parser.Usage = "logs CONTAINER [OPTIONS...]\n\nFetch the logs of a container" args, err := parser.Parse() if err != nil { if !strings.Contains(err.Error(), "Usage") { return err } else { return nil } } if len(args) <= 1 { return fmt.Errorf("%s ERROR: Can not accept the 'logs' command without argument!\n", os.Args[0]) } v := url.Values{} v.Set("container", args[1]) v.Set("stdout", "yes") v.Set("stderr", "yes") if opts.Since != "" { v.Set("since", timeutils.GetTimestamp(opts.Since, time.Now())) } if opts.Times { v.Set("timestamps", "yes") } if opts.Follow { v.Set("follow", "yes") } v.Set("tail", opts.Tail) headers := http.Header(make(map[string][]string)) return cli.stream("GET", "/container/logs?"+v.Encode(), nil, cli.out, headers) } <file_sep>package pod import ( "strings" "github.com/golang/glog" "github.com/opencontainers/runtime-spec/specs-go" ) func ConvertOCF2UserContainer(s *specs.Spec) *UserContainer { container := &UserContainer{ Command: s.Process.Args, Workdir: s.Process.Cwd, Tty: s.Process.Terminal, Image: s.Root.Path, Sysctl: s.Linux.Sysctl, RestartPolicy: "never", } for _, value := range s.Process.Env { glog.V(1).Infof("env: %s\n", value) values := strings.Split(value, "=") tmp := UserEnvironmentVar{ Env: values[0], Value: values[1], } container.Envs = append(container.Envs, tmp) } return container } func ConvertOCF2PureUserPod(s *specs.Spec) *UserPod { mem := 0 if s.Linux.Resources != nil && s.Linux.Resources.Memory != nil && s.Linux.Resources.Memory.Limit != nil { mem = int(*s.Linux.Resources.Memory.Limit >> 20) } return &UserPod{ Name: s.Hostname, Resource: UserResource{ Memory: mem, Vcpu: 0, }, Tty: s.Process.Terminal, Type: "OCF", RestartPolicy: "never", } } <file_sep>package rbd import ( "encoding/json" "fmt" "os/exec" "syscall" "sync" "github.com/docker/docker/pkg/idtools" "github.com/Sirupsen/logrus" "github.com/noahdesu/go-ceph/rados" "github.com/noahdesu/go-ceph/rbd" ) const ( DefaultRadosConfigFile = "/etc/ceph/ceph.conf" DefaultDockerBaseImageSize = 10 * 1024 * 1024 * 1024 DefaultMetaObjectDataSize = 256 ) type RbdMappingInfo struct { Pool string `json:"pool"` Name string `json:"name"` Snapshot string `json:"snap"` Device string `json:"device"` } type DevInfo struct { Hash string `json:"hash"` Device string `json:"-"` Size uint64 `json:"size"` BaseHash string `json:"base_hash"` Initialized bool `json:"initialized"` mountPath string `json:"-"` mountCount int `json:"-"` lock sync.Mutex `json:"-"` } type MetaData struct { Devices map[string]*DevInfo `json:"Devices"` devicesLock sync.Mutex } type RbdSet struct { MetaData conn *rados.Conn ioctx *rados.IOContext dataPoolName string imagePrefix string snapPrefix string metaPrefix string baseImageName string baseImageSize uint64 configFile string filesystem string mkfsArgs []string uidMaps []idtools.IDMap gidMaps []idtools.IDMap } func (devices *RbdSet) lookupDevice(hash string) (*DevInfo,error) { devices.devicesLock.Lock() defer devices.devicesLock.Unlock() info := devices.Devices[hash] // load the old data in cluster if info == nil { info,err := devices.loadMetadata(hash) if info != nil { devices.Devices[hash] = info } return info,err } return info,nil } func (devices *RbdSet) getRbdImageName(hash string) string { if hash == "" { return devices.imagePrefix + "_" + devices.baseImageName } else { return devices.imagePrefix + "_" + hash } } func (devices *RbdSet) getRbdSnapName(hash string) string { return devices.snapPrefix + "_" + hash } func (devices *RbdSet) getRbdMetaOid(hash string) string { if hash == "" { return devices.metaPrefix + "_" + devices.baseImageName } else { return devices.metaPrefix + "_" + hash } } func (devices *RbdSet) removeMetadata(info *DevInfo) error { metaOid := devices.getRbdMetaOid(info.Hash) if err := devices.ioctx.Delete(metaOid); err != nil { return fmt.Errorf("Rbd removing metadata %s failed: %s",info.Hash,err) } return nil } func (devices *RbdSet) saveMetadata(info *DevInfo) error { metaOid := devices.getRbdMetaOid(info.Hash) jsonData,err := json.Marshal(info) if err != nil { return fmt.Errorf("Error encoding metadata to json: %s",err) } if err := devices.ioctx.WriteFull(metaOid,jsonData); err != nil { logrus.Errorf("Rbd write metadata %s failed: %v",info.Hash,err) return err } return nil } func (devices *RbdSet) loadMetadata(hash string) (*DevInfo, error) { info := &DevInfo{Hash: hash} metaOid := devices.getRbdMetaOid(hash) data := make([]byte,DefaultMetaObjectDataSize) dataLen,err := devices.ioctx.Read(metaOid,data,0) if err != nil { if err != rados.RadosErrorNotFound { logrus.Errorf("Rbd read metadata %s failed: %v",metaOid,err) return nil,err } logrus.Debugf("Rbd read metadata %s not found",metaOid) return nil,nil } jsonData := data[:dataLen] if err := json.Unmarshal(jsonData,&info); err != nil { return nil,err } return info,err } func (devices *RbdSet) MountDevice(hash,mountPoint,mountLabel string) error { info,err := devices.lookupDevice(hash) if err != nil { return err } info.lock.Lock() defer info.lock.Unlock() if info.mountCount > 0 { if mountPoint != info.mountPath { return fmt.Errorf("Trying to mount rbd device in multiple places (%s,%s)",info.mountPath,info.Device) } info.mountCount++ return nil } logrus.Debugf("[rbdset] Mount image %s with device %s to %s",info.Hash,info.Device,mountPoint) if err := devices.mapImageToRbdDevice(info); err != nil { return err } var flags uintptr = syscall.MS_MGC_VAL /* fstype,err := ProbeFsType(info.Device) if err != nil { return err }*/ fstype := "ext4" options := "" /* if fstype == "xfs" { options = joinMountOptions(options,"nouuid") }*/ //options = joinMountOptions(options,devices.mountOptions) //options = joinMountOptions(options,label.FormatMountLabel("",mountLabel)) //err = syscall.Mount(info.Device,mountPoint,fstype,flags,joinMountOptions("discard",options)) err = syscall.Mount(info.Device,mountPoint,fstype,flags,options) if err != nil { return fmt.Errorf("Errorf mounting '%s' on '%s': %s",info.Device,mountPoint,err) } info.mountCount = 1 info.mountPath = mountPoint return nil } func (devices *RbdSet) UnmountDevice(hash string) error { info ,err := devices.lookupDevice(hash) if err != nil { return err } info.lock.Lock() defer info.lock.Unlock() if info.mountCount == 0 { return fmt.Errorf("UnmountDevice: device not-mounted id %s\n",hash) } info.mountCount-- if info.mountCount > 0 { return nil } logrus.Debugf("[rbdset] Unmount(%s)",info.mountPath) if err := syscall.Unmount(info.mountPath,0); err != nil { return err } logrus.Debugf("[rbdset] Unmount done") info.mountPath = "" if err := devices.unmapImageFromRbdDevice(info); err != nil { return err } return nil } func (devices *RbdSet) registerDevice(hash, baseHash string, size uint64) (*DevInfo, error) { logrus.Debugf("registerDevice(%s)",hash) info := &DevInfo { Hash: hash, Device: "", Size: size, BaseHash: baseHash, Initialized: false, } devices.devicesLock.Lock() devices.Devices[hash] = info devices.devicesLock.Unlock() if err := devices.saveMetadata(info); err != nil { // remove unused device devices.devicesLock.Lock() delete(devices.Devices,hash) devices.devicesLock.Unlock() logrus.Errorf("Error saving Meta data: %s",err) } return info,nil } func (devices *RbdSet) unRegisterDevice(info *DevInfo) error { devices.devicesLock.Lock() delete(devices.Devices,info.Hash) devices.devicesLock.Unlock() if err := devices.removeMetadata(info); err != nil { devices.devicesLock.Lock() devices.Devices[info.Hash] = info devices.devicesLock.Unlock() logrus.Errorf("Error removing meta data: %s",err) } return nil } func (devices *RbdSet) HasDevice(hash string) bool { info,_ := devices.lookupDevice(hash) return info != nil } func (devices *RbdSet) imageIsMapped(devInfo *DevInfo) (bool, error) { // Older rbd binaries are not printing the device on mapping so // we have to discover it with showmapped out,err := exec.Command("rbd","showmapped","--format","json").Output() if err != nil { logrus.Errorf("Rbd run rbd showmapped failed: %v",err) return false,err } pool := devices.dataPoolName imgName := devices.getRbdImageName(devInfo.Hash) mappingInfos := map[string]*RbdMappingInfo{} json.Unmarshal(out,&mappingInfos) for _,info := range mappingInfos { if info.Pool == pool && info.Name == imgName { if devInfo.Device == "" { devInfo.Device = info.Device } else { if devInfo.Device != info.Device { logrus.Errorf("Rbd image %s is mapped to %s, but not same as except %s",devInfo.Hash,info.Device,devInfo.Device) } } return true,nil } } return false,nil } func (devices *RbdSet) mapImageToRbdDevice(devInfo *DevInfo) error { if devInfo.Device != "" { return nil } pool := devices.dataPoolName imageName := devices.getRbdImageName(devInfo.Hash) _,err := exec.Command("rbd","--pool",pool,"map",imageName).Output() if err != nil { return err } v,_ := devices.imageIsMapped(devInfo) if v == true { return nil } else { return fmt.Errorf("Unable map image %s",imageName) } } func (devices *RbdSet) unmapImageFromRbdDevice(devInfo *DevInfo) error { if devInfo.Device == "" { return nil } v,_ := devices.imageIsMapped(devInfo) if v == false { devInfo.Device = "" return nil } if err := exec.Command("rbd","unmap",devInfo.Device).Run(); err != nil { logrus.Debugf("[rbdset] unmap device %s failed: %v",devInfo.Device,err) return err } devInfo.Device = "" return nil } func (devices *RbdSet) createFilesystem(info *DevInfo) error { devname := info.Device args := []string{} for _,arg := range devices.mkfsArgs { args = append(args,arg) } args = append(args,devname) var err error switch devices.filesystem { case "xfs": err = exec.Command("mkfs.xfs",args...).Run() case "ext4": // -E is the extended options ,the lazy* options are both used to speed up the initialization err = exec.Command("mkfs.ext4",append([]string{"-E","nodiscard,lazy_itable_init=0,lazy_journal_init=0"},args...)...).Run() if err != nil { err = exec.Command("mkfs.ext4",append([]string{"-E","nodiscard,lazy_itable_init=0"},args...)...).Run() } if err != nil { return err } //tune2fs is used to adjust tunable filesystem parameters on ext2/ext3/ext4 filesystems //err = exec.Command("tune2fs",append([]string{"-c","-l","-i","0"},devname)...).Run() default: err = fmt.Errorf("Unsupported filesystem type %s",devices.filesystem) } if err != nil { return err } return nil } func (devices *RbdSet) createImage(hash,baseHash string) error { var snapshot *rbd.Snapshot baseImgName := devices.getRbdImageName(baseHash) imgName := devices.getRbdImageName(hash) img := rbd.GetImage(devices.ioctx,baseImgName) // create snapshot for hash snapName := devices.getRbdSnapName(hash) if err := img.Open(snapName); err != nil { if err != rbd.RbdErrorNotFound { logrus.Errorf("Rbd open image %s with snap %s failed: %v",baseImgName,snapName,err) return err } // open image without snapshot name if err = img.Open(); err != nil { logrus.Errorf("Rbd open image %s failed: %v",baseImgName,err) return err } // create snapshot if snapshot,err = img.CreateSnapshot(snapName); err != nil { logrus.Errorf("Rbd create snapshot %s failed: %v",snapName,err) img.Close() return err } } else { snapshot = img.GetSnapshot(snapName) } defer img.Close() // protect snapshot if err := snapshot.Protect(); err != nil { logrus.Errorf("Rbd protect snapshot %s failed: %v",snapName,err) return err } // clone image _,err := img.Clone(snapName,devices.ioctx,imgName,rbd.RbdFeatureLayering) if err != nil { logrus.Errorf("Rbd clone snapshot %s@%s to %s failed: %v",baseImgName,snapName,imgName,err) return err } return nil } func (devices *RbdSet) deleteImage(info *DevInfo) error { var snapshot *rbd.Snapshot // remove image imgName := devices.getRbdImageName(info.Hash) img := rbd.GetImage(devices.ioctx,imgName) if err := img.Remove(); err != nil { logrus.Errorf("Rbd delete image %s failed: %v",imgName,err) return err } // hash's parent snapName := devices.getRbdSnapName(info.Hash) baseImgName := devices.getRbdImageName(info.BaseHash) parentImg := rbd.GetImage(devices.ioctx,baseImgName) if err := parentImg.Open(snapName); err != nil { logrus.Errorf("Rbd open image %s with snap %s failed: %v",baseImgName,snapName,err) return err } else { snapshot = parentImg.GetSnapshot(snapName) } defer parentImg.Close() // unprotect snapshot if err := snapshot.Unprotect(); err != nil { logrus.Errorf("Rbd unprotect snapshot %s failed: %v",snapName,err) return err } // remove snapshot if err := snapshot.Remove(); err != nil { logrus.Errorf("Rbd remove snapshot %s failed: %v",snapName,err) return err } // unregister it if err := devices.unRegisterDevice(info); err != nil { return err } return nil } func (devices *RbdSet) setupBaseImage() error { // check the base image if it exists oldInfo,err := devices.lookupDevice("") if err != nil { return err } // base image exist if oldInfo != nil {/* if oldInfo.Initialized { return nil } else { logrus.Debugf("Removing uninitialized base image") if err = devices.deleteImage(oldInfo); err != nil { logrus.Errorf("Removing uninitialized base image failed: %v",err) return err } }*/ return nil } baseName := devices.getRbdImageName("") logrus.Debugf("Create base rbd image %s",baseName) // create initial image _,err = rbd.Create(devices.ioctx,baseName,devices.baseImageSize,rbd.RbdFeatureLayering) if err != nil { logrus.Errorf("Rbd create image %s failed: %v",baseName,err) return err } // register it devInfo, err := devices.registerDevice("","",devices.baseImageSize) // map it err = devices.mapImageToRbdDevice(devInfo) if err != nil { logrus.Errorf("Rbd map image %s to %s",baseName,devInfo.Device) } // unmap it at last defer devices.unmapImageFromRbdDevice(devInfo) logrus.Debugf("Rbd map image %s to %s",baseName,devInfo.Device) // create filesystem if err = devices.createFilesystem(devInfo); err != nil { logrus.Errorf("Rbd create filesystem for image %s failed: %v",baseName,err) return err } devInfo.Initialized = true return nil } func (devices *RbdSet) AddDevice(hash, baseHash string) error { baseInfo,err := devices.lookupDevice(baseHash) if err != nil { return err } baseInfo.lock.Lock() defer baseInfo.lock.Unlock() if info,_ := devices.lookupDevice(hash); info != nil { logrus.Debugf("Rbd device %s already exists", hash) return nil } logrus.Debugf("[rbdset] Create image hash %s baseHash %s",hash,baseHash) if err := devices.createImage(hash,baseHash); err != nil { logrus.Errorf("Rbd error creating image %s (parent %s): %s",hash,baseHash,err) return err } if _,err := devices.registerDevice(hash,baseHash,baseInfo.Size); err != nil { devices.DeleteDevice(hash) logrus.Errorf("Rbd register device failed: %v",err) return err } return nil } func (devices *RbdSet) DeleteDevice(hash string) error { info,err := devices.lookupDevice(hash) if err != nil { return err } info.lock.Lock() defer info.lock.Unlock() logrus.Debugf("[rbdset] Delete image %s",info.Hash) return devices.deleteImage(info) } func (devices *RbdSet) initRbdSet(doInit bool) error { if err := devices.conn.ReadConfigFile(devices.configFile); err != nil { logrus.Errorf("Rbd read config file failed: %v",err) return err } if err := devices.conn.Connect(); err != nil { logrus.Errorf("Rbd connect failed: %v",err) return err } ioctx,err := devices.conn.OpenIOContext(devices.dataPoolName) if err != nil { logrus.Errorf("Rbd open pool %s failed: %v",devices.dataPoolName,err) devices.conn.Shutdown() return err } devices.ioctx = ioctx // Setup the base image if doInit { if err := devices.setupBaseImage(); err != nil { logrus.Errorf("Rbd error devices setupBaseImage: %s",err) return err } } return nil } func (devices *RbdSet) Shutdown() error { logrus.Debugf("[rbdset %s] shutdown()",devices.imagePrefix) defer logrus.Debugf("[rbdset %s] shutdown END",devices.imagePrefix) var devs []*DevInfo devices.devicesLock.Lock() for _,info := range devices.Devices { devs = append(devs,info) } devices.devicesLock.Unlock() for _,info := range devs { info.lock.Lock() if info.mountCount >0 { // We use MNT_DETACH here in case it is still busy in some running // container. This means it'll go away from the global scope directly. // and the device will be released when that container dies if err := syscall.Unmount(info.mountPath,syscall.MNT_DETACH); err != nil { logrus.Debugf("Shutdown unmounting %s, error: %s",info.Hash,err) } if err := devices.unmapImageFromRbdDevice(info); err != nil { logrus.Debugf("Shutdown unmap %s, error: %s",info.Hash,err) } } info.lock.Unlock() } // disconnect from rados logrus.Debugf("Disconnect from rados") devices.ioctx.Destroy() devices.conn.Shutdown() return nil } func NewRbdSet(root string,doInit bool,options []string,uidMaps, gidMaps []idtools.IDMap) (*RbdSet,error) { conn,_ := rados.NewConn() devices := &RbdSet{ MetaData: MetaData{Devices: make(map[string]*DevInfo)}, conn: conn, dataPoolName: "rbd", imagePrefix: "docker_image", snapPrefix: "docker_snap", metaPrefix: "docker_meta", baseImageName: "base_image", baseImageSize: DefaultDockerBaseImageSize, configFile: DefaultRadosConfigFile, filesystem: "ext4", uidMaps: uidMaps, gidMaps: gidMaps, } // no option parse if err := devices.initRbdSet(doInit); err != nil { return nil,err } return devices,nil }<file_sep>package rbd import ( "os" "io/ioutil" "path" "github.com/Sirupsen/logrus" "github.com/docker/docker/pkg/idtools" "github.com/docker/docker/pkg/mount" "github.com/hyperhq/hyper/lib/docker/daemon/graphdriver" ) func init() { graphdriver.Register("rbd",Init) } type Driver struct { home string *RbdSet uidMaps []idtools.IDMap gidMaps []idtools.IDMap } func Init(home string,options []string, uidMaps, gidMaps []idtools.IDMap) (graphdriver.Driver,error) { rbdSet,err := NewRbdSet(home,true,options,uidMaps,gidMaps) if err != nil { return nil,err } if err := os.MkdirAll(home,0700); err != nil && !os.IsExist(err) { logrus.Errorf("Rbd create home dir %s failed: %v",home,err) return nil,err } // MakePrivate ensures a mounted filesystem has the PRIVATE mount option enabled /* if err := mount.MakePrivate(home); err != nil { return nil,err }*/ d := &Driver { home: home, RbdSet: rbdSet, uidMaps: uidMaps, gidMaps: gidMaps, } return graphdriver.NewNaiveDiffDriver(d,uidMaps,gidMaps),nil } func (d *Driver) String() string { return "rbd" } func (d *Driver) Status() [][2]string { status := [][2]string{ } return status } // GetMetadata returns a map of information about the device. func (d *Driver) GetMetadata(id string) (map[string]string,error) { //m,err := d.RbdSet.exportDeviceMetadata(id) /* if err != nil { return nil,err }*/ metadata := make(map[string]string) //...... return metadata,nil } func (d *Driver) Cleanup() error { err := d.RbdSet.Shutdown() if err2 := mount.Unmount(d.home); err2 == nil { err = err2 } return err } func (d *Driver) Create(id, parent, mountLabel string) error { if err := d.RbdSet.AddDevice(id,parent); err != nil { return err } return nil } func (d *Driver) Remove(id string) error { if !d.RbdSet.HasDevice(id) { return nil } if err := d.RbdSet.DeleteDevice(id); err != nil { return err } mp := path.Join(d.home,"mnt",id) if err := os.RemoveAll(mp); err != nil && !os.IsNotExist(err) { return err } return nil } // Get mounts a device with given id into the root filesystem func (d *Driver) Get(id,mountLabel string) (string,error) { mp := path.Join(d.home,"mnt",id) uid,gid,err := idtools.GetRootUIDGID(d.uidMaps,d.gidMaps) if err != nil { return "",err } // Create the target directories if they don't exist if err := idtools.MkdirAllAs(path.Join(d.home,"mnt"),0755,uid,gid); err != nil && !os.IsExist(err) { return "",err } if err := idtools.MkdirAs(mp,0755,uid,gid); err != nil && !os.IsExist(err) { return "",err } // Mount the device if err := d.RbdSet.MountDevice(id,mp,mountLabel); err != nil { return "",err } rootFs := path.Join(mp,"rootfs") if err := idtools.MkdirAllAs(rootFs,0755,uid,gid); err != nil && os.IsExist(err) { d.RbdSet.UnmountDevice(id) return "",err } idFile := path.Join(mp,id) if _,err := os.Stat(idFile); err != nil && os.IsNotExist(err) { // Create an "id" file with the container/image id in it to help reconstruct this in case // of later problems if err := ioutil.WriteFile(idFile,[]byte(id),0600); err != nil { d.RbdSet.UnmountDevice(id) return "",err } } return rootFs,nil } // Put Unmount a device and removes it func (d *Driver) Put(id string) error { err := d.RbdSet.UnmountDevice(id) if err != nil { logrus.Errorf("Error unmounting device %s: %s",id,err) } //return err return nil } //Exists checks to see if the device exists. func (d *Driver) Exists(id string) bool { return d.RbdSet.HasDevice(id) return false } func (d *Driver) Setup() error { return nil }<file_sep>#! /bin/bash for i in $( echo '940512' | sudo ./hyper list | awk 'NR>2 {print $1}') do sudo ./hyper rm $i done <file_sep>package utils import ( "os" "syscall" ) func Mount(src, dst string, readOnly bool) error { if _, err := os.Stat(dst); os.IsNotExist(err) { os.MkdirAll(dst, 0755) } err := syscall.Mount(src, dst, "", syscall.MS_BIND|syscall.MS_REC, "") if err == nil && readOnly { err = syscall.Mount(src, dst, "", syscall.MS_BIND|syscall.MS_RDONLY|syscall.MS_REMOUNT|syscall.MS_REC, "") } return err } func Umount(root string) { syscall.Unmount(root, syscall.MNT_DETACH) } <file_sep>package docker import "github.com/docker/docker/api/types" func (cli Docker) SendCmdImages(all string) ([]*types.Image, error) { var ( allBoolValue = false ) if all == "yes" { allBoolValue = true } images, err := cli.daemon.ListImages("", "", allBoolValue) if err != nil { return nil, err } return images, nil } <file_sep>export GOPATH:=$(abs_top_srcdir)/Godeps/_workspace:$(GOPATH) if WITH_XEN XEN_BUILD_TAG=with_xen else XEN_BUILD_TAG= endif if WITH_LIBVIRT LIBVIRT_BUILD_TAG=with_libvirt else LIBVIRT_BUILD_TAG= endif HYPER_BULD_TAGS=$(XEN_BUILD_TAG) $(LIBVIRT_BUILD_TAG) libdm_no_deferred_remove if ON_DARWIN SUBDIRS=mac_installer endif VERSION_PARAM=-ldflags "-X github.com/hyperhq/hyper/utils.VERSION $(VERSION)" all-local: build-hyperd build-hyper clean-local: -rm -f hyperd hyper -rm -f Godeps/_workspace/src/github.com/opencontainers/specs/config-linux.go Godeps/_workspace/src/github.com/opencontainers/specs/runtime-config-linux.go install-exec-local: $(INSTALL_PROGRAM) hyper $(bindir) $(INSTALL_PROGRAM) hyperd $(bindir) # supporting linux container on non-linux platform (copy for catering to go build) if ON_LINUX linux_container: Godeps/_workspace/src/github.com/opencontainers/specs/config_linux.go Godeps/_workspace/src/github.com/opencontainers/specs/runtime_config_linux.go else linux_container: Godeps/_workspace/src/github.com/opencontainers/specs/config-linux.go Godeps/_workspace/src/github.com/opencontainers/specs/runtime-config-linux.go Godeps/_workspace/src/github.com/opencontainers/specs/config-linux.go: -cp Godeps/_workspace/src/github.com/opencontainers/specs/config_linux.go Godeps/_workspace/src/github.com/opencontainers/specs/config-linux.go Godeps/_workspace/src/github.com/opencontainers/specs/runtime-config-linux.go: -cp Godeps/_workspace/src/github.com/opencontainers/specs/runtime_config_linux.go Godeps/_workspace/src/github.com/opencontainers/specs/runtime-config-linux.go endif build-hyperd: linux_container go build -tags "static_build $(HYPER_BULD_TAGS)" $(VERSION_PARAM) hyperd.go build-hyper: go build $(VERSION_PARAM) hyper.go <file_sep>package hypervisor import ( "encoding/json" "fmt" "github.com/golang/glog" "github.com/hyperhq/runv/hypervisor/types" ) func LazyVmLoop(vmId string, hub chan VmEvent, client chan *types.VmResponse, boot *BootConfig, keep int) { glog.V(1).Infof("Start VM %s in lazy mode, not started yet actually", vmId) context, err := InitContext(vmId, hub, client, nil, boot, keep) if err != nil { client <- &types.VmResponse{ VmId: vmId, Code: types.E_BAD_REQUEST, Cause: err.Error(), } return } if _, ok := context.DCtx.(LazyDriverContext); !ok { glog.Error("not a lazy driver, cannot call lazy loop") context.reportBadRequest("not a lazy driver, cannot call lazy loop") return } err = context.DCtx.(LazyDriverContext).InitVM(context) if err != nil { estr := fmt.Sprintf("failed to create VM(%s): %s", vmId, err.Error()) glog.Error(estr) client <- &types.VmResponse{ VmId: vmId, Code: types.E_BAD_REQUEST, Cause: estr, } return } context.Become(statePreparing, "PREPARING") context.loop() } func statePreparing(ctx *VmContext, ev VmEvent) { switch ev.Event() { case EVENT_VM_EXIT, ERROR_INTERRUPTED: glog.Info("VM exited before start...") case COMMAND_SHUTDOWN, COMMAND_RELEASE: glog.Info("got shutdown or release command, not started yet") ctx.reportVmShutdown() ctx.Become(nil, "NONE") case COMMAND_EXEC: ctx.execCmd(ev.(*ExecCommand)) case COMMAND_ATTACH: ctx.attachCmd(ev.(*AttachCommand)) case COMMAND_WINDOWSIZE: cmd := ev.(*WindowSizeCommand) ctx.setWindowSize(cmd.ClientTag, cmd.Size) case COMMAND_RUN_POD, COMMAND_REPLACE_POD: glog.Info("got spec, prepare devices") if ok := ctx.lazyPrepareDevice(ev.(*RunPodCommand)); ok { ctx.startSocks() ctx.DCtx.(LazyDriverContext).LazyLaunch(ctx) ctx.setTimeout(60) ctx.Become(stateStarting, "STARTING") } else { glog.Warning("Fail to prepare devices, quit") ctx.Become(nil, "None") } case COMMAND_LISTEN_POD: if ok := ctx.lazyPrepareDeviceForListen(ev.(*ListenPodCommand)); ok { ctx.DCtx.(LazyDriverContext).Listen(ctx, ev.(*ListenPodCommand).Ip, ev.(*ListenPodCommand).Port) //ctx.setTimeout(60) ctx.startSocksInListen() ctx.Become(stateRunning,"RUNNING") } else { glog.Warning("Fail to prepare devices, quit") ctx.Become(nil,"None") } default: unexpectedEventHandler(ctx, ev, "pod initiating") } } func (ctx *VmContext) lazyPrepareDevice(cmd *RunPodCommand) bool { if len(cmd.Spec.Containers) != len(cmd.Containers) { ctx.reportBadRequest("Spec and Container Info mismatch") return false } ctx.InitDeviceContext(cmd.Spec, cmd.Wg, cmd.Containers, cmd.Volumes) if glog.V(2) { res, _ := json.MarshalIndent(*ctx.vmSpec, " ", " ") glog.Info("initial vm spec: ", string(res)) } pendings := ctx.pendingTtys ctx.pendingTtys = []*AttachCommand{} for _, acmd := range pendings { idx := ctx.Lookup(acmd.Container) if idx >= 0 { glog.Infof("attach pending client %s for %s", acmd.Streams.ClientTag, acmd.Container) ctx.attachTty2Container(idx, acmd) } else { glog.Infof("not attach %s for %s", acmd.Streams.ClientTag, acmd.Container) ctx.pendingTtys = append(ctx.pendingTtys, acmd) } } err := ctx.lazyAllocateNetworks() if err != nil { ctx.reportVmFault(err.Error()) return false } ctx.lazyAddBlockDevices() return true } func (ctx *VmContext) lazyPrepareDeviceForListen(cmd *ListenPodCommand) bool { if len(cmd.Spec.Containers) != len(cmd.Containers) { ctx.reportBadRequest("Spec and Container Info mismatch") return false } ctx.InitDeviceContext(cmd.Spec, cmd.Wg, cmd.Containers, cmd.Volumes) if glog.V(2) { res, _ := json.MarshalIndent(*ctx.vmSpec, " ", " ") glog.Info("initial vm spec: ", string(res)) } pendings := ctx.pendingTtys ctx.pendingTtys = []*AttachCommand{} for _, acmd := range pendings { idx := ctx.Lookup(acmd.Container) if idx >= 0 { glog.Infof("attach pending client %s for %s", acmd.Streams.ClientTag, acmd.Container) ctx.attachTty2Container(idx, acmd) } else { glog.Infof("not attach %s for %s", acmd.Streams.ClientTag, acmd.Container) ctx.pendingTtys = append(ctx.pendingTtys, acmd) } } err := ctx.lazyAllocateNetworks() if err != nil { ctx.reportVmFault(err.Error()) return false } ctx.lazyAddBlockDevices() return true } func networkConfigure(info *InterfaceCreated) (*HostNicInfo, *GuestNicInfo) { return &HostNicInfo{ Fd: uint64(info.Fd.Fd()), Device: info.HostDevice, Mac: info.MacAddr, Bridge: info.Bridge, Gateway: info.Bridge, }, &GuestNicInfo{ Device: info.DeviceName, Ipaddr: info.IpAddr, Index: info.Index, Busaddr: info.PCIAddr, } } func (ctx *VmContext) lazyAllocateNetworks() error { for i := range ctx.progress.adding.networks { name := fmt.Sprintf("eth%d", i) addr := ctx.nextPciAddr() nic, err := ctx.allocateInterface(i, addr, name) if err != nil { return err } ctx.interfaceCreated(nic) h, g := networkConfigure(nic) ctx.DCtx.(LazyDriverContext).LazyAddNic(ctx, h, g) } return nil } func (ctx *VmContext) lazyAddBlockDevices() { for blk := range ctx.progress.adding.blockdevs { if info, ok := ctx.devices.volumeMap[blk]; ok { sid := ctx.nextScsiId() ctx.DCtx.(LazyDriverContext).LazyAddDisk(ctx, info.info.Name, "volume", info.info.Filename, info.info.Format, sid) } else if info, ok := ctx.devices.imageMap[blk]; ok { sid := ctx.nextScsiId() ctx.DCtx.(LazyDriverContext).LazyAddDisk(ctx, info.info.Name, "image", info.info.Filename, info.info.Format, sid) } else { continue } } } <file_sep>package main import ( "fmt" "net" "os" "os/signal" "syscall" "github.com/hyperhq/runv/hypervisor" "github.com/hyperhq/runv/lib/term" ) type tty struct { root string container string tag string termFd uintptr terminal bool } type ttyWinSize struct { Tag string Height int Width int } // stdin/stdout <-> conn func containerTtySplice(root, container string, conn net.Conn, isContainer bool) (int, error) { tag, err := runvGetTag(conn) if err != nil { return -1, err } fmt.Printf("tag=%s\n", tag) outFd, isTerminalOut := term.GetFdInfo(os.Stdout) newTty(root, container, tag, outFd, isTerminalOut).monitorTtySize() _, err = term.TtySplice(conn) if err != nil { return -1, err } cmd := &ttyTagCmd{Root: root, Container: "", Tag: tag} if isContainer { cmd.Container = container } conn, err = runvRequest(root, container, RUNV_EXITSTATUS, cmd) if err != nil { fmt.Printf("runvRequest failed: %v\n", err) return -1, err } defer conn.Close() msg, err := hypervisor.ReadVmMessage(conn.(*net.UnixConn)) if err != nil { fmt.Printf("read runv server data failed: %v\n", err) return -1, err } if msg.Code != RUNV_EXITSTATUS { return -1, fmt.Errorf("unexpected respond code") } return int(msg.Message[0]), nil } func newTty(root, container, tag string, termFd uintptr, terminal bool) *tty { return &tty{ root: root, container: container, tag: tag, termFd: termFd, terminal: terminal, } } func (tty *tty) resizeTty() { if !tty.terminal { return } height, width := getTtySize(tty.termFd) ttyCmd := &ttyWinSize{Tag: tty.tag, Height: height, Width: width} conn, err := runvRequest(tty.root, tty.container, RUNV_WINSIZE, ttyCmd) if err != nil { fmt.Printf("Failed to reset winsize") return } conn.Close() } func (tty *tty) monitorTtySize() { tty.resizeTty() sigchan := make(chan os.Signal, 1) signal.Notify(sigchan, syscall.SIGWINCH) go func() { for range sigchan { tty.resizeTty() } }() } func getTtySize(termFd uintptr) (int, int) { ws, err := term.GetWinsize(termFd) if err != nil { fmt.Printf("Error getting size: %s", err.Error()) if ws == nil { return 0, 0 } } return int(ws.Height), int(ws.Width) } <file_sep>package main import ( "fmt" "os" "path/filepath" "strings" "github.com/codegangsta/cli" "github.com/hyperhq/runv/lib/utils" "github.com/kardianos/osext" "github.com/opencontainers/runtime-spec/specs-go" ) type startConfig struct { Name string BundlePath string Root string Driver string Kernel string Initrd string Vbox string *specs.Spec `json:"config"` } func loadStartConfig(context *cli.Context) (*startConfig, error) { config := &startConfig{ Name: context.Args().First(), Root: context.GlobalString("root"), Driver: context.GlobalString("driver"), Kernel: context.GlobalString("kernel"), Initrd: context.GlobalString("initrd"), Vbox: context.GlobalString("vbox"), BundlePath: context.String("bundle"), } var err error if config.Name == "" { return nil, fmt.Errorf("Please specify container ID") } // If config.BundlePath is "", this code sets it to the current work directory if !filepath.IsAbs(config.BundlePath) { config.BundlePath, err = filepath.Abs(config.BundlePath) if err != nil { return nil, fmt.Errorf("Cannot get abs path for bundle path: %s\n", err.Error()) } } ocffile := filepath.Join(config.BundlePath, specConfig) config.Spec, err = loadSpec(ocffile) if err != nil { return nil, err } return config, nil } func firstExistingFile(candidates []string) string { for _, file := range candidates { if _, err := os.Stat(file); err == nil { return file } } return "" } var startCommand = cli.Command{ Name: "start", Usage: "create and run a container", ArgsUsage: `<container-id> Where "<container-id>" is your name for the instance of the container that you are starting. The name you provide for the container instance must be unique on your host.`, Description: `The start command creates an instance of a container for a bundle. The bundle is a directory with a specification file named "` + specConfig + `" and a root filesystem. The specification file includes an args parameter. The args parameter is used to specify command(s) that get run when the container is started. To change the command(s) that get executed on start, edit the args parameter of the spec. See "runv spec --help" for more explanation.`, Flags: []cli.Flag{ cli.StringFlag{ Name: "bundle, b", Usage: "path to the root of the bundle directory", }, }, Action: func(context *cli.Context) { config, err := loadStartConfig(context) if err != nil { fmt.Printf("load config failed %v\n", err) os.Exit(-1) } if os.Geteuid() != 0 { fmt.Printf("runv should be run as root\n") os.Exit(-1) } _, err = os.Stat(filepath.Join(config.Root, config.Name)) if err == nil { fmt.Printf("Container %s exists\n", config.Name) os.Exit(-1) } var sharedContainer string for _, ns := range config.Spec.Linux.Namespaces { if ns.Path != "" { if strings.Contains(ns.Path, "/") { fmt.Printf("Runv doesn't support path to namespace file, it supports containers name as shared namespaces only\n") os.Exit(-1) } if ns.Type == "mount" { // TODO support it! fmt.Printf("Runv doesn't support shared mount namespace currently\n") os.Exit(-1) } sharedContainer = ns.Path _, err = os.Stat(filepath.Join(config.Root, sharedContainer, stateJson)) if err != nil { fmt.Printf("The container %s is not existing or not ready\n", sharedContainer) os.Exit(-1) } _, err = os.Stat(filepath.Join(config.Root, sharedContainer, "runv.sock")) if err != nil { fmt.Printf("The container %s is not ready\n", sharedContainer) os.Exit(-1) } } } // only set the default Kernel/Initrd/Vbox when it is the first container(sharedContainer == "") if config.Kernel == "" && sharedContainer == "" && config.Driver != "vbox" { config.Kernel = firstExistingFile([]string{ filepath.Join(config.BundlePath, config.Spec.Root.Path, "boot/vmlinuz"), filepath.Join(config.BundlePath, "boot/vmlinuz"), filepath.Join(config.BundlePath, "vmlinuz"), "/var/lib/hyper/kernel", }) } if config.Initrd == "" && sharedContainer == "" && config.Driver != "vbox" { config.Initrd = firstExistingFile([]string{ filepath.Join(config.BundlePath, config.Spec.Root.Path, "boot/initrd.img"), filepath.Join(config.BundlePath, "boot/initrd.img"), filepath.Join(config.BundlePath, "initrd.img"), "/var/lib/hyper/hyper-initrd.img", }) } if config.Vbox == "" && sharedContainer == "" && config.Driver == "vbox" { config.Vbox = firstExistingFile([]string{ filepath.Join(config.BundlePath, "vbox.iso"), "/opt/hyper/static/iso/hyper-vbox-boot.iso", }) } // convert the paths to abs if config.Kernel != "" && !filepath.IsAbs(config.Kernel) { config.Kernel, err = filepath.Abs(config.Kernel) if err != nil { fmt.Printf("Cannot get abs path for kernel: %s\n", err.Error()) os.Exit(-1) } } if config.Initrd != "" && !filepath.IsAbs(config.Initrd) { config.Initrd, err = filepath.Abs(config.Initrd) if err != nil { fmt.Printf("Cannot get abs path for initrd: %s\n", err.Error()) os.Exit(-1) } } if config.Vbox != "" && !filepath.IsAbs(config.Vbox) { config.Vbox, err = filepath.Abs(config.Vbox) if err != nil { fmt.Printf("Cannot get abs path for vbox: %s\n", err.Error()) os.Exit(-1) } } if sharedContainer != "" { initCmd := &initContainerCmd{Name: config.Name, Root: config.Root} conn, err := runvRequest(config.Root, sharedContainer, RUNV_INITCONTAINER, initCmd) if err != nil { os.Exit(-1) } conn.Close() } else { path, err := osext.Executable() if err != nil { fmt.Printf("cannot find self executable path for %s: %v\n", os.Args[0], err) os.Exit(-1) } os.MkdirAll(context.String("log_dir"), 0755) args := []string{ "runv-ns-daemon", "--root", config.Root, "--id", config.Name, } if context.GlobalBool("debug") { args = append(args, "-v", "3", "--log_dir", context.GlobalString("log_dir")) } _, err = utils.ExecInDaemon(path, args) if err != nil { fmt.Printf("failed to launch runv daemon, error:%v\n", err) os.Exit(-1) } } status, err := startContainer(config) if err != nil { fmt.Printf("start container failed: %v", err) } os.Exit(status) }, } type initContainerCmd struct { Name string Root string } // Shared namespaces multiple containers suppurt // The runv supports pod-style shared namespaces currently. // (More fine grain shared namespaces style (docker/runc style) is under implementation) // // Pod-style shared namespaces: // * if two containers share at least one type of namespace, they share all kinds of namespaces except the mount namespace // * mount namespace can't be shared, each container has its own mount namespace // // Implementation detail: // * Shared namespaces is configured in Spec.Linux.Namespaces, the namespace Path should be existing container name. // * In runv, shared namespaces multiple containers are located in the same VM which is managed by a runv-daemon. // * Any running container can exit in any arbitrary order, the runv-daemon and the VM are existed until the last container of the VM is existed func startContainer(config *startConfig) (int, error) { conn, err := runvRequest(config.Root, config.Name, RUNV_STARTCONTAINER, config) if err != nil { return -1, err } return containerTtySplice(config.Root, config.Name, conn, true) } <file_sep>package main import ( "encoding/json" "fmt" "os" "github.com/codegangsta/cli" "github.com/opencontainers/specs" ) var execCommand = cli.Command{ Name: "exec", Usage: "exec a new program in runv container", Action: func(context *cli.Context) { root := context.GlobalString("root") container := context.GlobalString("id") config, err := loadProcessConfig(context.Args().First()) if err != nil { fmt.Printf("load process config failed %v\n", err) os.Exit(-1) } if container == "" { fmt.Printf("Please specify container ID") os.Exit(-1) } if os.Geteuid() != 0 { fmt.Printf("runv should be run as root\n") os.Exit(-1) } conn, err := runvRequest(root, container, RUNV_EXECCMD, config.Args) if err != nil { fmt.Printf("exec failed: %v", err) } code, err := containerTtySplice(root, container, conn, false) os.Exit(code) }, } // loadProcessConfig loads the process configuration from the provided path. func loadProcessConfig(path string) (*specs.Process, error) { f, err := os.Open(path) if err != nil { if os.IsNotExist(err) { return nil, fmt.Errorf("JSON configuration file for %s not found", path) } return nil, err } defer f.Close() var s *specs.Process if err := json.NewDecoder(f).Decode(&s); err != nil { return nil, err } return s, nil } <file_sep># Growth Personal Code Hub <file_sep>package docker import ( "encoding/json" "fmt" "io" "os" "strings" "github.com/Sirupsen/logrus" "github.com/docker/docker/cliconfig" "github.com/docker/docker/graph/tags" "github.com/docker/docker/pkg/archive" "github.com/docker/docker/pkg/chrootarchive" "github.com/docker/docker/pkg/ioutils" "github.com/docker/docker/pkg/parsers" "github.com/docker/docker/pkg/progressreader" "github.com/docker/docker/pkg/streamformatter" "github.com/docker/docker/pkg/ulimit" "github.com/docker/docker/registry" "github.com/docker/docker/runconfig" "github.com/hyperhq/hyper/lib/docker/builder" "github.com/hyperhq/hyper/lib/docker/builder/dockerfile" "github.com/hyperhq/hyper/lib/docker/daemon/daemonbuilder" ) func (cli Docker) SendImageBuild(name string, size int, ctx io.ReadCloser) ([]byte, int, error) { var ( authConfigs = map[string]cliconfig.AuthConfig{} buildConfig = &dockerfile.Config{} buildArgs = map[string]string{} buildUlimits = []*ulimit.Ulimit{} isolation = "" // r.FormValue("isolation") ulimitsJSON = "" // r.FormValue("ulimits") buildArgsJSON = "" // r.FormValue("buildargs") remoteURL = "" // r.FormValue("remote") ) buildConfig.Remove = true buildConfig.Pull = true output := ioutils.NewWriteFlusher(os.Stdout) defer output.Close() sf := streamformatter.NewJSONStreamFormatter() errf := func(err error) error { // Do not write the error in the http output if it's still empty. // This prevents from writing a 200(OK) when there is an interal error. if !output.Flushed() { return err } return nil } buildConfig.DockerfileName = "" // r.FormValue("dockerfile") buildConfig.Verbose = true // !httputils.BoolValue(r, "q") buildConfig.UseCache = true // !httputils.BoolValue(r, "nocache") buildConfig.ForceRemove = true // httputils.BoolValue(r, "forcerm") buildConfig.MemorySwap = 0 // httputils.Int64ValueOrZero(r, "memswap") buildConfig.Memory = 0 // httputils.Int64ValueOrZero(r, "memory") buildConfig.ShmSize = 0 // httputils.Int64ValueOrZero(r, "shmsize") buildConfig.CPUShares = 0 // httputils.Int64ValueOrZero(r, "cpushares") buildConfig.CPUPeriod = 0 // httputils.Int64ValueOrZero(r, "cpuperiod") buildConfig.CPUQuota = 0 // httputils.Int64ValueOrZero(r, "cpuquota") buildConfig.CPUSetCpus = "" // r.FormValue("cpusetcpus") buildConfig.CPUSetMems = "" // r.FormValue("cpusetmems") buildConfig.CgroupParent = "" // r.FormValue("cgroupparent") if i := runconfig.IsolationLevel(isolation); i != "" { if !runconfig.IsolationLevel.IsValid(i) { return nil, -1, errf(fmt.Errorf("Unsupported isolation: %q", i)) } buildConfig.Isolation = i } if ulimitsJSON != "" { if err := json.NewDecoder(strings.NewReader(ulimitsJSON)).Decode(&buildUlimits); err != nil { return nil, -1, errf(err) } buildConfig.Ulimits = buildUlimits } if buildArgsJSON != "" { if err := json.NewDecoder(strings.NewReader(buildArgsJSON)).Decode(&buildArgs); err != nil { return nil, -1, errf(err) } buildConfig.BuildArgs = buildArgs } uidMaps, gidMaps := cli.daemon.GetUIDGIDMaps() defaultArchiver := &archive.Archiver{ Untar: chrootarchive.Untar, UIDMaps: uidMaps, GIDMaps: gidMaps, } docker := &daemonbuilder.Docker{ Daemon: cli.daemon, OutOld: output, AuthConfigs: authConfigs, Archiver: defaultArchiver, } // Currently, only used if context is from a remote url. // The field `In` is set by DetectContextFromRemoteURL. // Look at code in DetectContextFromRemoteURL for more information. pReader := &progressreader.Config{ // TODO: make progressreader streamformatter-agnostic Out: output, Formatter: sf, Size: int64(size), NewLines: true, ID: "Downloading context", Action: remoteURL, } context, dockerfileName, err := daemonbuilder.DetectContextFromRemoteURL(ctx, remoteURL, pReader) if err != nil { return nil, -1, errf(err) } defer func() { if err := context.Close(); err != nil { logrus.Debugf("[BUILDER] failed to remove temporary context: %v", err) } }() buildConfig.DockerfileName = dockerfileName b, err := dockerfile.NewBuilder(cli.daemon, buildConfig, docker, builder.DockerIgnoreContext{ModifiableContext: context}, nil) if err != nil { return nil, -1, errf(err) } b.Stdout = &streamformatter.StdoutFormatter{Writer: output, StreamFormatter: sf} b.Stderr = &streamformatter.StderrFormatter{Writer: output, StreamFormatter: sf} imgID, err := b.Build() if err != nil { return nil, -1, errf(err) } repo, tag := parsers.ParseRepositoryTag(name) if err := registry.ValidateRepositoryName(repo); err != nil { return nil, -1, errf(err) } if len(tag) > 0 { if err := tags.ValidateTagName(tag); err != nil { return nil, -1, errf(err) } } else { tag = tags.DefaultTag } if err := cli.daemon.TagImage(repo, tag, string(imgID), true); err != nil { return nil, -1, errf(err) } return nil, 0, nil } <file_sep>package utils import ( "net" "time" ) func DiskId2Name(id int) string { var ch byte = 'a' + byte(id%26) if id < 26 { return string(ch) } return DiskId2Name(id/26-1) + string(ch) } func UnixSocketConnect(name string) (conn net.Conn, err error) { for i := 0; i < 500; i++ { time.Sleep(20 * time.Millisecond) conn, err = net.Dial("unix", name) if err == nil { return } } return } <file_sep>// +build linux package main import ( "encoding/json" "fmt" "os" "path/filepath" "time" "github.com/codegangsta/cli" ) // cState represents the platform agnostic pieces relating to a running // container's status and state. Note: The fields in this structure adhere to // the opencontainers/runtime-spec/specs-go requirement for json fields that must be returned // in a state command. type cState struct { // Version is the OCI version for the container Version string `json:"ociVersion"` // ID is the container ID ID string `json:"id"` // InitProcessPid is the init process id in the parent namespace InitProcessPid int `json:"pid"` // Bundle is the path on the filesystem to the bundle Bundle string `json:"bundlePath"` // Rootfs is a path to a directory containing the container's root filesystem. Rootfs string `json:"rootfsPath"` // Status is the current status of the container, running, paused, ... Status string `json:"status"` // Created is the unix timestamp for the creation time of the container in UTC Created time.Time `json:"created"` } var stateCommand = cli.Command{ Name: "state", Usage: "output the state of a container", ArgsUsage: `<container-id> Where "<container-id>" is your name for the instance of the container.`, Description: `The state command outputs current state information for the instance of a container.`, Action: func(context *cli.Context) { id := context.Args().First() if id == "" { fatal(fmt.Errorf("You must specify one container id")) } cs, err := getContainer(context, id) if err != nil { fatal(err) } data, err := json.MarshalIndent(cs, "", " ") if err != nil { fatal(err) } os.Stdout.Write(data) }, } func getContainer(context *cli.Context, name string) (*cState, error) { root := context.GlobalString("root") absRoot, err := filepath.Abs(root) if err != nil { return nil, err } stateFile := filepath.Join(absRoot, name, stateJson) fi, err := os.Stat(stateFile) if err != nil { if os.IsNotExist(err) { return nil, fmt.Errorf("State file of %s not found", name) } return nil, fmt.Errorf("Stat file %s error: %s", stateFile, err.Error()) } state, err := loadStateFile(stateFile) if err != nil { return nil, fmt.Errorf("Load state file %s failed: %s", stateFile, err.Error()) } s := &cState{ Version: state.Version, ID: state.ID, InitProcessPid: state.Pid, Status: "running", Bundle: state.BundlePath, Rootfs: filepath.Join(state.BundlePath, "rootfs"), Created: fi.ModTime(), } return s, nil } <file_sep>[![Build Status](https://travis-ci.org/hyperhq/runv.svg)](https://travis-ci.org/hyperhq/runv) ## runV `runV` is a hypervisor-based runtime for [OCF](https://github.com/opencontainers/specs). ### OCF `runV` is compatible with OCF. However, due to the difference between hypervisors and containers, the following sections of OCF don't apply to runV: - Namespace - Capability - Device - `linux` and `mount` fields in OCI specs are ignored ### Hypervisor The current release of `runV` supports the following hypervisors: - KVM (QEMU 2.0 or later) - Xen (4.5 or later) - VirtualBox (Mac OS X) ### Distro The current release of `runV` supports the following distros: - Ubuntu 64bit - 15.04 Vivid - 14.10 Utopic - 14.04 Trusty - CentOS 64bit - 7.0 - 6.x (upgrade to QEMU 2.0) - Fedora 20-22 64bit - Debian 64bit - 8.0 jessie - 7.x wheezy (upgrade to QEMU 2.0) ### Build ```bash # create a 'github.com/hyperhq' in your GOPATH/src cd $GOPATH/src/github.com/hyperhq git clone https://github.com/hyperhq/runv/ cd runv ./autogen.sh ./configure --without-xen make sudo make install ``` ### Run To run a OCF image, execute `runv` with the [OCF JSON format file](https://github.com/opencontainers/runc#ocf-container-json-format) as argument, or have a `config.json` file in `CWD`. Also, a kernel and initrd images are needed too. We recommend you to build them from [HyperStart](https://github.com/hyperhq/hyperstart/) repo. If not specified, runV will try to load the `kernel` and `initrd.img` files from `CWD`. ```bash runv --kernel kernel --initrd initrd.img # ps aux USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND root 1 0.0 0.1 4352 232 ttyS0 S+ 05:54 0:00 /init root 2 0.0 0.5 4448 632 pts/0 Ss 05:54 0:00 sh root 4 0.0 1.6 15572 2032 pts/0 R+ 05:57 0:00 ps aux ``` ### Example Please check the runC example to get the container rootfs. https://github.com/opencontainers/runc#examples And you can get a sample OCF config.json at https://github.com/opencontainers/runc#oci-container-json-format or simply execute `runv spec`. <file_sep>package main import ( "flag" "net" "os" "sync" "github.com/hyperhq/runv/hypervisor" "github.com/hyperhq/runv/hypervisor/pod" ) // namespace context for runv daemon type nsContext struct { lock sync.Mutex podId string vmId string userPod *pod.UserPod podStatus *hypervisor.PodStatus vm *hypervisor.Vm firstConfig *startConfig ttyList map[string]*hypervisor.TtyIO actives map[string]*startConfig sockets map[string]net.Listener wg sync.WaitGroup sync.RWMutex } func runvNamespaceDaemon() { var root string var id string flag.StringVar(&root, "root", "", "") flag.StringVar(&id, "id", "", "") flag.Parse() if root == "" || id == "" { // should not happen in daemon os.Exit(-1) } context := &nsContext{} context.actives = make(map[string]*startConfig) context.sockets = make(map[string]net.Listener) context.ttyList = make(map[string]*hypervisor.TtyIO) startVContainer(context, root, id) context.wg.Wait() } <file_sep>package daemon import ( "fmt" "strconv" "time" "github.com/docker/docker/daemon/logger" "github.com/golang/glog" "github.com/hyperhq/hyper/engine" "github.com/hyperhq/runv/hypervisor/types" ) type logsCmdConfig struct { container string follow bool timestamps bool tail string since time.Time stdout bool stderr bool } func readLogsConfig(args []string) (*logsCmdConfig, error) { if len(args) < 1 { return nil, fmt.Errorf("container id or name must be provided") } cfg := &logsCmdConfig{ container: args[0], } if len(args) > 1 { cfg.tail = args[1] } if len(args) > 2 { s, err := strconv.ParseInt(args[2], 10, 64) if err == nil { cfg.since = time.Unix(s, 0) } } for _, s := range args[3:] { switch s { case "follow": cfg.follow = true case "timestamp": cfg.timestamps = true case "stdout": cfg.stdout = true case "stderr": cfg.stderr = true } } return cfg, nil } func (daemon *Daemon) CmdLogs(job *engine.Job) (err error) { var ( config *logsCmdConfig pod *Pod cidx int tailLines int ) config, err = readLogsConfig(job.Args) if err != nil { glog.Warningf("log args parsing error: %v", err) return } if !(config.stdout || config.stderr) { return fmt.Errorf("You must choose at least one stream") } outStream := job.Stdout errStream := outStream pod, cidx, err = daemon.GetPodByContainerIdOrName(config.container) if err != nil { return err } err = pod.getLogger(daemon) if err != nil { return err } logReader, ok := pod.status.Containers[cidx].Logs.Driver.(logger.LogReader) if !ok { return fmt.Errorf("logger not suppert read") } follow := config.follow && (pod.status.Status == types.S_POD_RUNNING) tailLines, err = strconv.Atoi(config.tail) if err != nil { tailLines = -1 } readConfig := logger.ReadConfig{ Since: config.since, Tail: tailLines, Follow: follow, } logs := logReader.ReadLogs(readConfig) for { select { case e := <-logs.Err: glog.Errorf("Error streaming logs: %v", e) return nil case msg, ok := <-logs.Msg: if !ok { glog.V(1).Info("logs: end stream") return nil } logLine := msg.Line if config.timestamps { logLine = append([]byte(msg.Timestamp.Format(logger.TimeFormat)+" "), logLine...) } if msg.Source == "stdout" && config.stdout { glog.V(2).Info("print stdout log: ", logLine) _, err := outStream.Write(logLine) if err != nil { return nil } } if msg.Source == "stderr" && config.stderr { glog.V(2).Info("print stderr log: ", logLine) _, err := errStream.Write(logLine) if err != nil { return nil } } } } } <file_sep>package main import ( "bytes" "crypto/rand" "encoding/hex" "encoding/json" "fmt" "io" "io/ioutil" "net" "os" "os/exec" "path/filepath" "strconv" "github.com/golang/glog" "github.com/hyperhq/runv/driverloader" "github.com/hyperhq/runv/hypervisor" "github.com/hyperhq/runv/hypervisor/pod" "github.com/hyperhq/runv/hypervisor/types" "github.com/hyperhq/runv/lib/utils" "github.com/opencontainers/runtime-spec/specs-go" ) const ( _ = iota RUNV_INITCONTAINER RUNV_STARTCONTAINER RUNV_ACK RUNV_EXECCMD RUNV_EXITSTATUS RUNV_WINSIZE RUNV_KILLCONTAINER ) const shortLen = 12 func TruncateID(id string) string { trimTo := shortLen if len(id) < shortLen { trimTo = len(id) } return id[:trimTo] } // GenerateRandomID returns an unique id func GenerateRandomID() string { for { id := make([]byte, 32) if _, err := io.ReadFull(rand.Reader, id); err != nil { panic(err) // This shouldn't happen } value := hex.EncodeToString(id) // if we try to parse the truncated for as an int and we don't have // an error then the value is all numberic and causes issues when // used as a hostname. ref #3869 if _, err := strconv.ParseInt(TruncateID(value), 10, 64); err == nil { continue } return value } } func execHook(hook specs.Hook, state *specs.State) error { b, err := json.Marshal(state) if err != nil { return err } cmd := exec.Cmd{ Path: hook.Path, Args: hook.Args, Env: hook.Env, Stdin: bytes.NewReader(b), } return cmd.Run() } func execPrestartHooks(rt *specs.Spec, state *specs.State) error { for _, hook := range rt.Hooks.Prestart { err := execHook(hook, state) if err != nil { return err } } return nil } func execPoststartHooks(rt *specs.Spec, state *specs.State) error { for _, hook := range rt.Hooks.Poststart { err := execHook(hook, state) if err != nil { glog.V(1).Infof("exec Poststart hook %s failed %s", hook.Path, err.Error()) } } return nil } func execPoststopHooks(rt *specs.Spec, state *specs.State) error { for _, hook := range rt.Hooks.Poststop { err := execHook(hook, state) if err != nil { glog.V(1).Infof("exec Poststop hook %s failed %s", hook.Path, err.Error()) } } return nil } func prepareInfo(config *startConfig, c *pod.UserContainer, vmId string) (*hypervisor.ContainerInfo, error) { var root string var err error containerId := GenerateRandomID() sharedDir := filepath.Join(hypervisor.BaseDir, vmId, hypervisor.ShareDirTag) rootDir := filepath.Join(sharedDir, containerId) os.MkdirAll(rootDir, 0755) rootDir = filepath.Join(rootDir, "rootfs") if !filepath.IsAbs(c.Image) { root = filepath.Join(config.BundlePath, c.Image) } else { root = c.Image } err = utils.Mount(root, rootDir, config.Spec.Root.Readonly) if err != nil { glog.V(1).Infof("mount %s to %s failed: %s\n", root, rootDir, err.Error()) return nil, err } envs := make(map[string]string) for _, env := range c.Envs { envs[env.Env] = env.Value } containerInfo := &hypervisor.ContainerInfo{ Id: containerId, Rootfs: "rootfs", Image: containerId, Fstype: "dir", Cmd: c.Command, Envs: envs, } return containerInfo, nil } func startVm(config *startConfig, userPod *pod.UserPod, vmId string) (*hypervisor.Vm, error) { var ( err error cpu = 1 mem = 128 ) vbox := config.Vbox if _, err = os.Stat(vbox); err == nil { vbox, err = filepath.Abs(vbox) if err != nil { glog.V(1).Infof("Cannot get abs path for vbox: %s\n", err.Error()) return nil, err } } if config.Driver == "vbox" { if _, err = os.Stat(config.Vbox); err != nil { return nil, err } } else { if _, err = os.Stat(config.Kernel); err != nil { return nil, err } if _, err = os.Stat(config.Initrd); err != nil { return nil, err } } if userPod.Resource.Vcpu > 0 { cpu = userPod.Resource.Vcpu } if userPod.Resource.Memory > 0 { mem = userPod.Resource.Memory } b := &hypervisor.BootConfig{ Kernel: config.Kernel, Initrd: config.Initrd, Bios: "", Cbfs: "", Vbox: config.Vbox, CPU: cpu, Memory: mem, } vm := hypervisor.NewVm(vmId, cpu, mem, false) err = vm.Launch(b) if err != nil { glog.V(1).Infof("%s\n", err.Error()) return nil, err } return vm, nil } func startRunvPod(context *nsContext, config *startConfig) (err error) { context.lock.Lock() defer context.lock.Unlock() if context.firstConfig == nil { context.firstConfig = config } else { // check stopped if len(context.actives) == 0 { return fmt.Errorf("The namespace service was stopped") } // check match if config.Root != "" && config.Root != context.firstConfig.Root { return fmt.Errorf("The root is not match") } if config.Driver != "" && config.Driver != context.firstConfig.Driver { return fmt.Errorf("The driver is not match") } if config.Kernel != "" && config.Kernel != context.firstConfig.Kernel { return fmt.Errorf("The kernel is not match") } if config.Initrd != "" && config.Initrd != context.firstConfig.Initrd { return fmt.Errorf("The initrd is not match") } if config.Vbox != "" && config.Vbox != context.firstConfig.Vbox { return fmt.Errorf("The vbox is not match") } // check shared namespace for _, ns := range config.Spec.Linux.Namespaces { if ns.Path == "" { continue } _, ok := context.actives[ns.Path] if !ok { return fmt.Errorf("Cann't share namespace with: %s", ns.Path) } } // OK, the pod has been started, add this config and return context.actives[config.Name] = config return nil } hypervisor.InterfaceCount = 0 driver := config.Driver if hypervisor.HDriver, err = driverloader.Probe(driver); err != nil { glog.V(1).Infof("%s\n", err.Error()) return err } context.podId = fmt.Sprintf("pod-%s", pod.RandStr(10, "alpha")) context.vmId = fmt.Sprintf("vm-%s", pod.RandStr(10, "alpha")) context.userPod = pod.ConvertOCF2PureUserPod(config.Spec) context.podStatus = hypervisor.NewPod(context.podId, context.userPod) context.vm, err = startVm(config, context.userPod, context.vmId) if err != nil { glog.V(1).Infof("%s\n", err.Error()) return err } Response := context.vm.StartPod(context.podStatus, context.userPod, nil, nil) if Response.Data == nil { glog.V(1).Infof("StartPod fail: QEMU response data is nil\n") return fmt.Errorf("StartPod fail") } glog.V(1).Infof("result: code %d %s\n", Response.Code, Response.Cause) context.actives[config.Name] = config return nil } func cleanupRunvPod(context *nsContext, name string) { context.lock.Lock() defer context.lock.Unlock() delete(context.actives, name) if len(context.actives) > 0 { return } Response := context.vm.StopPod(context.podStatus, "yes") if Response.Data == nil { glog.V(1).Infof("StopPod fail: QEMU response data is nil\n") return } glog.V(1).Infof("result: code %d %s\n", Response.Code, Response.Cause) os.RemoveAll(filepath.Join(hypervisor.BaseDir, context.vmId)) } func createVSocket(context *nsContext, root, container string) error { // create stateDir stateDir := filepath.Join(root, container) _, err := os.Stat(stateDir) if err == nil { glog.V(1).Infof("Container %s exists\n", container) return err } err = os.MkdirAll(stateDir, 0644) if err != nil { glog.V(1).Infof("%s\n", err.Error()) return err } defer func() { if err != nil { os.RemoveAll(stateDir) } }() // create connection sock sock, err := net.Listen("unix", filepath.Join(stateDir, "runv.sock")) if err != nil { glog.V(1).Infof("%s\n", err.Error()) return err } context.sockets[container] = sock return nil } func cleanupVSocket(context *nsContext, root, container string) { stateDir := filepath.Join(root, container) if sock, ok := context.sockets[container]; ok { sock.Close() delete(context.sockets, container) } os.RemoveAll(stateDir) } func startVContainer(context *nsContext, root, container string) { stateDir := filepath.Join(root, container) defer glog.Flush() err := createVSocket(context, root, container) if err != nil { glog.V(1).Infof("create runv Socket err: %v\n", err) return } sock, ok := context.sockets[container] if !ok { glog.V(1).Infof("can not find runv Socket, container %v\n", container) return } conn, err := sock.Accept() if err != nil { glog.V(1).Infof("accept on runv Socket err: %v\n", err) return } // get config from sock msg, err := hypervisor.ReadVmMessage(conn.(*net.UnixConn)) if err != nil || msg.Code != RUNV_STARTCONTAINER { glog.V(1).Infof("read runv client data failed: %v\n", err) return } config := &startConfig{} err = json.Unmarshal(msg.Message, config) if err != nil || config.Root != root || config.Name != container { glog.V(1).Infof("parse runv start config failed: %v\n", err) return } // start pure pod err = startRunvPod(context, config) if err != nil { glog.V(1).Infof("Start Pod failed: %s\n", err.Error()) return } defer cleanupRunvPod(context, container) // save the state state := &specs.State{ Version: config.Spec.Version, ID: container, Pid: -1, BundlePath: config.BundlePath, } stateData, err := json.MarshalIndent(state, "", "\t") if err != nil { glog.V(1).Infof("%s\n", err.Error()) return } stateFile := filepath.Join(stateDir, stateJson) err = ioutil.WriteFile(stateFile, stateData, 0644) if err != nil { glog.V(1).Infof("%s\n", err.Error()) return } userContainer := pod.ConvertOCF2UserContainer(config.Spec) info, err := prepareInfo(config, userContainer, context.vmId) if err != nil { glog.V(1).Infof("%s\n", err.Error()) return } defer func() { rootDir := filepath.Join(hypervisor.BaseDir, context.vmId, hypervisor.ShareDirTag, info.Id, "rootfs") utils.Umount(rootDir) os.RemoveAll(filepath.Join(hypervisor.BaseDir, context.vmId, hypervisor.ShareDirTag, info.Id)) }() tag, _ := runvAllocAndRespondTag(conn) tty := &hypervisor.TtyIO{ ClientTag: tag, Stdin: conn, Stdout: conn, Callback: make(chan *types.VmResponse, 1), } context.Lock() context.ttyList[tag] = tty context.Unlock() err = context.vm.Attach(tty, info.Id, nil) if err != nil { glog.V(1).Infof("StartPod fail: fail to set up tty connection.\n") return } err = execPrestartHooks(config.Spec, state) if err != nil { glog.V(1).Infof("execute Prestart hooks failed, %s\n", err.Error()) return } context.podStatus.AddContainer(info.Id, context.podId, "", []string{}, types.S_POD_CREATED) context.vm.NewContainer(userContainer, info) ListenAndHandleRunvRequests(context, info, sock) err = execPoststartHooks(config.Spec, state) if err != nil { glog.V(1).Infof("execute Poststart hooks failed %s\n", err.Error()) } err = tty.WaitForFinish() if err != nil { glog.V(1).Infof("get exit code failed %s\n", err.Error()) } err = execPoststopHooks(config.Spec, state) if err != nil { glog.V(1).Infof("execute Poststop hooks failed %s\n", err.Error()) return } } func runvRequest(root, name string, code uint32, msg interface{}) (net.Conn, error) { conn, err := utils.UnixSocketConnect(filepath.Join(root, name, "runv.sock")) if err != nil { return nil, err } cmd, err := json.Marshal(msg) if err != nil { conn.Close() return nil, err } m := &hypervisor.DecodedMessage{ Code: code, Message: cmd, } data := hypervisor.NewVmMessage(m) w, err := conn.Write(data[:]) if w != len(data) { err = fmt.Errorf("Not full write") // TODO } if err != nil { conn.Close() return nil, err } return conn, nil } func runvAllocAndRespondTag(conn net.Conn) (tag string, err error) { tag = pod.RandStr(8, "alphanum") m := &hypervisor.DecodedMessage{ Code: RUNV_ACK, Message: []byte(tag), } data := hypervisor.NewVmMessage(m) conn.Write(data) return tag, nil } func runvGetTag(conn net.Conn) (tag string, err error) { msg, err := hypervisor.ReadVmMessage(conn.(*net.UnixConn)) if err != nil { glog.V(1).Infof("read runv server data failed: %v\n", err) return "", err } if msg.Code != RUNV_ACK { return "", fmt.Errorf("unexpected respond code") } return string(msg.Message), nil } type ttyTagCmd struct { Root string Container string Tag string } func HandleRunvRequest(context *nsContext, info *hypervisor.ContainerInfo, conn net.Conn) { defer context.wg.Done() defer conn.Close() msg, err := hypervisor.ReadVmMessage(conn.(*net.UnixConn)) if err != nil { glog.V(1).Infof("read runv client data failed: %v\n", err) return } switch msg.Code { case RUNV_INITCONTAINER: { initCmd := &initContainerCmd{} err = json.Unmarshal(msg.Message, initCmd) if err != nil { glog.V(1).Infof("parse runv init container command failed: %v\n", err) return } startVContainer(context, initCmd.Root, initCmd.Name) } case RUNV_EXECCMD: { tag, _ := runvAllocAndRespondTag(conn) glog.V(1).Infof("client exec cmd request %s\n", msg.Message[:]) tty := &hypervisor.TtyIO{ ClientTag: tag, Stdin: conn, Stdout: conn, Callback: make(chan *types.VmResponse, 1), } context.Lock() context.ttyList[tag] = tty context.Unlock() err = context.vm.Exec(info.Id, string(msg.Message[:]), true, tty) if err != nil { glog.V(1).Infof("read runv client data failed: %v\n", err) } } case RUNV_EXITSTATUS: { var code uint8 = 255 tagCmd := &ttyTagCmd{} err = json.Unmarshal(msg.Message, &tagCmd) if err != nil { glog.V(1).Infof("parse exit status failed: %v\n", err) return } glog.V(1).Infof("client get exit status: tag %v\n", tagCmd) context.Lock() if tty, ok := context.ttyList[tagCmd.Tag]; ok { code = uint8(tty.ExitCode) delete(context.ttyList, tagCmd.Tag) } context.Unlock() m := &hypervisor.DecodedMessage{ Code: RUNV_EXITSTATUS, Message: []byte{code}, } data := hypervisor.NewVmMessage(m) conn.Write(data) /* Get exit code of Container, it's time to let container go */ if tagCmd.Container != "" { cleanupVSocket(context, tagCmd.Root, tagCmd.Container) } } case RUNV_WINSIZE: { var winSize ttyWinSize json.Unmarshal(msg.Message, &winSize) context.vm.Tty(winSize.Tag, winSize.Height, winSize.Width) } case RUNV_KILLCONTAINER: { killCmd := &killContainerCmd{} err = json.Unmarshal(msg.Message, killCmd) if err != nil { glog.V(1).Infof("parse runv kill container command failed: %v\n", err) return } context.vm.KillContainer(info.Id, killCmd.Signal) } default: glog.V(1).Infof("unknown cient request\n") } } func ListenAndHandleRunvRequests(context *nsContext, info *hypervisor.ContainerInfo, sock net.Listener) { context.wg.Add(1) go func() { defer context.wg.Done() for { conn, err := sock.Accept() if err != nil { glog.V(1).Infof("accept on runv Socket err: %v\n", err) break } context.wg.Add(1) go HandleRunvRequest(context, info, conn) } }() } <file_sep>package daemon import ( "fmt" "os" "strings" "github.com/golang/glog" "github.com/hyperhq/hyper/engine" "github.com/hyperhq/hyper/lib/sysinfo" "github.com/hyperhq/hyper/types" "github.com/hyperhq/hyper/utils" "github.com/hyperhq/runv/hypervisor" runvtypes "github.com/hyperhq/runv/hypervisor/types" ) func (daemon *Daemon) CmdInfo(job *engine.Job) error { cli := daemon.DockerCli sys, err := cli.SendCmdInfo("") if err != nil { return err } var num = daemon.PodList.CountContainers() glog.V(2).Infof("unlock read of PodList") v := &engine.Env{} v.Set("ID", daemon.ID) v.SetInt("Containers", int(num)) v.SetInt("Images", sys.Images) v.Set("Driver", sys.Driver) v.SetJson("DriverStatus", sys.DriverStatus) v.Set("DockerRootDir", sys.DockerRootDir) v.Set("IndexServerAddress", sys.IndexServerAddress) v.Set("ExecutionDriver", daemon.Hypervisor) // Get system infomation meminfo, err := sysinfo.GetMemInfo() if err != nil { return err } osinfo, err := sysinfo.GetOSInfo() if err != nil { return err } v.SetInt64("MemTotal", int64(meminfo.MemTotal)) v.SetInt64("Pods", daemon.GetPodNum()) v.Set("Operating System", osinfo.PrettyName) if hostname, err := os.Hostname(); err == nil { v.SetJson("Name", hostname) } if _, err := v.WriteTo(job.Stdout); err != nil { return err } return nil } func (daemon *Daemon) CmdVersion(job *engine.Job) error { v := &engine.Env{} v.Set("ID", daemon.ID) v.Set("Version", fmt.Sprintf("\"%s\"", utils.VERSION)) if _, err := v.WriteTo(job.Stdout); err != nil { return err } return nil } func (daemon *Daemon) CmdPodInfo(job *engine.Job) error { if len(job.Args) == 0 { return fmt.Errorf("Can not get Pod info without Pod ID") } daemon.PodList.RLock() glog.V(2).Infof("lock read of PodList") defer daemon.PodList.RUnlock() defer glog.V(2).Infof("unlock read of PodList") var ( pod *Pod podId string ok bool imageid string ) if strings.Contains(job.Args[0], "pod-") { podId = job.Args[0] pod, ok = daemon.PodList.Get(podId) if !ok { return fmt.Errorf("Can not get Pod info with pod ID(%s)", podId) } } else { pod = daemon.PodList.GetByName(job.Args[0]) if pod == nil { return fmt.Errorf("Can not get Pod info with pod name(%s)", job.Args[0]) } } // Construct the PodInfo JSON structure cStatus := []types.ContainerStatus{} containers := []types.Container{} for i, c := range pod.status.Containers { ports := []types.ContainerPort{} envs := []types.EnvironmentVar{} vols := []types.VolumeMount{} jsonResponse, err := daemon.DockerCli.GetContainerInfo(c.Id) if err == nil { for _, e := range jsonResponse.Config.Env { envs = append(envs, types.EnvironmentVar{ Env: e[:strings.Index(e, "=")], Value: e[strings.Index(e, "=")+1:]}) } imageid = jsonResponse.Image } for _, port := range pod.spec.Containers[i].Ports { ports = append(ports, types.ContainerPort{ HostPort: port.HostPort, ContainerPort: port.ContainerPort, Protocol: port.Protocol}) } for _, e := range pod.spec.Containers[i].Envs { envs = append(envs, types.EnvironmentVar{ Env: e.Env, Value: e.Value}) } for _, v := range pod.spec.Containers[i].Volumes { vols = append(vols, types.VolumeMount{ Name: v.Volume, MountPath: v.Path, ReadOnly: v.ReadOnly}) } container := types.Container{ Name: c.Name, ContainerID: c.Id, Image: c.Image, ImageID: imageid, Commands: pod.spec.Containers[i].Command, Args: []string{}, Workdir: pod.spec.Containers[i].Workdir, Ports: ports, Environment: envs, Volume: vols, ImagePullPolicy: "", } containers = append(containers, container) // Set ContainerStatus s := types.ContainerStatus{} s.Name = c.Name s.ContainerID = c.Id s.Waiting = types.WaitingStatus{Reason: ""} s.Running = types.RunningStatus{StartedAt: ""} s.Terminated = types.TermStatus{} if c.Status == runvtypes.S_POD_CREATED { s.Waiting.Reason = "Pending" s.Phase = "pending" } else if c.Status == runvtypes.S_POD_RUNNING { s.Running.StartedAt = pod.status.StartedAt s.Phase = "running" } else { // S_POD_FAILED or S_POD_SUCCEEDED if c.Status == runvtypes.S_POD_FAILED { s.Terminated.ExitCode = c.ExitCode s.Terminated.Reason = "Failed" s.Phase = "failed" } else { s.Terminated.ExitCode = c.ExitCode s.Terminated.Reason = "Succeeded" s.Phase = "succeeded" } s.Terminated.StartedAt = pod.status.StartedAt s.Terminated.FinishedAt = pod.status.FinishedAt } cStatus = append(cStatus, s) } podVoumes := []types.PodVolume{} for _, v := range pod.spec.Volumes { podVoumes = append(podVoumes, types.PodVolume{ Name: v.Name, HostPath: v.Source, Driver: v.Driver}) } spec := types.PodSpec{ Volumes: podVoumes, Containers: containers, Labels: pod.spec.Labels, Vcpu: pod.spec.Resource.Vcpu, Memory: pod.spec.Resource.Memory, } podIPs := []string{} if pod.vm != nil { podIPs = pod.status.GetPodIP(pod.vm) } status := types.PodStatus{ Status: cStatus, HostIP: utils.GetHostIP(), PodIP: podIPs, StartTime: pod.status.StartedAt, } switch pod.status.Status { case runvtypes.S_POD_CREATED: status.Phase = "Pending" break case runvtypes.S_POD_RUNNING: status.Phase = "Running" break case runvtypes.S_POD_SUCCEEDED: status.Phase = "Succeeded" break case runvtypes.S_POD_FAILED: status.Phase = "Failed" break } data := types.PodInfo{ Kind: "Pod", ApiVersion: utils.APIVERSION, Vm: pod.status.Vm, Spec: spec, Status: status, } v := &engine.Env{} v.SetJson("data", data) if _, err := v.WriteTo(job.Stdout); err != nil { return err } return nil } func (daemon *Daemon) CmdPodStats(job *engine.Job) error { if len(job.Args) == 0 { return fmt.Errorf("Can not get Pod stats without Pod ID") } daemon.PodList.RLock() glog.V(2).Infof("lock read of PodList") defer daemon.PodList.RUnlock() defer glog.V(2).Infof("unlock read of PodList") var ( pod *Pod podId string ok bool ) if strings.Contains(job.Args[0], "pod-") { podId = job.Args[0] pod, ok = daemon.PodList.Get(podId) if !ok { return fmt.Errorf("Can not get Pod stats with pod ID(%s)", podId) } } else { pod = daemon.PodList.GetByName(job.Args[0]) if pod == nil { return fmt.Errorf("Can not get Pod stats with pod name(%s)", job.Args[0]) } } if pod.vm == nil || pod.status.Status != runvtypes.S_POD_RUNNING { return fmt.Errorf("Can not get pod stats for non-running pod (%s)", job.Args[0]) } response := pod.vm.Stats() if response.Data == nil { return fmt.Errorf("Stats for pod %s is nil", job.Args[0]) } v := &engine.Env{} v.SetJson("data", response.Data) if _, err := v.WriteTo(job.Stdout); err != nil { return err } return nil } func (daemon *Daemon) CmdContainerInfo(job *engine.Job) error { if len(job.Args) == 0 { return fmt.Errorf("Can not get Pod info without Pod ID") } daemon.PodList.RLock() glog.V(2).Infof("lock read of PodList") defer daemon.PodList.RUnlock() defer glog.V(2).Infof("unlock read of PodList") var ( pod *Pod c *hypervisor.Container i int = 0 imageid string name string = job.Args[0] ) if name == "" { return fmt.Errorf("Null container name") } glog.Infof(name) wslash := name if name[0] != '/' { wslash = "/" + name } pod = daemon.PodList.Find(func(p *Pod) bool { for i, c = range p.status.Containers { if c.Name == wslash || c.Id == name { return true } } return false }) if pod == nil { return fmt.Errorf("Can not find container by name(%s)", name) } ports := []types.ContainerPort{} envs := []types.EnvironmentVar{} vols := []types.VolumeMount{} jsonResponse, err := daemon.DockerCli.GetContainerInfo(c.Id) if err == nil { for _, e := range jsonResponse.Config.Env { envs = append(envs, types.EnvironmentVar{ Env: e[:strings.Index(e, "=")], Value: e[strings.Index(e, "=")+1:]}) } imageid = jsonResponse.Image } for _, port := range pod.spec.Containers[i].Ports { ports = append(ports, types.ContainerPort{ HostPort: port.HostPort, ContainerPort: port.ContainerPort, Protocol: port.Protocol}) } for _, e := range pod.spec.Containers[i].Envs { envs = append(envs, types.EnvironmentVar{ Env: e.Env, Value: e.Value}) } for _, v := range pod.spec.Containers[i].Volumes { vols = append(vols, types.VolumeMount{ Name: v.Volume, MountPath: v.Path, ReadOnly: v.ReadOnly}) } s := types.ContainerStatus{} s.Name = c.Name s.ContainerID = c.Id s.Waiting = types.WaitingStatus{Reason: ""} s.Running = types.RunningStatus{StartedAt: ""} s.Terminated = types.TermStatus{} if c.Status == runvtypes.S_POD_CREATED { s.Waiting.Reason = "Pending" s.Phase = "pending" } else if c.Status == runvtypes.S_POD_RUNNING { s.Running.StartedAt = pod.status.StartedAt s.Phase = "running" } else { // S_POD_FAILED or S_POD_SUCCEEDED if c.Status == runvtypes.S_POD_FAILED { s.Terminated.ExitCode = c.ExitCode s.Terminated.Reason = "Failed" s.Phase = "failed" } else { s.Terminated.ExitCode = c.ExitCode s.Terminated.Reason = "Succeeded" s.Phase = "succeeded" } s.Terminated.StartedAt = pod.status.StartedAt s.Terminated.FinishedAt = pod.status.FinishedAt } container := types.ContainerInfo{ Name: c.Name, ContainerID: c.Id, PodID: pod.id, Image: c.Image, ImageID: imageid, Commands: pod.spec.Containers[i].Command, Args: []string{}, Workdir: pod.spec.Containers[i].Workdir, Ports: ports, Environment: envs, Volume: vols, ImagePullPolicy: "", Status: s, } v := &engine.Env{} v.SetJson("data", container) if _, err := v.WriteTo(job.Stdout); err != nil { return err } return nil } <file_sep>package supervisor import ( "bytes" "encoding/json" "fmt" "io/ioutil" "os" "os/exec" "path/filepath" "time" "github.com/golang/glog" "github.com/hyperhq/runv/hypervisor" "github.com/hyperhq/runv/hypervisor/pod" "github.com/hyperhq/runv/hypervisor/types" "github.com/hyperhq/runv/lib/utils" "github.com/opencontainers/runtime-spec/specs-go" ) type Container struct { Id string BundlePath string Spec *specs.Spec Processes map[string]*Process ownerPod *HyperPod } func (c *Container) start(p *Process) { e := Event{ ID: c.Id, Type: EventContainerStart, Timestamp: time.Now(), } c.ownerPod.sv.Events.notifySubscribers(e) go func() { err := c.run(p) e := Event{ ID: c.Id, Type: EventExit, Timestamp: time.Now(), PID: p.Id, Status: -1, } if err == nil { e.Status = int(p.stdio.ExitCode) } c.ownerPod.sv.Events.notifySubscribers(e) }() } func (c *Container) run(p *Process) error { // save the state glog.V(3).Infof("save state id %s, boundle %s", c.Id, c.BundlePath) state := &specs.State{ Version: c.Spec.Version, ID: c.Id, Pid: -1, BundlePath: c.BundlePath, } stateData, err := json.MarshalIndent(state, "", "\t") if err != nil { glog.V(1).Infof("%s\n", err.Error()) return err } stateFile := filepath.Join(c.ownerPod.sv.StateDir, "state.json") err = ioutil.WriteFile(stateFile, stateData, 0644) if err != nil { glog.V(1).Infof("%s\n", err.Error()) return err } glog.V(3).Infof("prepare hypervisor info") u := pod.ConvertOCF2UserContainer(c.Spec) if !filepath.IsAbs(u.Image) { u.Image = filepath.Join(c.BundlePath, u.Image) } vmRootfs := filepath.Join(hypervisor.BaseDir, c.ownerPod.vm.Id, hypervisor.ShareDirTag, c.Id, "rootfs") os.MkdirAll(vmRootfs, 0755) err = utils.Mount(u.Image, vmRootfs, c.Spec.Root.Readonly) if err != nil { glog.V(1).Infof("mount %s to %s failed: %s\n", u.Image, vmRootfs, err.Error()) return err } envs := make(map[string]string) for _, env := range u.Envs { envs[env.Env] = env.Value } info := &hypervisor.ContainerInfo{ Id: c.Id, Rootfs: "rootfs", Image: c.Id, Fstype: "dir", Cmd: u.Command, Envs: envs, } err = c.ownerPod.vm.Attach(p.stdio, c.Id, nil) if err != nil { glog.V(1).Infof("StartPod fail: fail to set up tty connection.\n") return err } err = execPrestartHooks(c.Spec, state) if err != nil { glog.V(1).Infof("execute Prestart hooks failed, %s\n", err.Error()) return err } c.ownerPod.podStatus.AddContainer(c.Id, c.ownerPod.podStatus.Id, "", []string{}, types.S_POD_CREATED) c.ownerPod.vm.NewContainer(u, info) err = execPoststartHooks(c.Spec, state) if err != nil { glog.V(1).Infof("execute Poststart hooks failed %s\n", err.Error()) } err = p.stdio.WaitForFinish() if err != nil { glog.V(1).Infof("get exit code failed %s\n", err.Error()) } err = execPoststopHooks(c.Spec, state) if err != nil { glog.V(1).Infof("execute Poststop hooks failed %s\n", err.Error()) return err } return nil } func (c *Container) addProcess(processId, stdin, stdout, stderr string, spec *specs.Process) (*Process, error) { if _, ok := c.ownerPod.Processes[processId]; ok { return nil, fmt.Errorf("conflict process ID") } if _, ok := c.Processes[processId]; ok { return nil, fmt.Errorf("conflict process ID") } if _, ok := c.Processes["init"]; !ok { return nil, fmt.Errorf("init process of the container %s had already exited", c.Id) } if processId == "init" { // test in case the init process is being reaped return nil, fmt.Errorf("conflict process ID") } p := &Process{ Id: processId, Stdin: stdin, Stdout: stdout, Stderr: stderr, Spec: spec, ProcId: -1, inerId: processId, ownerCont: c, } err := p.setupIO() if err != nil { return nil, err } c.ownerPod.Processes[processId] = p c.Processes[processId] = p e := Event{ ID: c.Id, Type: EventProcessStart, Timestamp: time.Now(), PID: processId, } c.ownerPod.sv.Events.notifySubscribers(e) go func() { err := c.ownerPod.vm.AddProcess(c.Id, spec.Terminal, spec.Args, spec.Env, spec.Cwd, p.stdio) if err != nil { glog.V(1).Infof("add process to container failed: %v\n", err) } else { err = p.stdio.WaitForFinish() } e := Event{ ID: c.Id, Type: EventExit, Timestamp: time.Now(), PID: processId, } if err != nil { e.Status = -1 glog.V(1).Infof("get exit code failed %s\n", err.Error()) } else { e.Status = int(p.stdio.ExitCode) } c.ownerPod.sv.Events.notifySubscribers(e) }() return p, nil } func execHook(hook specs.Hook, state *specs.State) error { b, err := json.Marshal(state) if err != nil { return err } cmd := exec.Cmd{ Path: hook.Path, Args: hook.Args, Env: hook.Env, Stdin: bytes.NewReader(b), } return cmd.Run() } func execPrestartHooks(rt *specs.Spec, state *specs.State) error { for _, hook := range rt.Hooks.Prestart { err := execHook(hook, state) if err != nil { return err } } return nil } func execPoststartHooks(rt *specs.Spec, state *specs.State) error { for _, hook := range rt.Hooks.Poststart { err := execHook(hook, state) if err != nil { glog.V(1).Infof("exec Poststart hook %s failed %s", hook.Path, err.Error()) } } return nil } func execPoststopHooks(rt *specs.Spec, state *specs.State) error { for _, hook := range rt.Hooks.Poststop { err := execHook(hook, state) if err != nil { glog.V(1).Infof("exec Poststop hook %s failed %s", hook.Path, err.Error()) } } return nil } func (c *Container) reap() { containerSharedDir := filepath.Join(hypervisor.BaseDir, c.ownerPod.vm.Id, hypervisor.ShareDirTag, c.Id) utils.Umount(filepath.Join(containerSharedDir, "rootfs")) os.RemoveAll(containerSharedDir) os.RemoveAll(filepath.Join(c.ownerPod.sv.StateDir, c.Id)) }
91e67495ec98adcd4bc2c17bd08c0e2d1910eaf5
[ "Makefile", "Go", "Markdown", "Shell" ]
80
Go
YaoZengzeng/Growth
555bd5a23cd48d8283bdbaa73e941a6ad9868160
6d9568318425dea0ed8852aca7a0a2156d342ddb
refs/heads/master
<repo_name>DanieleVeri/launchpad<file_sep>/HookingRawInputDemoDLL/HookingRawInputDemoDLL.cpp /* This project serves as a simple demonstration for the article "Combining Raw Input and keyboard Hook to selectively block input from multiple keyboards", which you should be able to find in this project folder (HookingRawInput.html), or on the CodeProject website (http://www.codeproject.com/). The project is based on the idea shown to me by <NAME> (http://www.hidmacros.eu/), and is published with his permission, huge thanks to Petr! The source code is licensed under The Code Project Open License (CPOL), feel free to adapt it. <NAME> (<EMAIL>), 2014 */ #include "stdafx.h" #include <stdio.h> #include "HookingRawInputDemoDLL.h" #pragma data_seg (".SHARED") // Windows message for communication between main executable and DLL module UINT const WM_HOOK = WM_APP + 1; // HWND of the main executable (managing application) HWND hwndServer = NULL; #pragma data_seg () #pragma comment (linker, "/section:.SHARED,RWS") HINSTANCE instanceHandle; HHOOK hookHandle; BOOL APIENTRY DllMain (HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved) { switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: instanceHandle = hModule; hookHandle = NULL; break; case DLL_THREAD_ATTACH: case DLL_THREAD_DETACH: case DLL_PROCESS_DETACH: break; } return TRUE; } // Keyboard Hook procedure static LRESULT CALLBACK KeyboardProc (int code, WPARAM wParam, LPARAM lParam) { if (code < 0) { return CallNextHookEx (hookHandle, code, wParam, lParam); } // Report the event to the main window. If the return value is 1, block the input; otherwise pass it along the Hook Chain if (SendMessage (hwndServer, WM_HOOK, wParam, lParam)) { return 1; } return CallNextHookEx (hookHandle, code, wParam, lParam); } BOOL InstallHook (HWND hwndParent) { if (hwndServer != NULL) { // Already hooked return FALSE; } // Register keyboard Hook hookHandle = SetWindowsHookEx (WH_KEYBOARD, (HOOKPROC)KeyboardProc, instanceHandle, 0); if (hookHandle == NULL) { return FALSE; } hwndServer = hwndParent; return TRUE; } BOOL UninstallHook () { if (hookHandle == NULL) { return TRUE; } // If unhook attempt fails, check whether it is because of invalid handle (in that case continue) if (!UnhookWindowsHookEx (hookHandle)) { DWORD error = GetLastError (); if (error != ERROR_INVALID_HOOK_HANDLE) { return FALSE; } } hwndServer = NULL; hookHandle = NULL; return TRUE; } <file_sep>/HookingRawInputDemoDLL/HookingRawInputDemoDLL.h #ifdef HOOKINGRAWINPUTDEMODLL_EXPORTS #define HOOKINGRAWINPUTDEMODLL_API __declspec(dllexport) #else #define HOOKINGRAWINPUTDEMODLL_API __declspec(dllimport) #endif HOOKINGRAWINPUTDEMODLL_API BOOL InstallHook (HWND hwndParent); HOOKINGRAWINPUTDEMODLL_API BOOL UninstallHook (); <file_sep>/HookingRawInputDemo/HookingRawInputDemo.cpp #include "stdafx.h" #include "HookingRawInputDemo.h" #include "HookingRawInputDemoDLL.h" #define MAX_LOADSTRING 100 #define MAX_PATH_LEN 255 #define KEY_NUM 45 #define KEY_LIST L"<KEY>"; #define CONFIG_FILE ".\\launchpad_config.txt" typedef struct { wchar_t ch; wchar_t file[MAX_PATH_LEN]; HWND button; HWND textbox; } MacroKey; // Global Variables: HINSTANCE hInst; // current instance TCHAR szTitle[MAX_LOADSTRING]; // The title bar text TCHAR szWindowClass[MAX_LOADSTRING]; // the main window class name // HWND of main executable HWND mainHwnd; // Windows message for communication between main executable and DLL module UINT const WM_HOOK = WM_APP + 1; // How long should Hook processing wait for the matching Raw Input message (ms) DWORD maxWaitingTime = 100; // Device name of my numeric keyboard (use escape for slashes) WCHAR* numericKeyboardDeviceName = NULL; // Buffer for the decisions whether to block the input with Hook std::deque<DecisionRecord> decisionBuffer; // Forward declarations of functions included in this code module: ATOM MyRegisterClass(HINSTANCE hInstance); BOOL InitInstance(HINSTANCE, int); LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); INT_PTR CALLBACK About(HWND, UINT, WPARAM, LPARAM); MacroKey macros[KEY_NUM]; OPENFILENAME ofn = { sizeof ofn }; void load_macros(); void save_macros(); void paired_key(HWND* hwnd); void play_vkey(USHORT vkey); int APIENTRY _tWinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPTSTR lpCmdLine, _In_ int nCmdShow) { UNREFERENCED_PARAMETER(hPrevInstance); UNREFERENCED_PARAMETER(lpCmdLine); // TODO: Place code here. MSG msg; HACCEL hAccelTable; // Initialize global strings LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING); LoadString(hInstance, IDC_HOOKINGRAWINPUTDEMO, szWindowClass, MAX_LOADSTRING); MyRegisterClass(hInstance); // Perform application initialization: if (!InitInstance (hInstance, nCmdShow)) { return FALSE; } hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_HOOKINGRAWINPUTDEMO)); // Main message loop: while (GetMessage(&msg, NULL, 0, 0)) { if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg)) { if (msg.message == WM_LBUTTONUP) { for (int i = 0; i < KEY_NUM; i++) { if (msg.hwnd == macros[i].button) { macros[i].file[0] = '\0'; ofn.lpstrFile = macros[i].file; ofn.nMaxFile = sizeof(macros[i].file); GetOpenFileName(&ofn); SetWindowText(macros[i].textbox, macros[i].file); break; } } } TranslateMessage(&msg); DispatchMessage(&msg); } } return (int) msg.wParam; } ATOM MyRegisterClass(HINSTANCE hInstance) { WNDCLASSEX wcex; wcex.cbSize = sizeof(WNDCLASSEX); wcex.style = CS_HREDRAW | CS_VREDRAW; wcex.lpfnWndProc = WndProc; wcex.cbClsExtra = 0; wcex.cbWndExtra = 0; wcex.hInstance = hInstance; wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_HOOKINGRAWINPUTDEMO)); wcex.hCursor = LoadCursor(NULL, IDC_ARROW); wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1); wcex.lpszMenuName = MAKEINTRESOURCE(IDC_HOOKINGRAWINPUTDEMO); wcex.lpszClassName = szWindowClass; wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL)); return RegisterClassEx(&wcex); } BOOL InitInstance(HINSTANCE hInstance, int nCmdShow) { HWND hWnd; hInst = hInstance; // Store instance handle in our global variable hWnd = CreateWindowEx(NULL, szWindowClass, szTitle, WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, 1050, 750, NULL, NULL, hInstance, NULL); if (!hWnd) { return FALSE; } // Save the HWND mainHwnd = hWnd; ShowWindow(hWnd, nCmdShow); UpdateWindow(hWnd); // Register for receiving Raw Input for keyboards RAWINPUTDEVICE rawInputDevice[1]; rawInputDevice[0].usUsagePage = 1; rawInputDevice[0].usUsage = 6; rawInputDevice[0].dwFlags = RIDEV_INPUTSINK; rawInputDevice[0].hwndTarget = hWnd; RegisterRawInputDevices (rawInputDevice, 1, sizeof (rawInputDevice[0])); ofn.lpstrFilter = L"Format: WAV\0*.wav\0"; ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_NOCHANGEDIR; // Set up the keyboard Hook InstallHook (hWnd); return TRUE; } LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { int wmId, wmEvent; PAINTSTRUCT ps; HDC hdc; switch (message) { // Raw Input Message case WM_INPUT: { UINT bufferSize; // Prepare buffer for the data GetRawInputData ((HRAWINPUT)lParam, RID_INPUT, NULL, &bufferSize, sizeof (RAWINPUTHEADER)); LPBYTE dataBuffer = new BYTE[bufferSize]; // Load data into the buffer GetRawInputData((HRAWINPUT)lParam, RID_INPUT, dataBuffer, &bufferSize, sizeof (RAWINPUTHEADER)); RAWINPUT* raw = (RAWINPUT*)dataBuffer; // Get the virtual key code of the key and report it USHORT virtualKeyCode = raw->data.keyboard.VKey; USHORT keyPressed = raw->data.keyboard.Flags & RI_KEY_BREAK ? 0 : 1; WCHAR text[128]; swprintf_s (text, 128, L"Raw Input: %X (%d)\n", virtualKeyCode, keyPressed); //OutputDebugString (text); // Prepare string buffer for the device name GetRawInputDeviceInfo (raw->header.hDevice, RIDI_DEVICENAME, NULL, &bufferSize); WCHAR* stringBuffer = new WCHAR[bufferSize]; // Load the device name into the buffer GetRawInputDeviceInfo (raw->header.hDevice, RIDI_DEVICENAME, stringBuffer, &bufferSize); if (numericKeyboardDeviceName == NULL) { numericKeyboardDeviceName = (WCHAR*) malloc(bufferSize * sizeof(wchar_t)); wcscpy_s(numericKeyboardDeviceName, bufferSize, stringBuffer); } //OutputDebugString(stringBuffer); // and remember the decision whether to block the input if (wcscmp (stringBuffer, numericKeyboardDeviceName) == 0) { decisionBuffer.push_back (DecisionRecord (virtualKeyCode, TRUE)); } else { decisionBuffer.push_back (DecisionRecord (virtualKeyCode, FALSE)); } delete[] stringBuffer; delete[] dataBuffer; return 0; } // Message from Hooking DLL case WM_HOOK: { USHORT virtualKeyCode = (USHORT)wParam; USHORT keyPressed = lParam & 0x80000000 ? 0 : 1; WCHAR text[128]; swprintf_s (text, 128, L"Hook: %X (%d)\n", virtualKeyCode, keyPressed); //OutputDebugString (text); // Check the buffer if this Hook message is supposed to be blocked; return 1 if it is BOOL blockThisHook = FALSE; BOOL recordFound = FALSE; int index = 1; if (!decisionBuffer.empty ()) { // Search the buffer for the matching record std::deque<DecisionRecord>::iterator iterator = decisionBuffer.begin (); while (iterator != decisionBuffer.end ()) { if (iterator->virtualKeyCode == virtualKeyCode) { blockThisHook = iterator->decision; recordFound = TRUE; // Remove this and all preceding messages from the buffer for (int i = 0; i < index; ++i) { decisionBuffer.pop_front (); } // Stop looking break; } ++iterator; ++index; } } // Wait for the matching Raw Input message if the decision buffer was empty or the matching record wasn't there DWORD currentTime, startTime; startTime = GetTickCount (); while (!recordFound) { MSG rawMessage; while (!PeekMessage (&rawMessage, mainHwnd, WM_INPUT, WM_INPUT, PM_REMOVE)) { // Test for the maxWaitingTime currentTime = GetTickCount (); // If current time is less than start, the time rolled over to 0 if ((currentTime < startTime ? ULONG_MAX - startTime + currentTime : currentTime - startTime) > maxWaitingTime) { // Ignore the Hook message, if it exceeded the limit WCHAR text[128]; swprintf_s (text, 128, L"Hook TIMED OUT: %X (%d)\n", virtualKeyCode, keyPressed); //OutputDebugString (text); return 0; } } // The Raw Input message has arrived; decide whether to block the input UINT bufferSize; // Prepare buffer for the data GetRawInputData ((HRAWINPUT)rawMessage.lParam, RID_INPUT, NULL, &bufferSize, sizeof (RAWINPUTHEADER)); LPBYTE dataBuffer = new BYTE[bufferSize]; // Load data into the buffer GetRawInputData((HRAWINPUT)rawMessage.lParam, RID_INPUT, dataBuffer, &bufferSize, sizeof (RAWINPUTHEADER)); RAWINPUT* raw = (RAWINPUT*)dataBuffer; // Get the virtual key code of the key and report it USHORT rawVirtualKeyCode = raw->data.keyboard.VKey; USHORT rawKeyPressed = raw->data.keyboard.Flags & RI_KEY_BREAK ? 0 : 1; WCHAR text[128]; swprintf_s (text, 128, L"Raw Input WAITING: %X (%d)\n", rawVirtualKeyCode, rawKeyPressed); //OutputDebugString (text); // Prepare string buffer for the device name GetRawInputDeviceInfo (raw->header.hDevice, RIDI_DEVICENAME, NULL, &bufferSize); WCHAR* stringBuffer = new WCHAR[bufferSize]; // Load the device name into the buffer GetRawInputDeviceInfo (raw->header.hDevice, RIDI_DEVICENAME, stringBuffer, &bufferSize); // If the Raw Input message doesn't match the Hook, push it into the buffer and continue waiting if (virtualKeyCode != rawVirtualKeyCode) { // decide whether to block the input if (wcscmp (stringBuffer, numericKeyboardDeviceName) == 0) { decisionBuffer.push_back (DecisionRecord (rawVirtualKeyCode, TRUE)); } else { decisionBuffer.push_back (DecisionRecord (rawVirtualKeyCode, FALSE)); } } else { // This is correct Raw Input message recordFound = TRUE; // decide whether to block the input if (wcscmp (stringBuffer, numericKeyboardDeviceName) == 0) { blockThisHook = TRUE; } else { blockThisHook= FALSE; } } delete[] stringBuffer; delete[] dataBuffer; } // Apply the decision if (blockThisHook) { play_vkey(virtualKeyCode); swprintf_s (text, 128, L"Keyboard event: %X (%d) is being blocked!\n", virtualKeyCode, keyPressed); //OutputDebugString (text); return 1; } return 0; } case WM_COMMAND: wmId = LOWORD(wParam); wmEvent = HIWORD(wParam); // Parse the menu selections: switch (wmId) { case IDM_ABOUT: DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About); break; case IDM_EXIT: DestroyWindow(hWnd); break; default: return DefWindowProc(hWnd, message, wParam, lParam); } break; case WM_PAINT: hdc = BeginPaint(hWnd, &ps); EndPaint(hWnd, &ps); break; case WM_DESTROY: save_macros(); UninstallHook(); PostQuitMessage(0); break; case WM_CREATE: MessageBox(hWnd, L"Press ENTER to register the launchpad keyboard", L"Welcome", MB_OK); load_macros(); paired_key(&hWnd); break; default: return DefWindowProc(hWnd, message, wParam, lParam); } return 0; } void play_vkey(USHORT vkey) { char c = MapVirtualKeyA(vkey, MAPVK_VK_TO_CHAR); if (c == 0) return; for (int i = 0; i < KEY_NUM; i++) { if (macros[i].ch == c) { wchar_t stop_command[MAX_PATH_LEN] = L"stop "; wchar_t start_command[MAX_PATH_LEN] = L"play "; wcsncat_s(stop_command, macros[i].file, wcslen(macros[i].file)); wcsncat_s(start_command, macros[i].file, wcslen(macros[i].file)); mciSendString(stop_command, NULL, 0, NULL); mciSendString(start_command, NULL, 0, NULL); break; } } } void paired_key(HWND* hwnd) { for (int i = 0; i<KEY_NUM; i++) { wchar_t s[2]; s[0] = macros[i].ch; s[1] = '\0'; macros[i].button = CreateWindow(L"button", s, WS_CHILD | WS_VISIBLE | BS_DEFPUSHBUTTON, 25 + (i / 25) * 500, 25 + (i % 25) * 25, 50, 20, *hwnd, (HMENU)1000+i, hInst, NULL); macros[i].textbox = CreateWindow(L"EDIT", macros[i].file, WS_CHILD | WS_VISIBLE | WS_BORDER | ES_LEFT | ES_AUTOHSCROLL | ES_WANTRETURN, 100 + (i / 25) * 500, 25 + (i % 25) * 25, 400, 20, *hwnd, (HMENU)1200+i, hInst, NULL); } } void load_macros() { char buf[MAX_PATH_LEN]; FILE* f; fopen_s(&f, CONFIG_FILE, "r"); // no config found const wchar_t* list = KEY_LIST; for (int i = 0; i < KEY_NUM; i++) { macros[i].ch = list[i]; if (f == NULL) macros[i].file[0] = '\0'; else { fgets(buf, sizeof buf, f); buf[strlen(buf) - 1] = '\0'; //remove \n swprintf(macros[i].file, MAX_PATH_LEN, L"%hs", buf); } } if (f != NULL) fclose(f); } void save_macros() { FILE* f; auto err = fopen_s(&f, CONFIG_FILE, "w+"); if (err) { auto e = GetLastError(); return; } for (int i = 0; i<KEY_NUM; i++) { char buf[MAX_PATH_LEN]; sprintf_s(buf, "%ws", macros[i].file); fprintf_s(f, "%s\n", buf); } fclose(f); } // Message handler for about box. INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) { UNREFERENCED_PARAMETER(lParam); switch (message) { case WM_INITDIALOG: return (INT_PTR)TRUE; case WM_COMMAND: if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL) { EndDialog(hDlg, LOWORD(wParam)); return (INT_PTR)TRUE; } break; } return (INT_PTR)FALSE; } <file_sep>/HookingRawInputDemo/HookingRawInputDemo.h /* This project serves as a simple demonstration for the article "Combining Raw Input and keyboard Hook to selectively block input from multiple keyboards", which you should be able to find in this project folder (HookingRawInput.html), or on the CodeProject website (http://www.codeproject.com/). The project is based on the idea shown to me by <NAME> (http://www.hidmacros.eu/), and is published with his permission, huge thanks to Petr! The source code is licensed under The Code Project Open License (CPOL), feel free to adapt it. <NAME> (<EMAIL>), 2014 */ #pragma once #include "resource.h" // Structure of a single record that will be saved in the decisionBuffer struct DecisionRecord { USHORT virtualKeyCode; BOOL decision; DecisionRecord (USHORT _virtualKeyCode, BOOL _decision) : virtualKeyCode (_virtualKeyCode), decision (_decision) {} };
5a63ec0f58f924678838c7ba33c85d0f4e46be36
[ "C", "C++" ]
4
C++
DanieleVeri/launchpad
2409bba022cc4355fe47ee8322d53977a91a3118
3d893d1c5a15ac4e4a9f156c843b0526d1390bbd
refs/heads/master
<file_sep># Automatic inserting image in green rectangles in other image taking into account their geometric distortions. ## For example: The image to be inserted:<br> ![insert](image/insert.jpg) The image into which is inserted: ![input](image/input.png) Resulting image: ![result](image/result.png) <file_sep>import sys import numpy as np import cv2 def image_insertion(img_to_be_inserted: str, img_into_which_is_inserted: str, img_result: str='./result.png'): input_img = cv2.imread(img_to_be_inserted) Yo, Xo, _ = input_img.shape insert_img = cv2.imread(img_into_which_is_inserted) Y, X, _ = insert_img.shape # color space change hsv = cv2.cvtColor(input_img, cv2.COLOR_BGR2HSV) # shades color limits lower_green = np.array([50, 50, 50]) upper_green = np.array([70, 255, 255]) # figure selection mask = cv2.inRange(hsv, lower_green, upper_green) # contour selection edged = cv2.Canny(mask, 1000, 1500) # contour closure kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (7, 7)) closed = cv2.morphologyEx(edged, cv2.MORPH_CLOSE, kernel) # find contours cnts = cv2.findContours(closed.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[0] for c in cnts: peri = cv2.arcLength(c, True) approx = cv2.approxPolyDP(c, 0.02*peri, True) if len(approx) == 4: pts1 = np.float32([[0, 0],[X, 0],[0, Y],[X, Y]]) pts2 = np.array([i[0] for i in approx]) pts2 = np.float32(pts2) pts2 = pts2 +1 pts2[0], pts2[1] = pts2[1].copy(), pts2[0].copy() if pts2[0][1] == np.min(np.min(pts2, axis=1)): temp = pts2[1:].copy() if not temp[0][1] == np.min(np.min(temp, axis=1)): pts2[0], pts2[1], pts2[2], pts2[3] = pts2[1].copy(), pts2[3].copy(), pts2[0].copy(), pts2[2].copy() elif pts2[1][1] == np.min(np.min(pts2, axis=1)): temp = np.concatenate(([pts2[0]], pts2[2:])) if not temp[0][1] == np.min(np.min(temp, axis=1)): pts2[0], pts2[1], pts2[2], pts2[3] = pts2[1].copy(), pts2[3].copy(), pts2[0].copy(), pts2[2].copy() M = cv2.getPerspectiveTransform(pts1, pts2) dst = cv2.warpPerspective(insert_img, M, (Xo, Yo)) # cut all black pixels dst = cv2.cvtColor(dst, cv2.COLOR_BGR2BGRA) dst[np.all(dst == [0, 0, 0, 255], axis=2)] = [0, 0, 0, 0] # cut green rectangle stencil = np.zeros(input_img.shape).astype(input_img.dtype) contours = [approx] cv2.fillPoly(input_img, contours, [0,0,0]) input_img = cv2.cvtColor(input_img, cv2.COLOR_BGR2BGRA) input_img[np.all(input_img == [0, 0, 0, 255], axis=2)] = [0, 0, 0, 0] added_image = cv2.addWeighted(input_img, 1, dst, 1, 0) cv2.imwrite(img_result, added_image) def main(): try: image_insertion(sys.argv[1], sys.argv[2]) except IndexError as e: print('Error: Must be entered path to image files.') if __name__ == '__main__': main()
61b49b5374d7e32e400fdabb1943bc3748353ef5
[ "Markdown", "Python" ]
2
Markdown
BublikR/image_insertion
41801c87ac6cb415d71174861a5b58c6e7bce076
081a9c537b6345d3454abedbd353d14b34ead919
refs/heads/master
<repo_name>malloc-wes/SScore<file_sep>/client/src/components/Main.js import React from 'react'; import { Switch, Route } from 'react-router-dom'; import LandingPage from '../components/LandingPage/LandingPage' import Home from './Home'; import Charts from './Charts'; import WhatIf from './WhatIf'; import Learn from './Learn'; import Logout from './Logout'; const Main = () => ( <main> <Switch> <Route exact path="/" component={LandingPage} /> <Route exact path='/Home' component={Home} /*onEnter={requireAuth}*/ /> <Route exact path='/Charts' component={Charts} /> <Route exact path='/WhatIf' component={WhatIf} /> <Route exact path='/learn' component={Learn} /> <Route exact path='/logout' component={Logout} /> </Switch> </main> ) export default Main;<file_sep>/client/src/components/NavBar.js import React, { Component } from 'react'; import mainlogo from './logo.png'; //If Links have to be used: import { Link } from 'react-router-dom'; class NavBar extends Component { render() { return( <div> <nav className="grey darken-3" > <div className="nav-wrapper"> <a href="/" className="brand-logo"><img src={mainlogo} alt="log"></img></a> <a href="home.html" data-target="mobile-demo" className="sidenav-trigger"><i className="material-icons">menu</i></a> <ul className="right hide-on-med-and-down"> <li><Link to="/charts"><i className="material-icons">pie_chart</i>Charts</Link></li> <li><Link to="/whatif"><i className="material-icons">live_help</i>What-If</Link></li> <li><Link to="/learn"><i className="material-icons">wb_incandescent</i>Learn</Link></li> <li><Link to="/logout"><i className="material-icons">offline_pin</i>Logout</Link></li> </ul> </div> </nav> <ul className="sidenav" id="mobile-demo"> <li><Link to="/charts"><i className="material-icons">pie_chart</i></Link></li> <li><Link to="/whatif"><i className="material-icons">live_help</i></Link></li> <li><Link to="/learn"><i className="material-icons">wb_incandescent</i></Link></li> <li><Link to="/logout"><i className="material-icons">offline_pin</i></Link></li> </ul> </div> ); } } export default NavBar;<file_sep>/client/src/App.js import React from 'react'; import { Switch, Route, Redirect } from "react-router-dom"; import './App.css'; import NavBar from './components/NavBar'; import LandingPage from './components/LandingPage/LandingPage' import Home from './components/Home'; import Charts from './components/Charts'; import WhatIf from './components/WhatIf'; import Learn from './components/Learn'; import Logout from './components/Logout'; import API from "./utils/API"; class App extends React.Component{ state = { loggedIn: false, user: null } handleSignup = newUser => { API.signUp(newUser) .then(function(data){ this.setState({ user: data.data }); }); } handleLogin = userInfo => { API.login(userInfo) .then(function(data){ this.setState({ user: data.data }); }); this.setState = this.setState.bind(this); } renderThis = () =>{ if(this.state.loggedIn){ return [ <Route key={"home"} exact path='/Home' component={Home} /*onEnter={requireAuth}*/ />, <Route key={"charts"} exact path='/Charts' component={Charts} />, <Route key={"whatIf"} exact path='/WhatIf' component={WhatIf} />, <Route key={"learn"} exact path='/learn' component={Learn} />, <Route key={"logout"} exact path='/logout' component={Logout} /> ]; } return <Redirect to={"/"}/>; } render(){ return ( <div> { this.state.loggedIn ? <NavBar /> : null } <Switch> <Route exact path="/" render={ () => { return <LandingPage signUp={this.handleSignup} signIn={this.handleLogin} />}} /> {this.renderThis()} </Switch> </div> ); } } export default App; <file_sep>/client/src/components/WhatIf.js import React, { Component } from 'react'; import axios from 'axios'; import ClassWhatIf from "./ClassWhatIf"; class WhatIf extends Component { state = { jobs: [] } getJob = (e) => { e.preventDefault(); const job = e.target.elements.jobtitle.value; axios.get(`https://indreed.herokuapp.com/api/jobs?q=${job}&limit=10`).then((res) => { //console.log(res); //I can display a sigle index with (jobs[0]): let jobs = res.data; //console.log(jobs[0].title); this.setState({ jobs: jobs }); console.log(this.state.jobs); }) } render() { return ( <div className="datapull"> <ClassWhatIf getJob={this.getJob} /> <h1> <img src="logo_a.png" className="App-logo" alt="logo" /></h1> {this.state.jobs.map((job) => { return <li style={{ fontWeight: "bold" }} key={job.id}>{job.title} <p style={{ fontFamily: "Serif", fontWeight: "normal", fontStyle: "italic" }}>{job.location}</p> <p style={{ fontFamily: "Serif", fontWeight: "normal" }}>{job.summary}</p> <p style={{ fontFamily: "Serif", fontWeight: "normal" }}>{job.url}</p> </li> })} </div> ); } } export default WhatIf;<file_sep>/client/src/utils/API.js import axios from "axios"; export default { login: function(userInfo){ return axios.post("/api/users", userInfo); }, signUp: function(newUser){ console.log("SIGNUP: ", newUser) return axios.post("/api/users", newUser); } } <file_sep>/client/src/components/ClassWhatIf.js import React from 'react'; import '../App.css'; const ClassWhatIf = (props) => { return ( <form className="box" onSubmit={props.getJob}> <input style={{ margin: "20px auto", display: "block"}} type="text" name="jobtitle" /> <button>Submit</button> </form> ); } export default ClassWhatIf;<file_sep>/scripts/SeedDB.js const mongoose = require("mongoose"); const db = require("../models"); // This file empties the SkillSets collection and inserts the skills below mongoose.connect( process.env.MONGODB_URI || "mongodb://localhost/skillScoredb" ); const skillSetSeed = [ { skill: "Is this working?" } ]; db.SkillSet .remove({}) .then(() => db.SkillSet.collection.insertMany(skillSetSeed)) .then(data => { console.log(data.result.n + " records inserted!"); process.exit(0); }) .catch(err => { console.error(err); process.exit(1); });
1e51509951943d4a5fbc1093bc45358973ccc88b
[ "JavaScript" ]
7
JavaScript
malloc-wes/SScore
1a6b992fdc7e9fc5e6979538ebbe2d2e2922f10d
63a2bab2093dc339cb339e53e7da681eda55fb76
refs/heads/master
<file_sep>create table PRODUCTS( NAME varchar(255), CATEGORY varchar(255) ); create table PRODUCTPRICEHISTORY( NAME varchar(255), PRICE float, STARTDATE date, ENDDATE date ); select * from PRODUCTS Inner Join PRODUCTPRICEHISTORY on PRODUCTS.NAME = PRODUCTPRICEHISTORY.Name;<file_sep># Taboola-Assessment Backend Engineer Intern Take Home Test The purpose of this test is to evaluate your technical abilities in a few aspects of software engineering. It allows common grounds for discussion in the interview that takes place after you complete the test. The test is a home test and you are encouraged to use any resources at your disposal - online or consulting friends, etc. Please submit your code via a Github repository and send us link to the Github repo. You should be able to answer these 3 questions within 1 hour. 1. Write a Java program that take a string input and convert it to an integer without using the build-in parse function. Example: input value “123”, convert it to an integer type with value 123 2. Write a Java program that take a input and detect whether there’s integer in there. Example: input value “45222” return true, input value “This Is A Test4me” return true, input value “IAMGOOD” return false 3. Please design two new tables to store information about: a. products b. product price history The product tables should include the name and category of the product. The product price history table should refer to the product table and should include the price information of products and the start date and/or end date for the product. The current price of a product will have no end date. Please list the table creation scripts for these two tables and a sample query to join two tables together. <file_sep>public class question1and2 { public static int toInt(String word) { int x = 1; if(word.charAt(0) == '-') { x = x * -1; word = word.substring(1,word.length()); } int ans = 0; for(int i = 0; i < word.length(); i++) { ans *= 10; ans = ans + (word.charAt(i) - 48); } ans = ans * x; return ans; } public static boolean hasInteger(String word) { for(int i = 0; i < word.length(); i++) { if(word.charAt(i) > 47 && word.charAt(i) <= 57) return true; } return false; } public static void main(String arg[]) { System.out.println(toInt("-123")); System.out.println(toInt("123")); System.out.println(toInt("0")); System.out.println(toInt("-1")); System.out.println(hasInteger("sa3fe")); System.out.println(hasInteger("safe")); System.out.println(hasInteger("sa:fe")); System.out.println(hasInteger("3safe")); } }
b5f340cc1805119f11147975cb0f492c2b5bdd00
[ "Markdown", "SQL", "Java" ]
3
SQL
wongalex349/Taboola-Assessment
450f07c3d11a6178d88f2005f28520b50906b455
db2d489b5bfb30916f9ee1d2520bcda153a38104
refs/heads/master
<repo_name>wycliffkas/ALC-challenge<file_sep>/README.md ## ALC-challenge This challenge is a simple Android Application with three Activities, the first Activity is the main Activity with two Buttons. - Button 1 takes you to Activity B when clicked. - Button 2 takes you to Activity C when clicked. Activity B is the About ALC page, it contains only a Webview that loads the URL https://andela.com/alc/ which is the ALC about page. Activity C is your profile, it contains an ImageView which should display your photo, TextViews showing your name, Track, Country, Email and Phone Number. <p float="left"> <img src="https://github.com/wycliffkas/ALC-challenge/blob/master/Screenshot.png" width="250" height="400" /> <img src="https://github.com/wycliffkas/ALC-challenge/blob/master/Screenshot2.png" width="250" height="400" /> <img src="https://github.com/wycliffkas/ALC-challenge/blob/master/Screenshot3.png" width="250" height="400" /> </p> ### Prerequisites You need the following : - Android studio. - Linux, macOS or Windows. ### Getting Started - Clone this repository to your local machine, using the command below. git clone https://github.com/wycliffkas/ALC-challenge.git - Change directory into "ALC-challenge", by running the command below. cd ALC-challenge - Then open your project in Android Studio and click Run.<file_sep>/app/src/main/java/com/r/alc_challenge/AboutALC.java package com.r.alc_challenge; import androidx.annotation.NonNull; import androidx.appcompat.app.ActionBar; import androidx.appcompat.app.AppCompatActivity; import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.content.Intent; import android.graphics.Bitmap; import android.net.Uri; import android.net.http.SslError; import android.os.Bundle; import android.view.MenuItem; import android.view.View; import android.webkit.SslErrorHandler; import android.webkit.WebResourceError; import android.webkit.WebResourceRequest; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.ProgressBar; import android.widget.Toast; public class AboutALC extends AppCompatActivity { private WebView webView; private ProgressBar progressBar; String url = "https://andela.com/alc"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_about_alc); webView = findViewById(R.id.web_view_about); progressBar = findViewById(R.id.progressDialog); progressBar.setVisibility(View.VISIBLE); webView.setWebViewClient(new WebViewClient() { @Override public void onReceivedSslError(WebView v, SslErrorHandler handler, SslError er){ handler.proceed(); } @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { super.onPageStarted(view, url, favicon); progressBar.setVisibility(View.VISIBLE); } @Override public void onPageFinished(WebView view, String url) { progressBar.setVisibility(View.GONE); } }); webView.getSettings().setJavaScriptEnabled(true); webView.getSettings().setLoadWithOverviewMode(true); webView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL); webView.getSettings().setUseWideViewPort(true); webView.loadUrl("https://andela.com/alc"); if(getSupportActionBar()!=null){ getSupportActionBar().setDisplayHomeAsUpEnabled(true); } } @Override public boolean onOptionsItemSelected(@NonNull MenuItem item) { if(item.getItemId() == android.R.id.home){ onBackPressed(); return true; } return super.onOptionsItemSelected(item); } }
274bded29ff92dade221aeb70767dbc3654a6007
[ "Markdown", "Java" ]
2
Markdown
wycliffkas/ALC-challenge
73dbc609b6f603341931c25ea5198854d81bc438
0b365455e99cc5c37abec97122a7e4c861cb2497
refs/heads/master
<file_sep>#! /usr/bin/python import os.path import tornado.httpserver import tornado.websocket import tornado.ioloop import tornado.web import RPi.GPIO as GPIO import time #def putarSudut(sudut): #siklus = ((sudut/180)+2.5) #pwm.ChangeDutyCycle(siklus) #Initialize Raspberry PI GPIO #GPIO.setwarnings(False) #GPIO.setmode(GPIO.BCM) #GPIO.setup(16, GPIO.OUT) GPIO.setwarnings(False) GPIO.setmode(GPIO.BOARD) GPIO.setup(11, GPIO.OUT) GPIO.setup(13, GPIO.OUT) GPIO.setup(16, GPIO.OUT) GPIO.setup(18, GPIO.OUT) GPIO.setup(22, GPIO.OUT) #GPIO.setup(24, GPIO.OUT) sebelas=11 #tigabelas=13 pwm=GPIO.PWM(sebelas, 50) #pwm=GPIO.PWM(tigabelas, 50) pwm.start(0) #pinServo=11 #Tornado Folder Paths settings = dict( template_path = os.path.join(os.path.dirname(__file__), "templates"), static_path = os.path.join(os.path.dirname(__file__), "static") ) #Tonado server port PORT = 80 class MainHandler(tornado.web.RequestHandler): def get(self): print "[HTTP](MainHandler) User Connected." self.render("login_rpl_1.html") class WSHandler(tornado.websocket.WebSocketHandler): def open(self): print '[WS] Connection was opened.' def on_message(self, message): print '[WS] Incoming message:', message #control LED 1 if message == "on_g": GPIO.output(18, True) if message == "off_g": GPIO.output(18, False) #control LED 2 if message == "on1_g": GPIO.output (22, True) if message == "off1_g": GPIO.output (22, False) #control LED 3 # if message == "nyala": # GPIO.output (24, True) # if message == "mati": # GPIO.output (24, False) #control relay if message == "on_TV": GPIO.output(16, True) if message == "off_TV": GPIO.output(16, False) #control Servo lockdoor if message == "on_kirim": pwm.ChangeDutyCycle(9) time.sleep(2) if message == "off_Pagar_kirim": pwm.ChangeDutyCycle(3.6) time.sleep(2) #control Servo Garansi #if message == "on_kirim_data_Pagar": # pwm.ChangeDutyCycle(9) # time.sleep(1) #if message == "off_kirim_data_Pagar": #pwm.ChangeDutyCycle(2) #time.sleep(1) def on_close(self): print '[WS] Connection was closed.' application = tornado.web.Application([ (r'/(favicon.ico)', tornado.web.StaticFileHandler, {"path": ""}), (r'/', MainHandler), (r'/ws', WSHandler), ], **settings) if __name__ == "__main__": try: http_server = tornado.httpserver.HTTPServer(application) http_server.listen(PORT) main_loop = tornado.ioloop.IOLoop.instance() print "Tornado Server started" main_loop.start() except: print "Exception triggered - Tornado Server stopped." GPIO.cleanup() #End of Program <file_sep>#! /usr/bin/python import os.path import tornado.httpserver import tornado.websocket import tornado.ioloop import tornado.web import RPi.GPIO as GPIO import time #def putarSudut(sudut): #siklus = ((sudut/180)+2.5) #pwm.ChangeDutyCycle(siklus) #Initialize Raspberry PI GPIO #GPIO.setwarnings(False) #GPIO.setmode(GPIO.BCM) #GPIO.setup(16, GPIO.OUT) GPIO.setwarnings(False) GPIO.setmode(GPIO.BOARD) GPIO.setup(11, GPIO.OUT) GPIO.setup(16, GPIO.OUT) GPIO.setup(22, GPIO.OUT) GPIO.setup(18, GPIO.OUT) pwm=GPIO.PWM(11, 50) pwm.start(0) #pinServo=11 #Tornado Folder Paths settings = dict( template_path = os.path.join(os.path.dirname(__file__), "templates"), static_path = os.path.join(os.path.dirname(__file__), "static") ) #Tonado server port PORT = 80 class MainHandler(tornado.web.RequestHandler): def get(self): print "[HTTP](MainHandler) User Connected." self.render("login.html") class WSHandler(tornado.websocket.WebSocketHandler): def open(self): print '[WS] Connection was opened.' def on_message(self, message): print '[WS] Incoming message:', message #control LED 1 if message == "on_g": GPIO.output(18, True) if message == "off_g": GPIO.output(18, False) #control LED 2 if message == "on1_g": GPIO.output (22, True) if message == "off1_g": GPIO.output (22, False) #control relay if message == "on_TV": GPIO.output(16, True) if message == "off_TV": GPIO.output(16, False) #control Servo if message == "on_kirim": pwm.ChangeDutyCycle(9) time.sleep(1) if message == "off_Pagar_kirim": pwm.ChangeDutyCycle(3.5) time.sleep(1) def on_close(self): print '[WS] Connection was closed.' application = tornado.web.Application([ (r'/', MainHandler), (r'/ws', WSHandler), ], **settings) if __name__ == "__main__": try: http_server = tornado.httpserver.HTTPServer(application) http_server.listen(PORT) main_loop = tornado.ioloop.IOLoop.instance() print "Tornado Server started" main_loop.start() except: print "Exception triggered - Tornado Server stopped." GPIO.cleanup() #End of Program<file_sep># IOT-smarthome-bootstrap-and-tornado-with-Raspberry-PI Using Bootstrap and Tornado on Raspberry PI before you use this source code to run Tornado Web Server on raspberry, there are some installation things that need to be done first. ### Upgrade & update dist your Raspberry Pi ```Upgrade & update sudo apt-get update && sudo apt-get dist-upgrade ``` ### Install python 3 ```python 3 sudo pip3 install --upgrade pip ``` ### Install Tornado Web Server ```python 3 sudo pip3 install tornado ``` finally you can use this source code for you to control the relay or led according to the port initialization that has been configured on server.py and you just type on your browser localhost then Tornado web server work <file_sep>$(document).ready(function(){ var WEBSOCKET_ROUTE = "/ws"; if(window.location.protocol == "http:"){ //localhost var ws = new WebSocket("ws://" + window.location.host + WEBSOCKET_ROUTE); } else if(window.location.protocol == "https:"){ //Dataplicity var ws = new WebSocket("wss://" + window.location.host + WEBSOCKET_ROUTE); } ws.onopen = function(evt) { $("#ws-status").html("Connected"); }; ws.onmessage = function(evt) { }; ws.onclose = function(evt) { $("#ws-status").html("Disconnected"); }; $("#Tombol_tombol").click(function (events) { $("#Panel_tombol").slideToggle() events.preventDefault()//untuk referesh tanpa tambah # }) //display kamar $("#Tombol_Action").click(function (events) { $("#Panel_Action").slideToggle() events.preventDefault() }) //display Dapur $("#Tombol_Dapur").click(function (events) { $("#Panel_Dapur").slideToggle() events.preventDefault() }) //tombol warna kirim sinyal (led_1) var stateLampuOn=true; $("#tombol_button").click(function (events) { //$(this).toggleClass("btn-primary") //events.preventDefault()//untuk referesh tanpa tambah # if(stateLampuOn){ $(this).toggleClass ("btn-primary"); $(this).removeClass ("btn-default"); $("#tombol_button").text("Hidup") //melakukan pergantian text ke hidup stateLampuOn=false; ws.send("on_g"); } else{ $(this).toggleClass ("btn-default"); $(this).removeClass ("btn-primary"); $("#tombol_button").text("Mati") stateLampuOn=true; ws.send("off_g"); } }) //tombol warna kirim sinyal (led_2) var stateLampuOn_1=true; $("#tombol_button_1").click(function (events) { //$(this).toggleClass("btn-primary") //events.preventDefault()//untuk referesh tanpa tambah # if(stateLampuOn_1){ $(this).toggleClass ("btn-primary"); $(this).removeClass ("btn-default"); $("#tombol_button_1").text("Hidup") //melakukan pergantian text ke hidup stateLampuOn_1=false; ws.send("nyala"); } else{ $(this).toggleClass ("btn-default"); $(this).removeClass ("btn-primary"); $("#tombol_button_1").text("Mati") stateLampuOn_1=true; ws.send("mati"); } }) //tombol warna kirim sinyal (led_3) var stateLampuOn2=true; $("#tombol_button2").click(function (events) { //$(this).toggleClass("btn-primary") //events.preventDefault()//untuk referesh tanpa tambah # if(stateLampuOn2){ $(this).toggleClass ("btn-primary"); $(this).removeClass ("btn-default"); $("#tombol_button2").text("Hidup") //melakukan pergantian text ke hidup stateLampuOn2=false; ws.send("on1_g"); } else{ $(this).toggleClass ("btn-default"); $(this).removeClass ("btn-primary"); $("#tombol_button2").text("Mati") stateLampuOn2=true; ws.send("off1_g"); } }) //tombol warna kirim sinyal (relay) var stateRelayOn=true; $("#tombol_button3").click(function (events) { //$(this).toggleClass("btn-primary") //events.preventDefault()//untuk referesh tanpa tambah # if(stateRelayOn){ $(this).toggleClass ("btn-primary"); $(this).removeClass ("btn-default"); $("#tombol_button3").text("Mati") //melakukan pergantian text ke hidup stateRelayOn=false; ws.send("on_TV"); } else{ $(this).toggleClass ("btn-default"); $(this).removeClass ("btn-primary"); $("#tombol_button3").text("Hidup") stateRelayOn=true; ws.send("off_TV"); } }) //tombol warna kirim sinyal (servo) var stateServoOn=true; $("#tombol_button4").click(function (events) { //$(this).toggleClass("btn-primary") //events.preventDefault()//untuk referesh tanpa tambah # if(stateServoOn){ $(this).toggleClass ("btn-primary"); $(this).removeClass ("btn-default"); $("#tombol_button4").text("Unlock") //melakukan pergantian text ke hidup stateServoOn=false; ws.send("on_kirim"); } else{ $(this).toggleClass ("btn-default"); $(this).removeClass ("btn-primary"); $("#tombol_button4").text("Lock") stateServoOn=true; ws.send("off_Pagar_kirim"); } }) //tombol warna kirim sinyal (servo pagar) var stateServo_1_On=true; $("#tombol_button_5").click(function (events) { //$(this).toggleClass("btn-primary") //events.preventDefault()//untuk referesh tanpa tambah # if(stateServo_1_On){ $(this).toggleClass ("btn-primary"); $(this).removeClass ("btn-default"); $("#tombol_button_5").text("Buka") //melakukan pergantian text ke hidup stateServo_1_On=false; ws.send("on_kirim_data_Pagar"); } else{ $(this).toggleClass ("btn-default"); $(this).removeClass ("btn-primary"); $("#tombol_button_5").text("Tutup") stateServo_1_On=true; ws.send("off_kirim_data_Pagar"); } }) });
4d3fea716227150badea7ae895a1a4c071ff0f44
[ "Markdown", "Python", "JavaScript" ]
4
Python
anjasmaradwisetiadi/IOT-smarthome-bootstrap-and-tornado
a54492bac832e85209dfd9cda4e277dd9f16a7b9
1f5ac290fd81a10a42137fcfcd0f3832a8491a95
refs/heads/master
<repo_name>miguelmota/rx-todo<file_sep>/Dockerfile FROM node:argon # Create app directory RUN mkdir -p /usr/src/app WORKDIR /usr/src/app # Install app dependencies COPY /package.json /usr/src/app/ RUN npm install RUN npm install babel-cli -g # Bundle app source COPY ./ /usr/src/app # Expose port EXPOSE 8080 # Set environment variables ENV NODE_ENV production CMD ["npm", "start"] <file_sep>/README.md # Yolk/RxJS/Express/Postgres Todo App > A Todo application built on top of [Yolk.js](https://github.com/garbles/yolk), [RxJS](https://github.com/Reactive-Extensions/RxJS), [Express](http://expressjs.com/), and [Postgres](http://www.postgresql.org/), which runs in [Docker](https://www.docker.com/) container. <img src="./screenshot.png" width="500"> # Demo [https://lab.miguelmota.com/rx-todo/](https://lab.miguelmota.com/rx-todo/) # Running To see it in action follow these steps: 1. Install Docker from [Downloads](https://docs.docker.com/engine/installation/) page. 2. Git clone this repo. ```bash $ git clone <EMAIL>:miguelmota/rx-todo.git ``` 3. Set up Docker and build. ```bash # Start docker daemon $ eval "$(docker-machine env default)" # Build $ docker-compose build ``` 4. Run Docker container. ```bash $ docker-compose up ``` 5. Open app url in browser. ```bash $ open http://$(docker-machine ip):8080/ ``` 6. Write todos! # Development Follow these steps to set up development environment. 1. Install Postgres from the [Downloads](http://www.postgresql.org/download/) page. 2. Configure postgres credentials in `app/config/config.json`. 3. Install node dependencies. ```bash $ npm install $ npm install babel-cli -g $ npm install gulp-cli -g $ npm install browserify -g $ npm install mocha-phantomjs -g ``` 4. Run Express server. ```bash $ npm start ``` 5. Run [Gulp](http://gulpjs.com/) watchers to compile client JavaScript and Sass on save. ```bash $ cd app/public/ $ gulp watch ``` Available Gulp tasks. ```bash # Compile JavaScript. $ gulp scripts # Compile Sass. $ gulp sass # Compile JavaScript and Sass. $ gulp build # Compile JavaScript and Sass on file save. $ gulp watch # Open client only url in browser. $ gulp browser ``` 6. Open app url in browser. ```bash $ open http://localhost:8080/ ``` # Test ```bash $ npm test ``` # Docs ```bash $ npm run docs ``` # License MIT. <file_sep>/gulpfile.js 'use strict'; const gulp = require('gulp'); const babel = require('gulp-babel'); const browserify = require('browserify'); const source = require('vinyl-source-stream'); const browserSync = require('browser-sync').create(); const sass = require('gulp-sass'); const concat = require('gulp-concat'); /** * @desc Compile browser script files. */ gulp.task('scripts', function() { return browserify({ entries: './app/public/scripts/index.jsx', extensions: ['.jsx'], debug: true }) .transform('babelify') .bundle() .pipe(source('app.js')) .pipe(gulp.dest('./app/public/dist')); }); /** * @desc Start browser sync. */ gulp.task('browser', function() { browserSync.init({ server: { baseDir: './app/public' } }); }); /** * @desc Compile SASS. */ gulp.task('sass', function() { return gulp.src('./app/public/styles/**/*.scss') .pipe(sass().on('error', sass.logError)) .pipe(gulp.dest('./app/public/dist')); }); /** * @desc Move files for build. */ gulp.task('move', function() { gulp.src([ './app/public/assets/themes/default/assets/fonts/*' ], { base: './app/public/assets/themes/default/assets/fonts/' }) .pipe(gulp.dest('./app/public/dist/themes/default/assets/fonts/')); }); /** * @desc Watch and compile files. */ gulp.task('watch', function() { gulp.watch('./app/public/scripts/**/*', ['scripts']); gulp.watch('./app/public/styles/**/*.scss', ['sass']); }); /** * @desc Build task. */ gulp.task('build', ['scripts', 'sass', 'move']); /** * @desc Default task. */ gulp.task('default', ['watch']); <file_sep>/app/public/scripts/constants/ApiEndpoints.js 'use strict'; const hostname = (typeof window === 'object' ? window.location.hostname : 'localhost'); /** * API_BASE_URL * @type {String} * @memberof client/constants */ export const API_BASE_URL = `http://${hostname}:8080/api`; /** * API_ENPOINTS * @desc Enum containing API endpoints. * @type {Object} * @memberof client/constants */ export const API_Endpoints = { TODOS: `${API_BASE_URL}/todos` }; <file_sep>/app/public/scripts/utils/createTodo.js 'use strict'; import Immutable from 'immutable'; import {generateId} from './generateId' /** * createTodo * @desc Creates a todo Map from a task value. * @type {Function} * @param {String} task - task value * @return {Map} - immutable Map * @memberof client/utils */ export function createTodo(task) { return Immutable.fromJS({ id: generateId(), task, willDelete: false }); } /** * createTodoFromObject * @desc Creates a todo Map from a todo object. * @type {Function} * @param {Object} todo - todo object * @param {String} todo.task - task value * @param {Number} todo.id - task ID * @param {Boolean} todo.willDelete - deletion flag * @return {Map} - immutable Map * @memberof client/utils */ export function createTodoFromObject(todo) { const {id, task, willDelete} = todo; return Immutable.fromJS({ id, task, willDelete: !!willDelete }); } <file_sep>/app/public/scripts/stores/index.js /** * stores * @namespace client/stores */ <file_sep>/app/actions/TodoActions.js 'use strict'; const models = require('../models'); /** * TodoActions * @desc Contains todo actions. * @namespace server/actions/TodoActions * @type {Object} */ const TodoActions = { /** * @method getTodos * @desc Returns todos from database. * @type {Function} * @return {Promise} * @memberof server/actions/TodoActions */ getTodos() { return models.Todo.findAll() .then(todos => { return todos.map(({task, id}) => ({task, id})); }); }, /** * @method createOrUpdateTodo * @desc Creates a new todo, or updates the todo if * it already exists based on ID. * @type {Function} * @param {Object} todo - todo object * @param {String} todo.task - todo task value * @param {Number} [todo.id] - todo id * @return {Promise} * @memberof server/actions/TodoActions */ createOrUpdateTodo(todo) { const {task, id} = todo; return models.Todo.upsert( {id, task}, {where: {id} }); }, /** * @method deleteTodo * @desc Deletes todo from database. * @type {Function} * @param {Number} id - todo ID * @return {Promise} * @memberof server/actions/TodoActions */ deleteTodo(id) { return models.Todo.destroy({ where: {id} }).then(() => id); } }; module.exports = TodoActions; <file_sep>/app/public/scripts/utils/generateId.js 'use strict'; /** * generateId * @desc Generates a random ID * @type {Function} * @return {Number} - randomly geneated ID * @memberof client/utils */ export function generateId() { return ((Math.random() * 1e9) >>> 0); } <file_sep>/app/models/index.js 'use strict'; /** * Models * @namespace server/models */ const fs = require('fs'); const path = require('path'); const Sequelize = require('sequelize'); const env = process.env.NODE_ENV || 'development'; const config = require(path.join(__dirname, '..', 'config', 'config.json'))[env] || {}; const dialect = config.dialect || 'postgres'; const host = config.host || process.env.POSTGRES_HOST || '127.0.0.1'; const port = config.port || process.env.POSTGRES_PORT || 5432; const database = config.database || process.env.POSTGRES_DB || 'test'; const username = config.username || process.env.POSTGRES_USER || 'root'; const password = config.password || process.env.POSTGRES_PASSWORD || <PASSWORD>; const sequelize = new Sequelize(`${dialect}://${username}:${password}@${host}:${port}/${database}`); const db = {}; const model = sequelize.import(path.join(__dirname, 'todo.js')); /** * db * @desc Object containing all the Sequelize models. * @type {Object} * @memberof server/models */ db[model.name] = model; db.sequelize = sequelize; db.Sequelize = Sequelize; module.exports = db; <file_sep>/app/public/scripts/actions/index.js /** * actions * @namespace client/actions */ <file_sep>/app/public/scripts/stores/State.js 'use strict'; import Rx from 'rx'; import Immutable from 'immutable'; /** * KeyConstants * @desc Contains keys for state object. * @type {Object} */ export const KeyConstants = { TODOS: 'todos' } /** * State * @desc Class used for state management * @type {Function} * @namespace client/stores/State */ export function State() { /** * @desc Initial state object. * @type {Object} */ const initial = { [KeyConstants.TODOS]: [] }; /** * @member updates * @memberof client/stores/State * @desc `updates` property is a BehaviorSubject which * represents a value the changes over time. * It receives operations to be applied on the todos list. */ this.updates = new Rx.BehaviorSubject(Immutable.fromJS(initial)); /** * @member asObservable * @memberof client/stores/State * @desc `asObservable` property is an observable sequence that shares a single subscription. * `scan` is like reduce, but returns each intermediate result on each `onNext` call. */ this.asObservable = this.updates.scan((state, operation) => operation(state)).shareReplay(1); } <file_sep>/docs/public_scripts_Footer.jsx.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>JSDoc: Source: public/scripts/Footer.jsx</title> <script src="scripts/prettify/prettify.js"> </script> <script src="scripts/prettify/lang-css.js"> </script> <!--[if lt IE 9]> <script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> <link type="text/css" rel="stylesheet" href="styles/prettify-tomorrow.css"> <link type="text/css" rel="stylesheet" href="styles/jsdoc-default.css"> </head> <body> <div id="main"> <h1 class="page-title">Source: public/scripts/Footer.jsx</h1> <section> <article> <pre class="prettyprint source linenums"><code>'use strict'; import {h} from 'yolk'; import Rx from 'rx'; import RxDOM from 'rx-dom'; import {API_Endpoints} from './constants/ApiEndpoints'; import {TodoActions} from './actions/TodoActions'; /** * Footer * @desc View containing the footer. * @type {Function} * @memberof client/views */ export function Footer({props, createEventHandler}) { const {todos} = props; const handleSave$ = createEventHandler(); const isSaving$ = new Rx.BehaviorSubject(false); handleSave$ .withLatestFrom(todos, (handleDave, todos) => { return todos.valueSeq().toArray().map(map => map.toObject()); }) .subscribe(todos => { console.log(todos); const toSaveTodos = todos.filter(todo => !todo.willDelete); const toDeleteTodoIds = todos.filter(todo => todo.willDelete).map(todo => todo.id); // Make ajax calls to save and delete todos. TodoActions.saveTodos$(toSaveTodos) .merge(TodoActions.deleteTodos$(toDeleteTodoIds)) .subscribe(xhr => { const {response} = xhr; isSaving$.onNext(false); if (response.error) { console.error(response.error); } }); }); // Set loading state when saving. handleSave$ .map(() => true) .subscribe(isSaving$); const classNames = [ isSaving$.map(ok => ok ? `loading` : ``), 'ui', 'primary', 'large', 'button' ]; return ( &lt;footer className="ui row"> &lt;button onClick={handleSave$} className={classNames}>&lt;i className="icon save">&lt;/i> Save&lt;/button> &lt;/footer> ); } </code></pre> </article> </section> </div> <nav> <h2><a href="index.html">Home</a></h2><h3>Classes</h3><ul><li><a href="Represents%2520a%2520join%2520pattern%2520over%2520observable%2520sequences..html">Represents a join pattern over observable sequences.</a></li></ul><h3>Namespaces</h3><ul><li><a href="client_actions.html">client/actions</a></li><li><a href="client_actions_TodoActions.html">client/actions/TodoActions</a></li><li><a href="client_constants.html">client/constants</a></li><li><a href="client_stores.html">client/stores</a></li><li><a href="client_stores_State.html">client/stores/State</a></li><li><a href="client_utils.html">client/utils</a></li><li><a href="client_views.html">client/views</a></li><li><a href="server_actions.html">server/actions</a></li><li><a href="server_actions_TodoActions.html">server/actions/TodoActions</a></li><li><a href="server_app.html">server/app</a></li><li><a href="server_models.html">server/models</a></li><li><a href="server_utils.html">server/utils</a></li></ul><h3>Global</h3><ul><li><a href="global.html#asArrayBuffer">asArrayBuffer</a></li><li><a href="global.html#asBinaryString">asBinaryString</a></li><li><a href="global.html#asDataURL">asDataURL</a></li><li><a href="global.html#asText">asText</a></li><li><a href="global.html#dispose">dispose</a></li><li><a href="global.html#getValue">getValue</a></li><li><a href="global.html#handleError">handleError</a></li><li><a href="global.html#hasObservers">hasObservers</a></li><li><a href="global.html#KeyConstants">KeyConstants</a></li><li><a href="global.html#onCompleted">onCompleted</a></li><li><a href="global.html#onError">onError</a></li><li><a href="global.html#onNext">onNext</a></li><li><a href="global.html#requests">requests</a></li></ul> </nav> <br class="clear"> <footer> Documentation generated by <a href="https://github.com/jsdoc3/jsdoc">JSDoc 3.4.0</a> on Wed Apr 06 2016 16:07:32 GMT-0700 (PDT) </footer> <script> prettyPrint(); </script> <script src="scripts/linenumber.js"> </script> </body> </html> <file_sep>/app/public/scripts/constants/index.js /** * constants * @namespace client/constants */ <file_sep>/docs/global.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>JSDoc: Global</title> <script src="scripts/prettify/prettify.js"> </script> <script src="scripts/prettify/lang-css.js"> </script> <!--[if lt IE 9]> <script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> <link type="text/css" rel="stylesheet" href="styles/prettify-tomorrow.css"> <link type="text/css" rel="stylesheet" href="styles/jsdoc-default.css"> </head> <body> <div id="main"> <h1 class="page-title">Global</h1> <section> <header> <h2></h2> </header> <article> <div class="container-overview"> <dl class="details"> </dl> </div> <h3 class="subsection-title">Members</h3> <h4 class="name" id="KeyConstants"><span class="type-signature">(constant) </span>KeyConstants<span class="type-signature"> :Object</span></h4> <div class="description"> Contains keys for state object. </div> <h5>Type:</h5> <ul> <li> <span class="param-type">Object</span> </li> </ul> <dl class="details"> <dt class="tag-source">Source:</dt> <dd class="tag-source"><ul class="dummy"><li> <a href="public_scripts_stores_State.js.html">public/scripts/stores/State.js</a>, <a href="public_scripts_stores_State.js.html#line11">line 11</a> </li></ul></dd> </dl> <h4 class="name" id="requests"><span class="type-signature">(constant) </span>requests<span class="type-signature"></span></h4> <div class="description"> Observables for handling requests. </div> <dl class="details"> <dt class="tag-source">Source:</dt> <dd class="tag-source"><ul class="dummy"><li> <a href="routes_todos.js.html">routes/todos.js</a>, <a href="routes_todos.js.html#line12">line 12</a> </li></ul></dd> </dl> <h3 class="subsection-title">Methods</h3> <h4 class="name" id="asArrayBuffer"><span class="type-signature"></span>asArrayBuffer<span class="signature">()</span><span class="type-signature"> &rarr; {Observable}</span></h4> <div class="description"> This method is used to read the file as an ArrayBuffer as an Observable stream. </div> <dl class="details"> <dt class="tag-source">Source:</dt> <dd class="tag-source"><ul class="dummy"><li> <a href="public_dist_app.js.html">public/dist/app.js</a>, <a href="public_dist_app.js.html#line8916">line 8916</a> </li></ul></dd> </dl> <h5>Returns:</h5> <div class="param-desc"> An observable stream of an ArrayBuffer </div> <dl> <dt> Type </dt> <dd> <span class="param-type">Observable</span> </dd> </dl> <h4 class="name" id="asBinaryString"><span class="type-signature"></span>asBinaryString<span class="signature">()</span><span class="type-signature"> &rarr; {Observable}</span></h4> <div class="description"> This method is used to read the file as a binary data string as an Observable stream. </div> <dl class="details"> <dt class="tag-source">Source:</dt> <dd class="tag-source"><ul class="dummy"><li> <a href="public_dist_app.js.html">public/dist/app.js</a>, <a href="public_dist_app.js.html#line8923">line 8923</a> </li></ul></dd> </dl> <h5>Returns:</h5> <div class="param-desc"> An observable stream of a binary data string. </div> <dl> <dt> Type </dt> <dd> <span class="param-type">Observable</span> </dd> </dl> <h4 class="name" id="asDataURL"><span class="type-signature"></span>asDataURL<span class="signature">()</span><span class="type-signature"> &rarr; {Observable}</span></h4> <div class="description"> This method is used to read the file as a URL of the file's data as an Observable stream. </div> <dl class="details"> <dt class="tag-source">Source:</dt> <dd class="tag-source"><ul class="dummy"><li> <a href="public_dist_app.js.html">public/dist/app.js</a>, <a href="public_dist_app.js.html#line8930">line 8930</a> </li></ul></dd> </dl> <h5>Returns:</h5> <div class="param-desc"> An observable stream of a URL representing the file's data. </div> <dl> <dt> Type </dt> <dd> <span class="param-type">Observable</span> </dd> </dl> <h4 class="name" id="asText"><span class="type-signature"></span>asText<span class="signature">()</span><span class="type-signature"> &rarr; {Observable}</span></h4> <div class="description"> This method is used to read the file as a string as an Observable stream. </div> <dl class="details"> <dt class="tag-source">Source:</dt> <dd class="tag-source"><ul class="dummy"><li> <a href="public_dist_app.js.html">public/dist/app.js</a>, <a href="public_dist_app.js.html#line8937">line 8937</a> </li></ul></dd> </dl> <h5>Returns:</h5> <div class="param-desc"> An observable stream of the string contents of the file. </div> <dl> <dt> Type </dt> <dd> <span class="param-type">Observable</span> </dd> </dl> <h4 class="name" id="dispose"><span class="type-signature"></span>dispose<span class="signature">()</span><span class="type-signature"></span></h4> <div class="description"> Unsubscribe all observers and release resources. </div> <dl class="details"> <dt class="tag-source">Source:</dt> <dd class="tag-source"><ul class="dummy"><li> <a href="public_dist_app.js.html">public/dist/app.js</a>, <a href="public_dist_app.js.html#line21348">line 21348</a> </li></ul></dd> </dl> <h4 class="name" id="dispose"><span class="type-signature"></span>dispose<span class="signature">()</span><span class="type-signature"></span></h4> <div class="description"> Unsubscribe all observers and release resources. </div> <dl class="details"> <dt class="tag-source">Source:</dt> <dd class="tag-source"><ul class="dummy"><li> <a href="public_dist_app.js.html">public/dist/app.js</a>, <a href="public_dist_app.js.html#line21228">line 21228</a> </li></ul></dd> </dl> <h4 class="name" id="dispose"><span class="type-signature"></span>dispose<span class="signature">()</span><span class="type-signature"></span></h4> <div class="description"> Unsubscribe all observers and release resources. </div> <dl class="details"> <dt class="tag-source">Source:</dt> <dd class="tag-source"><ul class="dummy"><li> <a href="public_dist_app.js.html">public/dist/app.js</a>, <a href="public_dist_app.js.html#line21451">line 21451</a> </li></ul></dd> </dl> <h4 class="name" id="dispose"><span class="type-signature"></span>dispose<span class="signature">()</span><span class="type-signature"></span></h4> <div class="description"> Unsubscribe all observers and release resources. </div> <dl class="details"> <dt class="tag-source">Source:</dt> <dd class="tag-source"><ul class="dummy"><li> <a href="public_dist_app.js.html">public/dist/app.js</a>, <a href="public_dist_app.js.html#line21587">line 21587</a> </li></ul></dd> </dl> <h4 class="name" id="getValue"><span class="type-signature"></span>getValue<span class="signature">()</span><span class="type-signature"> &rarr; {Mixed}</span></h4> <div class="description"> Gets the current value or throws an exception. Value is frozen after onCompleted is called. After onError is called always throws the specified exception. An exception is always thrown after dispose is called. </div> <dl class="details"> <dt class="tag-source">Source:</dt> <dd class="tag-source"><ul class="dummy"><li> <a href="public_dist_app.js.html">public/dist/app.js</a>, <a href="public_dist_app.js.html#line21396">line 21396</a> </li></ul></dd> </dl> <h5>Returns:</h5> <div class="param-desc"> The initial value passed to the constructor until onNext is called; after which, the last value passed to onNext. </div> <dl> <dt> Type </dt> <dd> <span class="param-type">Mixed</span> </dd> </dl> <h4 class="name" id="handleError"><span class="type-signature"></span>handleError<span class="signature">(error)</span><span class="type-signature"></span></h4> <div class="description"> Generic error handler that logs message. </div> <h5>Parameters:</h5> <table class="params"> <thead> <tr> <th>Name</th> <th>Type</th> <th class="last">Description</th> </tr> </thead> <tbody> <tr> <td class="name"><code>error</code></td> <td class="type"> <span class="param-type">String</span> </td> <td class="description last">error message</td> </tr> </tbody> </table> <dl class="details"> <dt class="tag-source">Source:</dt> <dd class="tag-source"><ul class="dummy"><li> <a href="routes_todos.js.html">routes/todos.js</a>, <a href="routes_todos.js.html#line134">line 134</a> </li></ul></dd> </dl> <h4 class="name" id="hasObservers"><span class="type-signature"></span>hasObservers<span class="signature">()</span><span class="type-signature"> &rarr; {Boolean}</span></h4> <div class="description"> Indicates whether the subject has observers subscribed to it. </div> <dl class="details"> <dt class="tag-source">Source:</dt> <dd class="tag-source"><ul class="dummy"><li> <a href="public_dist_app.js.html">public/dist/app.js</a>, <a href="public_dist_app.js.html#line21405">line 21405</a> </li></ul></dd> </dl> <h5>Returns:</h5> <div class="param-desc"> Indicates whether the subject has observers subscribed to it. </div> <dl> <dt> Type </dt> <dd> <span class="param-type">Boolean</span> </dd> </dl> <h4 class="name" id="hasObservers"><span class="type-signature"></span>hasObservers<span class="signature">()</span><span class="type-signature"> &rarr; {Boolean}</span></h4> <div class="description"> Indicates whether the subject has observers subscribed to it. </div> <dl class="details"> <dt class="tag-source">Source:</dt> <dd class="tag-source"><ul class="dummy"><li> <a href="public_dist_app.js.html">public/dist/app.js</a>, <a href="public_dist_app.js.html#line21181">line 21181</a> </li></ul></dd> </dl> <h5>Returns:</h5> <div class="param-desc"> Indicates whether the subject has observers subscribed to it. </div> <dl> <dt> Type </dt> <dd> <span class="param-type">Boolean</span> </dd> </dl> <h4 class="name" id="hasObservers"><span class="type-signature"></span>hasObservers<span class="signature">()</span><span class="type-signature"> &rarr; {Boolean}</span></h4> <div class="description"> Indicates whether the subject has observers subscribed to it. </div> <dl class="details"> <dt class="tag-source">Source:</dt> <dd class="tag-source"><ul class="dummy"><li> <a href="public_dist_app.js.html">public/dist/app.js</a>, <a href="public_dist_app.js.html#line21523">line 21523</a> </li></ul></dd> </dl> <h5>Returns:</h5> <div class="param-desc"> Indicates whether the subject has observers subscribed to it. </div> <dl> <dt> Type </dt> <dd> <span class="param-type">Boolean</span> </dd> </dl> <h4 class="name" id="hasObservers"><span class="type-signature"></span>hasObservers<span class="signature">()</span><span class="type-signature"> &rarr; {Boolean}</span></h4> <div class="description"> Indicates whether the subject has observers subscribed to it. </div> <dl class="details"> <dt class="tag-source">Source:</dt> <dd class="tag-source"><ul class="dummy"><li> <a href="public_dist_app.js.html">public/dist/app.js</a>, <a href="public_dist_app.js.html#line21291">line 21291</a> </li></ul></dd> </dl> <h5>Returns:</h5> <div class="param-desc"> Indicates whether the subject has observers subscribed to it. </div> <dl> <dt> Type </dt> <dd> <span class="param-type">Boolean</span> </dd> </dl> <h4 class="name" id="onCompleted"><span class="type-signature"></span>onCompleted<span class="signature">()</span><span class="type-signature"></span></h4> <div class="description"> Notifies all subscribed observers about the end of the sequence, also causing the last received value to be sent out (if any). </div> <dl class="details"> <dt class="tag-source">Source:</dt> <dd class="tag-source"><ul class="dummy"><li> <a href="public_dist_app.js.html">public/dist/app.js</a>, <a href="public_dist_app.js.html#line21295">line 21295</a> </li></ul></dd> </dl> <h4 class="name" id="onCompleted"><span class="type-signature"></span>onCompleted<span class="signature">()</span><span class="type-signature"></span></h4> <div class="description"> Notifies all subscribed observers about the end of the sequence. </div> <dl class="details"> <dt class="tag-source">Source:</dt> <dd class="tag-source"><ul class="dummy"><li> <a href="public_dist_app.js.html">public/dist/app.js</a>, <a href="public_dist_app.js.html#line21185">line 21185</a> </li></ul></dd> </dl> <h4 class="name" id="onCompleted"><span class="type-signature"></span>onCompleted<span class="signature">()</span><span class="type-signature"></span></h4> <div class="description"> Notifies all subscribed observers about the end of the sequence. </div> <dl class="details"> <dt class="tag-source">Source:</dt> <dd class="tag-source"><ul class="dummy"><li> <a href="public_dist_app.js.html">public/dist/app.js</a>, <a href="public_dist_app.js.html#line21571">line 21571</a> </li></ul></dd> </dl> <h4 class="name" id="onCompleted"><span class="type-signature"></span>onCompleted<span class="signature">()</span><span class="type-signature"></span></h4> <div class="description"> Notifies all subscribed observers about the end of the sequence. </div> <dl class="details"> <dt class="tag-source">Source:</dt> <dd class="tag-source"><ul class="dummy"><li> <a href="public_dist_app.js.html">public/dist/app.js</a>, <a href="public_dist_app.js.html#line21409">line 21409</a> </li></ul></dd> </dl> <h4 class="name" id="onError"><span class="type-signature"></span>onError<span class="signature">(error)</span><span class="type-signature"></span></h4> <div class="description"> Notifies all subscribed observers about the exception. </div> <h5>Parameters:</h5> <table class="params"> <thead> <tr> <th>Name</th> <th>Type</th> <th class="last">Description</th> </tr> </thead> <tbody> <tr> <td class="name"><code>error</code></td> <td class="type"> <span class="param-type">Mixed</span> </td> <td class="description last">The exception to send to all observers.</td> </tr> </tbody> </table> <dl class="details"> <dt class="tag-source">Source:</dt> <dd class="tag-source"><ul class="dummy"><li> <a href="public_dist_app.js.html">public/dist/app.js</a>, <a href="public_dist_app.js.html#line21423">line 21423</a> </li></ul></dd> </dl> <h4 class="name" id="onError"><span class="type-signature"></span>onError<span class="signature">(error)</span><span class="type-signature"></span></h4> <div class="description"> Notifies all subscribed observers about the exception. </div> <h5>Parameters:</h5> <table class="params"> <thead> <tr> <th>Name</th> <th>Type</th> <th class="last">Description</th> </tr> </thead> <tbody> <tr> <td class="name"><code>error</code></td> <td class="type"> <span class="param-type">Mixed</span> </td> <td class="description last">The exception to send to all observers.</td> </tr> </tbody> </table> <dl class="details"> <dt class="tag-source">Source:</dt> <dd class="tag-source"><ul class="dummy"><li> <a href="public_dist_app.js.html">public/dist/app.js</a>, <a href="public_dist_app.js.html#line21553">line 21553</a> </li></ul></dd> </dl> <h4 class="name" id="onError"><span class="type-signature"></span>onError<span class="signature">(error)</span><span class="type-signature"></span></h4> <div class="description"> Notifies all subscribed observers about the exception. </div> <h5>Parameters:</h5> <table class="params"> <thead> <tr> <th>Name</th> <th>Type</th> <th class="last">Description</th> </tr> </thead> <tbody> <tr> <td class="name"><code>error</code></td> <td class="type"> <span class="param-type">Mixed</span> </td> <td class="description last">The exception to send to all observers.</td> </tr> </tbody> </table> <dl class="details"> <dt class="tag-source">Source:</dt> <dd class="tag-source"><ul class="dummy"><li> <a href="public_dist_app.js.html">public/dist/app.js</a>, <a href="public_dist_app.js.html#line21200">line 21200</a> </li></ul></dd> </dl> <h4 class="name" id="onError"><span class="type-signature"></span>onError<span class="signature">(error)</span><span class="type-signature"></span></h4> <div class="description"> Notifies all subscribed observers about the error. </div> <h5>Parameters:</h5> <table class="params"> <thead> <tr> <th>Name</th> <th>Type</th> <th class="last">Description</th> </tr> </thead> <tbody> <tr> <td class="name"><code>error</code></td> <td class="type"> <span class="param-type">Mixed</span> </td> <td class="description last">The Error to send to all observers.</td> </tr> </tbody> </table> <dl class="details"> <dt class="tag-source">Source:</dt> <dd class="tag-source"><ul class="dummy"><li> <a href="public_dist_app.js.html">public/dist/app.js</a>, <a href="public_dist_app.js.html#line21321">line 21321</a> </li></ul></dd> </dl> <h4 class="name" id="onNext"><span class="type-signature"></span>onNext<span class="signature">(value)</span><span class="type-signature"></span></h4> <div class="description"> Notifies all subscribed observers about the arrival of the specified element in the sequence. </div> <h5>Parameters:</h5> <table class="params"> <thead> <tr> <th>Name</th> <th>Type</th> <th class="last">Description</th> </tr> </thead> <tbody> <tr> <td class="name"><code>value</code></td> <td class="type"> <span class="param-type">Mixed</span> </td> <td class="description last">The value to send to all observers.</td> </tr> </tbody> </table> <dl class="details"> <dt class="tag-source">Source:</dt> <dd class="tag-source"><ul class="dummy"><li> <a href="public_dist_app.js.html">public/dist/app.js</a>, <a href="public_dist_app.js.html#line21217">line 21217</a> </li></ul></dd> </dl> <h4 class="name" id="onNext"><span class="type-signature"></span>onNext<span class="signature">(value)</span><span class="type-signature"></span></h4> <div class="description"> Sends a value to the subject. The last value received before successful termination will be sent to all subscribed and future observers. </div> <h5>Parameters:</h5> <table class="params"> <thead> <tr> <th>Name</th> <th>Type</th> <th class="last">Description</th> </tr> </thead> <tbody> <tr> <td class="name"><code>value</code></td> <td class="type"> <span class="param-type">Mixed</span> </td> <td class="description last">The value to store in the subject.</td> </tr> </tbody> </table> <dl class="details"> <dt class="tag-source">Source:</dt> <dd class="tag-source"><ul class="dummy"><li> <a href="public_dist_app.js.html">public/dist/app.js</a>, <a href="public_dist_app.js.html#line21339">line 21339</a> </li></ul></dd> </dl> <h4 class="name" id="onNext"><span class="type-signature"></span>onNext<span class="signature">(value)</span><span class="type-signature"></span></h4> <div class="description"> Notifies all subscribed observers about the arrival of the specified element in the sequence. </div> <h5>Parameters:</h5> <table class="params"> <thead> <tr> <th>Name</th> <th>Type</th> <th class="last">Description</th> </tr> </thead> <tbody> <tr> <td class="name"><code>value</code></td> <td class="type"> <span class="param-type">Mixed</span> </td> <td class="description last">The value to send to all observers.</td> </tr> </tbody> </table> <dl class="details"> <dt class="tag-source">Source:</dt> <dd class="tag-source"><ul class="dummy"><li> <a href="public_dist_app.js.html">public/dist/app.js</a>, <a href="public_dist_app.js.html#line21536">line 21536</a> </li></ul></dd> </dl> <h4 class="name" id="onNext"><span class="type-signature"></span>onNext<span class="signature">(value)</span><span class="type-signature"></span></h4> <div class="description"> Notifies all subscribed observers about the arrival of the specified element in the sequence. </div> <h5>Parameters:</h5> <table class="params"> <thead> <tr> <th>Name</th> <th>Type</th> <th class="last">Description</th> </tr> </thead> <tbody> <tr> <td class="name"><code>value</code></td> <td class="type"> <span class="param-type">Mixed</span> </td> <td class="description last">The value to send to all observers.</td> </tr> </tbody> </table> <dl class="details"> <dt class="tag-source">Source:</dt> <dd class="tag-source"><ul class="dummy"><li> <a href="public_dist_app.js.html">public/dist/app.js</a>, <a href="public_dist_app.js.html#line21440">line 21440</a> </li></ul></dd> </dl> </article> </section> </div> <nav> <h2><a href="index.html">Home</a></h2><h3>Classes</h3><ul><li><a href="Represents%2520a%2520join%2520pattern%2520over%2520observable%2520sequences..html">Represents a join pattern over observable sequences.</a></li></ul><h3>Namespaces</h3><ul><li><a href="client_actions.html">client/actions</a></li><li><a href="client_actions_TodoActions.html">client/actions/TodoActions</a></li><li><a href="client_constants.html">client/constants</a></li><li><a href="client_stores.html">client/stores</a></li><li><a href="client_stores_State.html">client/stores/State</a></li><li><a href="client_utils.html">client/utils</a></li><li><a href="client_views.html">client/views</a></li><li><a href="server_actions.html">server/actions</a></li><li><a href="server_actions_TodoActions.html">server/actions/TodoActions</a></li><li><a href="server_app.html">server/app</a></li><li><a href="server_models.html">server/models</a></li><li><a href="server_utils.html">server/utils</a></li></ul><h3>Global</h3><ul><li><a href="global.html#asArrayBuffer">asArrayBuffer</a></li><li><a href="global.html#asBinaryString">asBinaryString</a></li><li><a href="global.html#asDataURL">asDataURL</a></li><li><a href="global.html#asText">asText</a></li><li><a href="global.html#dispose">dispose</a></li><li><a href="global.html#getValue">getValue</a></li><li><a href="global.html#handleError">handleError</a></li><li><a href="global.html#hasObservers">hasObservers</a></li><li><a href="global.html#KeyConstants">KeyConstants</a></li><li><a href="global.html#onCompleted">onCompleted</a></li><li><a href="global.html#onError">onError</a></li><li><a href="global.html#onNext">onNext</a></li><li><a href="global.html#requests">requests</a></li></ul> </nav> <br class="clear"> <footer> Documentation generated by <a href="https://github.com/jsdoc3/jsdoc">JSDoc 3.4.0</a> on Wed Apr 06 2016 16:07:32 GMT-0700 (PDT) </footer> <script> prettyPrint(); </script> <script src="scripts/linenumber.js"> </script> </body> </html><file_sep>/app/public/scripts/actions/TodoActions.js 'use strict'; import Rx from 'rx'; import Immutable from 'immutable'; import RxDOM from 'rx-dom'; import {KeyConstants} from '../stores/State'; import {createTodo, createTodoFromObject} from '../utils/createTodo'; import {isTodoUnique} from '../utils/isTodoUnique'; import {API_Endpoints} from '../constants/ApiEndpoints'; const USE_LOCAL_STORAGE = false; /** * TodoActions * @desc Object containing actions for todo items. * Rx.Subject represents an object that is both an observable and observer. * @namespace client/actions/TodoActions * @type {Object} */ export const TodoActions = { /** * @method createTodo$ * @desc Creates a local todo. * @type {Observable} * @memberof client/actions/TodoActions */ createTodo$: new Rx.Subject(), /** * @method deleteTodo$ * @desc Marks local todo for deletion. * @type {Observable} * @memberof client/actions/TodoActions */ deleteTodo$: new Rx.Subject(), /** * @method updateTodo$ * @desc Updates local todo value. * @type {Observable} * @memberof client/actions/TodoActions */ updateTodo$: new Rx.Subject(), /** * @method loadTodo$ * @desc Loads a local todo when todo ID is known. * @type {Observable} * @memberof client/actions/TodoActions */ loadTodo$: new Rx.Subject(), /** * @method fetchTodos$ * @desc Fetches todos from server. * @type {Observable} * @memberof client/actions/TodoActions */ fetchTodos$: Rx.Observable.create((observable) => { if (USE_LOCAL_STORAGE) { const todos = localStorage.getItem(KeyConstants.TODOS); const todos$ = Rx.Observable.fromArray(JSON.parse(todos)) .map(todo => new Rx.BehaviorSubject(todo)); observable.onNext(todos$); } else { Rx.DOM.get({ url: API_Endpoints.TODOS, responseType: 'json' }) .subscribe(xhr => { const {response} = xhr; const {error} = response; const {todos} = response.data; if (error) { console.error(error); observable.onError(error); } const todos$ = Rx.Observable.fromArray(todos) .map(todo => new Rx.BehaviorSubject(todo)); observable.onNext(todos$); }); } }), /** * @method saveTodos$ * @desc Saves todos to server. * @type {Function} * @param {Array} todos - list of todos * @return {Observable} * @memberof client/actions/TodoActions */ saveTodos$: (todos) => { if (USE_LOCAL_STORAGE) { localStorage.setItem(KeyConstants.TODOS, JSON.stringify(todos)); return Rx.Observable.return({response: { data: todos }}); } else { return Rx.DOM.post({ url: API_Endpoints.TODOS, headers: { 'Content-Type': 'application/json' }, responseType: 'json', body: JSON.stringify({todos: todos}) }); } }, /** * @method deleteTodos$ * @desc Deletes todos from server. * @type {Function} * @param {Array} todoIds - list of todos IDs * @return {Observable} * @memberof client/actions/TodoActions */ deleteTodos$: (todoIds) => { if (USE_LOCAL_STORAGE) { const todos = JSON.parse(localStorage.getItem(KeyConstants.TODOS)) || []; const newTodos = todos.filter(todo => { let shouldFilter = false; todoIds.forEach(todoId => { shouldFilter = (todos.id === todoId); }); return shouldFilter; }); //localStorage.setItem(KeyConstants.TODOS, JSON.stringify(newTodos)); return Rx.Observable.return({response: { data: todoIds }}); } else { return Rx.DOM.ajax({ method: 'DELETE', url: API_Endpoints.TODOS, headers: { 'Content-Type': 'application/json' }, responseType: 'json', body: JSON.stringify({todos: todoIds}) }); } } }; /** * @method register * @desc Takes in an observer that gets with an action. * @type {Observer} * @param {Function} updates - Observer * @memberof client/actions/TodoActions */ TodoActions.register = function(updates) { /** * @desc Add new todo to todos list. */ this.createTodo$ .map(task => { const todo = createTodo(task); return state => { const todos = state.get(KeyConstants.TODOS); const isUnique = isTodoUnique(todos, task); if (isUnique) { return state.update(KeyConstants.TODOS, todos => todos.unshift(todo)); } else { // temporary, need to return error alert('Item already exists.'); return state; } }; }) .subscribe(updates); /** * @desc Mark todo for deletion. */ this.deleteTodo$ .map(todo => { return state => { return state.update(KeyConstants.TODOS, todos => { let index = todos.indexOf(todo); if (typeof todo === 'string') { index = todos.findIndex(item => { return item.get('task') === todo; }); } return todos.update(index, (todo) => todo.set('willDelete', true)); }); }; }) .subscribe(updates); /** * @desc Update todo value. */ this.updateTodo$ .map(([todo, task]) => { return state => { return state.update(KeyConstants.TODOS, todos => { const index = todos.indexOf(todo); return todos.set(index, todo.set('task', task)) }) }; }) .subscribe(updates); /** * @desc Add existing todo to todos list. */ this.loadTodo$ .map(task => { const todo = createTodoFromObject(task); return state => { const todos = state.get(KeyConstants.TODOS); return state.update(KeyConstants.TODOS, todos => todos.unshift(todo)); }; }) .subscribe(updates); }; <file_sep>/app/public/scripts/TodoList.jsx 'use strict'; import {h} from 'yolk'; import {TodoItem} from './TodoItem.jsx'; /** * TodoList * @desc View containing the todo list. * @type {Function} * @memberof client/views */ export function TodoList({props}) { const {todos} = props; const todoItems = todos.map(list => list.filter( // Filter out todo items marked for deletion. todo => !todo.get('willDelete')) // Create todo item view. .map(todo => <TodoItem todo={todo} key={todo.get('id')} />)); return ( <div className="ui segments row"> {todoItems} </div> ); } <file_sep>/app/public/scripts/TodoItem.jsx 'use strict'; import {h} from 'yolk'; import Rx from 'rx'; import {TodoActions} from './actions/TodoActions'; /** * TodoItem * @desc View containing the todo item. * @type {Function} * @memberof client/views */ export function TodoItem({props, createEventHandler}) { const {todo} = props; const task = todo.map(t => t.get('task')) const isEditing$ = new Rx.BehaviorSubject(false); const handleDelete$ = createEventHandler(); const handleEdit$ = createEventHandler(); const handleSubmit$ = createEventHandler(); const handleInputChange$ = createEventHandler(event => event.target.value); // Mark todo item for deletion on delete button click. handleDelete$ .withLatestFrom(todo, (handleDelete, todo) => todo) .subscribe(TodoActions.deleteTodo$); // Set editting flat to true on edit button click. handleEdit$ .map(() => true) .subscribe(isEditing$); // Update todo item on edit save. handleSubmit$ .tap(() => isEditing$.onNext(false)) .withLatestFrom(todo, handleInputChange$, (handleEdit, todo, newValue) => [todo, newValue]) .subscribe(value => { return TodoActions.updateTodo$.onNext(value); }); // Set class names for when in editing state. const classNames = [ isEditing$.map(ok => ok ? `editing` : ``), 'ui', 'segment' ]; return ( <div className={classNames}> <section className="edit"> <div className="ui action fluid input"> <input type="text" onInput={handleInputChange$} value={task} /> <button type="submit" onClick={handleSubmit$} className="ui primary button"> <i className="icon check circle"></i> Done </button> </div> </section> <section className="label"> <div className="ui fluid input"> <input type="text" value={task} /> <div className="ui icon basic buttons"> <button onClick={handleEdit$} className="left attached ui button"> <i className="icon edit"></i> Edit </button> <button onClick={handleDelete$} className="right attached ui button" aria={{label: 'delete'}}> <i className="icon remove circle"></i> </button> </div> </div> </section> </div> ); } <file_sep>/test/server/index.js 'use strict'; const test = require('tape'); const request = require('supertest'); const async = require('async'); const app = require('../../app/app'); /** * @test Server */ test('Server', (t) => { t.plan(11); const todos = [1,2].map(generateTodo); async.series([ /** * @desc Test index route. */ (callback) => { request(app) .get('/') .expect('Content-Type', /text\/html/) .expect(200) .end((error, response) => { t.notOk(error); t.ok(response.body); callback() }); }, /** * @desc Test todos GET. */ (callback) => { request(app) .get('/api/todos') .expect('Content-Type', /json/) .expect(200) .end((error, response) => { t.notOk(error); t.ok(Array.isArray(response.body.data.todos)); callback(); }); }, /** * @desc Test todos POST. */ (callback) => { request(app) .post('/api/todos') .set('Content-type', 'application/json') .send({ todos: todos }) .expect('Content-Type', /json/) .expect(200) .end((error, response) => { t.notOk(error); t.ok(Array.isArray(response.body.data.todos)); t.equal(response.body.data.todos.length, todos.length); callback(); }); }, /** * @desc Test todos GET. */ (callback) => { /** * @desc Test todos DELETE. */ request(app) .delete('/api/todos') .set('Content-type', 'application/json') .send({ todos: todos.map(todo => todo.id) }) .expect('Content-Type', /json/) .expect(200) .end((error, response) => { t.notOk(error); t.ok(Array.isArray(response.body.data.todos)); t.equal(response.body.data.todos.length, todos.length); callback(); }); } ], (error, result) => { t.notOk(error); }); }); function generateId() { return ((Math.random() * 1e9) >>> 0); } function generateString() { return Math.random().toString(36).slice(-10); } function generateTodo() { return { task: generateString(), id: generateId() }; } <file_sep>/app/routes/todos.js 'use strict'; const express = require('express'); const Rx = require('rx'); const router = express.Router(); const TodoActions = require('../actions/TodoActions'); /** * @desc Observables for handling requests. */ const requests = { /** * @desc Saves todos to database. */ saveTodos$: new Rx.Subject(), /** * @desc Returns saved todos from database. */ getTodos$: new Rx.Subject(), /** * @desc Deletes todos from datbase. */ deleteTodos$: new Rx.Subject() }; /** * @desc Observable for getting todos. */ requests.getTodos$ .map(event => { return Rx.Observable.forkJoin(TodoActions.getTodos(), (todos) => [event, todos]); }) // Return a single array. .concatAll() // Format response. .map(([event, todos]) => { const data = { data: {todos} }; return [event, data]; }) // Emit response. .subscribe(([event, data]) => { event.response.json(data); }, handleError); /** * @desc Observable for saving todos. */ requests.saveTodos$ // Get todos from request body. .map(event => { const {todos} = event.request.body; return [event, todos]; }) // Create or update todos in database. .map(([event, todos]) => { if (!Array.isArray(todos)) { return event.response.json(400, { error: '`todos` must be an array.' }); } const sources = todos.map(todo => TodoActions.createOrUpdateTodo(todo)); return Rx.Observable.forkJoin(sources, () => [event, todos]); }) // Return a single array. .concatAll() // Format response. .map(([event, todos]) => { const data = { data: {todos} }; return [event, data]; }) // Emit response. .subscribe(([event, data]) => { event.response.json(data); }, handleError); /** * @desc Observable for deleting todos. */ requests.deleteTodos$ // Get todo ids from request body. .map(event => { const {todos} = event.request.body; return [event, todos]; }) // Delete todos from database. .map(([event, todos]) => { if (!Array.isArray(todos)) { return event.response.json(400, { error: '`todos` must be an array of IDs.' }); } const sources = todos.map(todoId => TodoActions.deleteTodo(todoId)); return Rx.Observable.forkJoin(sources, () => [event, todos]); }) // Return a single array. .concatAll() // Format response. .map(([event, todos]) => { const data = { data: {todos} }; return [event, data]; }) // Emit response. .subscribe(([event, data]) => { event.response.json(data); }, handleError); /** * @desc Set up route handlers to use observables to process request. */ router.get('/', (request, response) => requests.getTodos$.onNext({request, response})); router.post('/', (request, response) => requests.saveTodos$.onNext({request, response})); router.delete('/', (request, response) => requests.deleteTodos$.onNext({request, response})); /** * handleError * @desc Generic error handler that logs message. * @type {Function} * @param {String} error - error message */ function handleError(error) { console.error(error); } module.exports = router; <file_sep>/lib/init.sql /* CREATE USER docker; CREATE DATABASE docker; GRANT ALL PRIVILEGES ON DATABASE docker TO docker; CREATE TABLE todos (task varchar(255)); INSERT INTO todos VALUES ('Hello world'); */ <file_sep>/app/utils/normalizePort.js 'use strict'; /** * normalizePort * @desc Normalize a port into a number, string, or false. * @param {String|Number} value - value to normalize * @type {Function} * @return {Number} normalized port number * @memberof server/utils */ function normalizePort(value) { const port = parseInt(value, 10); if (isNaN(port) || port < 0) { throw new TypeError(`Port number \`${value}\` could not be normalized.`); } return port; } module.exports = normalizePort; <file_sep>/app/public/scripts/Footer.jsx 'use strict'; import {h} from 'yolk'; import Rx from 'rx'; import RxDOM from 'rx-dom'; import {API_Endpoints} from './constants/ApiEndpoints'; import {TodoActions} from './actions/TodoActions'; /** * Footer * @desc View containing the footer. * @type {Function} * @memberof client/views */ export function Footer({props, createEventHandler}) { const {todos} = props; const handleSave$ = createEventHandler(); const isSaving$ = new Rx.BehaviorSubject(false); // Set loading state when saving. handleSave$ .map(() => true) .subscribe(isSaving$); handleSave$ .withLatestFrom(todos, (handleDave, todos) => { return todos.valueSeq().toArray().map(map => map.toObject()); }) .subscribe(todos => { console.log(todos); const toSaveTodos = todos.filter(todo => !todo.willDelete); const toDeleteTodoIds = todos.filter(todo => todo.willDelete).map(todo => todo.id); // Make ajax calls to save and delete todos. TodoActions.saveTodos$(toSaveTodos) .merge(TodoActions.deleteTodos$(toDeleteTodoIds)) .subscribe(xhr => { const {response} = xhr; isSaving$.onNext(false); if (response.error) { console.error(response.error); } }); }); const classNames = [ isSaving$.map(ok => ok ? `loading` : ``), 'ui', 'primary', 'large', 'button' ]; return ( <footer className="ui row"> <button onClick={handleSave$} className={classNames}><i className="icon save"></i> Save</button> </footer> ); }
6b1a76d52ee2ed6293980e94aba144c1cec72c02
[ "SQL", "HTML", "Markdown", "JavaScript", "Dockerfile" ]
22
Dockerfile
miguelmota/rx-todo
ebeb8befeea6ae42f4f6fc4efab52bbf2e8aaf2d
e5515e9c31424d8cfd86b43dcd550b435f74dfa8
refs/heads/master
<repo_name>andrewkolas/moto_match<file_sep>/app/models/motorcycle.rb class Motorcycle < ApplicationRecord belongs_to :category end <file_sep>/db/migrate/20180320230044_create_categories.rb class CreateCategories < ActiveRecord::Migration[5.1] def change create_table :categories do |t| t.string :name t.boolean :street_legal t.boolean :offroad_capable t.float :distance_comfort_rating t.float :speed_rating t.timestamps end end end <file_sep>/db/migrate/20180321000143_motorcycles_drop_speed.rb class MotorcyclesDropSpeed < ActiveRecord::Migration[5.1] def change remove_column :motorcycles, :top_speed end end
eab253225b444d68e5ffbd65ca0d14ed8b52290a
[ "Ruby" ]
3
Ruby
andrewkolas/moto_match
ef1548a875a792ee498023d250c0fa97f740f760
20df995673bb386c1cf98203ac0d1b5b318f0e65
refs/heads/master
<repo_name>fazanki/www<file_sep>/scripts/views/slide.js define(['backbone', 'helpers'], function(Backbone, Helpers){ var Slide = Backbone.View.extend({ className: 'slide', template: _.template($('#quote').html()), // quote: function() { // return App.Templates('quote'); // } // }, render: function() { var contentType = this.getContentType(); this['render'+Helpers.capitalize(contentType)](); return this; }, getContentType: function() { if ( this.model.get('image') ) { return 'image'; //this.renderImage(); } else if ( this.model.get('snippet') ) { return 'snippet'; //this.renderSnippet() } else if ( this.model.get('quote') ) { return 'quote'; //this.renderQuote(); } else if ( this.model.get('bullets') ) { return 'bullets'; //this.renderBullets(); } else { return 'heading'; //this.renderHeading(); } }, renderHeading: function() { var size = this.model.get('size'); this.$el.append( '<h1 class="'+ size +'">' + this.model.get('title') + '</h1>' ); }, renderSnippet: function() { var self = this; var snippet = this.model.get('snippet'); if ( this.model.get('title') ) { this.renderHeading() } if ( $.isPlainObject(snippet)) { /// IMPORTANT TO REMEMBER /// USING JQUERY ISPLAINOBJECT TO TO CHECK IF IS AN OBJECT return _.each(snippet, function(snippetPath, heading) { self.setSnippet(snippetPath, heading); }); } this.setSnippet(snippet); }, setSnippet: function(snippetPath, heading) { var self = this, list = $('<ul />'); if ($.type(snippetPath) === "string") { var title = heading ? '<h1>' + heading + '</h1>' : ''; // if ( heading ) { // self.$el.append('<h1>' + heading + '</h1>') // } $.get(snippetPath, function(snippet) { self.$el .addClass('snippet') .append([ '<div class="snipetContaner">', title, '<pre class="prettyprint">' + _.escape(snippet) + '</pre>', '</div>' ].join('')); prettyPrint(); }); } else if ($.type(snippetPath) === "array") { snippetPath.map(function(bullet) { list.append( $('<li />').html($('<a />').attr({'href': bullet.url, 'target':'_blank'}).text(bullet.name)) ); }); var contanerHeading = $('<div />', {'class': 'linksContaner'}).append($('<h1 />').text(heading)); self.$el.append(contanerHeading.append(list)); } }, renderImage: function() { this.$el .addClass('image') .append( '<img src="' + this.model.get('image') + '" />' ); }, renderBullets: function() { var el = this.$el; var contaner = $('<div />', {'class':'bullets'}); //contaner.addClass('bullets'); if ( this.model.get('title') ) { contaner.append( '<h1>' + this.model.get('title') + '</h1>' ); } contaner.append([ '<ul>', '<li>' + this.model.get('bullets').join('</li><li>'), '</ul>', ].join('') ); el.append(contaner) }, renderQuote: function() { var template = this.template(this.model.toJSON()); this.$el .addClass('quote') .append( template ); } }); return Slide; });<file_sep>/scripts/views/slides.js define(['backbone', 'views/slide'], function(Backbone, SlideView){ var SlidesView = Backbone.View.extend({ el: $('.slides'), initialize: function() { this.currentSlideIndex = 1; this.numSlides = this.collection.length; this.transitionSpeed = 400; this.renderAll(); App.Vent.on('init', this.hideAllButFirst, this); App.Vent.on('changeSlide', this.changeSlide, this); }, templates: function() { }, hideAllButFirst: function() { this.$el.children(':nth-child(n+2)').hide(); }, changeSlide: function(opts) { //debugger; var newSlide; var slides = this.$el.children(); var self = this; console.log(opts); this.setCurrentSlideIndex(opts); // fileter the new slide /// VERY IMPORTANT !!! THIS IS WHRE ALL THE LOGGIC IS HAPPENING /// AND FIGURING WHICH SLIDE WE ARE WORKING ON newSlide = slides.eq(this.currentSlideIndex - 1); newSlide = this.getNextSlide(slides); //console.log( newSlide ) //slides.css('position','absolute')// TEMPORARY this.animateToNewSlide(slides, newSlide, opts.direction); App.router.navigate('fazanki/' + this.currentSlideIndex); }, setCurrentSlideIndex: function(opts) { if (opts.slideIndex) { return this.currentSlideIndex = ~~opts.slideIndex; } this.currentSlideIndex += (opts.direction === 'next') ? 1 : -1; if( this.currentSlideIndex > this.numSlides ) { // go back to slide 1 this.currentSlideIndex = 1; } if ( this.currentSlideIndex <= 0) { this.currentSlideIndex = this.numSlides; } }, animateToNewSlide: function(slides, newSlide, direction) { slides.filter(':visible') .animate({ top: direction === 'next' ? '100%' : '-100%', //top: '-100%', opacity: 'hide' }, this.transitionSpeed, function() { $(this).css('top','0'); newSlide .css('top', direction ==='next' ? '-100%' : '100%') .animate({ top:0, opacity: 'show' }, self.transitionSpeed); }); }, getNextSlide: function(slides) { return slides.eq(this.currentSlideIndex - 1); }, renderAll: function() { //console.log(this.collection); this.$el.empty(); this.collection.each(this.render, this); }, render: function(slide) { //console.log(slide); var slideView = new SlideView({ model: slide }); this.$el.append(slideView.render().el); return this; } }); return SlidesView; }); <file_sep>/scripts/slides.js window.slides = [ { snippet: { '<NAME>': 'snippets/ex1.js', 'Things I Like': 'snippets/ex1.css', 'Contacts': [ {'name':'twitter', 'url':"http://www.twitter.com"}, {'name':'linkedin', 'url':"http://www.linked.com"}, {'name':'<EMAIL>', 'url':"mailto:<EMAIL>"}, {'name':'yunojuno', 'url':"https://www.yunojuno.com/p/franco-zanki"} ] }, }, { title: "Hello", quote:"I am full service web development guru. I specilaise in launching websites that add value and make users happy", cite: 'Franco Zanki' } // // { // // snippet: 'snippets/ex1.js' // // }, // { // quote: "<a href='http://wwww.google.com' >google</a> this is going to be my first quote done with Backbonejs. I really like the whay it works and I like Jeffry prenentation", // cite: 'Franco Zanki' // }, // { // title: 'Why This Matters', // bullets: ['Pont one ', 'Point two', 'Point three'] // }, // { image: 'http://placekitten.com/600/300'}, // { // title: "grazie mille per il caffee di stamatina" // } ];<file_sep>/snippets/ex1.js var FrancoZanki = new Profile("<NAME>"); function Profile (name) { this.name = name; } Profile.prototype.about = function () { console.log ( "Professional user interface developer specialising in agile web development with a passion for web standards and user centered design" ); console.log ( "Freelanced and contracted on a variety of challenging projects including e-commerce, social, media, corporate, banking and property" ); console.log ( "Welivering high quality code to tight deadlines with a focus on accessibility." ); console.log ( "Working closely with owners, analysts, designers and developers, delivering complex cross-browser UI's for websites and applications, using modular semantic c HTML5, CSS3, SASS, LESS and JavaScript, on RESTful MVC, MVVM architectures." ); console.log ( "Proficient JavaScript developer with experience writing UI frameworks such as Angular.js,, Backbone.js using progressive enhancement, Ajax, object-oriented patterns, event-driven and data-binding architecture, Jasmine.js for BDD." ); }; FrancoZanki.about();
dfdc2afdb1dce8e71fdf01ae8afd22a424ce73c6
[ "JavaScript" ]
4
JavaScript
fazanki/www
cde471051ca0e0cc992fd6fa6e0f9c8077700949
5ce7d86e864448630e6333c90af4c1ca45f74b50
refs/heads/master
<repo_name>Ektai-Solution-Pty-Ltd/CommunityServer<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/IMAP/Client/IMAP_ClientException.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.IMAP.Client { #region usings using System; #endregion /// <summary> /// IMAP client exception. /// </summary> public class IMAP_ClientException : Exception { #region Members private readonly string m_ResponseText = ""; private readonly string m_StatusCode = ""; #endregion #region Properties /// <summary> /// Gets IMAP server error status code. /// </summary> public string StatusCode { get { return m_StatusCode; } } /// <summary> /// Gets IMAP server response text after status code. /// </summary> public string ResponseText { get { return m_ResponseText; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="responseLine">IMAP server response line.</param> /// <exception cref="ArgumentNullException">Is raised when <b>responseLine</b> is null.</exception> public IMAP_ClientException(string responseLine) : base(responseLine) { if (responseLine == null) { throw new ArgumentNullException("responseLine"); } // <status-code> SP <response-text> string[] code_text = responseLine.Split(new char[] {}, 2); m_StatusCode = code_text[0]; if (code_text.Length == 2) { m_ResponseText = code_text[1]; } } #endregion } }<file_sep>/common/ASC.Core.Common/Billing/License/LicenseReader.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Configuration; using System.IO; using System.Linq; using ASC.Common.Logging; using ASC.Core.Tenants; using ASC.Core.Users; namespace ASC.Core.Billing { public static class LicenseReader { private static readonly ILog Log = LogManager.GetLogger("ASC"); public static readonly string LicensePath; private static readonly string LicensePathTemp; public const string CustomerIdKey = "CustomerId"; public const int MaxUserCount = 10000; static LicenseReader() { LicensePath = (ConfigurationManagerExtension.AppSettings["license.file.path"] ?? "").Trim(); LicensePathTemp = LicensePath + ".tmp"; } public static string CustomerId { get { return CoreContext.Configuration.GetSetting(CustomerIdKey); } private set { CoreContext.Configuration.SaveSetting(CustomerIdKey, value); } } private static Stream GetLicenseStream(bool temp = false) { var path = temp ? LicensePathTemp : LicensePath; if (!File.Exists(path)) throw new BillingNotFoundException("License not found"); return File.OpenRead(path); } public static void RejectLicense() { if (File.Exists(LicensePathTemp)) File.Delete(LicensePathTemp); if (File.Exists(LicensePath)) File.Delete(LicensePath); CoreContext.PaymentManager.DeleteDefaultTariff(); } public static void RefreshLicense() { try { var temp = true; if (!File.Exists(LicensePathTemp)) { Log.Debug("Temp license not found"); if (!File.Exists(LicensePath)) { throw new BillingNotFoundException("License not found"); } temp = false; } using (var licenseStream = GetLicenseStream(temp)) using (var reader = new StreamReader(licenseStream)) { var licenseJsonString = reader.ReadToEnd(); var license = License.Parse(licenseJsonString); LicenseToDB(license); if (temp) { SaveLicense(licenseStream, LicensePath); } } if (temp) File.Delete(LicensePathTemp); } catch (Exception ex) { LogError(ex); throw; } } public static DateTime SaveLicenseTemp(Stream licenseStream) { try { using (var reader = new StreamReader(licenseStream)) { var licenseJsonString = reader.ReadToEnd(); var license = License.Parse(licenseJsonString); var dueDate = Validate(license); SaveLicense(licenseStream, LicensePathTemp); return dueDate; } } catch (Exception ex) { LogError(ex); throw; } } private static void SaveLicense(Stream licenseStream, string path) { if (licenseStream == null) throw new ArgumentNullException("licenseStream"); if (licenseStream.CanSeek) { licenseStream.Seek(0, SeekOrigin.Begin); } const int bufferSize = 4096; using (var fs = File.Open(path, FileMode.Create)) { var buffer = new byte[bufferSize]; int readed; while ((readed = licenseStream.Read(buffer, 0, bufferSize)) != 0) { fs.Write(buffer, 0, readed); } } } private static DateTime Validate(License license) { if (string.IsNullOrEmpty(license.CustomerId) || string.IsNullOrEmpty(license.Signature)) { throw new BillingNotConfiguredException("License not correct", license.OriginalLicense); } if (license.DueDate.Date < VersionReleaseDate) { throw new LicenseExpiredException("License expired", license.OriginalLicense); } if (license.ActiveUsers.Equals(default(int)) || license.ActiveUsers < 1) license.ActiveUsers = MaxUserCount; if (license.ActiveUsers < CoreContext.UserManager.GetUsers(EmployeeStatus.Default, EmployeeType.User).Length) { throw new LicenseQuotaException("License quota", license.OriginalLicense); } if (license.PortalCount <= 0) { license.PortalCount = CoreContext.TenantManager.GetTenantQuota(Tenant.DEFAULT_TENANT).CountPortals; } var activePortals = CoreContext.TenantManager.GetTenants().Count(); if (activePortals > 1 && license.PortalCount < activePortals) { throw new LicensePortalException("License portal count", license.OriginalLicense); } return license.DueDate.Date; } private static void LicenseToDB(License license) { Validate(license); CustomerId = license.CustomerId; var defaultQuota = CoreContext.TenantManager.GetTenantQuota(Tenant.DEFAULT_TENANT); var quota = new TenantQuota(-1000) { ActiveUsers = license.ActiveUsers, MaxFileSize = defaultQuota.MaxFileSize, MaxTotalSize = defaultQuota.MaxTotalSize, Name = "license", DocsEdition = true, HasDomain = true, Audit = true, ControlPanel = true, HealthCheck = true, Ldap = true, Sso = true, Customization = license.Customization, WhiteLabel = license.WhiteLabel || license.Customization, Branding = license.Branding, SSBranding = license.SSBranding, Update = true, Support = true, Trial = license.Trial, CountPortals = license.PortalCount, DiscEncryption = true, PrivacyRoom = true, }; if (defaultQuota.Name != "overdue" && !defaultQuota.Trial) { quota.WhiteLabel |= defaultQuota.WhiteLabel; quota.Branding |= defaultQuota.Branding; quota.SSBranding |= defaultQuota.SSBranding; quota.CountPortals = Math.Max(defaultQuota.CountPortals, quota.CountPortals); } CoreContext.TenantManager.SaveTenantQuota(quota); var tariff = new Tariff { QuotaId = quota.Id, DueDate = license.DueDate, }; CoreContext.PaymentManager.SetTariff(-1, tariff); if (!string.IsNullOrEmpty(license.AffiliateId)) { var tenant = CoreContext.TenantManager.GetCurrentTenant(); tenant.AffiliateId = license.AffiliateId; CoreContext.TenantManager.SaveTenant(tenant); } } private static void LogError(Exception error) { if (error is BillingNotFoundException) { Log.DebugFormat("License not found: {0}", error.Message); } else { if (Log.IsDebugEnabled) { Log.Error(error); } else { Log.Error(error.Message); } } } private static DateTime _date = DateTime.MinValue; public static DateTime VersionReleaseDate { get { // release sign is not longer requered return _date; /* if (_date != DateTime.MinValue) return _date; _date = DateTime.MaxValue; try { var versionDate = ConfigurationManagerExtension.AppSettings["version.release-date"]; var sign = ConfigurationManagerExtension.AppSettings["version.release-date.sign"]; if (!sign.StartsWith("ASC ")) { throw new Exception("sign without ASC"); } var splitted = sign.Substring(4).Split(':'); var pkey = splitted[0]; if (pkey != versionDate) { throw new Exception("sign with different date"); } var date = splitted[1]; var orighash = splitted[2]; var skey = MachinePseudoKeys.GetMachineConstant(); using (var hasher = new HMACSHA1(skey)) { var data = string.Join("\n", date, pkey); var hash = hasher.ComputeHash(Encoding.UTF8.GetBytes(data)); if (HttpServerUtility.UrlTokenEncode(hash) != orighash && Convert.ToBase64String(hash) != orighash) { throw new Exception("incorrect hash"); } } var year = Int32.Parse(versionDate.Substring(0, 4)); var month = Int32.Parse(versionDate.Substring(4, 2)); var day = Int32.Parse(versionDate.Substring(6, 2)); _date = new DateTime(year, month, day); } catch (Exception ex) { LogManager.GetLogger("ASC").Error("VersionReleaseDate", ex); } return _date;*/ } } } }<file_sep>/module/ASC.Api/ASC.Api.Documents/FileShareWrapper.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using ASC.Api.Employee; using ASC.Core; using ASC.Files.Core; using ASC.Files.Core.Security; using ASC.Web.Files.Services.WCFService; namespace ASC.Api.Documents { /// <summary> /// </summary> public class FileShareWrapper { private FileShareWrapper() { } /// <summary> /// </summary> /// <param name="aceWrapper"></param> public FileShareWrapper(AceWrapper aceWrapper) { IsOwner = aceWrapper.Owner; IsLocked = aceWrapper.LockedRights; if (aceWrapper.SubjectGroup) { if (aceWrapper.SubjectId == FileConstant.ShareLinkId) { SharedTo = new FileShareLink { Id = aceWrapper.SubjectId, ShareLink = aceWrapper.Link }; } else { //Shared to group SharedTo = new GroupWrapperSummary(CoreContext.UserManager.GetGroupInfo(aceWrapper.SubjectId)); } } else { SharedTo = new EmployeeWraperFull(CoreContext.UserManager.GetUsers(aceWrapper.SubjectId)); } Access = aceWrapper.Share; } /// <summary> /// </summary> public FileShare Access { get; set; } /// <summary> /// </summary> public object SharedTo { get; set; } /// <summary> /// </summary> public bool IsLocked { get; set; } /// <summary> /// </summary> public bool IsOwner { get; set; } /// <summary> /// </summary> /// <returns></returns> public static FileShareWrapper GetSample() { return new FileShareWrapper { Access = FileShare.ReadWrite, IsLocked = false, IsOwner = true, SharedTo = EmployeeWraper.GetSample() }; } } /// <summary> /// </summary> public class FileShareLink { /// <summary> /// </summary> public Guid Id; /// <summary> /// </summary> public string ShareLink; } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/AUTH/AUTH_e_Authenticate.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.AUTH { #region usings using System; #endregion /// <summary> /// This class provides data for server userName/password authentications. /// </summary> public class AUTH_e_Authenticate : EventArgs { #region Members private readonly string m_AuthorizationID = ""; private readonly string m_Password = ""; private readonly string m_UserName = ""; #endregion #region Properties /// <summary> /// Gets or sets if specified user is authenticated. /// </summary> public bool IsAuthenticated { get; set; } /// <summary> /// Gets authorization ID. /// </summary> public string AuthorizationID { get { return m_AuthorizationID; } } /// <summary> /// Gets user name. /// </summary> public string UserName { get { return m_UserName; } } /// <summary> /// Gets password. /// </summary> public string Password { get { return m_Password; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="authorizationID">Authorization ID.</param> /// <param name="userName">User name.</param> /// <param name="password"><PASSWORD>.</param> /// <exception cref="ArgumentNullException">Is raised when <b>userName</b> is null reference.</exception> /// <exception cref="ArgumentException">Is raised when any of the argumnets has invalid value.</exception> public AUTH_e_Authenticate(string authorizationID, string userName, string password) { if (userName == null) { throw new ArgumentNullException("userName"); } if (userName == string.Empty) { throw new ArgumentException("Argument 'userName' value must be specified.", "userName"); } m_AuthorizationID = authorizationID; m_UserName = userName; m_Password = <PASSWORD>; } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/SIP/Message/SIP_t_SecMechanism.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.SIP.Message { #region usings using System; using System.Globalization; using System.Text; #endregion /// <summary> /// Implements SIP "sec-mechanism" value. Defined in RFC 3329. /// </summary> /// <remarks> /// <code> /// RFC 3329 Syntax: /// sec-mechanism = mechanism-name *(SEMI mech-parameters) /// mechanism-name = ( "digest" / "tls" / "ipsec-ike" / "ipsec-man" / token ) /// mech-parameters = ( preference / digest-algorithm / digest-qop / digest-verify / extension ) /// preference = "q" EQUAL qvalue /// qvalue = ( "0" [ "." 0*3DIGIT ] ) / ( "1" [ "." 0*3("0") ] ) /// digest-algorithm = "d-alg" EQUAL token /// digest-qop = "d-qop" EQUAL token /// digest-verify = "d-ver" EQUAL LDQUOT 32LHEX RDQUOT /// extension = generic-param /// </code> /// </remarks> public class SIP_t_SecMechanism : SIP_t_ValueWithParams { #region Members private string m_Mechanism = ""; #endregion #region Properties /// <summary> /// Gets or sets security mechanism name. Defined values: "digest","tls","ipsec-ike","ipsec-man". /// </summary> /// <exception cref="ArgumentNullException">Is raised when null value is passed.</exception> /// <exception cref="ArgumentException">Is raised when invalid Mechanism value is passed.</exception> public string Mechanism { get { return m_Mechanism; } set { if (value == null) { throw new ArgumentNullException("Mechanism"); } if (value == "") { throw new ArgumentException("Property Mechanism value may not be '' !"); } if (!TextUtils.IsToken(value)) { throw new ArgumentException("Property Mechanism value must be 'token' !"); } m_Mechanism = value; } } /// <summary> /// Gets or sets 'q' parameter value. Value -1 means not specified. /// </summary> public double Q { get { if (!Parameters.Contains("qvalue")) { return -1; } else { return double.Parse(Parameters["qvalue"].Value, NumberStyles.Any); } } set { if (value < 0 || value > 2) { throw new ArgumentException("Property QValue value must be between 0.0 and 2.0 !"); } if (value < 0) { Parameters.Remove("qvalue"); } else { Parameters.Set("qvalue", value.ToString()); } } } /// <summary> /// Gets or sets 'd-alg' parameter value. Value null means not specified. /// </summary> public string D_Alg { get { SIP_Parameter parameter = Parameters["d-alg"]; if (parameter != null) { return parameter.Value; } else { return null; } } set { if (string.IsNullOrEmpty(value)) { Parameters.Remove("d-alg"); } else { Parameters.Set("d-alg", value); } } } /// <summary> /// Gets or sets 'd-qop' parameter value. Value null means not specified. /// </summary> public string D_Qop { get { SIP_Parameter parameter = Parameters["d-qop"]; if (parameter != null) { return parameter.Value; } else { return null; } } set { if (string.IsNullOrEmpty(value)) { Parameters.Remove("d-qop"); } else { Parameters.Set("d-qop", value); } } } /// <summary> /// Gets or sets 'd-ver' parameter value. Value null means not specified. /// </summary> public string D_Ver { get { SIP_Parameter parameter = Parameters["d-ver"]; if (parameter != null) { return parameter.Value; } else { return null; } } set { if (string.IsNullOrEmpty(value)) { Parameters.Remove("d-ver"); } else { Parameters.Set("d-ver", value); } } } #endregion #region Methods /// <summary> /// Parses "sec-mechanism" from specified value. /// </summary> /// <param name="value">SIP "sec-mechanism" value.</param> /// <exception cref="ArgumentNullException">Raised when <b>value</b> is null.</exception> /// <exception cref="SIP_ParseException">Raised when invalid SIP message.</exception> public void Parse(string value) { if (value == null) { throw new ArgumentNullException("value"); } Parse(new StringReader(value)); } /// <summary> /// Parses "sec-mechanism" from specified reader. /// </summary> /// <param name="reader">Reader from where to parse.</param> /// <exception cref="ArgumentNullException">Raised when <b>reader</b> is null.</exception> /// <exception cref="SIP_ParseException">Raised when invalid SIP message.</exception> public override void Parse(StringReader reader) { /* sec-mechanism = mechanism-name *(SEMI mech-parameters) mechanism-name = ( "digest" / "tls" / "ipsec-ike" / "ipsec-man" / token ) mech-parameters = ( preference / digest-algorithm / digest-qop / digest-verify / extension ) preference = "q" EQUAL qvalue qvalue = ( "0" [ "." 0*3DIGIT ] ) / ( "1" [ "." 0*3("0") ] ) digest-algorithm = "d-alg" EQUAL token digest-qop = "d-qop" EQUAL token digest-verify = "d-ver" EQUAL LDQUOT 32LHEX RDQUOT extension = generic-param */ if (reader == null) { throw new ArgumentNullException("reader"); } // mechanism-name string word = reader.ReadWord(); if (word == null) { throw new SIP_ParseException("Invalid 'sec-mechanism', 'mechanism-name' is missing !"); } // Parse parameters ParseParameters(reader); } /// <summary> /// Converts this to valid "sec-mechanism" value. /// </summary> /// <returns>Returns "sec-mechanism" value.</returns> public override string ToStringValue() { /* sec-mechanism = mechanism-name *(SEMI mech-parameters) mechanism-name = ( "digest" / "tls" / "ipsec-ike" / "ipsec-man" / token ) mech-parameters = ( preference / digest-algorithm / digest-qop / digest-verify / extension ) preference = "q" EQUAL qvalue qvalue = ( "0" [ "." 0*3DIGIT ] ) / ( "1" [ "." 0*3("0") ] ) digest-algorithm = "d-alg" EQUAL token digest-qop = "d-qop" EQUAL token digest-verify = "d-ver" EQUAL LDQUOT 32LHEX RDQUOT extension = generic-param */ StringBuilder retVal = new StringBuilder(); // mechanism-name retVal.Append(m_Mechanism); // Add parameters retVal.Append(ParametersToString()); return retVal.ToString(); } #endregion } }<file_sep>/web/core/ASC.Web.Core/WarmupPage.cs using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Web; using ASC.Common.Logging; namespace ASC.Web.Core { public abstract class WarmupPage : BasePage { protected virtual List<string> Pages { get; } protected virtual List<string> Exclude { get; } protected void Page_Load(object sender, EventArgs e) { var path = Path.GetDirectoryName(HttpContext.Current.Request.PhysicalPath); var files = Directory.GetFiles(path, "*.aspx", SearchOption.TopDirectoryOnly) .Select(r => Path.GetFileName(r)) .Where(r => !r.EndsWith("warmup.aspx", StringComparison.OrdinalIgnoreCase)) .ToList(); if (Pages != null && Pages.Any()) { files.AddRange(Pages); } if (Exclude != null && Exclude.Any()) { files = files.Except(Exclude).ToList(); } foreach (var file in files.Distinct()) { var page = Path.GetFileName(file); try { HttpContext.Current.Server.Execute(page); } catch (Exception ex) { LogManager.GetLogger("ASC").Error("Warmup " + page, ex); } } HttpContext.Current.Response.Clear(); } } } <file_sep>/module/ASC.Socket.IO/app/hubs/voipListPhones.js const VoipPhone = require('./voipPhone.js'); class ListVoipPhone { constructor() { this.phones = []; } addPhone(numberId) { const existingPhone = this.phones.find((item) => item.numberId === numberId); if (!existingPhone) { this.phones.push(new VoipPhone(numberId)); } } getPhone(numberId) { return this.phones.find((item) => item.numberId === numberId); } addOrUpdateAgent(numberId, agent) { const phone = this.getPhone(numberId); if (!phone) return; phone.addOrUpdateAgent(agent); } removeAgent(numberId, agentId) { const phone = this.getPhone(numberId); if (!phone) return; phone.removeAgent(agentId); } anyCalls(numberId) { const phone = this.getPhone(numberId); if (!phone) return false; return phone.anyCalls(); } dequeueCall(numberId) { const phone = this.getPhone(numberId); if (!phone) return ""; return phone.dequeueCall(); } removeCall(numberId, callId) { const phone = this.getPhone(numberId); if (!phone) return; phone.removeCall(callId); } enqueue(numberId, callId, agent) { const phone = this.getPhone(numberId); if (!phone) return ""; return phone.enqueue(callId, agent); } onlineAgents(numberId) { const phone = this.getPhone(numberId); if (!phone) return []; return phone.onlineAgents(); } getStatus(numberId, agentId) { const phone = this.getPhone(numberId); if (!phone) return 2; return phone.getAgentStatus(agentId); } getAgent(numberId, contactResponsibles) { const phone = this.getPhone(numberId); if (!phone) return null; return phone.getAgent(contactResponsibles); } } module.exports = ListVoipPhone;<file_sep>/web/studio/ASC.Web.Studio/UserControls/Management/SingleSignOnSettings/js/singlesignonsettings.js /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ //TODO: Remove this or re-write like in Control Panel? var SsoSettings = (function () { var already = false, canSave = false, SAML = "SAML", JWT = "JWT", HMAC_SHA256 = "HMAC SHA-256", RSA_SHA256 = "RSA SHA-256", X509 = "X.509", uploadData = null, isStandalone, $ssoCertFile = jq("#ssoCertFile"), $ssoCertStatusContainer = jq("#ssoCertStatusContainer"), $ssoCertUploader = jq("#ssoCertUploader"), $ssoSettingsContainer = jq(".sso-settings-container"), $ssoSettingsMainContainer = jq(".sso-settings-main-container") $fileInput = jq("#ssoCertFile .name"), $ssoSettingsDownloadPublicKey = jq(".sso-settings-download-public-key"), $ssoSettingsTokenType = jq(".sso-settings-token-type"), $ssoSettingsCertPwd = jq(".sso-settings-cert-pwd"), $ssoSettingsSave = jq(".sso-settings-save"), $ssoSettingsValidationType = jq(".sso-settings-validation-type"), $ssoSettingsClientCrtBlock = jq(".sso-settings-client-crt-block"); function canSaveSettings() { canSave = true; $ssoSettingsSave.removeClass("disable"); } function createFileuploadInput(buttonObj) { var inputObj = jq("<input/>") .attr("id", "ssoFileUpload") .attr("type", "file") .css("width", "0") .css("height", "0") .hide(); inputObj.appendTo(buttonObj.parent()); buttonObj.on("click", function (e) { e.preventDefault(); jq("#ssoFileUpload").click(); }); } function getFileExtension(fileTitle) { if (typeof fileTitle == "undefined" || fileTitle == null) { return ""; } fileTitle = fileTitle.trim(); var posExt = fileTitle.lastIndexOf("."); return 0 <= posExt ? fileTitle.substring(posExt).trim().toLowerCase() : ""; } function createUploader() { var $ssoFileUpload = jq("#ssoFileUpload"); if ($ssoFileUpload.length) { var uploader = $ssoFileUpload.fileupload({ url: "ajaxupload.ashx?type=ASC.Web.Studio.UserControls.Management.SingleSignOnSettings.SingleSignOnSettings,ASC.Web.Studio", autoUpload: false, singleFileUploads: true, sequentialUploads: true }); uploader.bind("fileuploadadd", function (e, data) { if (getFileExtension(data.files[0].name) != ".pfx") { uploadData = null; $ssoCertStatusContainer.addClass("error-popup"). removeClass("display-none").text(ASC.Resources.Master.Resource.UploadHttpsFileTypeError); } else { uploadData = data; $fileInput.text(data.files[0].name); $ssoCertFile.show(); $ssoFileUpload.prop("disabled", true); jq("#ssoFileUpload").prop("disabled", true); $ssoCertUploader.addClass("gray"); $ssoCertStatusContainer.addClass("display-none"); $ssoSettingsCertPwd.removeAttr("disabled"); canSaveSettings(); } }); uploader.bind("fileuploadfail", function (e, data) { uploadData = null; var msg = data.errorThrown || data.textStatus; if (data.jqXHR && data.jqXHR.responseText) { msg = jq.parseJSON(data.jqXHR.responseText).Message; } LoadingBanner.showMesInfoBtn(".sso-settings-main-container", Encoder.htmlEncode(msg), "error"); }); uploader.bind("fileuploaddone", function (e, data) { var res = JSON.parse(data.result); if (res.Success) { uploadData = null; jq("#ssoFileUpload").prop("disabled", false); $ssoCertUploader.removeClass("gray"); $ssoCertStatusContainer.addClass("display-none"); saveSettings(); } else { LoadingBanner.showMesInfoBtn(".sso-settings-main-container", Encoder.htmlEncode(res.Message), "error"); } }); } } function ratioButtonChange() { canSaveSettings(); if (jq(this).is(":checked") && jq(this).is("#ssoSettingsEnable")) { $ssoSettingsContainer.removeClass("sso-settings-disabled"); $ssoSettingsContainer. find("input, textarea.sso-settings-public-key-area, select:not(.sso-settings-validation-type)"). removeAttr("disabled"); if ($ssoSettingsTokenType.val() == JWT) { $ssoSettingsValidationType.removeAttr("disabled"); } $ssoCertUploader.removeClass("gray"); if (jq(".sso-settings-client-public-key-area").val()) { $ssoSettingsDownloadPublicKey.removeClass("sso-link-not-active"); } } else { $ssoSettingsContainer.addClass("sso-settings-disabled"); $ssoSettingsContainer.find("input, textarea.sso-settings-public-key-area, select").attr("disabled", ""); $ssoCertUploader.addClass("gray"); $ssoSettingsDownloadPublicKey.addClass("sso-link-not-active"); } } function saveSettings() { if (already || !canSave) { return; } already = true; HideRequiredError(); var result = false, publicKey = jq(".sso-settings-public-key-area").val(), issuer = jq(".sso-settings-issuer-url").val(), ssoEndPoint = jq(".sso-settings-endpoint-url").val(), enableSso = jq("#ssoSettingsEnable").is(":checked"); if (enableSso) { if (publicKey == "") { result = true; ShowRequiredError(jq("#ssoSettingsPublicKeyError")); } if (issuer == "") { result = true; ShowRequiredError(jq("#ssoSettingsIssuerUrlError")); } if (ssoEndPoint == "") { result = true; ShowRequiredError(jq("#ssoSettingsEndpointUrlError")); } if (result) { already = false; return; } } var $ssoSettingsStatus = jq(".sso-settings-status"), $ssoSettingsLoader = jq(".sso-settings-loader"); $ssoSettingsMainContainer.addClass("sso-settings-disabled"); $ssoSettingsMainContainer.find("input, textarea, select").attr("disabled", ""); $ssoSettingsStatus.text(ASC.Resources.Master.Resource.LoadingProcessing); $ssoSettingsStatus.removeClass("display-none"); $ssoSettingsLoader.removeClass("display-none"); /*SsoSettingsController.SaveSettings(JSON.stringify({ EnableSso: enableSso, TokenType: $ssoSettingsTokenType.val(), ValidationType: $ssoSettingsValidationType.val(), PublicKey: publicKey, Issuer: issuer, SsoEndPoint: ssoEndPoint, SloEndPoint: jq(".slo-settings-endpoint-url").val(), ClientPassword: <PASSWORD>(), ClientCertificateFileName: $ssoSettingsClientCrtBlock.find(".name").text() }), function (result) { jq("#ssoSettingsEnable").removeAttr("disabled"); jq("#ssoSettingsDisable").removeAttr("disabled"); $ssoSettingsMainContainer.removeClass("sso-settings-disabled"); var status = result.value.Status; if (!status) { if (isStandalone) { jq(".sso-settings-client-public-key-area").val(result.value.PublicKey); } status = ASC.Resources.Master.Resource.SavedTitle; LoadingBanner.showMesInfoBtn(".sso-settings-main-container", Encoder.htmlEncode(status), "success"); } else { LoadingBanner.showMesInfoBtn(".sso-settings-main-container", Encoder.htmlEncode(status), "error"); } if (jq("#ssoSettingsEnable").is(":checked")) { $ssoSettingsContainer. find("input, textarea.sso-settings-public-key-area, select:not(.sso-settings-validation-type)").removeAttr("disabled"); if (jq(".sso-settings-client-public-key-area").val()) { $ssoSettingsDownloadPublicKey.removeClass("sso-link-not-active"); } if ($ssoSettingsTokenType.val() == JWT) { $ssoSettingsValidationType.removeAttr("disable"); } } $ssoSettingsLoader.addClass("display-none"); $ssoSettingsStatus.addClass("display-none"); canSave = false; $ssoSettingsSave.addClass("disable"); already = false; });*/ } jq(window).on("load", function () { $ssoSettingsMainContainer.on("click", ".sso-settings-save", function () { /*SsoSettingsController.IsStandalone($ssoSettingsCertPwd.val(), function (result) { isStandalone = result.value; if (result.value && uploadData != null) { uploadData.submit(); } else { saveSettings(); } });*/ } ); jq("#ssoCertFile .trash").on("click", function () { if (jq("#ssoSettingsEnable").is(":checked")) { uploadData = null; jq("#ssoFileUpload").prop("disabled", false); $ssoCertUploader.removeClass("gray"); $ssoCertFile.hide(); $ssoCertFile.find(".name").text(""); $ssoCertStatusContainer.addClass("display-none"); jq(".sso-settings-client-public-key-area").val(""); $ssoSettingsDownloadPublicKey.addClass("sso-link-not-active"); jq("#ssoFileUpload").prop("disabled", false); canSaveSettings(); } }); $ssoSettingsTokenType.change(function (e) { canSaveSettings(); if (jq(e.currentTarget).val() == JWT) { $ssoSettingsValidationType.removeAttr("disabled"); $ssoSettingsClientCrtBlock.addClass("display-none"); } else if (jq(e.currentTarget).val() == SAML) { $ssoSettingsValidationType.find("option[value='X.509']").attr("selected", ""); $ssoSettingsValidationType.attr("disabled", ""); $ssoSettingsClientCrtBlock.removeClass("display-none"); } }); createFileuploadInput($ssoCertUploader); createUploader(); if (!jq("#ssoSettingsEnable").is(":checked")) { jq("#ssoFileUpload").prop("disabled", true); } jq("#ssoSettingsEnable").change(ratioButtonChange); jq("#ssoSettingsDisable").change(ratioButtonChange); $ssoSettingsValidationType.change(canSaveSettings); $ssoSettingsMainContainer.on("keydown", ".sso-settings-public-key-area", canSaveSettings); $ssoSettingsMainContainer.on("keydown", ".sso-settings-issuer-url", canSaveSettings); $ssoSettingsMainContainer.on("keydown", ".sso-settings-endpoint-url", canSaveSettings); $ssoSettingsMainContainer.on("keydown", ".slo-settings-endpoint-url", canSaveSettings); $ssoSettingsMainContainer.on("keydown", ".sso-settings-cert-pwd", canSaveSettings); }); })();<file_sep>/common/ASC.Core.Common/Billing/BillingClient.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Runtime.Serialization; using System.ServiceModel; using System.Web; using System.Xml.Linq; using System.Xml.XPath; using ASC.Common.Logging; namespace ASC.Core.Billing { public class BillingClient : ClientBase<IService>, IDisposable { private static readonly ILog Log = LogManager.GetLogger("ASC"); private readonly bool _test; public BillingClient() : this(false) { } public BillingClient(bool test) { _test = test; } public PaymentLast GetLastPayment(string portalId) { var result = Request("GetLatestActiveResourceEx", portalId); var xelement = ToXElement("<root>" + result + "</root>"); var dedicated = xelement.Element("dedicated-resource"); var payment = xelement.Element("payment"); if (!_test && GetValueString(payment.Element("status")) == "4") { throw new BillingException("Can not accept test payment.", new { PortalId = portalId }); } var autorenewal = string.Empty; try { autorenewal = Request("GetLatestAvangateLicenseRecurringStatus", portalId); } catch (BillingException err) { Log.Debug(err); // ignore } return new PaymentLast { ProductId = GetValueString(dedicated.Element("product-id")), EndDate = GetValueDateTime(dedicated.Element("end-date")), Autorenewal = "enabled".Equals(autorenewal, StringComparison.InvariantCultureIgnoreCase), }; } public IEnumerable<PaymentInfo> GetPayments(string portalId, DateTime from, DateTime to) { string result; if (from == DateTime.MinValue && to == DateTime.MaxValue) { result = Request("GetPayments", portalId); } else { result = Request("GetListOfPaymentsByTimeSpan", portalId, Tuple.Create("StartDate", from.ToString("yyyy-MM-dd HH:mm:ss")), Tuple.Create("EndDate", to.ToString("yyyy-MM-dd HH:mm:ss"))); } var xelement = ToXElement(result); return xelement.Elements("payment").Select(ToPaymentInfo); } public IDictionary<string, Tuple<Uri, Uri>> GetPaymentUrls(string portalId, string[] products, string affiliateId = null, string campaign = null, string currency = null, string language = null, string customerId = null) { var urls = new Dictionary<string, Tuple<Uri, Uri>>(); var additionalParameters = new List<Tuple<string, string>>(2) { Tuple.Create("PaymentSystemId", "1") }; if (!string.IsNullOrEmpty(affiliateId)) { additionalParameters.Add(Tuple.Create("AffiliateId", affiliateId)); } if (!string.IsNullOrEmpty(campaign)) { additionalParameters.Add(Tuple.Create("campaign", campaign)); } if (!string.IsNullOrEmpty(currency)) { additionalParameters.Add(Tuple.Create("Currency", currency)); } if (!string.IsNullOrEmpty(language)) { additionalParameters.Add(Tuple.Create("Language", language)); } if (!string.IsNullOrEmpty(customerId)) { additionalParameters.Add(Tuple.Create("CustomerID", customerId)); } var parameters = products .Distinct() .Select(p => Tuple.Create("ProductId", p)) .Concat(additionalParameters) .ToArray(); //max 100 products var paymentUrls = ToXElement(Request("GetBatchPaymentSystemUrl", portalId, parameters)) .Elements() .ToDictionary(e => e.Attribute("id").Value, e => ToUrl(e.Attribute("value").Value)); var upgradeUrls = new Dictionary<string, string>(); if (!string.IsNullOrEmpty(portalId)) { try { //max 100 products upgradeUrls = ToXElement(Request("GetBatchPaymentSystemUpgradeUrl", portalId, parameters)) .Elements() .ToDictionary(e => e.Attribute("id").Value, e => ToUrl(e.Attribute("value").Value)); } catch (BillingException) { } } foreach (var p in products) { string url; var paymentUrl = (Uri)null; var upgradeUrl = (Uri)null; if (paymentUrls.TryGetValue(p, out url) && !string.IsNullOrEmpty(url)) { paymentUrl = new Uri(url); } if (upgradeUrls.TryGetValue(p, out url) && !string.IsNullOrEmpty(url)) { upgradeUrl = new Uri(url); } urls[p] = Tuple.Create(paymentUrl, upgradeUrl); } return urls; } public Invoice GetInvoice(string paymentId) { var result = Request("GetInvoice", null, Tuple.Create("PaymentId", paymentId)); var xelement = ToXElement(result); return new Invoice { Sale = GetValueString(xelement.Element("sale")), Refund = GetValueString(xelement.Element("refund")), }; } public IDictionary<string, IEnumerable<Tuple<string, decimal>>> GetProductPriceInfo(params string[] productIds) { if (productIds == null) { throw new ArgumentNullException("productIds"); } var responce = Request("GetBatchAvangateProductPriceInfo", null, productIds.Select(pid => Tuple.Create("ProductId", pid)).ToArray()); var xelement = ToXElement(responce); return productIds .Select(p => { var prices = Enumerable.Empty<Tuple<string, decimal>>(); var product = xelement.XPathSelectElement(string.Format("/avangate-product/internal-id[text()=\"{0}\"]", p)); if (product != null) { prices = product.Parent.Element("prices").Elements("price-item") .Select(e => Tuple.Create(e.Element("currency").Value, decimal.Parse(e.Element("amount").Value))); } return new { ProductId = p, Prices = prices, }; }) .ToDictionary(e => e.ProductId, e => e.Prices); } private string Request(string method, string portalId, params Tuple<string, string>[] parameters) { var request = new XElement(method); if (!string.IsNullOrEmpty(portalId)) { request.Add(new XElement("PortalId", portalId)); } request.Add(parameters.Select(p => new XElement(p.Item1, p.Item2)).ToArray()); var responce = Channel.Request(new Message { Type = MessageType.Data, Content = request.ToString(SaveOptions.DisableFormatting), }); if (responce.Content == null) { throw new BillingNotConfiguredException("Billing response is null"); } if (responce.Type == MessageType.Data) { var result = responce.Content; var invalidChar = ((char)65279).ToString(); return result.Contains(invalidChar) ? result.Replace(invalidChar, string.Empty) : result; } var @params = (parameters ?? Enumerable.Empty<Tuple<string, string>>()).Select(p => string.Format("{0}: {1}", p.Item1, p.Item2)); var info = new { Method = method, PortalId = portalId, Params = string.Join(", ", @params) }; if (responce.Content.Contains("error: cannot find ")) { throw new BillingNotFoundException(responce.Content, info); } throw new BillingException(responce.Content, info); } private static XElement ToXElement(string xml) { return XElement.Parse(xml); } private static PaymentInfo ToPaymentInfo(XElement x) { return new PaymentInfo { ID = (int)GetValueDecimal(x.Element("id")), Status = (int)GetValueDecimal(x.Element("status")), PaymentType = GetValueString(x.Element("reserved-str-2")), ExchangeRate = (double)GetValueDecimal(x.Element("exch-rate")), GrossSum = (double)GetValueDecimal(x.Element("gross-sum")), Name = (GetValueString(x.Element("fname")) + " " + GetValueString(x.Element("lname"))).Trim(), Email = GetValueString(x.Element("email")), Date = GetValueDateTime(x.Element("payment-date")), Price = GetValueDecimal(x.Element("price")), Currency = GetValueString(x.Element("payment-currency")), Method = GetValueString(x.Element("payment-method")), CartId = GetValueString(x.Element("cart-id")), ProductId = GetValueString(x.Element("product-ref")), TenantID = GetValueString(x.Element("customer-id")), Country = GetValueString(x.Element("country")), DiscountSum = GetValueDecimal(x.Element("discount-sum")) }; } private string ToUrl(string s) { s = s.Trim(); if (s.StartsWith("error", StringComparison.InvariantCultureIgnoreCase)) { return string.Empty; } if (_test && !s.Contains("&DOTEST = 1")) { s += "&DOTEST=1"; } return s; } private static string GetValueString(XElement xelement) { return xelement != null ? HttpUtility.HtmlDecode(xelement.Value) : default(string); } private static DateTime GetValueDateTime(XElement xelement) { return xelement != null ? DateTime.ParseExact(xelement.Value, "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture) : default(DateTime); } private static Decimal GetValueDecimal(XElement xelement) { if (xelement == null || string.IsNullOrEmpty(xelement.Value)) { return default(Decimal); } var sep = CultureInfo.InvariantCulture.NumberFormat.CurrencyDecimalSeparator; decimal value; return Decimal.TryParse(xelement.Value.Replace(".", sep).Replace(",", sep), NumberStyles.Currency, CultureInfo.InvariantCulture, out value) ? value : default(Decimal); } void IDisposable.Dispose() { try { Close(); } catch (CommunicationException) { Abort(); } catch (TimeoutException) { Abort(); } catch (Exception) { Abort(); throw; } } } [ServiceContract] public interface IService { [OperationContract] Message Request(Message message); } [DataContract(Name = "Message", Namespace = "http://schemas.datacontract.org/2004/07/BillingService")] [Serializable] public class Message { [DataMember] public string Content { get; set; } [DataMember] public MessageType Type { get; set; } } [DataContract(Name = "MessageType", Namespace = "http://schemas.datacontract.org/2004/07/BillingService")] public enum MessageType { [EnumMember] Undefined = 0, [EnumMember] Data = 1, [EnumMember] Error = 2, } [Serializable] public class BillingException : Exception { public BillingException(string message, object debugInfo = null) : base(message + (debugInfo != null ? " Debug info: " + debugInfo : string.Empty)) { } public BillingException(string message, Exception inner) : base(message, inner) { } protected BillingException(SerializationInfo info, StreamingContext context) : base(info, context) { } } [Serializable] public class BillingNotFoundException : BillingException { public BillingNotFoundException(string message, object debugInfo = null) : base(message, debugInfo) { } protected BillingNotFoundException(SerializationInfo info, StreamingContext context) : base(info, context) { } } [Serializable] public class BillingNotConfiguredException : BillingException { public BillingNotConfiguredException(string message, object debugInfo = null) : base(message, debugInfo) { } public BillingNotConfiguredException(string message, Exception inner) : base(message, inner) { } protected BillingNotConfiguredException(SerializationInfo info, StreamingContext context) : base(info, context) { } } }<file_sep>/common/Tests/ASC.Core.Common.Tests/TariffSyncServiceTest.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #if DEBUG namespace ASC.Core.Common.Tests { using ASC.Core.Billing; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Linq; [TestClass] public class TariffSyncServiceTest { private readonly ITariffSyncService tariffSyncService; public TariffSyncServiceTest() { tariffSyncService = new TariffSyncService(); } [TestMethod] public void GetTeriffsTest() { var tariff = tariffSyncService.GetTariffs(70, null).FirstOrDefault(t => t.Id == -38); Assert.AreEqual(1024 * 1024 * 1024, tariff.MaxFileSize); tariff = tariffSyncService.GetTariffs(74, null).FirstOrDefault(t => t.Id == -38); Assert.AreEqual(100 * 1024 * 1024, tariff.MaxFileSize); } [TestMethod] public void SyncTest() { using (var wcfClient = new TariffSyncClient()) { var tariffs = wcfClient.GetTariffs(74, null); Assert.IsTrue(tariffs.Any()); } } } } #endif <file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/SDP/SDP_Attribute.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.SDP { #region usings using System; #endregion /// <summary> /// Implements SDP attribute. /// </summary> public class SDP_Attribute { #region Members private readonly string m_Name = ""; private string m_Value = ""; #endregion #region Properties /// <summary> /// Gets attribute name. /// </summary> public string Name { get { return m_Name; } } /// <summary> /// Gets or sets attribute value. /// </summary> public string Value { get { return m_Value; } set { m_Value = value; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="name">Attribute name.</param> /// <param name="value">Attribute value.</param> public SDP_Attribute(string name, string value) { m_Name = name; Value = value; } #endregion #region Methods /// <summary> /// Parses media from "a" SDP message field. /// </summary> /// <param name="aValue">"a" SDP message field.</param> /// <returns></returns> public static SDP_Attribute Parse(string aValue) { // a=<attribute> // a=<attribute>:<value> // Remove a= StringReader r = new StringReader(aValue); r.QuotedReadToDelimiter('='); //--- <attribute> ------------------------------------------------------------ string name = ""; string word = r.QuotedReadToDelimiter(':'); if (word == null) { throw new Exception("SDP message \"a\" field <attribute> name is missing !"); } name = word; //--- <value> ---------------------------------------------------------------- string value = ""; word = r.ReadToEnd(); if (word != null) { value = word; } return new SDP_Attribute(name, value); } /// <summary> /// Converts this to valid "a" string. /// </summary> /// <returns></returns> public string ToValue() { // a=<attribute> // a=<attribute>:<value> // a=<attribute> if (string.IsNullOrEmpty(m_Value)) { return "a=" + m_Name + "\r\n"; } // a=<attribute>:<value> else { return "a=" + m_Name + ":" + m_Value + "\r\n"; } } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/vCard/Name.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.Mime.vCard { /// <summary> /// vCard name implementation. /// </summary> public class Name { #region Members private string m_AdditionalNames = ""; private string m_FirstName = ""; private string m_HonorificPrefix = ""; private string m_HonorificSuffix = ""; private string m_LastName = ""; #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="lastName">Last name.</param> /// <param name="firstName">First name.</param> /// <param name="additionalNames">Comma separated additional names.</param> /// <param name="honorificPrefix">Honorific prefix.</param> /// <param name="honorificSuffix">Honorific suffix.</param> public Name(string lastName, string firstName, string additionalNames, string honorificPrefix, string honorificSuffix) { m_LastName = lastName; m_FirstName = firstName; m_AdditionalNames = additionalNames; m_HonorificPrefix = honorificPrefix; m_HonorificSuffix = honorificSuffix; } /// <summary> /// Internal parse constructor. /// </summary> internal Name() {} #endregion #region Properties /// <summary> /// Gets comma separated additional names. /// </summary> public string AdditionalNames { get { return m_AdditionalNames; } } /// <summary> /// Gets first name. /// </summary> public string FirstName { get { return m_FirstName; } } /// <summary> /// Gets honorific prefix. /// </summary> public string HonorificPerfix { get { return m_HonorificPrefix; } } /// <summary> /// Gets honorific suffix. /// </summary> public string HonorificSuffix { get { return m_HonorificSuffix; } } /// <summary> /// Gets last name. /// </summary> public string LastName { get { return m_LastName; } } #endregion #region Methods /// <summary> /// Converts item to vCard N structure string. /// </summary> /// <returns></returns> public string ToValueString() { return m_LastName + ";" + m_FirstName + ";" + m_AdditionalNames + ";" + m_HonorificPrefix + ";" + m_HonorificSuffix; } #endregion #region Internal methods /// <summary> /// Parses name info from vCard N item. /// </summary> /// <param name="item">vCard N item.</param> internal static Name Parse(Item item) { string[] items = item.DecodedValue.Split(';'); Name name = new Name(); if (items.Length >= 1) { name.m_LastName = items[0]; } if (items.Length >= 2) { name.m_FirstName = items[1]; } if (items.Length >= 3) { name.m_AdditionalNames = items[2]; } if (items.Length >= 4) { name.m_HonorificPrefix = items[3]; } if (items.Length >= 5) { name.m_HonorificSuffix = items[4]; } return name; } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/POP3/Client/POP3_Client.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System.Globalization; namespace ASC.Mail.Net.POP3.Client { #region usings using System; using System.Collections.Generic; using System.IO; using System.Security.Principal; using IO; using TCP; #endregion /// <summary> /// POP3 Client. Defined in RFC 1939. /// </summary> /// <example> /// <code> /// /// /* /// To make this code to work, you need to import following namespaces: /// using LumiSoft.Net.Mime; /// using LumiSoft.Net.POP3.Client; /// */ /// /// using(POP3_Client c = new POP3_Client()){ /// c.Connect("ivx",WellKnownPorts.POP3); /// c.Authenticate("test","test",true); /// /// // Get first message if there is any /// if(c.Messages.Count > 0){ /// // Do your suff /// /// // Parse message /// Mime m = Mime.Parse(c.Messages[0].MessageToByte()); /// string from = m.MainEntity.From; /// string subject = m.MainEntity.Subject; /// // ... /// } /// } /// </code> /// </example> public class POP3_Client : TCP_Client { #region Nested type: AuthenticateDelegate /// <summary> /// Internal helper method for asynchronous Authenticate method. /// </summary> private delegate void AuthenticateDelegate(string userName, string password, bool tryApop); #endregion #region Nested type: NoopDelegate /// <summary> /// Internal helper method for asynchronous Noop method. /// </summary> private delegate void NoopDelegate(); #endregion #region Nested type: ResetDelegate /// <summary> /// Internal helper method for asynchronous Reset method. /// </summary> private delegate void ResetDelegate(); #endregion #region Nested type: StartTLSDelegate /// <summary> /// Internal helper method for asynchronous StartTLS method. /// </summary> private delegate void StartTLSDelegate(); #endregion #region Members private readonly List<string> m_pExtCapabilities; private string m_ApopHashKey = ""; private string m_GreetingText = ""; private bool m_IsUidlSupported; private GenericIdentity m_pAuthdUserIdentity; private POP3_ClientMessageCollection m_pMessages; #endregion #region Properties /// <summary> /// Gets greeting text which was sent by POP3 server. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when this property is accessed and POP3 client is not connected.</exception> public string GreetingText { get { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (!IsConnected) { throw new InvalidOperationException("You must connect first."); } return m_GreetingText; } } /// <summary> /// Gets POP3 exteneded capabilities supported by POP3 server. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when this property is accessed and POP3 client is not connected.</exception> [Obsolete("USe ExtendedCapabilities instead !")] public string[] ExtenededCapabilities { get { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (!IsConnected) { throw new InvalidOperationException("You must connect first."); } return m_pExtCapabilities.ToArray(); } } /// <summary> /// Gets POP3 exteneded capabilities supported by POP3 server. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when this property is accessed and POP3 client is not connected.</exception> public string[] ExtendedCapabilities { get { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (!IsConnected) { throw new InvalidOperationException("You must connect first."); } return m_pExtCapabilities.ToArray(); } } /// <summary> /// Gets if POP3 server supports UIDL command. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when this property is accessed and /// POP3 client is not connected and authenticated.</exception> public bool IsUidlSupported { get { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (!IsConnected) { throw new InvalidOperationException("You must connect first."); } if (!IsAuthenticated) { throw new InvalidOperationException("You must authenticate first."); } return m_IsUidlSupported; } } /// <summary> /// Gets messages collection. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when this property is accessed and /// POP3 client is not connected and authenticated.</exception> public POP3_ClientMessageCollection Messages { get { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (!IsConnected) { throw new InvalidOperationException("You must connect first."); } if (!IsAuthenticated) { throw new InvalidOperationException("You must authenticate first."); } return m_pMessages; } } /// <summary> /// Gets session authenticated user identity, returns null if not authenticated. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when this property is accessed and POP3 client is not connected.</exception> public override GenericIdentity AuthenticatedUserIdentity { get { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (!IsConnected) { throw new InvalidOperationException("You must connect first."); } return m_pAuthdUserIdentity; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> public POP3_Client(int default_login_delay) { m_pExtCapabilities = new List<string>(); this.default_login_delay = default_login_delay; AuthSucceed += OnAuthSucceed; } #endregion #region Methods /// <summary> /// Clean up any resources being used. /// </summary> public override void Dispose() { base.Dispose(); } /// <summary> /// Closes connection to POP3 server. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when POP3 client is not connected.</exception> public override void Disconnect() { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (!IsConnected) { throw new InvalidOperationException("POP3 client is not connected."); } try { // Send QUIT command to server. WriteLine("QUIT"); } catch {} try { base.Disconnect(); } catch {} if (m_pMessages != null) { m_pMessages.Dispose(); m_pMessages = null; } m_ApopHashKey = ""; m_pExtCapabilities.Clear(); m_IsUidlSupported = false; } /// <summary> /// Starts switching to SSL. /// </summary> /// <returns>An IAsyncResult that references the asynchronous operation.</returns> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when POP3 client is not connected or is authenticated or is already secure connection.</exception> public IAsyncResult BeginStartTLS(AsyncCallback callback, object state) { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (!IsConnected) { throw new InvalidOperationException("You must connect first."); } if (IsAuthenticated) { throw new InvalidOperationException( "The STLS command is only valid in non-authenticated state."); } if (IsSecureConnection) { throw new InvalidOperationException("Connection is already secure."); } StartTLSDelegate asyncMethod = StartTLS; AsyncResultState asyncState = new AsyncResultState(this, asyncMethod, callback, state); asyncState.SetAsyncResult(asyncMethod.BeginInvoke(asyncState.CompletedCallback, null)); return asyncState; } /// <summary> /// Ends a pending asynchronous StartTLS request. /// </summary> /// <param name="asyncResult">An IAsyncResult that stores state information and any user defined data for this asynchronous operation.</param> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="ArgumentNullException">Is raised when <b>asyncResult</b> is null.</exception> /// <exception cref="ArgumentException">Is raised when invalid <b>asyncResult</b> passed to this method.</exception> /// <exception cref="POP3_ClientException">Is raised when POP3 server returns error.</exception> public void EndStartTLS(IAsyncResult asyncResult) { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (asyncResult == null) { throw new ArgumentNullException("asyncResult"); } AsyncResultState castedAsyncResult = asyncResult as AsyncResultState; if (castedAsyncResult == null || castedAsyncResult.AsyncObject != this) { throw new ArgumentException( "Argument asyncResult was not returned by a call to the BeginReset method."); } if (castedAsyncResult.IsEndCalled) { throw new InvalidOperationException( "BeginReset was previously called for the asynchronous connection."); } castedAsyncResult.IsEndCalled = true; if (castedAsyncResult.AsyncDelegate is StartTLSDelegate) { ((StartTLSDelegate) castedAsyncResult.AsyncDelegate).EndInvoke(castedAsyncResult.AsyncResult); } else { throw new ArgumentException( "Argument asyncResult was not returned by a call to the BeginReset method."); } } /// <summary> /// Switches POP3 connection to SSL. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when POP3 client is not connected or is authenticated or is already secure connection.</exception> /// <exception cref="POP3_ClientException">Is raised when POP3 server returns error.</exception> public void StartTLS() { /* RFC 2595 4. POP3 STARTTLS extension. Arguments: none Restrictions: Only permitted in AUTHORIZATION state. Possible Responses: +OK -ERR Examples: C: STLS S: +OK Begin TLS negotiation <TLS negotiation, further commands are under TLS layer> ... C: STLS S: -ERR Command not permitted when TLS active */ if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (!IsConnected) { throw new InvalidOperationException("You must connect first."); } if (IsAuthenticated) { throw new InvalidOperationException( "The STLS command is only valid in non-authenticated state."); } if (IsSecureConnection) { throw new InvalidOperationException("Connection is already secure."); } WriteLine("STLS"); string line = ReadLine(); if (!line.ToUpper().StartsWith("+OK")) { throw new POP3_ClientException(line); } SwitchToSecure(); } /// <summary> /// Starts authentication. /// </summary> /// <param name="userName">User login name.</param> /// <param name="password"><PASSWORD>.</param> /// <param name="tryApop"> If true and POP3 server supports APOP, then APOP is used, otherwise normal login used.</param> /// <param name="callback">Callback to call when the asynchronous operation is complete.</param> /// <param name="state">User data.</param> /// <returns>An IAsyncResult that references the asynchronous operation.</returns> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when POP3 client is not connected or is already authenticated.</exception> public IAsyncResult BeginAuthenticate(string userName, string password, bool tryApop, AsyncCallback callback, object state) { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (!IsConnected) { throw new InvalidOperationException("You must connect first."); } if (IsAuthenticated) { throw new InvalidOperationException("Session is already authenticated."); } AuthenticateDelegate asyncMethod = Authenticate; AsyncResultState asyncState = new AsyncResultState(this, asyncMethod, callback, state); asyncState.SetAsyncResult(asyncMethod.BeginInvoke(userName, password, tryApop, asyncState.CompletedCallback, null)); return asyncState; } /// <summary> /// Ends a pending asynchronous authentication request. /// </summary> /// <param name="asyncResult">An IAsyncResult that stores state information and any user defined data for this asynchronous operation.</param> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="ArgumentNullException">Is raised when <b>asyncResult</b> is null.</exception> /// <exception cref="ArgumentException">Is raised when invalid <b>asyncResult</b> passed to this method.</exception> /// <exception cref="POP3_ClientException">Is raised when POP3 server returns error.</exception> public void EndAuthenticate(IAsyncResult asyncResult) { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (asyncResult == null) { throw new ArgumentNullException("asyncResult"); } AsyncResultState castedAsyncResult = asyncResult as AsyncResultState; if (castedAsyncResult == null || castedAsyncResult.AsyncObject != this) { throw new ArgumentException( "Argument asyncResult was not returned by a call to the BeginAuthenticate method."); } if (castedAsyncResult.IsEndCalled) { throw new InvalidOperationException( "BeginAuthenticate was previously called for the asynchronous connection."); } castedAsyncResult.IsEndCalled = true; if (castedAsyncResult.AsyncDelegate is AuthenticateDelegate) { ((AuthenticateDelegate) castedAsyncResult.AsyncDelegate).EndInvoke( castedAsyncResult.AsyncResult); } else { throw new ArgumentException( "Argument asyncResult was not returned by a call to the BeginAuthenticate method."); } } public delegate void AuthSucceedDelegate(); public event AuthSucceedDelegate AuthSucceed; public delegate void AuthFailedDelegate(string response_line); public event AuthFailedDelegate AuthFailed; /// <summary> /// Authenticates user. /// </summary> /// <param name="userName">User login name.</param> /// <param name="password"><PASSWORD>.</param> /// <param name="tryApop"> If true and POP3 server supports APOP, then APOP is used, otherwise normal login used.</param> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when POP3 client is not connected or is already authenticated.</exception> /// <exception cref="POP3_ClientException">Is raised when POP3 server returns error.</exception> public void Authenticate(string userName, string password, bool tryApop) { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (!IsConnected) { throw new InvalidOperationException("You must connect first."); } if (IsAuthenticated) { throw new InvalidOperationException("Session is already authenticated."); } // Supports APOP, use it. if (tryApop && m_ApopHashKey.Length > 0) { string hexHash = Core.ComputeMd5(m_ApopHashKey + password, true); int countWritten = TcpStream.WriteLine("APOP " + userName + " " + hexHash); LogAddWrite(countWritten, "APOP " + userName + " " + hexHash); string line = ReadLine(); if (line.StartsWith("+OK")) { m_pAuthdUserIdentity = new GenericIdentity(userName, "apop"); } else { if (AuthFailed != null) { AuthFailed.Invoke(line); } throw new POP3_ClientException(line); } } // Use normal LOGIN, don't support APOP. else { int countWritten = TcpStream.WriteLine("USER " + userName); LogAddWrite(countWritten, "USER " + userName); string line = ReadLine(); if (line.StartsWith("+OK")) { countWritten = TcpStream.WriteLine("PASS " + password); LogAddWrite(countWritten, "PASS <***REMOVED***>"); line = ReadLine(); if (line.StartsWith("+OK")) { m_pAuthdUserIdentity = new GenericIdentity(userName, "pop3-user/pass"); } else { if (AuthFailed != null) { AuthFailed.Invoke(line); } throw new POP3_ClientException(line); } } else { if (AuthFailed != null) { AuthFailed.Invoke(line); } throw new POP3_ClientException(line); } } if (IsAuthenticated) { if (AuthSucceed != null) { AuthSucceed.Invoke(); } FillMessages(); } } private void OnAuthSucceed() { if (need_precise_login_delay) { GetCAPA_Parameters(); LoginDelay = ObtainLoginDelay(default_login_delay); } } /// <summary> /// Starts sending NOOP command to server. This method can be used for keeping connection alive(not timing out). /// </summary> /// <param name="callback">Callback to call when the asynchronous operation is complete.</param> /// <param name="state">User data.</param> /// <returns>An IAsyncResult that references the asynchronous operation.</returns> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when POP3 client is not connected.</exception> public IAsyncResult BeginNoop(AsyncCallback callback, object state) { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (!IsConnected) { throw new InvalidOperationException("You must connect first."); } NoopDelegate asyncMethod = Noop; AsyncResultState asyncState = new AsyncResultState(this, asyncMethod, callback, state); asyncState.SetAsyncResult(asyncMethod.BeginInvoke(asyncState.CompletedCallback, null)); return asyncState; } /// <summary> /// Ends a pending asynchronous Noop request. /// </summary> /// <param name="asyncResult">An IAsyncResult that stores state information and any user defined data for this asynchronous operation.</param> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="ArgumentNullException">Is raised when <b>asyncResult</b> is null.</exception> /// <exception cref="ArgumentException">Is raised when invalid <b>asyncResult</b> passed to this method.</exception> /// <exception cref="POP3_ClientException">Is raised when POP3 server returns error.</exception> public void EndNoop(IAsyncResult asyncResult) { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (asyncResult == null) { throw new ArgumentNullException("asyncResult"); } AsyncResultState castedAsyncResult = asyncResult as AsyncResultState; if (castedAsyncResult == null || castedAsyncResult.AsyncObject != this) { throw new ArgumentException( "Argument asyncResult was not returned by a call to the BeginNoop method."); } if (castedAsyncResult.IsEndCalled) { throw new InvalidOperationException( "BeginNoop was previously called for the asynchronous connection."); } castedAsyncResult.IsEndCalled = true; if (castedAsyncResult.AsyncDelegate is NoopDelegate) { ((NoopDelegate) castedAsyncResult.AsyncDelegate).EndInvoke(castedAsyncResult.AsyncResult); } else { throw new ArgumentException( "Argument asyncResult was not returned by a call to the BeginNoop method."); } } /// <summary> /// Send NOOP command to server. This method can be used for keeping connection alive(not timing out). /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when POP3 client is not connected.</exception> /// <exception cref="POP3_ClientException">Is raised when POP3 server returns error.</exception> public void Noop() { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (!IsConnected) { throw new InvalidOperationException("You must connect first."); } if (!IsAuthenticated) { throw new InvalidOperationException("The NOOP command is only valid in TRANSACTION state."); } /* RFC 1939 5 NOOP. Arguments: none Restrictions: may only be given in the TRANSACTION state Discussion: The POP3 server does nothing, it merely replies with a positive response. Possible Responses: +OK Examples: C: NOOP S: +OK */ WriteLine("NOOP"); string line = ReadLine(); if (!line.ToUpper().StartsWith("+OK")) { throw new POP3_ClientException(line); } } /// <summary> /// Starts resetting session. Messages marked for deletion will be unmarked. /// </summary> /// <param name="callback">Callback to call when the asynchronous operation is complete.</param> /// <param name="state">User data.</param> /// <returns>An IAsyncResult that references the asynchronous operation.</returns> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when POP3 client is not connected and authenticated.</exception> public IAsyncResult BeginReset(AsyncCallback callback, object state) { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (!IsConnected) { throw new InvalidOperationException("You must connect first."); } if (!IsAuthenticated) { throw new InvalidOperationException("The RSET command is only valid in authenticated state."); } ResetDelegate asyncMethod = Reset; AsyncResultState asyncState = new AsyncResultState(this, asyncMethod, callback, state); asyncState.SetAsyncResult(asyncMethod.BeginInvoke(asyncState.CompletedCallback, null)); return asyncState; } /// <summary> /// Ends a pending asynchronous reset request. /// </summary> /// <param name="asyncResult">An IAsyncResult that stores state information and any user defined data for this asynchronous operation.</param> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="ArgumentNullException">Is raised when <b>asyncResult</b> is null.</exception> /// <exception cref="ArgumentException">Is raised when invalid <b>asyncResult</b> passed to this method.</exception> /// <exception cref="POP3_ClientException">Is raised when POP3 server returns error.</exception> public void EndReset(IAsyncResult asyncResult) { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (asyncResult == null) { throw new ArgumentNullException("asyncResult"); } AsyncResultState castedAsyncResult = asyncResult as AsyncResultState; if (castedAsyncResult == null || castedAsyncResult.AsyncObject != this) { throw new ArgumentException( "Argument asyncResult was not returned by a call to the BeginReset method."); } if (castedAsyncResult.IsEndCalled) { throw new InvalidOperationException( "BeginReset was previously called for the asynchronous connection."); } castedAsyncResult.IsEndCalled = true; if (castedAsyncResult.AsyncDelegate is ResetDelegate) { ((ResetDelegate) castedAsyncResult.AsyncDelegate).EndInvoke(castedAsyncResult.AsyncResult); } else { throw new ArgumentException( "Argument asyncResult was not returned by a call to the BeginReset method."); } } /// <summary> /// Resets session. Messages marked for deletion will be unmarked. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when POP3 client is not connected and authenticated.</exception> /// <exception cref="POP3_ClientException">Is raised when POP3 server returns error.</exception> public void Reset() { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (!IsConnected) { throw new InvalidOperationException("You must connect first."); } if (!IsAuthenticated) { throw new InvalidOperationException("The RSET command is only valid in TRANSACTION state."); } /* RFC 1939 5. RSET. Arguments: none Restrictions: may only be given in the TRANSACTION state Discussion: If any messages have been marked as deleted by the POP3 server, they are unmarked. The POP3 server then replies with a positive response. Possible Responses: +OK Examples: C: RSET S: +OK maildrop has 2 messages (320 octets) */ WriteLine("RSET"); // Read first line of reply, check if it's ok. string line = ReadLine(); if (!line.StartsWith("+OK")) { throw new POP3_ClientException(line); } foreach (POP3_ClientMessage message in m_pMessages) { message.SetMarkedForDeletion(false); } } #endregion #region Overrides /// <summary> /// This method is called after TCP client has sucessfully connected. /// </summary> protected override void OnConnected() { // Read first line of reply, check if it's ok. string line = ReadLine(); if (line.ToUpper().StartsWith("+OK")) { m_GreetingText = line.Substring(3).Trim(); // Try to read APOP hash key, if supports APOP. if (line.IndexOf("<") > -1 && line.IndexOf(">") > -1) { m_ApopHashKey = line.Substring(line.IndexOf("<"), line.LastIndexOf(">") - line.IndexOf("<") + 1); } } else { throw new POP3_ClientException(line); } // Try to get POP3 server supported capabilities, if command not supported, just skip tat command. GetCAPA_Parameters(); LoginDelay = ObtainLoginDelay(default_login_delay); } private static int GetIntParam(string capa, int position /* 1-based */, int unspecifiedValue) { var capaParams = capa.Split(' '); if (capaParams.Length >= position) { int param; if (int.TryParse(capaParams[position-1], NumberStyles.Integer, CultureInfo.InvariantCulture, out param)) { return param; } } return unspecifiedValue; } public int LoginDelay { get; set; } private bool need_precise_login_delay = false; private int default_login_delay; #endregion #region Utility methods /// <summary> /// Fills messages info. /// </summary> private void FillMessages() { m_pMessages = new POP3_ClientMessageCollection(this); /* First make messages info, then try to add UIDL if server supports. */ /* NOTE: If reply is +OK, this is multiline respone and is terminated with '.'. Examples: C: LIST S: +OK 2 messages (320 octets) S: 1 120 S: 2 200 S: . ... C: LIST 3 S: -ERR no such message, only 2 messages in maildrop */ WriteLine("LIST"); // Read first line of reply, check if it's ok. string line = ReadLine(); if (!string.IsNullOrEmpty(line) && line.StartsWith("+OK")) { // Read lines while get only '.' on line itshelf. while (true) { line = ReadLine(); // End of data if (line.Trim() == ".") { break; } else { string[] no_size = line.Trim().Split(new[] {' '}); m_pMessages.Add(Convert.ToInt32(no_size[1])); } } } else { throw new POP3_ClientException(line); } // Try to fill messages UIDs. /* NOTE: If reply is +OK, this is multiline respone and is terminated with '.'. Examples: C: UIDL S: +OK S: 1 whqtswO00WBw418f9t5JxYwZ S: 2 QhdPYR:00WBw1Ph7x7 S: . ... C: UIDL 3 S: -ERR no such message */ WriteLine("UIDL"); // Read first line of reply, check if it's ok line = ReadLine(); if (line.StartsWith("+OK")) { m_IsUidlSupported = true; // Read lines while get only '.' on line itshelf. while (true) { line = ReadLine(); // End of data if (line.Trim() == ".") { break; } else { string[] no_uid = line.Trim().Split(new[] {' '}); m_pMessages[Convert.ToInt32(no_uid[0]) - 1].UIDL = no_uid[1]; } } } else { m_IsUidlSupported = false; } } /// <summary> /// Executes CAPA command and reads its parameters. /// /// RFC 2449 CAPA /// Arguments: /// none /// /// Restrictions: /// none /// /// Discussion: /// An -ERR response indicates the capability command is not /// implemented and the client will have to probe for /// capabilities as before. /// /// An +OK response is followed by a list of capabilities, one /// per line. Each capability name MAY be followed by a single /// space and a space-separated list of parameters. Each /// capability line is limited to 512 octets (including the /// CRLF). The capability list is terminated by a line /// containing a termination octet (".") and a CRLF pair. /// /// Possible Responses: /// +OK -ERR /// /// Examples: /// C: CAPA /// S: +OK Capability list follows /// S: TOP /// S: USER /// S: SASL CRAM-MD5 KERBEROS_V4 /// S: RESP-CODES /// S: LOGIN-DELAY 900 /// S: PIPELINING /// S: EXPIRE 60 /// S: UIDL /// S: IMPLEMENTATION Shlemazle-Plotz-v302 /// S: . /// /// Note: beware that parameters list may be different in authentication step and in transaction step /// </summary> private void GetCAPA_Parameters() { m_pExtCapabilities.Clear(); WriteLine("CAPA"); // CAPA command supported, read capabilities. if (ReadLine().ToUpper().StartsWith("+OK")) { string line; while ((line = ReadLine()) != ".") { m_pExtCapabilities.Add(line.ToUpper()); } } } /// <summary> /// Obtains LOOGIN-DELAY tag from CAPA parameters /// </summary> /// <returns>login delay read or 'default_value' if the parameter is absent</returns> private int ObtainLoginDelay(int default_value) { need_precise_login_delay = m_pExtCapabilities.Count != 0; foreach (string capa_line in m_pExtCapabilities) { if (capa_line.StartsWith("LOGIN-DELAY")) { string[] capaParams = capa_line.Split(' '); if (capaParams.Length > 1) { int delay; if (int.TryParse(capaParams[1], NumberStyles.Integer, CultureInfo.InvariantCulture, out delay)) { need_precise_login_delay = capaParams.Length > 2 && capaParams[2].ToUpper() == "USER"; return delay; } } } } return default_value; } #endregion #region Internal methods /// <summary> /// Marks specified message for deletion. /// </summary> /// <param name="sequenceNumber">Message sequence number.</param> internal void MarkMessageForDeletion(int sequenceNumber) { WriteLine("DELE " + sequenceNumber); // Read first line of reply, check if it's ok. string line = ReadLine(); if (!line.StartsWith("+OK")) { throw new POP3_ClientException(line); } } /// <summary> /// Stores specified message to the specified stream. /// </summary> /// <param name="sequenceNumber">Message 1 based sequence number.</param> /// <param name="stream">Stream where to store message.</param> internal void GetMessage(int sequenceNumber, Stream stream) { WriteLine("RETR " + sequenceNumber); // Read first line of reply, check if it's ok. string line = ReadLine(); if (line.StartsWith("+OK")) { SmartStream.ReadPeriodTerminatedAsyncOP readTermOP = new SmartStream.ReadPeriodTerminatedAsyncOP(stream, 999999999, SizeExceededAction.ThrowException); TcpStream.ReadPeriodTerminated(readTermOP, false); if (readTermOP.Error != null) { throw readTermOP.Error; } LogAddWrite(readTermOP.BytesStored, readTermOP.BytesStored + " bytes read."); } else { throw new POP3_ClientException(line); } } /// <summary> /// Stores specified message header + specified lines of body to the specified stream. /// </summary> /// <param name="sequenceNumber">Message 1 based sequence number.</param> /// <param name="stream">Stream where to store data.</param> /// <param name="lineCount">Number of lines of message body to get.</param> internal void GetTopOfMessage(int sequenceNumber, Stream stream, int lineCount) { TcpStream.WriteLine("TOP " + sequenceNumber + " " + lineCount); // Read first line of reply, check if it's ok. string line = ReadLine(); if (line.StartsWith("+OK")) { SmartStream.ReadPeriodTerminatedAsyncOP readTermOP = new SmartStream.ReadPeriodTerminatedAsyncOP(stream, 999999999, SizeExceededAction.ThrowException); TcpStream.ReadPeriodTerminated(readTermOP, false); if (readTermOP.Error != null) { throw readTermOP.Error; } LogAddWrite(readTermOP.BytesStored, readTermOP.BytesStored + " bytes read."); } else { throw new POP3_ClientException(line); } } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/UDP/UDP_PacketEventArgs.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.UDP { #region usings using System; using System.Net; using System.Net.Sockets; #endregion /// <summary> /// This class provides data for <b>UdpServer.PacketReceived</b> event. /// </summary> public class UDP_PacketEventArgs : EventArgs { #region Members private readonly byte[] m_pData; private readonly IPEndPoint m_pRemoteEP; private readonly Socket m_pSocket; private readonly UDP_Server m_pUdpServer; #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="server">UDP server which received packet.</param> /// <param name="socket">Socket which received packet.</param> /// <param name="remoteEP">Remote end point which sent data.</param> /// <param name="data">UDP data.</param> internal UDP_PacketEventArgs(UDP_Server server, Socket socket, IPEndPoint remoteEP, byte[] data) { m_pUdpServer = server; m_pSocket = socket; m_pRemoteEP = remoteEP; m_pData = data; } #endregion #region Properties /// <summary> /// Gets UDP packet data. /// </summary> public byte[] Data { get { return m_pData; } } /// <summary> /// Gets local end point what recieved packet. /// </summary> public IPEndPoint LocalEndPoint { get { return (IPEndPoint) m_pSocket.LocalEndPoint; } } /// <summary> /// Gets remote end point what sent data. /// </summary> public IPEndPoint RemoteEndPoint { get { return m_pRemoteEP; } } /// <summary> /// Gets UDP server which received packet. /// </summary> public UDP_Server UdpServer { get { return m_pUdpServer; } } /// <summary> /// Gets socket which received packet. /// </summary> internal Socket Socket { get { return m_pSocket; } } #endregion #region Methods /// <summary> /// Sends reply to received packet. This method uses same local end point to send packet which /// received packet, this ensures right NAT traversal. /// </summary> /// <param name="data">Data buffer.</param> /// <param name="offset">Offset in the buffer.</param> /// <param name="count">Number of bytes to send.</param> /// <exception cref="ArgumentNullException">Is raised when <b>data</b> is null.</exception> public void SendReply(byte[] data, int offset, int count) { if (data == null) { throw new ArgumentNullException("data"); } IPEndPoint localEP = null; m_pUdpServer.SendPacket(m_pSocket, data, offset, count, m_pRemoteEP, out localEP); } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/SMTP/Relay/Relay_Server.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.SMTP.Relay { #region usings using System; using System.Collections.Generic; using System.Diagnostics; using System.Net; using System.Net.Sockets; using System.Threading; using Log; using TCP; #endregion #region Delegates /// <summary> /// Represents the method that will handle the <b>Relay_Server.SessionCompleted</b> event. /// </summary> /// <param name="e">Event data.</param> public delegate void Relay_SessionCompletedEventHandler(Relay_SessionCompletedEventArgs e); #endregion /// <summary> /// This class implements SMTP relay server. Defined in RFC 2821. /// </summary> public class Relay_Server : IDisposable { #region Events /// <summary> /// This event is raised when unhandled exception happens. /// </summary> public event ErrorEventHandler Error = null; /// <summary> /// This event is raised when relay session processing completes. /// </summary> public event Relay_SessionCompletedEventHandler SessionCompleted = null; #endregion #region Members private bool m_HasBindingsChanged; private bool m_IsDisposed; private bool m_IsRunning; private long m_MaxConnections; private long m_MaxConnectionsPerIP; private IPBindInfo[] m_pBindings = new IPBindInfo[0]; private Dictionary<IPAddress, long> m_pConnectionsPerIP; private CircleCollection<IPBindInfo> m_pLocalEndPoints; private List<Relay_Queue> m_pQueues; private TCP_SessionCollection<Relay_Session> m_pSessions; private CircleCollection<Relay_SmartHost> m_pSmartHosts; private Relay_Mode m_RelayMode = Relay_Mode.Dns; private int m_SessionIdleTimeout = 30; private BalanceMode m_SmartHostsBalanceMode = BalanceMode.LoadBalance; #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> public Relay_Server() { m_pQueues = new List<Relay_Queue>(); m_pSmartHosts = new CircleCollection<Relay_SmartHost>(); } #endregion #region Properties /// <summary> /// Gets or sets relay server IP bindings. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> public IPBindInfo[] Bindings { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_pBindings; } set { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (value == null) { value = new IPBindInfo[0]; } //--- See binds has changed -------------- bool changed = false; if (m_pBindings.Length != value.Length) { changed = true; } else { for (int i = 0; i < m_pBindings.Length; i++) { if (!m_pBindings[i].Equals(value[i])) { changed = true; break; } } } if (changed) { m_pBindings = value; m_HasBindingsChanged = true; } } } /// <summary> /// Gets if server is disposed. /// </summary> public bool IsDisposed { get { return m_IsDisposed; } } /// <summary> /// Gets if server is running. /// </summary> public bool IsRunning { get { return m_IsRunning; } } /// <summary> /// Gets or sets relay logger. Value null means no logging. /// </summary> public Logger Logger { get; set; } /// <summary> /// Gets or sets maximum allowed concurent connections. Value 0 means unlimited. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> /// <exception cref="ArgumentException">Is raised when negative value is passed.</exception> public long MaxConnections { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_MaxConnections; } set { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (value < 0) { throw new ArgumentException("Property 'MaxConnections' value must be >= 0."); } m_MaxConnections = value; } } /// <summary> /// Gets or sets maximum allowed connections to 1 IP address. Value 0 means unlimited. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> public long MaxConnectionsPerIP { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_MaxConnectionsPerIP; } set { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (m_MaxConnectionsPerIP < 0) { throw new ArgumentException("Property 'MaxConnectionsPerIP' value must be >= 0."); } m_MaxConnectionsPerIP = value; } } /// <summary> /// Gets relay queues. Queue with lower index number has higher priority. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> public List<Relay_Queue> Queues { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_pQueues; } } /// <summary> /// Gets or sets relay mode. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> public Relay_Mode RelayMode { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_RelayMode; } set { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } m_RelayMode = value; } } /// <summary> /// Gets or sets session idle time in seconds when it will be timed out. Value 0 means unlimited (strongly not recomended). /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> /// <exception cref="ArgumentException">Is raised when invalid value is passed.</exception> public int SessionIdleTimeout { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_SessionIdleTimeout; } set { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (m_SessionIdleTimeout < 0) { throw new ArgumentException("Property 'SessionIdleTimeout' value must be >= 0."); } m_SessionIdleTimeout = value; } } /// <summary> /// Gets active relay sessions. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when this property is accessed and relay server is not running.</exception> public TCP_SessionCollection<Relay_Session> Sessions { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (!m_IsRunning) { throw new InvalidOperationException("Relay server not running."); } return m_pSessions; } } /// <summary> /// Gets or sets smart hosts. Smart hosts must be in priority order, lower index number means higher priority. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> /// <exception cref="ArgumentNullException">Is raised when null value is passed.</exception> public Relay_SmartHost[] SmartHosts { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_pSmartHosts.ToArray(); } set { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (value == null) { throw new ArgumentNullException("SmartHosts"); } m_pSmartHosts.Add(value); } } /// <summary> /// Gets or sets how smart hosts will be balanced. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> public BalanceMode SmartHostsBalanceMode { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_SmartHostsBalanceMode; } set { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } m_SmartHostsBalanceMode = value; } } #endregion #region Methods /// <summary> /// Cleans up any resources being used. /// </summary> public void Dispose() { if (m_IsDisposed) { return; } try { if (m_IsRunning) { Stop(); } } catch {} m_IsDisposed = true; // Release events. Error = null; SessionCompleted = null; m_pQueues = null; m_pSmartHosts = null; } /// <summary> /// Starts SMTP relay server. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> public virtual void Start() { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (m_IsRunning) { return; } m_IsRunning = true; m_pLocalEndPoints = new CircleCollection<IPBindInfo>(); m_pSessions = new TCP_SessionCollection<Relay_Session>(); m_pConnectionsPerIP = new Dictionary<IPAddress, long>(); Thread tr1 = new Thread(Run); tr1.Start(); Thread tr2 = new Thread(Run_CheckTimedOutSessions); tr2.Start(); } /// <summary> /// Stops SMTP relay server. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> public virtual void Stop() { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (!m_IsRunning) { return; } m_IsRunning = false; // TODO: We need to send notify to all not processed messages, then they can be Disposed as needed. // Clean up. m_pLocalEndPoints = null; //m_pSessions.Dispose(); m_pSessions = null; m_pConnectionsPerIP = null; } #endregion #region Virtual methods /// <summary> /// Raises <b>SessionCompleted</b> event. /// </summary> /// <param name="session">Session what completed processing.</param> /// <param name="exception">Exception happened or null if relay completed successfully.</param> protected internal virtual void OnSessionCompleted(Relay_Session session, Exception exception) { if (SessionCompleted != null) { SessionCompleted(new Relay_SessionCompletedEventArgs(session, exception)); } } /// <summary> /// Raises <b>Error</b> event. /// </summary> /// <param name="x">Exception happned.</param> protected internal virtual void OnError(Exception x) { if (Error != null) { Error(this, new Error_EventArgs(x, new StackTrace())); } } #endregion #region Internal methods /// <summary> /// Increases specified IP address connactions count if maximum allowed connections to /// the specified IP address isn't exceeded. /// </summary> /// <param name="ip">IP address.</param> /// <exception cref="ArgumentNullException">Is raised when <b>ip</b> is null.</exception> /// <returns>Returns true if specified IP usage increased, false if maximum allowed connections to the specified IP address is exceeded.</returns> internal bool TryAddIpUsage(IPAddress ip) { if (ip == null) { throw new ArgumentNullException("ip"); } lock (m_pConnectionsPerIP) { long count = 0; // Specified IP entry exists, increase usage. if (m_pConnectionsPerIP.TryGetValue(ip, out count)) { // Maximum allowed connections to the specified IP address is exceeded. if (m_MaxConnectionsPerIP > 0 && count >= m_MaxConnectionsPerIP) { return false; } m_pConnectionsPerIP[ip] = count + 1; } // Specified IP entry doesn't exist, create new entry and increase usage. else { m_pConnectionsPerIP.Add(ip, 1); } return true; } } /// <summary> /// Decreases specified IP address connactions count. /// </summary> /// <param name="ip">IP address.</param> /// <exception cref="ArgumentNullException">Is raised when <b>ip</b> is null.</exception> internal void RemoveIpUsage(IPAddress ip) { if (ip == null) { throw new ArgumentNullException("ip"); } lock (m_pConnectionsPerIP) { long count = 0; // Specified IP entry exists, increase usage. if (m_pConnectionsPerIP.TryGetValue(ip, out count)) { // This is last usage to that IP, remove that IP entry. if (count == 1) { m_pConnectionsPerIP.Remove(ip); } // Decrease Ip usage. else { m_pConnectionsPerIP[ip] = count - 1; } } else { // No such entry, just skip it. } } } /// <summary> /// Gets how many connections to the specified IP address. /// </summary> /// <param name="ip">IP address.</param> /// <returns>Returns number of connections to the specified IP address.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>ip</b> is null.</exception> internal long GetIpUsage(IPAddress ip) { if (ip == null) { throw new ArgumentNullException("ip"); } lock (m_pConnectionsPerIP) { long count = 0; // Specified IP entry exists, return usage. if (m_pConnectionsPerIP.TryGetValue(ip, out count)) { return count; } // No usage to specified IP. else { return 0; } } } #endregion #region Utility methods /// <summary> /// Processes relay queue. /// </summary> private void Run() { while (m_IsRunning) { try { // Bind info has changed, create new local end points. if (m_HasBindingsChanged) { m_pLocalEndPoints.Clear(); foreach (IPBindInfo binding in m_pBindings) { if (binding.IP == IPAddress.Any) { foreach (IPAddress ip in Dns.GetHostAddresses("")) { if (ip.AddressFamily == AddressFamily.InterNetwork) { IPBindInfo b = new IPBindInfo(binding.HostName, binding.Protocol, ip, 25); if (!m_pLocalEndPoints.Contains(b)) { m_pLocalEndPoints.Add(b); } } } } else if (binding.IP == IPAddress.IPv6Any) { foreach (IPAddress ip in Dns.GetHostAddresses("")) { if (ip.AddressFamily == AddressFamily.InterNetworkV6) { IPBindInfo b = new IPBindInfo(binding.HostName, binding.Protocol, ip, 25); if (!m_pLocalEndPoints.Contains(b)) { m_pLocalEndPoints.Add(b); } } } } else { IPBindInfo b = new IPBindInfo(binding.HostName, binding.Protocol, binding.IP, 25); if (!m_pLocalEndPoints.Contains(b)) { m_pLocalEndPoints.Add(b); } } } m_HasBindingsChanged = false; } // There are no local end points specified. if (m_pLocalEndPoints.Count == 0) { Thread.Sleep(10); } // Maximum allowed relay sessions exceeded, skip adding new ones. else if (m_MaxConnections != 0 && m_pSessions.Count >= m_MaxConnections) { Thread.Sleep(10); } else { Relay_QueueItem item = null; // Get next queued message from highest possible priority queue. foreach (Relay_Queue queue in m_pQueues) { item = queue.DequeueMessage(); // There is queued message. if (item != null) { break; } // No messages in this queue, see next lower priority queue. } // There are no messages in any queue. if (item == null) { Thread.Sleep(10); } // Create new session for queued relay item. else { // Get round-robin local end point for that session. // This ensures if multiple network connections, all will be load balanced. IPBindInfo localBindInfo = m_pLocalEndPoints.Next(); if (m_RelayMode == Relay_Mode.Dns) { Relay_Session session = new Relay_Session(this, localBindInfo, item); m_pSessions.Add(session); ThreadPool.QueueUserWorkItem(session.Start); } else if (m_RelayMode == Relay_Mode.SmartHost) { // Get smart hosts in balance mode order. Relay_SmartHost[] smartHosts = null; if (m_SmartHostsBalanceMode == BalanceMode.FailOver) { smartHosts = m_pSmartHosts.ToArray(); } else { smartHosts = m_pSmartHosts.ToCurrentOrderArray(); } Relay_Session session = new Relay_Session(this, localBindInfo, item, smartHosts); m_pSessions.Add(session); ThreadPool.QueueUserWorkItem(session.Start); } } } } catch (Exception x) { OnError(x); } } } /// <summary> /// This method checks timed out relay sessions while server is running. /// </summary> private void Run_CheckTimedOutSessions() { DateTime lastCheck = DateTime.Now; while (IsRunning) { try { // Check interval reached. if (m_SessionIdleTimeout > 0 && lastCheck.AddSeconds(30) < DateTime.Now) { foreach (Relay_Session session in Sessions.ToArray()) { try { if (session.LastActivity.AddSeconds(m_SessionIdleTimeout) < DateTime.Now) { session.Dispose(new Exception("Session idle timeout.")); } } catch {} } lastCheck = DateTime.Now; } // Not check interval yet. else { Thread.Sleep(1000); } } catch (Exception x) { OnError(x); } } } #endregion } }<file_sep>/module/ASC.CdnCheck/Global.asax.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Linq; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using System.Web.Http; using System.Web.Mvc; using System.Web.Routing; using log4net.Config; namespace ASC.CdnCheck { // Note: For instructions on enabling IIS6 or IIS7 classic mode, // visit http://go.microsoft.com/?LinkId=9394801 public class WebApiApplication : System.Web.HttpApplication { protected void Application_Start() { XmlConfigurator.Configure(); AreaRegistration.RegisterAllAreas(); WebApiConfig.Register(GlobalConfiguration.Configuration); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); GlobalConfiguration.Configuration.MessageHandlers.Add(new CorsHandler()); } } }<file_sep>/build/install/rpm/Files/god/conf.d/onlyoffice.god %w{onlyofficeFeed onlyofficeThumb onlyofficeSocketIO onlyofficeIndex onlyofficeStorageMigrate onlyofficeStorageEncryption onlyofficeTelegram onlyofficeNotify onlyofficeBackup onlyofficeMailCleaner onlyofficeMailWatchdog onlyofficeRadicale onlyofficeUrlShortener}.each do |serviceName| God.watch do |w| w.name = serviceName w.group = "onlyoffice" w.grace = 15.seconds w.start = "systemctl start #{serviceName}" w.stop = "systemctl stop #{serviceName}" w.restart = "systemctl restart #{serviceName}" w.pid_file = "/tmp/#{serviceName}" w.start_if do |start| start.condition(:process_running) do |c| c.interval = 10.seconds c.running = false end end w.restart_if do |restart| restart.condition(:memory_usage) do |c| c.above = 700.megabytes c.times = 5 c.interval = 10.seconds end restart.condition(:cpu_usage) do |c| c.above = 90.percent c.times = 5 c.interval = 10.seconds end end end end <file_sep>/module/ASC.Files.Thirdparty/Sharpbox/SharpBoxFolderDao.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Security; using System.Threading; using AppLimit.CloudComputing.SharpBox; using AppLimit.CloudComputing.SharpBox.Exceptions; using ASC.Common.Data.Sql.Expressions; using ASC.Core; using ASC.Files.Core; using ASC.Web.Files.Resources; using ASC.Web.Studio.Core; namespace ASC.Files.Thirdparty.Sharpbox { internal class SharpBoxFolderDao : SharpBoxDaoBase, IFolderDao { public SharpBoxFolderDao(SharpBoxDaoSelector.SharpBoxInfo sharpBoxInfo, SharpBoxDaoSelector sharpBoxDaoSelector) : base(sharpBoxInfo, sharpBoxDaoSelector) { } public Folder GetFolder(object folderId) { return ToFolder(GetFolderById(folderId)); } public Folder GetFolder(string title, object parentId) { var parentFolder = SharpBoxProviderInfo.Storage.GetFolder(MakePath(parentId)); return ToFolder(parentFolder.OfType<ICloudDirectoryEntry>().FirstOrDefault(x => x.Name.Equals(title, StringComparison.OrdinalIgnoreCase))); } public Folder GetRootFolder(object folderId) { return ToFolder(RootFolder()); } public Folder GetRootFolderByFile(object fileId) { return ToFolder(RootFolder()); } public List<Folder> GetFolders(object parentId) { var parentFolder = SharpBoxProviderInfo.Storage.GetFolder(MakePath(parentId)); return parentFolder.OfType<ICloudDirectoryEntry>().Select(ToFolder).ToList(); } public List<Folder> GetFolders(object parentId, OrderBy orderBy, FilterType filterType, bool subjectGroup, Guid subjectID, string searchText, bool withSubfolders = false) { if (filterType == FilterType.FilesOnly || filterType == FilterType.ByExtension || filterType == FilterType.DocumentsOnly || filterType == FilterType.ImagesOnly || filterType == FilterType.PresentationsOnly || filterType == FilterType.SpreadsheetsOnly || filterType == FilterType.ArchiveOnly || filterType == FilterType.MediaOnly) return new List<Folder>(); var folders = GetFolders(parentId).AsEnumerable(); //TODO:!!! //Filter if (subjectID != Guid.Empty) { folders = folders.Where(x => subjectGroup ? CoreContext.UserManager.IsUserInGroup(x.CreateBy, subjectID) : x.CreateBy == subjectID); } if (!string.IsNullOrEmpty(searchText)) folders = folders.Where(x => x.Title.IndexOf(searchText, StringComparison.OrdinalIgnoreCase) != -1); if (orderBy == null) orderBy = new OrderBy(SortedByType.DateAndTime, false); switch (orderBy.SortedBy) { case SortedByType.Author: folders = orderBy.IsAsc ? folders.OrderBy(x => x.CreateBy) : folders.OrderByDescending(x => x.CreateBy); break; case SortedByType.AZ: folders = orderBy.IsAsc ? folders.OrderBy(x => x.Title) : folders.OrderByDescending(x => x.Title); break; case SortedByType.DateAndTime: folders = orderBy.IsAsc ? folders.OrderBy(x => x.ModifiedOn) : folders.OrderByDescending(x => x.ModifiedOn); break; case SortedByType.DateAndTimeCreation: folders = orderBy.IsAsc ? folders.OrderBy(x => x.CreateOn) : folders.OrderByDescending(x => x.CreateOn); break; default: folders = orderBy.IsAsc ? folders.OrderBy(x => x.Title) : folders.OrderByDescending(x => x.Title); break; } return folders.ToList(); } public List<Folder> GetFolders(object[] folderIds, FilterType filterType = FilterType.None, bool subjectGroup = false, Guid? subjectID = null, string searchText = "", bool searchSubfolders = false, bool checkShare = true) { if (filterType == FilterType.FilesOnly || filterType == FilterType.ByExtension || filterType == FilterType.DocumentsOnly || filterType == FilterType.ImagesOnly || filterType == FilterType.PresentationsOnly || filterType == FilterType.SpreadsheetsOnly || filterType == FilterType.ArchiveOnly || filterType == FilterType.MediaOnly) return new List<Folder>(); var folders = folderIds.Select(GetFolder); if (subjectID.HasValue && subjectID != Guid.Empty) { folders = folders.Where(x => subjectGroup ? CoreContext.UserManager.IsUserInGroup(x.CreateBy, subjectID.Value) : x.CreateBy == subjectID); } if (!string.IsNullOrEmpty(searchText)) folders = folders.Where(x => x.Title.IndexOf(searchText, StringComparison.OrdinalIgnoreCase) != -1); return folders.ToList(); } public List<Folder> GetParentFolders(object folderId) { var path = new List<Folder>(); var folder = GetFolderById(folderId); if (folder != null) { do { path.Add(ToFolder(folder)); } while ((folder = folder.Parent) != null); } path.Reverse(); return path; } public object SaveFolder(Folder folder) { try { if (folder.ID != null) { //Create with id var savedfolder = SharpBoxProviderInfo.Storage.CreateFolder(MakePath(folder.ID)); return MakeId(savedfolder); } if (folder.ParentFolderID != null) { var parentFolder = GetFolderById(folder.ParentFolderID); folder.Title = GetAvailableTitle(folder.Title, parentFolder, IsExist); var newFolder = SharpBoxProviderInfo.Storage.CreateFolder(folder.Title, parentFolder); return MakeId(newFolder); } } catch (SharpBoxException e) { var webException = (WebException)e.InnerException; if (webException != null) { var response = ((HttpWebResponse)webException.Response); if (response != null) { if (response.StatusCode == HttpStatusCode.Unauthorized || response.StatusCode == HttpStatusCode.Forbidden) { throw new SecurityException(FilesCommonResource.ErrorMassage_SecurityException_Create); } } throw; } } return null; } public void DeleteFolder(object folderId) { var folder = GetFolderById(folderId); var id = MakeId(folder); using (var db = GetDb()) using (var tx = db.BeginTransaction()) { var hashIDs = db.ExecuteList(Query("files_thirdparty_id_mapping") .Select("hash_id") .Where(Exp.Like("id", id, SqlLike.StartWith))) .ConvertAll(x => x[0]); db.ExecuteNonQuery(Delete("files_tag_link").Where(Exp.In("entry_id", hashIDs))); db.ExecuteNonQuery(Delete("files_tag").Where(Exp.EqColumns("0", Query("files_tag_link l").SelectCount().Where(Exp.EqColumns("tag_id", "id"))))); db.ExecuteNonQuery(Delete("files_security").Where(Exp.In("entry_id", hashIDs))); db.ExecuteNonQuery(Delete("files_thirdparty_id_mapping").Where(Exp.In("hash_id", hashIDs))); tx.Commit(); } if (!(folder is ErrorEntry)) SharpBoxProviderInfo.Storage.DeleteFileSystemEntry(folder); } public bool IsExist(string title, ICloudDirectoryEntry folder) { try { return SharpBoxProviderInfo.Storage.GetFileSystemObject(title, folder) != null; } catch (ArgumentException) { throw; } catch (Exception) { } return false; } public object MoveFolder(object folderId, object toFolderId, CancellationToken? cancellationToken) { var entry = GetFolderById(folderId); var folder = GetFolderById(toFolderId); var oldFolderId = MakeId(entry); if (!SharpBoxProviderInfo.Storage.MoveFileSystemEntry(entry, folder)) throw new Exception("Error while moving"); var newFolderId = MakeId(entry); UpdatePathInDB(oldFolderId, newFolderId); return newFolderId; } public Folder CopyFolder(object folderId, object toFolderId, CancellationToken? cancellationToken) { var folder = GetFolderById(folderId); if (!SharpBoxProviderInfo.Storage.CopyFileSystemEntry(MakePath(folderId), MakePath(toFolderId))) throw new Exception("Error while copying"); return ToFolder(GetFolderById(toFolderId).OfType<ICloudDirectoryEntry>().FirstOrDefault(x => x.Name == folder.Name)); } public IDictionary<object, string> CanMoveOrCopy(object[] folderIds, object to) { return new Dictionary<object, string>(); } public object RenameFolder(Folder folder, string newTitle) { var entry = GetFolderById(folder.ID); var oldId = MakeId(entry); var newId = oldId; if ("/".Equals(MakePath(folder.ID))) { //It's root folder SharpBoxDaoSelector.RenameProvider(SharpBoxProviderInfo, newTitle); //rename provider customer title } else { var parentFolder = GetFolderById(folder.ParentFolderID); newTitle = GetAvailableTitle(newTitle, parentFolder, IsExist); //rename folder if (SharpBoxProviderInfo.Storage.RenameFileSystemEntry(entry, newTitle)) { //Folder data must be already updated by provider //We can't search google folders by title because root can have multiple folders with the same name //var newFolder = SharpBoxProviderInfo.Storage.GetFileSystemObject(newTitle, folder.Parent); newId = MakeId(entry); } } UpdatePathInDB(oldId, newId); return newId; } public int GetItemsCount(object folderId) { throw new NotImplementedException(); } public bool IsEmpty(object folderId) { return GetFolderById(folderId).Count == 0; } public bool UseTrashForRemove(Folder folder) { return false; } public bool UseRecursiveOperation(object folderId, object toRootFolderId) { return false; } public bool CanCalculateSubitems(object entryId) { return false; } public long GetMaxUploadSize(object folderId, bool chunkedUpload) { var storageMaxUploadSize = chunkedUpload ? SharpBoxProviderInfo.Storage.CurrentConfiguration.Limits.MaxChunkedUploadFileSize : SharpBoxProviderInfo.Storage.CurrentConfiguration.Limits.MaxUploadFileSize; if (storageMaxUploadSize == -1) storageMaxUploadSize = long.MaxValue; return chunkedUpload ? storageMaxUploadSize : Math.Min(storageMaxUploadSize, SetupInfo.AvailableFileSize); } #region Only for TMFolderDao public void ReassignFolders(object[] folderIds, Guid newOwnerId) { } public IEnumerable<Folder> Search(string text, bool bunch) { return null; } public object GetFolderID(string module, string bunch, string data, bool createIfNotExists) { return null; } public IEnumerable<object> GetFolderIDs(string module, string bunch, IEnumerable<string> data, bool createIfNotExists) { return new List<object>(); } public object GetFolderIDCommon(bool createIfNotExists) { return null; } public object GetFolderIDUser(bool createIfNotExists, Guid? userId) { return null; } public object GetFolderIDShare(bool createIfNotExists) { return null; } public object GetFolderIDRecent(bool createIfNotExists) { return null; } public object GetFolderIDFavorites(bool createIfNotExists) { return null; } public object GetFolderIDTemplates(bool createIfNotExists) { return null; } public object GetFolderIDPrivacy(bool createIfNotExists, Guid? userId) { return null; } public object GetFolderIDTrash(bool createIfNotExists, Guid? userId) { return null; } public object GetFolderIDPhotos(bool createIfNotExists) { return null; } public object GetFolderIDProjects(bool createIfNotExists) { return null; } public string GetBunchObjectID(object folderID) { return null; } public Dictionary<string, string> GetBunchObjectIDs(List<object> folderIDs) { return null; } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/Net_Core.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System.Globalization; namespace ASC.Mail.Net { #region usings using System; using System.IO; using System.Net; using System.Net.Sockets; using System.Security.Cryptography; using System.Text; using Dns.Client; using System.Text.RegularExpressions; #endregion #region enum AuthType /// <summary> /// Authentication type. /// </summary> public enum AuthType { /// <summary> /// Plain username/password authentication. /// </summary> Plain = 0, /// <summary> /// APOP /// </summary> APOP = 1, /// <summary> /// Not implemented. /// </summary> LOGIN = 2, /// <summary> /// Cram-md5 authentication. /// </summary> CRAM_MD5 = 3, /// <summary> /// DIGEST-md5 authentication. /// </summary> DIGEST_MD5 = 4, } #endregion /// <summary> /// Provides net core utility methods. /// </summary> public class Core { #region Methods /// <summary> /// Gets host name. If fails returns ip address. /// </summary> /// <param name="ip">IP address which to reverse lookup.</param> /// <returns>Returns host name of specified IP address.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>ip</b> is null.</exception> public static string GetHostName(IPAddress ip) { if (ip == null) { throw new ArgumentNullException("ip"); } string retVal = ip.ToString(); try { Dns_Client dns = new Dns_Client(); DnsServerResponse response = dns.Query(ip.ToString(), QTYPE.PTR); if (response.ResponseCode == RCODE.NO_ERROR) { DNS_rr_PTR[] ptrs = response.GetPTRRecords(); if (ptrs.Length > 0) { retVal = ptrs[0].DomainName; } } } catch {} return retVal; } /// <summary> /// Gets argument part of command text. /// </summary> /// <param name="input">Input srting from where to remove value.</param> /// <param name="cmdTxtToRemove">Command text which to remove.</param> /// <returns></returns> public static string GetArgsText(string input, string cmdTxtToRemove) { string buff = input.Trim(); if (buff.Length >= cmdTxtToRemove.Length) { buff = buff.Substring(cmdTxtToRemove.Length); } buff = buff.Trim(); return buff; } /// <summary> /// Checks if specified string is number(long). /// </summary> /// <param name="str"></param> /// <returns></returns> public static bool IsNumber(string str) { try { Convert.ToInt64(str); return true; } catch { return false; } } /// <summary> /// Reverses the specified array elements. /// </summary> /// <param name="array">Array elements to reverse.</param> /// <returns>Returns array with reversed items.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>array</b> is null.</exception> public static Array ReverseArray(Array array) { if (array == null) { throw new ArgumentNullException("array"); } Array.Reverse(array); return array; } /// <summary> /// Encodes specified data with base64 encoding. /// </summary> /// <param name="data">Data to encode.</param> /// <returns></returns> public static byte[] Base64Encode(byte[] data) { return Base64EncodeEx(data, null, true); } /// <summary> /// Encodes specified data with bas64 encoding. /// </summary> /// <param name="data">Data to to encode.</param> /// <param name="base64Chars">Custom base64 chars (64 chars) or null if default chars used.</param> /// <param name="padd">Padd missing block chars. Normal base64 must be 4 bytes blocks, if not 4 bytes in block, /// missing bytes must be padded with '='. Modified base64 just skips missing bytes.</param> /// <returns></returns> public static byte[] Base64EncodeEx(byte[] data, char[] base64Chars, bool padd) { /* RFC 2045 6.8. Base64 Content-Transfer-Encoding Base64 is processed from left to right by 4 6-bit byte block, 4 6-bit byte block are converted to 3 8-bit bytes. If base64 4 byte block doesn't have 3 8-bit bytes, missing bytes are marked with =. Value Encoding Value Encoding Value Encoding Value Encoding 0 A 17 R 34 i 51 z 1 B 18 S 35 j 52 0 2 C 19 T 36 k 53 1 3 D 20 U 37 l 54 2 4 E 21 V 38 m 55 3 5 F 22 W 39 n 56 4 6 G 23 X 40 o 57 5 7 H 24 Y 41 p 58 6 8 I 25 Z 42 q 59 7 9 J 26 a 43 r 60 8 10 K 27 b 44 s 61 9 11 L 28 c 45 t 62 + 12 M 29 d 46 u 63 / 13 N 30 e 47 v 14 O 31 f 48 w (pad) = 15 P 32 g 49 x 16 Q 33 h 50 y NOTE: 4 base64 6-bit bytes = 3 8-bit bytes // | 6-bit | 6-bit | 6-bit | 6-bit | // | 1 2 3 4 5 6 | 1 2 3 4 5 6 | 1 2 3 4 5 6 | 1 2 3 4 5 6 | // | 8-bit | 8-bit | 8-bit | */ if (base64Chars != null && base64Chars.Length != 64) { throw new Exception("There must be 64 chars in base64Chars char array !"); } if (base64Chars == null) { base64Chars = new[] { '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', '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', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/' }; } // Convert chars to bytes byte[] base64LoockUpTable = new byte[64]; for (int i = 0; i < 64; i++) { base64LoockUpTable[i] = (byte) base64Chars[i]; } int encodedDataLength = (int) Math.Ceiling((data.Length*8)/(double) 6); // Retrun value won't be interegral 4 block, but has less. Padding requested, padd missing with '=' if (padd && (encodedDataLength/(double) 4 != Math.Ceiling(encodedDataLength/(double) 4))) { encodedDataLength += (int) (Math.Ceiling(encodedDataLength/(double) 4)*4) - encodedDataLength; } // See how many line brakes we need int numberOfLineBreaks = 0; if (encodedDataLength > 76) { numberOfLineBreaks = (int) Math.Ceiling(encodedDataLength/(double) 76) - 1; } // Construc return valu buffer byte[] retVal = new byte[encodedDataLength + (numberOfLineBreaks*2)]; // * 2 - CRLF int lineBytes = 0; // Loop all 3 bye blocks int position = 0; for (int i = 0; i < data.Length; i += 3) { // Do line splitting if (lineBytes >= 76) { retVal[position + 0] = (byte) '\r'; retVal[position + 1] = (byte) '\n'; position += 2; lineBytes = 0; } // Full 3 bytes data block if ((data.Length - i) >= 3) { retVal[position + 0] = base64LoockUpTable[data[i + 0] >> 2]; retVal[position + 1] = base64LoockUpTable[(data[i + 0] & 0x3) << 4 | data[i + 1] >> 4]; retVal[position + 2] = base64LoockUpTable[(data[i + 1] & 0xF) << 2 | data[i + 2] >> 6]; retVal[position + 3] = base64LoockUpTable[data[i + 2] & 0x3F]; position += 4; lineBytes += 4; } // 2 bytes data block, left (last block) else if ((data.Length - i) == 2) { retVal[position + 0] = base64LoockUpTable[data[i + 0] >> 2]; retVal[position + 1] = base64LoockUpTable[(data[i + 0] & 0x3) << 4 | data[i + 1] >> 4]; retVal[position + 2] = base64LoockUpTable[(data[i + 1] & 0xF) << 2]; if (padd) { retVal[position + 3] = (byte) '='; } } // 1 bytes data block, left (last block) else if ((data.Length - i) == 1) { retVal[position + 0] = base64LoockUpTable[data[i + 0] >> 2]; retVal[position + 1] = base64LoockUpTable[(data[i + 0] & 0x3) << 4]; if (padd) { retVal[position + 2] = (byte) '='; retVal[position + 3] = (byte) '='; } } } return retVal; } /// <summary> /// Decodes base64 data. Defined in RFC 2045 6.8. Base64 Content-Transfer-Encoding. /// </summary> /// <param name="base64Data">Base64 decoded data.</param> /// <returns></returns> public static byte[] Base64Decode(byte[] base64Data) { return Base64DecodeEx(base64Data, null); } /// <summary> /// Decodes base64 data. Defined in RFC 2045 6.8. Base64 Content-Transfer-Encoding. /// </summary> /// <param name="base64Data">Base64 decoded data.</param> /// <param name="base64Chars">Custom base64 chars (64 chars) or null if default chars used.</param> /// <returns></returns> public static byte[] Base64DecodeEx(byte[] base64Data, char[] base64Chars) { /* RFC 2045 6.8. Base64 Content-Transfer-Encoding Base64 is processed from left to right by 4 6-bit byte block, 4 6-bit byte block are converted to 3 8-bit bytes. If base64 4 byte block doesn't have 3 8-bit bytes, missing bytes are marked with =. Value Encoding Value Encoding Value Encoding Value Encoding 0 A 17 R 34 i 51 z 1 B 18 S 35 j 52 0 2 C 19 T 36 k 53 1 3 D 20 U 37 l 54 2 4 E 21 V 38 m 55 3 5 F 22 W 39 n 56 4 6 G 23 X 40 o 57 5 7 H 24 Y 41 p 58 6 8 I 25 Z 42 q 59 7 9 J 26 a 43 r 60 8 10 K 27 b 44 s 61 9 11 L 28 c 45 t 62 + 12 M 29 d 46 u 63 / 13 N 30 e 47 v 14 O 31 f 48 w (pad) = 15 P 32 g 49 x 16 Q 33 h 50 y NOTE: 4 base64 6-bit bytes = 3 8-bit bytes // | 6-bit | 6-bit | 6-bit | 6-bit | // | 1 2 3 4 5 6 | 1 2 3 4 5 6 | 1 2 3 4 5 6 | 1 2 3 4 5 6 | // | 8-bit | 8-bit | 8-bit | */ if (base64Chars != null && base64Chars.Length != 64) { throw new Exception("There must be 64 chars in base64Chars char array !"); } if (base64Chars == null) { base64Chars = new[] { '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', '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', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/' }; } //--- Create decode table ---------------------// byte[] decodeTable = new byte[128]; for (int i = 0; i < 128; i++) { int mappingIndex = -1; for (int bc = 0; bc < base64Chars.Length; bc++) { if (i == base64Chars[bc]) { mappingIndex = bc; break; } } if (mappingIndex > -1) { decodeTable[i] = (byte) mappingIndex; } else { decodeTable[i] = 0xFF; } } //---------------------------------------------// byte[] decodedDataBuffer = new byte[((base64Data.Length*6)/8) + 4]; int decodedBytesCount = 0; int nByteInBase64Block = 0; byte[] decodedBlock = new byte[3]; byte[] base64Block = new byte[4]; for (int i = 0; i < base64Data.Length; i++) { byte b = base64Data[i]; // Read 4 byte base64 block and process it // Any characters outside of the base64 alphabet are to be ignored in base64-encoded data. // Padding char if (b == '=') { base64Block[nByteInBase64Block] = 0xFF; } else { byte decodeByte = decodeTable[b & 0x7F]; if (decodeByte != 0xFF) { base64Block[nByteInBase64Block] = decodeByte; nByteInBase64Block++; } } /* Check if we can decode some bytes. * We must have full 4 byte base64 block or reached at the end of data. */ int encodedBytesCount = -1; // We have full 4 byte base64 block if (nByteInBase64Block == 4) { encodedBytesCount = 3; } // We have reached at the end of base64 data, there may be some bytes left else if (i == base64Data.Length - 1) { // Invalid value, we can't have only 6 bit, just skip if (nByteInBase64Block == 1) { encodedBytesCount = 0; } // There is 1 byte in two base64 bytes (6 + 2 bit) else if (nByteInBase64Block == 2) { encodedBytesCount = 1; } // There are 2 bytes in two base64 bytes ([6 + 2],[4 + 4] bit) else if (nByteInBase64Block == 3) { encodedBytesCount = 2; } } // We have some bytes available to decode, decode them if (encodedBytesCount > -1) { decodedDataBuffer[decodedBytesCount + 0] = (byte) (base64Block[0] << 2 | base64Block[1] >> 4); decodedDataBuffer[decodedBytesCount + 1] = (byte) ((base64Block[1] & 0xF) << 4 | base64Block[2] >> 2); decodedDataBuffer[decodedBytesCount + 2] = (byte) ((base64Block[2] & 0x3) << 6 | base64Block[3] >> 0); // Increase decoded bytes count decodedBytesCount += encodedBytesCount; // Reset this block, reade next if there is any nByteInBase64Block = 0; } } // There is some decoded bytes, construct return value if (decodedBytesCount > -1) { byte[] retVal = new byte[decodedBytesCount]; Array.Copy(decodedDataBuffer, 0, retVal, 0, decodedBytesCount); return retVal; } // There is no decoded bytes else { return new byte[0]; } } /// <summary> /// Encodes data with quoted-printable encoding. /// </summary> /// <param name="data">Data to encode.</param> /// <returns></returns> public static byte[] QuotedPrintableEncode(byte[] data) { /* Rfc 2045 6.7. Quoted-Printable Content-Transfer-Encoding (2) (Literal representation) Octets with decimal values of 33 through 60 inclusive, and 62 through 126, inclusive, MAY be represented as the US-ASCII characters which correspond to those octets (EXCLAMATION POINT through LESS THAN, and GREATER THAN through TILDE, respectively). (3) (White Space) Octets with values of 9 and 32 MAY be represented as US-ASCII TAB (HT) and SPACE characters, respectively, but MUST NOT be so represented at the end of an encoded line. You must encode it =XX. (5) Encoded lines must not be longer than 76 characters, not counting the trailing CRLF. If longer lines are to be encoded with the Quoted-Printable encoding, "soft" line breaks must be used. An equal sign as the last character on a encoded line indicates such a non-significant ("soft") line break in the encoded text. *) If binary data is encoded in quoted-printable, care must be taken to encode CR and LF characters as "=0D" and "=0A", respectively. */ int lineLength = 0; // Encode bytes <= 33 , >= 126 and 61 (=) MemoryStream retVal = new MemoryStream(); foreach (byte b in data) { // Suggested line length is exceeded, add soft line break if (lineLength > 75) { retVal.Write(new[] {(byte) '=', (byte) '\r', (byte) '\n'}, 0, 3); lineLength = 0; } // We need to encode that byte if (b <= 33 || b >= 126 || b == 61) { retVal.Write(new[] {(byte) '='}, 0, 1); retVal.Write(ToHex(b), 0, 2); lineLength += 3; } // We don't need to encode that byte, just write it to stream else { retVal.WriteByte(b); lineLength++; } } return retVal.ToArray(); } private static readonly Regex QuotedRegex = new Regex(@"(=[A-F0-9][A-F0-9])+", RegexOptions.Compiled | RegexOptions.Multiline); /// <summary> /// quoted-printable decoder. Defined in RFC 2045 6.7. /// </summary> /// <param name="data">Data which to encode.</param> /// <returns></returns> public static string QuotedPrintableDecode(string data, Encoding encoding) { /* RFC 2045 6.7. Quoted-Printable Content-Transfer-Encoding (1) (General 8bit representation) Any octet, except a CR or LF that is part of a CRLF line break of the canonical (standard) form of the data being encoded, may be represented by an "=" followed by a two digit hexadecimal representation of the octet's value. The digits of the hexadecimal alphabet, for this purpose, are "0123456789ABCDEF". Uppercase letters must be used; lowercase letters are not allowed. (2) (Literal representation) Octets with decimal values of 33 through 60 inclusive, and 62 through 126, inclusive, MAY be represented as the US-ASCII characters which correspond to those octets (EXCLAMATION POINT through LESS THAN, and GREATER THAN through TILDE, respectively). (3) (White Space) Octets with values of 9 and 32 MAY be represented as US-ASCII TAB (HT) and SPACE characters, respectively, but MUST NOT be so represented at the end of an encoded line. Any TAB (HT) or SPACE characters on an encoded line MUST thus be followed on that line by a printable character. In particular, an "=" at the end of an encoded line, indicating a soft line break (see rule #5) may follow one or more TAB (HT) or SPACE characters. It follows that an octet with decimal value 9 or 32 appearing at the end of an encoded line must be represented according to Rule #1. This rule is necessary because some MTAs (Message Transport Agents, programs which transport messages from one user to another, or perform a portion of such transfers) are known to pad lines of text with SPACEs, and others are known to remove "white space" characters from the end of a line. Therefore, when decoding a Quoted-Printable body, any trailing white space on a line must be deleted, as it will necessarily have been added by intermediate transport agents. (4) (Line Breaks) A line break in a text body, represented as a CRLF sequence in the text canonical form, must be represented by a (RFC 822) line break, which is also a CRLF sequence, in the Quoted-Printable encoding. Since the canonical representation of media types other than text do not generally include the representation of line breaks as CRLF sequences, no hard line breaks (i.e. line breaks that are intended to be meaningful and to be displayed to the user) can occur in the quoted-printable encoding of such types. Sequences like "=0D", "=0A", "=0A=0D" and "=0D=0A" will routinely appear in non-text data represented in quoted- printable, of course. (5) (Soft Line Breaks) The Quoted-Printable encoding REQUIRES that encoded lines be no more than 76 characters long. If longer lines are to be encoded with the Quoted-Printable encoding, "soft" line breaks */ var result = QuotedRegex.Replace(data, new MatchEvaluator(x=>EvalQuoted(x,encoding))); return result; } private static string EvalQuoted(Match match, Encoding encoding) { try { if (match.Success) { var values = match.Value.Split(new[]{'='},StringSplitOptions.RemoveEmptyEntries); var buffer = new byte[values.Length]; for (int index = 0; index < values.Length; index++) { var value = values[index]; byte parsed; if (byte.TryParse(value, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out parsed)) { buffer[index] = parsed; } } return encoding.GetString(buffer); } } catch (Exception) { } return match.Value; } /// <summary> /// "Q" decoder. This is same as quoted-printable, except '_' is converted to ' '. /// Defined in RFC 2047 4.2. /// </summary> /// <param name="encoding">Input string encoding.</param> /// <param name="data">String which to encode.</param> /// <returns>Returns decoded string.</returns> public static string QDecode(Encoding encoding, string data) { //It's simple return QuotedPrintableDecode(data.Replace("_", " "),encoding); // REMOVEME: // 15.09.2004 - replace must be done before encoding // return QuotedPrintableDecode(encoding,System.Text.Encoding.ASCII.GetBytes(data)).Replace("_"," "); } /// <summary> /// Canonical decoding. Decodes all canonical encoding occurences in specified text. /// Usually mime message header unicode/8bit values are encoded as Canonical. /// Format: =?charSet?type[Q or B]?encoded_string?= . /// Defined in RFC 2047. /// </summary> /// <param name="text">Text to decode.</param> /// <returns></returns> [Obsolete("Use MimeUtils.DecodeWords method instead.")] public static string CanonicalDecode(string text) { /* RFC 2047 Generally, an "encoded-word" is a sequence of printable ASCII characters that begins with "=?", ends with "?=", and has two "?"s in between. Syntax: =?charSet?type[Q or B]?encoded_string?= Examples: =?utf-8?q?Buy a Rolex?= =?iso-8859-1?B?bORs5D8=?= */ StringBuilder retVal = new StringBuilder(); int offset = 0; while (offset < text.Length) { // Search start and end of canonical entry int iStart = text.IndexOf("=?", offset); int iEnd = -1; if (iStart > -1) { // End index must be over start index position iEnd = text.IndexOf("?=", iStart + 2); } if (iStart > -1 && iEnd > -1) { // Add left side non encoded text of encoded text, if there is any if ((iStart - offset) > 0) { retVal.Append(text.Substring(offset, iStart - offset)); } while (true) { // Check if it is encoded entry string[] charset_type_text = text.Substring(iStart + 2, iEnd - iStart - 2).Split('?'); if (charset_type_text.Length == 3) { // Try to parse encoded text try { Encoding enc = EncodingTools.GetEncodingByCodepageName_Throws(charset_type_text[0]); // QEncoded text if (charset_type_text[1].ToLower() == "q") { retVal.Append(QDecode(enc, charset_type_text[2])); } // Base64 encoded text else { retVal.Append( enc.GetString( Base64Decode(Encoding.Default.GetBytes(charset_type_text[2])))); } } catch { // Parsing failed, just leave text as is. retVal.Append(text.Substring(iStart, iEnd - iStart + 2)); } // Move current offset in string offset = iEnd + 2; break; } // This isn't right end tag, try next else if (charset_type_text.Length < 3) { // Try next end tag iEnd = text.IndexOf("?=", iEnd + 2); // No suitable end tag for active start tag, move offset over start tag. if (iEnd == -1) { retVal.Append("=?"); offset = iStart + 2; break; } } // Illegal start tag or start tag is just in side some text, move offset over start tag. else { retVal.Append("=?"); offset = iStart + 2; break; } } } // There are no more entries else { // Add remaining non encoded text, if there is any. if (text.Length > offset) { retVal.Append(text.Substring(offset)); offset = text.Length; } } } return retVal.ToString(); } /// <summary> /// Canonical encoding. /// </summary> /// <param name="str">String to encode.</param> /// <param name="charSet">With what charset to encode string. If you aren't sure about it, utf-8 is suggested.</param> /// <returns>Returns encoded text.</returns> public static string CanonicalEncode(string str, string charSet) { /* RFC 2049 2. (9),(10) =?encodedWord?= encodedWord -> charset?encoding?encodedText encoding -> Q(Q encode) or B(base64) */ // Contains non ascii chars, must to encode. if (!IsAscii(str)) { string retVal = "=?" + charSet + "?" + "B?"; retVal += Convert.ToBase64String(EncodingTools.GetEncodingByCodepageName_Throws(charSet).GetBytes(str)); retVal += "?="; return retVal; } return str; } /// <summary> /// Encodes specified data with IMAP modified UTF7 encoding. Defined in RFC 3501 5.1.3. Mailbox International Naming Convention. /// Example: �� is encoded to &amp;APYA9g-. /// </summary> /// <param name="text">Text to encode.</param> /// <returns></returns> public static string Encode_IMAP_UTF7_String(string text) { /* RFC 3501 5.1.3. Mailbox International Naming Convention In modified UTF-7, printable US-ASCII characters, except for "&", represent themselves; that is, characters with octet values 0x20-0x25 and 0x27-0x7e. The character "&" (0x26) is represented by the two-octet sequence "&-". All other characters (octet values 0x00-0x1f and 0x7f-0xff) are represented in modified BASE64, with a further modification from [UTF-7] that "," is used instead of "/". Modified BASE64 MUST NOT be used to represent any printing US-ASCII character which can represent itself. "&" is used to shift to modified BASE64 and "-" to shift back to US-ASCII. There is no implicit shift from BASE64 to US-ASCII, and null shifts ("-&" while in BASE64; note that "&-" while in US-ASCII means "&") are not permitted. However, all names start in US-ASCII, and MUST end in US-ASCII; that is, a name that ends with a non-ASCII ISO-10646 character MUST end with a "-"). */ // Base64 chars, except '/' is replaced with ',' char[] base64Chars = new[] { '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', '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', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', ',' }; MemoryStream retVal = new MemoryStream(); for (int i = 0; i < text.Length; i++) { char c = text[i]; // The character "&" (0x26) is represented by the two-octet sequence "&-". if (c == '&') { retVal.Write(new[] {(byte) '&', (byte) '-'}, 0, 2); } // It is allowed char, don't need to encode else if (c >= 0x20 && c <= 0x25 || c >= 0x27 && c <= 0x7E) { retVal.WriteByte((byte) c); } // Not allowed char, encode it else { // Superfluous shifts are not allowed. // For example: �� may not encoded as &APY-&APY-, but must be &APYA9g-. // Get all continuous chars that need encoding and encode them as one block MemoryStream encodeBlock = new MemoryStream(); for (int ic = i; ic < text.Length; ic++) { char cC = text[ic]; // Allowed char if (cC >= 0x20 && cC <= 0x25 || cC >= 0x27 && cC <= 0x7E) { break; } else { encodeBlock.WriteByte((byte) ((cC & 0xFF00) >> 8)); encodeBlock.WriteByte((byte) (cC & 0xFF)); i = ic; } } // Ecode block byte[] encodedData = Base64EncodeEx(encodeBlock.ToArray(), base64Chars, false); retVal.WriteByte((byte) '&'); retVal.Write(encodedData, 0, encodedData.Length); retVal.WriteByte((byte) '-'); } } return Encoding.Default.GetString(retVal.ToArray()); } /// <summary> /// Decodes IMAP modified UTF7 encoded data. Defined in RFC 3501 5.1.3. Mailbox International Naming Convention. /// Example: &amp;APYA9g- is decoded to ��. /// </summary> /// <param name="text">Text to encode.</param> /// <returns></returns> public static string Decode_IMAP_UTF7_String(string text) { /* RFC 3501 5.1.3. Mailbox International Naming Convention In modified UTF-7, printable US-ASCII characters, except for "&", represent themselves; that is, characters with octet values 0x20-0x25 and 0x27-0x7e. The character "&" (0x26) is represented by the two-octet sequence "&-". All other characters (octet values 0x00-0x1f and 0x7f-0xff) are represented in modified BASE64, with a further modification from [UTF-7] that "," is used instead of "/". Modified BASE64 MUST NOT be used to represent any printing US-ASCII character which can represent itself. "&" is used to shift to modified BASE64 and "-" to shift back to US-ASCII. There is no implicit shift from BASE64 to US-ASCII, and null shifts ("-&" while in BASE64; note that "&-" while in US-ASCII means "&") are not permitted. However, all names start in US-ASCII, and MUST end in US-ASCII; that is, a name that ends with a non-ASCII ISO-10646 character MUST end with a "-"). */ // Base64 chars, except '/' is replaced with ',' char[] base64Chars = new[] { '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', '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', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', ',' }; StringBuilder retVal = new StringBuilder(); for (int i = 0; i < text.Length; i++) { char c = text[i]; // Encoded block or escaped & if (c == '&') { int endingPos = -1; // Read encoded block for (int b = i + 1; b < text.Length; b++) { // - marks block end if (text[b] == '-') { endingPos = b; break; } // Invalid & sequence, just treat it as '&' char and not like shift. // &....&, but must be &....- else if (text[b] == '&') { break; } } // If no ending -, invalid encoded block. Treat it like it is if (endingPos == -1) { // Just let main for to handle other chars after & retVal.Append(c); } // If empty block, then escaped & else if (endingPos - i == 1) { retVal.Append(c); // Move i over '-' i++; } // Decode block else { // Get encoded block byte[] encodedBlock = Encoding.Default.GetBytes(text.Substring(i + 1, endingPos - i - 1)); // Convert to UTF-16 char byte[] decodedData = Base64DecodeEx(encodedBlock, base64Chars); char[] decodedChars = new char[decodedData.Length/2]; for (int iC = 0; iC < decodedChars.Length; iC++) { decodedChars[iC] = (char) (decodedData[iC*2] << 8 | decodedData[(iC*2) + 1]); } // Decode data retVal.Append(decodedChars); // Move i over '-' i += encodedBlock.Length + 1; } } // Normal byte else { retVal.Append(c); } } return retVal.ToString(); } /// <summary> /// Checks if specified string data is acii data. /// </summary> /// <param name="data"></param> /// <returns></returns> public static bool IsAscii(string data) { foreach (char c in data) { if (c > 127) { return false; } } return true; } /// <summary> /// Gets file name from path. /// </summary> /// <param name="filePath">File file path with file name. For examples: c:\fileName.xxx, aaa\fileName.xxx.</param> /// <returns></returns> public static string GetFileNameFromPath(string filePath) { return Path.GetFileName(filePath); } /// <summary> /// Gets if specified value is IP address. /// </summary> /// <param name="value">String value.</param> /// <returns>Returns true if specified value is IP address.</returns> public static bool IsIP(string value) { try { IPAddress.Parse(value); return true; } catch { return false; } } /// <summary> /// Compares 2 IP addresses. Returns 0 if IPs are equal, /// returns positive value if destination IP is bigger than source IP, /// returns negative value if destination IP is smaller than source IP. /// </summary> /// <param name="source">Source IP address.</param> /// <param name="destination">Destination IP address.</param> /// <returns></returns> public static int CompareIP(IPAddress source, IPAddress destination) { byte[] sourceIpBytes = source.GetAddressBytes(); byte[] destinationIpBytes = destination.GetAddressBytes(); // IPv4 and IPv6 if (sourceIpBytes.Length < destinationIpBytes.Length) { return 1; } // IPv6 and IPv4 else if (sourceIpBytes.Length > destinationIpBytes.Length) { return -1; } // IPv4 and IPv4 OR IPv6 and IPv6 else { for (int i = 0; i < sourceIpBytes.Length; i++) { if (sourceIpBytes[i] < destinationIpBytes[i]) { return 1; } else if (sourceIpBytes[i] > destinationIpBytes[i]) { return -1; } } return 0; } } /// <summary> /// Gets if specified IP address is private LAN IP address. For example 192.168.x.x is private ip. /// </summary> /// <param name="ip">IP address to check.</param> /// <exception cref="ArgumentNullException">Is raised when <b>ip</b> is null reference.</exception> /// <returns>Returns true if IP is private IP.</returns> public static bool IsPrivateIP(string ip) { if (ip == null) { throw new ArgumentNullException("ip"); } return IsPrivateIP(IPAddress.Parse(ip)); } /// <summary> /// Gets if specified IP address is private LAN IP address. For example 192.168.x.x is private ip. /// </summary> /// <param name="ip">IP address to check.</param> /// <returns>Returns true if IP is private IP.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>ip</b> is null reference.</exception> public static bool IsPrivateIP(IPAddress ip) { if (ip == null) { throw new ArgumentNullException("ip"); } if (ip.AddressFamily == AddressFamily.InterNetwork) { byte[] ipBytes = ip.GetAddressBytes(); /* Private IPs: First Octet = 192 AND Second Octet = 168 (Example: 192.168.X.X) First Octet = 172 AND (Second Octet >= 16 AND Second Octet <= 31) (Example: 172.16.X.X - 172.31.X.X) First Octet = 10 (Example: 10.X.X.X) First Octet = 169 AND Second Octet = 254 (Example: 169.254.X.X) */ if (ipBytes[0] == 192 && ipBytes[1] == 168) { return true; } if (ipBytes[0] == 172 && ipBytes[1] >= 16 && ipBytes[1] <= 31) { return true; } if (ipBytes[0] == 10) { return true; } if (ipBytes[0] == 169 && ipBytes[1] == 254) { return true; } } return false; } /// <summary> /// Creates new socket for the specified end point. /// </summary> /// <param name="localEP">Local end point.</param> /// <param name="protocolType">Protocol type.</param> /// <returns>Retruns newly created socket.</returns> public static Socket CreateSocket(IPEndPoint localEP, ProtocolType protocolType) { SocketType socketType = SocketType.Dgram; if (protocolType == ProtocolType.Udp) { socketType = SocketType.Dgram; } if (localEP.AddressFamily == AddressFamily.InterNetwork) { Socket socket = new Socket(AddressFamily.InterNetwork, socketType, protocolType); socket.Bind(localEP); return socket; } else if (localEP.AddressFamily == AddressFamily.InterNetworkV6) { Socket socket = new Socket(AddressFamily.InterNetworkV6, socketType, protocolType); socket.Bind(localEP); return socket; } else { throw new ArgumentException("Invalid IPEndPoint address family."); } } /// <summary> /// Converts string to hex string. /// </summary> /// <param name="data">String to convert.</param> /// <returns>Returns data as hex string.</returns> public static string ToHexString(string data) { return Encoding.Default.GetString(ToHex(Encoding.Default.GetBytes(data))); } /// <summary> /// Converts string to hex string. /// </summary> /// <param name="data">Data to convert.</param> /// <returns>Returns data as hex string.</returns> public static string ToHexString(byte[] data) { return Encoding.Default.GetString(ToHex(data)); } /// <summary> /// Convert byte to hex data. /// </summary> /// <param name="byteValue">Byte to convert.</param> /// <returns></returns> public static byte[] ToHex(byte byteValue) { return ToHex(new[] {byteValue}); } /// <summary> /// Converts data to hex data. /// </summary> /// <param name="data">Data to convert.</param> /// <returns></returns> public static byte[] ToHex(byte[] data) { char[] hexChars = new[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; MemoryStream retVal = new MemoryStream(data.Length*2); foreach (byte b in data) { byte[] hexByte = new byte[2]; // left 4 bit of byte hexByte[0] = (byte) hexChars[(b & 0xF0) >> 4]; // right 4 bit of byte hexByte[1] = (byte) hexChars[b & 0x0F]; retVal.Write(hexByte, 0, 2); } return retVal.ToArray(); } /// <summary> /// Converts hex byte data to normal byte data. Hex data must be in two bytes pairs, for example: 0F,FF,A3,... . /// </summary> /// <param name="hexData">Hex data.</param> /// <returns></returns> public static byte[] FromHex(byte[] hexData) { if (hexData.Length < 2 || (hexData.Length/(double) 2 != Math.Floor(hexData.Length/(double) 2))) { throw new Exception( "Illegal hex data, hex data must be in two bytes pairs, for example: 0F,FF,A3,... ."); } MemoryStream retVal = new MemoryStream(hexData.Length/2); // Loop hex value pairs for (int i = 0; i < hexData.Length; i += 2) { byte[] hexPairInDecimal = new byte[2]; // We need to convert hex char to decimal number, for example F = 15 for (int h = 0; h < 2; h++) { if (((char) hexData[i + h]) == '0') { hexPairInDecimal[h] = 0; } else if (((char) hexData[i + h]) == '1') { hexPairInDecimal[h] = 1; } else if (((char) hexData[i + h]) == '2') { hexPairInDecimal[h] = 2; } else if (((char) hexData[i + h]) == '3') { hexPairInDecimal[h] = 3; } else if (((char) hexData[i + h]) == '4') { hexPairInDecimal[h] = 4; } else if (((char) hexData[i + h]) == '5') { hexPairInDecimal[h] = 5; } else if (((char) hexData[i + h]) == '6') { hexPairInDecimal[h] = 6; } else if (((char) hexData[i + h]) == '7') { hexPairInDecimal[h] = 7; } else if (((char) hexData[i + h]) == '8') { hexPairInDecimal[h] = 8; } else if (((char) hexData[i + h]) == '9') { hexPairInDecimal[h] = 9; } else if (((char) hexData[i + h]) == 'A' || ((char) hexData[i + h]) == 'a') { hexPairInDecimal[h] = 10; } else if (((char) hexData[i + h]) == 'B' || ((char) hexData[i + h]) == 'b') { hexPairInDecimal[h] = 11; } else if (((char) hexData[i + h]) == 'C' || ((char) hexData[i + h]) == 'c') { hexPairInDecimal[h] = 12; } else if (((char) hexData[i + h]) == 'D' || ((char) hexData[i + h]) == 'd') { hexPairInDecimal[h] = 13; } else if (((char) hexData[i + h]) == 'E' || ((char) hexData[i + h]) == 'e') { hexPairInDecimal[h] = 14; } else if (((char) hexData[i + h]) == 'F' || ((char) hexData[i + h]) == 'f') { hexPairInDecimal[h] = 15; } } // Join hex 4 bit(left hex cahr) + 4bit(right hex char) in bytes 8 it retVal.WriteByte((byte) ((hexPairInDecimal[0] << 4) | hexPairInDecimal[1])); } return retVal.ToArray(); } /// <summary> /// Computes md5 hash. /// </summary> /// <param name="text">Text to hash.</param> /// <param name="hex">Specifies if md5 value is returned as hex string.</param> /// <returns>Resturns md5 value or md5 hex value.</returns> public static string ComputeMd5(string text, bool hex) { MD5 md5 = new MD5CryptoServiceProvider(); byte[] hash = md5.ComputeHash(Encoding.Default.GetBytes(text)); if (hex) { return ToHexString(Encoding.Default.GetString(hash)).ToLower(); } else { return Encoding.Default.GetString(hash); } } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/SIP/Message/SIP_t_AddressParam.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.SIP.Message { #region usings using System; using System.Text; #endregion /// <summary> /// Implements SIP_t_NameAddress + parameters value. /// </summary> public class SIP_t_AddressParam : SIP_t_ValueWithParams { #region Members private SIP_t_NameAddress m_pAddress; #endregion #region Properties /// <summary> /// Gets address. /// </summary> public SIP_t_NameAddress Address { get { return m_pAddress; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> public SIP_t_AddressParam() {} /// <summary> /// Default constructor. /// </summary> /// <param name="value">SIP_t_NameAddress + parameters value.</param> public SIP_t_AddressParam(string value) { Parse(value); } #endregion #region Methods /// <summary> /// Parses this from specified value. /// </summary> /// <param name="value">Address + params value.</param> /// <exception cref="ArgumentNullException">Raised when <b>value</b> is null.</exception> /// <exception cref="SIP_ParseException">Raised when invalid SIP message.</exception> public void Parse(string value) { if (value == null) { throw new ArgumentNullException("value"); } Parse(new StringReader(value)); } /// <summary> /// Parses this from address param string. /// </summary> /// <param name="reader">Reader what contains address param string.</param> /// <exception cref="ArgumentNullException">Raised when <b>reader</b> is null.</exception> /// <exception cref="SIP_ParseException">Raised when invalid SIP message.</exception> public override void Parse(StringReader reader) { if (reader == null) { throw new ArgumentNullException("reader"); } // Parse address SIP_t_NameAddress address = new SIP_t_NameAddress(); address.Parse(reader); m_pAddress = address; // Parse parameters. ParseParameters(reader); } /// <summary> /// Converts this to valid value string. /// </summary> /// <returns></returns> public override string ToStringValue() { StringBuilder retVal = new StringBuilder(); // Add address retVal.Append(m_pAddress.ToStringValue()); // Add parameters foreach (SIP_Parameter parameter in Parameters) { if (parameter.Value != null) { retVal.Append(";" + parameter.Name + "=" + parameter.Value); } else { retVal.Append(";" + parameter.Name); } } return retVal.ToString(); } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/RTP/RTP_Participant_Local.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.RTP { #region usings using System; #endregion /// <summary> /// This class represents RTP session/multimedia-session local participant. /// </summary> /// <remarks>Term <b>participant</b> is not well commented/defined in RTP. In general for single media session <b>participant</b> /// is RTP session itself, for multimedia sesssion <b>participant</b> is multimedia session(RTP sessions group).</remarks> public class RTP_Participant_Local : RTP_Participant { #region Members private readonly CircleCollection<string> m_pOtionalItemsRoundRobin; private string m_Email; private string m_Location; private string m_Name; private string m_Note; private string m_Phone; private string m_Tool; #endregion #region Properties /// <summary> /// Gets or sets the real name, eg. "<NAME>". Value null means not specified. /// </summary> public string Name { get { return m_Name; } set { m_Name = value; ConstructOptionalItems(); } } /// <summary> /// Gets or sets email address. For example "<EMAIL>". Value null means not specified. /// </summary> public string Email { get { return m_Email; } set { m_Email = value; ConstructOptionalItems(); } } /// <summary> /// Gets or sets phone number. For example "+1 908 555 1212". Value null means not specified. /// </summary> public string Phone { get { return m_Phone; } set { m_Phone = value; ConstructOptionalItems(); } } /// <summary> /// Gets or sets location string. It may be geographic address or for example chat room name. /// Value null means not specified. /// </summary> public string Location { get { return m_Location; } set { m_Location = value; ConstructOptionalItems(); } } /// <summary> /// Gets or sets streaming application name/version. /// Value null means not specified. /// </summary> public string Tool { get { return m_Tool; } set { m_Tool = value; ConstructOptionalItems(); } } /// <summary> /// Gets or sets note text. The NOTE item is intended for transient messages describing the current state /// of the source, e.g., "on the phone, can't talk". Value null means not specified. /// </summary> public string Note { get { return m_Note; } set { m_Note = value; ConstructOptionalItems(); } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="cname">Canonical name of participant.</param> /// <exception cref="ArgumentNullException">Is raised when <b>cname</b> is null reference.</exception> public RTP_Participant_Local(string cname) : base(cname) { m_pOtionalItemsRoundRobin = new CircleCollection<string>(); } #endregion #region Utility methods /// <summary> /// Constructs optional SDES items round-robin. /// </summary> private void ConstructOptionalItems() { lock (m_pOtionalItemsRoundRobin) { m_pOtionalItemsRoundRobin.Clear(); if (!string.IsNullOrEmpty(m_Note)) { m_pOtionalItemsRoundRobin.Add("note"); } if (!string.IsNullOrEmpty(m_Name)) { m_pOtionalItemsRoundRobin.Add("name"); } if (!string.IsNullOrEmpty(m_Email)) { m_pOtionalItemsRoundRobin.Add("email"); } if (!string.IsNullOrEmpty(m_Phone)) { m_pOtionalItemsRoundRobin.Add("phone"); } if (!string.IsNullOrEmpty(m_Location)) { m_pOtionalItemsRoundRobin.Add("location"); } if (!string.IsNullOrEmpty(m_Tool)) { m_pOtionalItemsRoundRobin.Add("tool"); } } } #endregion #region Internal methods /// <summary> /// Adds next(round-robined) optional SDES item to SDES chunk, if any available. /// </summary> /// <param name="sdes">SDES chunk where to add item.</param> /// <exception cref="ArgumentNullException">Is raised when <b>sdes</b> is null reference.</exception> internal void AddNextOptionalSdesItem(RTCP_Packet_SDES_Chunk sdes) { if (sdes == null) { throw new ArgumentNullException("sdes"); } lock (m_pOtionalItemsRoundRobin) { if (m_pOtionalItemsRoundRobin.Count > 0) { string itemName = m_pOtionalItemsRoundRobin.Next(); if (itemName == "name") { sdes.Name = m_Name; } else if (itemName == "email") { sdes.Email = m_Email; } else if (itemName == "phone") { sdes.Phone = m_Phone; } else if (itemName == "location") { sdes.Location = m_Location; } else if (itemName == "tool") { sdes.Tool = m_Tool; } else if (itemName == "note") { sdes.Note = m_Note; } } } } #endregion // TODO: PRIV } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Autoreply/ParameterResolvers/ContentResolver.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using ASC.Mail.Autoreply.Utility; using ASC.Mail.Autoreply.Utility.Html; using ASC.Mail.Net.Mail; using HtmlAgilityPack; namespace ASC.Mail.Autoreply.ParameterResolvers { internal class HtmlContentResolver : IParameterResolver { public object ResolveParameterValue(Mail_Message mailMessage) { var messageText = !string.IsNullOrEmpty(mailMessage.BodyHtmlText) ? mailMessage.BodyHtmlText : Text2HtmlConverter.Convert(mailMessage.BodyText.Trim(' ')); messageText = messageText.Replace(Environment.NewLine, "").Replace(@"\t", ""); messageText = HtmlEntity.DeEntitize(messageText); messageText = HtmlSanitizer.Sanitize(messageText); return messageText.Trim("<br>").Trim("</br>").Trim(' '); } } internal class PlainTextContentResolver : IParameterResolver { public object ResolveParameterValue(Mail_Message mailMessage) { var messageText = new HtmlContentResolver().ResolveParameterValue(mailMessage) as string; if (!string.IsNullOrEmpty(messageText)) messageText = Html2TextConverter.Convert(messageText); return messageText; } } } <file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/RTP/RTCP_Packet.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.RTP { #region usings using System; #endregion /// <summary> /// This is base class for RTCP packets. /// </summary> public abstract class RTCP_Packet { #region Members private int m_PaddBytesCount; #endregion #region Properties /// <summary> /// Gets RTCP version. /// </summary> public abstract int Version { get; } /// <summary> /// Gets if packet is padded to some bytes boundary. /// </summary> public bool IsPadded { get { if (m_PaddBytesCount > 0) { return true; } else { return false; } } } /// <summary> /// Gets RTCP packet type. /// </summary> public abstract int Type { get; } /// <summary> /// Gets or sets number empty bytes to add at the end of packet. /// </summary> public int PaddBytesCount { get { return m_PaddBytesCount; } set { if (value < 0) { throw new ArgumentException("Property 'PaddBytesCount' value must be >= 0."); } m_PaddBytesCount = value; } } /// <summary> /// Gets number of bytes needed for this packet. /// </summary> public abstract int Size { get; } #endregion #region Methods /// <summary> /// Parses 1 RTCP packet from the specified buffer. /// </summary> /// <param name="buffer">Buffer which contains RTCP packet.</param> /// <param name="offset">Offset in buffer.</param> /// <returns>Returns parsed RTCP packet.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>buffer</b> is null.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> public static RTCP_Packet Parse(byte[] buffer, ref int offset) { if (buffer == null) { throw new ArgumentNullException("buffer"); } if (offset < 0) { throw new ArgumentException("Argument 'offset' value must be >= 0."); } /* RFC 3550 RTCP header. 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ header |V=2|P| XX | type | length | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ int type = buffer[offset + 1]; // SR if (type == RTCP_PacketType.SR) { RTCP_Packet_SR packet = new RTCP_Packet_SR(); packet.ParseInternal(buffer, ref offset); return packet; } // RR else if (type == RTCP_PacketType.RR) { RTCP_Packet_RR packet = new RTCP_Packet_RR(); packet.ParseInternal(buffer, ref offset); return packet; } // SDES else if (type == RTCP_PacketType.SDES) { RTCP_Packet_SDES packet = new RTCP_Packet_SDES(); packet.ParseInternal(buffer, ref offset); return packet; } // BYE else if (type == RTCP_PacketType.BYE) { RTCP_Packet_BYE packet = new RTCP_Packet_BYE(); packet.ParseInternal(buffer, ref offset); return packet; } // APP else if (type == RTCP_PacketType.APP) { RTCP_Packet_APP packet = new RTCP_Packet_APP(); packet.ParseInternal(buffer, ref offset); return packet; } else { // We need to move offset. offset += 2; int length = buffer[offset++] << 8 | buffer[offset++]; offset += length; throw new ArgumentException("Unknown RTCP packet type '" + type + "'."); } } /// <summary> /// Stores this packet to the specified buffer. /// </summary> /// <param name="buffer">Buffer where to store packet.</param> /// <param name="offset">Offset in buffer.</param> public abstract void ToByte(byte[] buffer, ref int offset); #endregion #region Abstract methods /// <summary> /// Parses RTCP packet from the specified buffer. /// </summary> /// <param name="buffer">Buffer which contains packet.</param> /// <param name="offset">Offset in buffer.</param> protected abstract void ParseInternal(byte[] buffer, ref int offset); #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/IMAP/IMAP_BODY_Entity.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.IMAP { #region usings using System; using System.Collections.Generic; using Mime; #endregion /// <summary> /// IMAP BODY mime entity info. /// </summary> public class IMAP_BODY_Entity { #region Members private readonly List<IMAP_BODY_Entity> m_pChildEntities; private string m_ContentDescription; private ContentTransferEncoding_enum m_ContentEncoding = ContentTransferEncoding_enum._7bit; private string m_ContentID; private int m_ContentLines; private int m_ContentSize; private MediaType_enum m_pContentType = MediaType_enum.Text_plain; private HeaderFieldParameter[] m_pContentTypeParams; private IMAP_Envelope m_pEnvelope; private IMAP_BODY_Entity m_pParentEntity; #endregion #region Properties /// <summary> /// Gets parent entity of this entity. If this entity is top level, then this property returns null. /// </summary> public IMAP_BODY_Entity ParentEntity { get { return m_pParentEntity; } } /// <summary> /// Gets child entities. This property is available only if ContentType = multipart/... . /// </summary> public IMAP_BODY_Entity[] ChildEntities { get { // if((this.ContentType & MediaType_enum.Multipart) == 0){ // throw new Exception("NOTE: ChildEntities property is available only for non-multipart contentype !"); // } return m_pChildEntities.ToArray(); } } /// <summary> /// Gets header field "<b>Content-Type:</b>" value. /// </summary> public MediaType_enum ContentType { get { return m_pContentType; } } /// <summary> /// Gets header field "<b>Content-Type:</b>" prameters. This value is null if no parameters. /// </summary> public HeaderFieldParameter[] ContentType_Paramters { get { return m_pContentTypeParams; } } /// <summary> /// Gets header field "<b>Content-ID:</b>" value. Returns null if value isn't set. /// </summary> public string ContentID { get { return m_ContentID; } } /// <summary> /// Gets header field "<b>Content-Description:</b>" value. Returns null if value isn't set. /// </summary> public string ContentDescription { get { return m_ContentDescription; } } /// <summary> /// Gets header field "<b>Content-Transfer-Encoding:</b>" value. /// </summary> public ContentTransferEncoding_enum ContentTransferEncoding { get { return m_ContentEncoding; } } /// <summary> /// Gets content encoded data size. NOTE: This property is available only for non-multipart contentype ! /// </summary> public int ContentSize { get { if ((ContentType & MediaType_enum.Multipart) != 0) { throw new Exception( "NOTE: ContentSize property is available only for non-multipart contentype !"); } return m_ContentSize; } } /// <summary> /// Gets content envelope. NOTE: This property is available only for message/xxx content type ! /// Yhis value can be also null if no ENVELOPE provided by server. /// </summary> public IMAP_Envelope Envelope { get { if ((ContentType & MediaType_enum.Message) == 0) { throw new Exception( "NOTE: Envelope property is available only for non-multipart contentype !"); } return null; } } /// <summary> /// Gets content encoded data lines. NOTE: This property is available only for text/xxx content type ! /// </summary> public int ContentLines { get { if ((ContentType & MediaType_enum.Text) == 0) { throw new Exception( "NOTE: ContentLines property is available only for text/xxx content type !"); } return m_ContentSize; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> internal IMAP_BODY_Entity() { m_pChildEntities = new List<IMAP_BODY_Entity>(); } #endregion #region Internal methods /// <summary> /// Parses entity and it's child entities. /// </summary> internal void Parse(string text) { StringReader r = new StringReader(text); r.ReadToFirstChar(); // If starts with ( then multipart/xxx, otherwise normal single part entity if (r.StartsWith("(")) { // Entities are (entity1)(entity2)(...) <SP> ContentTypeSubType while (r.StartsWith("(")) { IMAP_BODY_Entity entity = new IMAP_BODY_Entity(); entity.Parse(r.ReadParenthesized()); entity.m_pParentEntity = this; m_pChildEntities.Add(entity); r.ReadToFirstChar(); } // Read multipart values. (nestedMimeEntries) contentTypeSubMediaType string contentTypeSubMediaType = r.ReadWord(); m_pContentType = MimeUtils.ParseMediaType("multipart/" + contentTypeSubMediaType); } else { // Basic fields for non-multipart // contentTypeMainMediaType contentTypeSubMediaType (conentTypeParameters) contentID contentDescription contentEncoding contentSize [envelope] [contentLine] // Content-Type string contentTypeMainMediaType = r.ReadWord(); string contentTypeSubMediaType = r.ReadWord(); if (contentTypeMainMediaType.ToUpper() != "NIL" && contentTypeSubMediaType.ToUpper() != "NIL") { m_pContentType = MimeUtils.ParseMediaType(contentTypeMainMediaType + "/" + contentTypeSubMediaType); } // Content-Type header field parameters // Parameters syntax: "name" <SP> "value" <SP> "name" <SP> "value" <SP> ... . r.ReadToFirstChar(); string conentTypeParameters = "NIL"; if (r.StartsWith("(")) { conentTypeParameters = r.ReadParenthesized(); StringReader contentTypeParamReader = new StringReader(MimeUtils.DecodeWords(conentTypeParameters)); List<HeaderFieldParameter> parameters = new List<HeaderFieldParameter>(); while (contentTypeParamReader.Available > 0) { string parameterName = contentTypeParamReader.ReadWord(); string parameterValue = contentTypeParamReader.ReadWord(); parameters.Add(new HeaderFieldParameter(parameterName, parameterValue)); } m_pContentTypeParams = parameters.ToArray(); } else { // Skip NIL r.ReadWord(); } // Content-ID: string contentID = r.ReadWord(); if (contentID.ToUpper() != "NIL") { m_ContentID = contentID; } // Content-Description: string contentDescription = r.ReadWord(); if (contentDescription.ToUpper() != "NIL") { m_ContentDescription = contentDescription; } // Content-Transfer-Encoding: string contentEncoding = r.ReadWord(); if (contentEncoding.ToUpper() != "NIL") { m_ContentEncoding = MimeUtils.ParseContentTransferEncoding(contentEncoding); } // Content Encoded data size in bytes string contentSize = r.ReadWord(); if (contentSize.ToUpper() != "NIL") { m_ContentSize = Convert.ToInt32(contentSize); } // Only for ContentType message/rfc822 if (ContentType == MediaType_enum.Message_rfc822) { r.ReadToFirstChar(); // envelope if (r.StartsWith("(")) { m_pEnvelope = new IMAP_Envelope(); m_pEnvelope.Parse(r.ReadParenthesized()); } else { // Skip NIL, ENVELOPE wasn't included r.ReadWord(); } // TODO: // BODYSTRUCTURE // contentLine } // Only for ContentType text/xxx if (contentTypeMainMediaType.ToLower() == "text") { // contentLine string contentLines = r.ReadWord(); if (contentLines.ToUpper() != "NIL") { m_ContentLines = Convert.ToInt32(contentLines); } } } } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/RTP/RTP_SendStream.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.RTP { #region usings using System; #endregion /// <summary> /// Implements RTP session send stream. /// </summary> public class RTP_SendStream { #region Events /// <summary> /// Is raised when stream is closed. /// </summary> public event EventHandler Closed = null; /// <summary> /// Is raised when stream has disposed. /// </summary> public event EventHandler Disposed = null; #endregion #region Members private bool m_IsDisposed; private uint m_LastPacketRtpTimestamp; private DateTime m_LastPacketTime; private RTP_Source_Local m_pSource; private int m_RtcpCyclesSinceWeSent = 9999; private long m_RtpBytesSent; private long m_RtpDataBytesSent; private long m_RtpPacketsSent; private int m_SeqNo; private int m_SeqNoWrapCount; #endregion #region Properties /// <summary> /// Gets if this object is disposed. /// </summary> public bool IsDisposed { get { return m_IsDisposed; } } /// <summary> /// Gets stream owner RTP session. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public RTP_Session Session { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_pSource.Session; } } /// <summary> /// Gets stream owner source. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public RTP_Source Source { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_pSource; } } /// <summary> /// Gets number of times <b>SeqNo</b> has wrapped around. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public int SeqNoWrapCount { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_SeqNoWrapCount; } } /// <summary> /// Gets next packet sequence number. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public int SeqNo { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_SeqNo; } } /// <summary> /// Gets last packet send time. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public DateTime LastPacketTime { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_LastPacketTime; } } /// <summary> /// Gets last sent RTP packet RTP timestamp header value. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public uint LastPacketRtpTimestamp { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_LastPacketRtpTimestamp; } } /// <summary> /// Gets how many RTP packets has sent by this stream. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public long RtpPacketsSent { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_RtpPacketsSent; } } /// <summary> /// Gets how many RTP bytes has sent by this stream. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public long RtpBytesSent { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_RtpBytesSent; } } /// <summary> /// Gets how many RTP data(no RTP header included) bytes has sent by this stream. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public long RtpDataBytesSent { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_RtpDataBytesSent; } } /// <summary> /// Gets how many RTCP cycles has passed since we sent data. /// </summary> internal int RtcpCyclesSinceWeSent { get { return m_RtcpCyclesSinceWeSent; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="source">Owner RTP source.</param> /// <exception cref="ArgumentNullException">Is raised when <b>source</b> is null reference.</exception> internal RTP_SendStream(RTP_Source_Local source) { if (source == null) { throw new ArgumentNullException("source"); } m_pSource = source; /* RFC 3550 4. The initial value of the sequence number SHOULD be random (unpredictable) to make known-plaintext attacks on encryption more difficult. */ m_SeqNo = new Random().Next(1, Workaround.Definitions.MaxStreamLineLength); } #endregion #region Methods /// <summary> /// Closes this sending stream. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this method is accessed.</exception> public void Close() { Close(null); } /// <summary> /// Closes this sending stream. /// </summary> /// <param name="closeReason">Stream closing reason text what is reported to the remote party. Value null means not specified.</param> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this method is accessed.</exception> public void Close(string closeReason) { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } m_pSource.Close(closeReason); OnClosed(); Dispose(); } /// <summary> /// Sends specified packet to the RTP session remote party. /// </summary> /// <param name="packet">RTP packet.</param> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this method is accessed.</exception> /// <exception cref="ArgumentNullException">Is raised when <b>packet</b> is null reference.</exception> /// <remarks>Properties <b>packet.SSRC</b>,<b>packet.SeqNo</b>,<b>packet.PayloadType</b> filled by this method automatically.</remarks> public void Send(RTP_Packet packet) { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (packet == null) { throw new ArgumentNullException("packet"); } // RTP was designed around the concept of Application Level Framing (ALF), // because of it we only allow to send packets and don't deal with breaking frames into packets. packet.SSRC = Source.SSRC; packet.SeqNo = NextSeqNo(); packet.PayloadType = Session.Payload; // Send RTP packet. m_RtpBytesSent += m_pSource.SendRtpPacket(packet); m_RtpPacketsSent++; m_RtpDataBytesSent += packet.Data.Length; m_LastPacketTime = DateTime.Now; m_LastPacketRtpTimestamp = packet.Timestamp; m_RtcpCyclesSinceWeSent = 0; } #endregion #region Utility methods /// <summary> /// Cleans up any resources being used. /// </summary> private void Dispose() { if (m_IsDisposed) { return; } m_IsDisposed = true; m_pSource = null; OnDisposed(); Disposed = null; Closed = null; } /// <summary> /// Gets next packet sequence number. /// </summary> /// <returns>Returns next packet sequence number.</returns> private ushort NextSeqNo() { // Wrap around sequence number. if (m_SeqNo >= ushort.MaxValue) { m_SeqNo = 0; m_SeqNoWrapCount++; } return (ushort) m_SeqNo++; } /// <summary> /// Raises <b>Disposed</b> event. /// </summary> private void OnDisposed() { if (Disposed != null) { Disposed(this, new EventArgs()); } } /// <summary> /// Raises <b>Closed</b> event. /// </summary> private void OnClosed() { if (Closed != null) { Closed(this, new EventArgs()); } } #endregion #region Internal methods /// <summary> /// Is called by RTP session if RTCP cycle compled. /// </summary> internal void RtcpCycle() { m_RtcpCyclesSinceWeSent++; } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/SMTP/Server/old/SMTP_Session.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.IO; using System.Net; using System.Net.Sockets; using System.Collections; using System.Text; using LumiSoft.Net; using LumiSoft.Net.SMTP; using LumiSoft.Net.AUTH; namespace LumiSoft.Net.SMTP.Server { /// <summary> /// SMTP Session. /// </summary> public class SMTP_Session : SocketServerSession { private SMTP_Server m_pServer = null; private Stream m_pMsgStream = null; private SMTP_Cmd_Validator m_CmdValidator = null; private long m_BDAT_ReadedCount = 0; private string m_EhloName = ""; private string m_Reverse_path = ""; // Holds sender's reverse path. private Hashtable m_Forward_path = null; // Holds Mail to. private int m_BadCmdCount = 0; // Holds number of bad commands. private BodyType m_BodyType; private bool m_BDat = false; /// <summary> /// Default constructor. /// </summary> /// <param name="sessionID">Session ID.</param> /// <param name="socket">Server connected socket.</param> /// <param name="bindInfo">BindInfo what accepted socket.</param> /// <param name="server">Reference to server.</param> internal SMTP_Session(string sessionID,SocketEx socket,IPBindInfo bindInfo,SMTP_Server server) : base(sessionID,socket,bindInfo,server) { m_pServer = server; m_BodyType = BodyType.x7_bit; m_Forward_path = new Hashtable(); m_CmdValidator = new SMTP_Cmd_Validator(); // Start session proccessing StartSession(); } #region method StartSession /// <summary> /// Starts session. /// </summary> private void StartSession() { // Add session to session list m_pServer.AddSession(this); try{ // Check if ip is allowed to connect this computer ValidateIP_EventArgs oArg = m_pServer.OnValidate_IpAddress(this); if(oArg.Validated){ //--- Dedicated SSL connection, switch to SSL -----------------------------------// if(this.BindInfo.SslMode == SslMode.SSL){ try{ this.Socket.SwitchToSSL(this.BindInfo.Certificate); if(this.Socket.Logger != null){ this.Socket.Logger.AddTextEntry("SSL negotiation completed successfully."); } } catch(Exception x){ if(this.Socket.Logger != null){ this.Socket.Logger.AddTextEntry("SSL handshake failed ! " + x.Message); EndSession(); return; } } } //-------------------------------------------------------------------------------// if(!string.IsNullOrEmpty(m_pServer.GreetingText)){ this.Socket.WriteLine("220 " + m_pServer.GreetingText); } else{ this.Socket.WriteLine("220 " + Net_Utils.GetLocalHostName(this.BindInfo.HostName) + " SMTP Server ready"); } BeginRecieveCmd(); } else{ // There is user specified error text, send it to connected socket if(oArg.ErrorText.Length > 0){ this.Socket.WriteLine(oArg.ErrorText); } EndSession(); } } catch(Exception x){ OnError(x); } } #endregion #region method EndSession /// <summary> /// Ends session, closes socket. /// </summary> private void EndSession() { try{ try{ // Message storing not completed successfully, otherwise it must be null here. // This can happen if BDAT -> QUIT and LAST BDAT block wasn't sent or // when session times out on DATA or BDAT command. if(m_pMsgStream != null){ // We must call that method to notify Message stream owner to close/dispose that stream. m_pServer.OnMessageStoringCompleted(this,"Message storing not completed successfully",m_pMsgStream); m_pMsgStream = null; } } catch{ } if(this.Socket != null){ // Write logs to log file, if needed if(m_pServer.LogCommands){ this.Socket.Logger.Flush(); } this.Socket.Shutdown(SocketShutdown.Both); this.Socket.Disconnect(); //this.Socket = null; } } catch{ // We don't need to check errors here, because they only may be Socket closing errors. } finally{ m_pServer.RemoveSession(this); } } #endregion #region method Kill /// <summary> /// Kill this session. /// </summary> public override void Kill() { EndSession(); } #endregion #region method OnSessionTimeout /// <summary> /// Is called by server when session has timed out. /// </summary> internal protected override void OnSessionTimeout() { try{ this.Socket.WriteLine("421 Session timeout, closing transmission channel"); } catch{ } EndSession(); } #endregion #region method OnError /// <summary> /// Is called when error occures. /// </summary> /// <param name="x"></param> private void OnError(Exception x) { try{ // We must see InnerException too, SocketException may be as inner exception. SocketException socketException = null; if(x is SocketException){ socketException = (SocketException)x; } else if(x.InnerException != null && x.InnerException is SocketException){ socketException = (SocketException)x.InnerException; } if(socketException != null){ // Client disconnected without shutting down. if(socketException.ErrorCode == 10054 || socketException.ErrorCode == 10053){ if(m_pServer.LogCommands){ this.Socket.Logger.AddTextEntry("Client aborted/disconnected"); } EndSession(); // Exception handled, return return; } // Connection timed out. else if(socketException.ErrorCode == 10060){ if(m_pServer.LogCommands){ this.Socket.Logger.AddTextEntry("Connection timeout."); } EndSession(); // Exception handled, return return; } } m_pServer.OnSysError("",x); } catch(Exception ex){ m_pServer.OnSysError("",ex); } } #endregion #region method BeginRecieveCmd /// <summary> /// Starts recieveing command. /// </summary> private void BeginRecieveCmd() { MemoryStream strm = new MemoryStream(); this.Socket.BeginReadLine(strm,1024,strm,new SocketCallBack(this.EndRecieveCmd)); } #endregion #region method EndRecieveCmd /// <summary> /// Is called if command is recieved. /// </summary> /// <param name="result"></param> /// <param name="count"></param> /// <param name="exception"></param> /// <param name="tag"></param> private void EndRecieveCmd(SocketCallBackResult result,long count,Exception exception,object tag) { try{ switch(result) { case SocketCallBackResult.Ok: MemoryStream strm = (MemoryStream)tag; string cmdLine = System.Text.Encoding.Default.GetString(strm.ToArray()); // Exceute command if(SwitchCommand(cmdLine)){ // Session end, close session EndSession(); } break; case SocketCallBackResult.LengthExceeded: this.Socket.WriteLine("500 Line too long."); BeginRecieveCmd(); break; case SocketCallBackResult.SocketClosed: EndSession(); break; case SocketCallBackResult.Exception: OnError(exception); break; } } catch(ReadException x){ if(x.ReadReplyCode == ReadReplyCode.LengthExceeded){ this.Socket.WriteLine("500 Line too long."); BeginRecieveCmd(); } else if(x.ReadReplyCode == ReadReplyCode.SocketClosed){ EndSession(); } else if(x.ReadReplyCode == ReadReplyCode.UnKnownError){ OnError(x); } } catch(Exception x){ OnError(x); } } #endregion #region method SwitchCommand /// <summary> /// Executes SMTP command. /// </summary> /// <param name="SMTP_commandTxt">Original command text.</param> /// <returns>Returns true if must end session(command loop).</returns> private bool SwitchCommand(string SMTP_commandTxt) { //---- Parse command --------------------------------------------------// string[] cmdParts = SMTP_commandTxt.TrimStart().Split(new char[]{' '}); string SMTP_command = cmdParts[0].ToUpper().Trim(); string argsText = Core.GetArgsText(SMTP_commandTxt,SMTP_command); //---------------------------------------------------------------------// bool getNextCmd = true; switch(SMTP_command) { case "HELO": HELO(argsText); getNextCmd = false; break; case "EHLO": EHLO(argsText); getNextCmd = false; break; case "STARTTLS": STARTTLS(argsText); getNextCmd = false; break; case "AUTH": AUTH(argsText); break; case "MAIL": MAIL(argsText); getNextCmd = false; break; case "RCPT": RCPT(argsText); getNextCmd = false; break; case "DATA": BeginDataCmd(argsText); getNextCmd = false; break; case "BDAT": BeginBDATCmd(argsText); getNextCmd = false; break; case "RSET": RSET(argsText); getNextCmd = false; break; // case "VRFY": // VRFY(); // break; // case "EXPN": // EXPN(); // break; case "HELP": HELP(); break; case "NOOP": NOOP(); getNextCmd = false; break; case "QUIT": QUIT(argsText); getNextCmd = false; return true; default: this.Socket.WriteLine("500 command unrecognized"); //---- Check that maximum bad commands count isn't exceeded ---------------// if(m_BadCmdCount > m_pServer.MaxBadCommands-1){ this.Socket.WriteLine("421 Too many bad commands, closing transmission channel"); return true; } m_BadCmdCount++; //-------------------------------------------------------------------------// break; } if(getNextCmd){ BeginRecieveCmd(); } return false; } #endregion #region method HELO private void HELO(string argsText) { /* Rfc 2821 192.168.127.12 These commands, and a "250 OK" reply to one of them, confirm that both the SMTP client and the SMTP server are in the initial state, that is, there is no transaction in progress and all state tables and buffers are cleared. Arguments: Host name. Syntax: "HELO" SP Domain CRLF */ m_EhloName = argsText; ResetState(); this.Socket.BeginWriteLine("250 " + Net_Utils.GetLocalHostName(this.BindInfo.HostName) + " Hello [" + this.RemoteEndPoint.Address.ToString() + "]",new SocketCallBack(this.EndSend)); m_CmdValidator.Helo_ok = true; } #endregion #region method EHLO private void EHLO(string argsText) { /* Rfc 2821 192.168.127.12 These commands, and a "250 OK" reply to one of them, confirm that both the SMTP client and the SMTP server are in the initial state, that is, there is no transaction in progress and all state tables and buffers are cleared. */ m_EhloName = argsText; ResetState(); //--- Construct supported AUTH types value ----------------------------// string authTypesString = ""; if((m_pServer.SupportedAuthentications & SaslAuthTypes.Login) != 0){ authTypesString += "LOGIN "; } if((m_pServer.SupportedAuthentications & SaslAuthTypes.Cram_md5) != 0){ authTypesString += "CRAM-MD5 "; } if((m_pServer.SupportedAuthentications & SaslAuthTypes.Digest_md5) != 0){ authTypesString += "DIGEST-MD5 "; } authTypesString = authTypesString.Trim(); //-----------------------------------------------------------------------// string reply = ""; reply += "250-" + Net_Utils.GetLocalHostName(this.BindInfo.HostName) + " Hello [" + this.RemoteEndPoint.Address.ToString() + "]\r\n"; reply += "250-PIPELINING\r\n"; reply += "250-SIZE " + m_pServer.MaxMessageSize + "\r\n"; // reply += "250-DSN\r\n"; // reply += "250-HELP\r\n"; reply += "250-8BITMIME\r\n"; reply += "250-BINARYMIME\r\n"; reply += "250-CHUNKING\r\n"; if(authTypesString.Length > 0){ reply += "250-AUTH " + authTypesString + "\r\n"; } if(!this.Socket.SSL && this.BindInfo.Certificate != null){ reply += "250-STARTTLS\r\n"; } reply += "250 Ok\r\n"; this.Socket.BeginWriteLine(reply,null,new SocketCallBack(this.EndSend)); m_CmdValidator.Helo_ok = true; } #endregion #region method STARTTLS private void STARTTLS(string argsText) { /* RFC 2487 STARTTLS 5. STARTTLS Command. The format for the STARTTLS command is: STARTTLS with no parameters. After the client gives the STARTTLS command, the server responds with one of the following reply codes: 220 Ready to start TLS 501 Syntax error (no parameters allowed) 454 TLS not available due to temporary reason 5.2 Result of the STARTTLS Command Upon completion of the TLS handshake, the SMTP protocol is reset to the initial state (the state in SMTP after a server issues a 220 service ready greeting). */ if(this.Socket.SSL){ this.Socket.WriteLine("500 TLS already started !"); return; } if(this.BindInfo.Certificate == null){ this.Socket.WriteLine("454 TLS not available, SSL certificate isn't specified !"); return; } this.Socket.WriteLine("220 Ready to start TLS"); try{ this.Socket.SwitchToSSL(this.BindInfo.Certificate); if(m_pServer.LogCommands){ this.Socket.Logger.AddTextEntry("TLS negotiation completed successfully."); } } catch(Exception x){ this.Socket.WriteLine("500 TLS handshake failed ! " + x.Message); } ResetState(); BeginRecieveCmd(); } #endregion #region method AUTH private void AUTH(string argsText) { /* Rfc 2554 AUTH --------------------------------------------------// Restrictions: After an AUTH command has successfully completed, no more AUTH commands may be issued in the same session. After a successful AUTH command completes, a server MUST reject any further AUTH commands with a 503 reply. Remarks: If an AUTH command fails, the server MUST behave the same as if the client had not issued the AUTH command. */ if(this.Authenticated){ this.Socket.WriteLine("503 already authenticated"); return; } try{ //------ Parse parameters -------------------------------------// string userName = ""; string password = ""; AuthUser_EventArgs aArgs = null; string[] param = argsText.Split(new char[]{' '}); switch(param[0].ToUpper()) { case "PLAIN": this.Socket.WriteLine("504 Unrecognized authentication type."); break; case "LOGIN": #region LOGIN authentication //---- AUTH = LOGIN ------------------------------ /* Login C: AUTH LOGIN S: 334 VXNlcm5hbWU6 C: username_in_base64 S: 334 UGFzc3dvcmQ6 C: password_in_base64 or (initial-response argument included to avoid one 334 server response) C: AUTH LOGIN username_in_base64 S: 334 UGFzc3dvcmQ6 C: password_in_base64 VXNlcm5hbWU6 base64_decoded= USERNAME UGFzc3dvcmQ6 base64_decoded= PASSWORD */ // Note: all strings are base64 strings eg. VXNlcm5hbWU6 = UserName. // No user name included (initial-response argument) if(param.Length == 1){ // Query UserName this.Socket.WriteLine("334 VXNlcm5hbWU6"); string userNameLine = this.Socket.ReadLine(); // Encode username from base64 if(userNameLine.Length > 0){ userName = System.Text.Encoding.Default.GetString(Convert.FromBase64String(userNameLine)); } } // User name included, use it else{ userName = System.Text.Encoding.Default.GetString(Convert.FromBase64String(param[1])); } // Query Password this.Socket.WriteLine("334 UGFzc3dvcmQ6"); string passwordLine = this.Socket.ReadLine(); // Encode password from base64 if(passwordLine.Length > 0){ password = System.Text.Encoding.Default.GetString(Convert.FromBase64String(passwordLine)); } aArgs = m_pServer.OnAuthUser(this,userName,password,"",AuthType.Plain); if(aArgs.Validated){ this.Socket.WriteLine("235 Authentication successful."); this.SetUserName(userName); } else{ this.Socket.WriteLine("535 Authentication failed"); } #endregion break; case "CRAM-MD5": #region CRAM-MD5 authentication /* Cram-M5 C: AUTH CRAM-MD5 S: 334 <md5_calculation_hash_in_base64> C: base64(username password_hash) */ string md5Hash = "<" + Guid.NewGuid().ToString().ToLower() + ">"; this.Socket.WriteLine("334 " + Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes(md5Hash))); string reply = this.Socket.ReadLine(); reply = System.Text.Encoding.Default.GetString(Convert.FromBase64String(reply)); string[] replyArgs = reply.Split(' '); userName = replyArgs[0]; aArgs = m_pServer.OnAuthUser(this,userName,replyArgs[1],md5Hash,AuthType.CRAM_MD5); if(aArgs.Validated){ this.Socket.WriteLine("235 Authentication successful."); this.SetUserName(userName); } else{ this.Socket.WriteLine("535 Authentication failed"); } #endregion break; case "DIGEST-MD5": #region DIGEST-MD5 authentication /* RFC 2831 AUTH DIGEST-MD5 * * Example: * * C: AUTH DIGEST-MD5 * S: 334 base64(realm="elwood.innosoft.com",nonce="OA6MG9tEQGm2hh",qop="auth",algorithm=md5-sess) * C: base64(username="chris",realm="elwood.innosoft.com",nonce="OA6MG9tEQGm2hh", * nc=00000001,cnonce="OA6MHXh6VqTrRk",digest-uri="smtp/elwood.innosoft.com", * response=d388dad90d4bbd760a152321f2143af7,qop=auth) * S: 334 base64(rspauth=ea40f60335c427b5527b84dbabcdfffd) * C: * S: 235 Authentication successful. */ string nonce = Auth_HttpDigest.CreateNonce(); string opaque = Auth_HttpDigest.CreateOpaque(); Auth_HttpDigest digest = new Auth_HttpDigest(this.BindInfo.HostName,nonce,opaque); digest.Algorithm = "md5-sess"; this.Socket.WriteLine("334 " + AuthHelper.Base64en(digest.ToChallange(false))); string clientResponse = AuthHelper.Base64de(this.Socket.ReadLine()); digest = new Auth_HttpDigest(clientResponse,"AUTHENTICATE"); // Check that realm,nonce and opaque in client response are same as we specified. if(this.BindInfo.HostName != digest.Realm){ this.Socket.WriteLine("535 Authentication failed, 'realm' won't match."); return; } if(nonce != digest.Nonce){ this.Socket.WriteLine("535 Authentication failed, 'nonce' won't match."); return; } if(opaque != digest.Opaque){ this.Socket.WriteLine("535 Authentication failed, 'opaque' won't match."); return; } userName = digest.UserName; aArgs = m_pServer.OnAuthUser(this,userName,digest.Response,clientResponse,AuthType.DIGEST_MD5); if(aArgs.Validated){ // Send server computed password hash this.Socket.WriteLine("334 " + AuthHelper.Base64en("rspauth=" + aArgs.ReturnData)); // We must got empty line here clientResponse = this.Socket.ReadLine(); if(clientResponse == ""){ this.Socket.WriteLine("235 Authentication successful."); this.SetUserName(userName); } else{ this.Socket.WriteLine("535 Authentication failed, unexpected client response."); } } else{ this.Socket.WriteLine("535 Authentication failed."); } #endregion break; default: this.Socket.WriteLine("504 Unrecognized authentication type."); break; } //-----------------------------------------------------------------// } catch{ this.Socket.WriteLine("535 Authentication failed."); } } #endregion #region method MAIL private void MAIL(string argsText) { /* RFC 2821 3.3 NOTE: This command tells the SMTP-receiver that a new mail transaction is starting and to reset all its state tables and buffers, including any recipients or mail data. The <reverse-path> portion of the first or only argument contains the source mailbox (between "<" and ">" brackets), which can be used to report errors (see section 4.2 for a discussion of error reporting). If accepted, the SMTP server returns a 250 OK reply. MAIL FROM:<reverse-path> [SP <mail-parameters> ] <CRLF> reverse-path = "<" [ A-d-l ":" ] Mailbox ">" Mailbox = Local-part "@" Domain body-value ::= "7BIT" / "8BITMIME" / "BINARYMIME" Examples: C: MAIL FROM:<<EMAIL>> C: MAIL FROM:<<EMAIL>> SIZE=500000 BODY=8BITMIME AUTH=xxxx */ if(!m_CmdValidator.MayHandle_MAIL){ if(m_CmdValidator.MailFrom_ok){ this.Socket.BeginWriteLine("503 Sender already specified",new SocketCallBack(this.EndSend)); } else{ this.Socket.BeginWriteLine("503 Bad sequence of commands",new SocketCallBack(this.EndSend)); } return; } //------ Parse parameters -------------------------------------------------------------------// string senderEmail = ""; long messageSize = 0; BodyType bodyType = BodyType.x7_bit; bool isFromParam = false; // Parse while all params parsed or while is breaked while(argsText.Length > 0){ if(argsText.ToLower().StartsWith("from:")){ // Remove from: argsText = argsText.Substring(5).Trim(); // If there is more parameters if(argsText.IndexOf(" ") > -1){ senderEmail = argsText.Substring(0,argsText.IndexOf(" ")); argsText = argsText.Substring(argsText.IndexOf(" ")).Trim(); } else{ senderEmail = argsText; argsText = ""; } // If address between <>, remove <> if(senderEmail.StartsWith("<") && senderEmail.EndsWith(">")){ senderEmail = senderEmail.Substring(1,senderEmail.Length - 2); } isFromParam = true; } else if(argsText.ToLower().StartsWith("size=")){ // Remove size= argsText = argsText.Substring(5).Trim(); string sizeS = ""; // If there is more parameters if(argsText.IndexOf(" ") > -1){ sizeS = argsText.Substring(0,argsText.IndexOf(" ")); argsText = argsText.Substring(argsText.IndexOf(" ")).Trim(); } else{ sizeS = argsText; argsText = ""; } // See if value ok if(Core.IsNumber(sizeS)){ messageSize = Convert.ToInt64(sizeS); } else{ this.Socket.BeginWriteLine("501 SIZE parameter value is invalid. Syntax:{MAIL FROM:<address> [SIZE=msgSize] [BODY=8BITMIME]}",new SocketCallBack(this.EndSend)); return; } } else if(argsText.ToLower().StartsWith("body=")){ // Remove body= argsText = argsText.Substring(5).Trim(); string bodyTypeS = ""; // If there is more parameters if(argsText.IndexOf(" ") > -1){ bodyTypeS = argsText.Substring(0,argsText.IndexOf(" ")); argsText = argsText.Substring(argsText.IndexOf(" ")).Trim(); } else{ bodyTypeS = argsText; argsText = ""; } // See if value ok switch(bodyTypeS.ToUpper()) { case "7BIT": bodyType = BodyType.x7_bit; break; case "8BITMIME": bodyType = BodyType.x8_bit; break; case "BINARYMIME": bodyType = BodyType.binary; break; default: this.Socket.BeginWriteLine("501 BODY parameter value is invalid. Syntax:{MAIL FROM:<address> [BODY=(7BIT/8BITMIME)]}",new SocketCallBack(this.EndSend)); return; } } else if(argsText.ToLower().StartsWith("auth=")){ // Currently just eat AUTH keyword // Remove auth= argsText = argsText.Substring(5).Trim(); string authS = ""; // If there is more parameters if(argsText.IndexOf(" ") > -1){ authS = argsText.Substring(0,argsText.IndexOf(" ")); argsText = argsText.Substring(argsText.IndexOf(" ")).Trim(); } else{ authS = argsText; argsText = ""; } } else{ this.Socket.BeginWriteLine("501 Error in parameters. Syntax:{MAIL FROM:<address> [SIZE=msgSize] [BODY=8BITMIME]}",new SocketCallBack(this.EndSend)); return; } } // If required parameter 'FROM:' is missing if(!isFromParam){ this.Socket.BeginWriteLine("501 Required param FROM: is missing. Syntax:{MAIL FROM:<address> [SIZE=msgSize] [BODY=8BITMIME]}",new SocketCallBack(this.EndSend)); return; } //---------------------------------------------------------------------------------------------// //--- Check message size if(m_pServer.MaxMessageSize > messageSize){ // Check if sender is ok ValidateSender_EventArgs eArgs = m_pServer.OnValidate_MailFrom(this,senderEmail,senderEmail); if(eArgs.Validated){ // See note above ResetState(); // Store reverse path m_Reverse_path = senderEmail; m_CmdValidator.MailFrom_ok = true; //-- Store params m_BodyType = bodyType; this.Socket.BeginWriteLine("250 OK <" + senderEmail + "> Sender ok",new SocketCallBack(this.EndSend)); } else{ if(eArgs.ErrorText != null && eArgs.ErrorText.Length > 0){ this.Socket.BeginWriteLine("550 " + eArgs.ErrorText,new SocketCallBack(this.EndSend)); } else{ this.Socket.BeginWriteLine("550 You are refused to send mail here",new SocketCallBack(this.EndSend)); } } } else{ this.Socket.BeginWriteLine("552 Message exceeds allowed size",new SocketCallBack(this.EndSend)); } } #endregion #region method RCPT private void RCPT(string argsText) { /* RFC 2821 4.1.1.3 RCPT NOTE: This command is used to identify an individual recipient of the mail data; multiple recipients are specified by multiple use of this command. The argument field contains a forward-path and may contain optional parameters. Relay hosts SHOULD strip or ignore source routes, and names MUST NOT be copied into the reverse-path. Example: RCPT TO:<@hosta.int,@jkl.org:<EMAIL>> will normally be sent directly on to host d.bar.org with envelope commands RCPT TO:<<EMAIL>> RCPT TO:<<EMAIL>> SIZE=40000 RCPT TO:<forward-path> [ SP <rcpt-parameters> ] <CRLF> */ /* RFC 2821 3.3 If a RCPT command appears without a previous MAIL command, the server MUST return a 503 "Bad sequence of commands" response. */ if(!m_CmdValidator.MayHandle_RCPT || m_BDat){ this.Socket.BeginWriteLine("503 Bad sequence of commands",new SocketCallBack(this.EndSend)); return; } // Check that recipient count isn't exceeded if(m_Forward_path.Count > m_pServer.MaxRecipients){ this.Socket.BeginWriteLine("452 Too many recipients",new SocketCallBack(this.EndSend)); return; } //------ Parse parameters -------------------------------------------------------------------// string recipientEmail = ""; long messageSize = 0; bool isToParam = false; // Parse while all params parsed or while is breaked while(argsText.Length > 0){ if(argsText.ToLower().StartsWith("to:")){ // Remove to: argsText = argsText.Substring(3).Trim(); // If there is more parameters if(argsText.IndexOf(" ") > -1){ recipientEmail = argsText.Substring(0,argsText.IndexOf(" ")); argsText = argsText.Substring(argsText.IndexOf(" ")).Trim(); } else{ recipientEmail = argsText; argsText = ""; } // If address between <>, remove <> if(recipientEmail.StartsWith("<") && recipientEmail.EndsWith(">")){ recipientEmail = recipientEmail.Substring(1,recipientEmail.Length - 2); } // See if value ok if(recipientEmail.Length == 0){ this.Socket.BeginWriteLine("501 Recipient address isn't specified. Syntax:{RCPT TO:<address> [SIZE=msgSize]}",new SocketCallBack(this.EndSend)); return; } isToParam = true; } else if(argsText.ToLower().StartsWith("size=")){ // Remove size= argsText = argsText.Substring(5).Trim(); string sizeS = ""; // If there is more parameters if(argsText.IndexOf(" ") > -1){ sizeS = argsText.Substring(0,argsText.IndexOf(" ")); argsText = argsText.Substring(argsText.IndexOf(" ")).Trim(); } else{ sizeS = argsText; argsText = ""; } // See if value ok if(Core.IsNumber(sizeS)){ messageSize = Convert.ToInt64(sizeS); } else{ this.Socket.BeginWriteLine("501 SIZE parameter value is invalid. Syntax:{RCPT TO:<address> [SIZE=msgSize]}",new SocketCallBack(this.EndSend)); return; } } else{ this.Socket.BeginWriteLine("501 Error in parameters. Syntax:{RCPT TO:<address> [SIZE=msgSize]}",new SocketCallBack(this.EndSend)); return; } } // If required parameter 'TO:' is missing if(!isToParam){ this.Socket.BeginWriteLine("501 Required param TO: is missing. Syntax:<RCPT TO:{address> [SIZE=msgSize]}",new SocketCallBack(this.EndSend)); return; } //---------------------------------------------------------------------------------------------// // Check message size if(m_pServer.MaxMessageSize > messageSize){ // Check if email address is ok ValidateRecipient_EventArgs rcpt_args = m_pServer.OnValidate_MailTo(this,recipientEmail,recipientEmail,this.Authenticated); if(rcpt_args.Validated){ // Check if mailbox size isn't exceeded if(m_pServer.Validate_MailBoxSize(this,recipientEmail,messageSize)){ // Store reciptient if(!m_Forward_path.Contains(recipientEmail)){ m_Forward_path.Add(recipientEmail,recipientEmail); } m_CmdValidator.RcptTo_ok = true; this.Socket.BeginWriteLine("250 OK <" + recipientEmail + "> Recipient ok",new SocketCallBack(this.EndSend)); } else{ this.Socket.BeginWriteLine("552 Mailbox size limit exceeded",new SocketCallBack(this.EndSend)); } } // Recipient rejected else{ if(rcpt_args.LocalRecipient){ this.Socket.BeginWriteLine("550 <" + recipientEmail + "> No such user here",new SocketCallBack(this.EndSend)); } else{ this.Socket.BeginWriteLine("550 <" + recipientEmail + "> Relay not allowed",new SocketCallBack(this.EndSend)); } } } else{ this.Socket.BeginWriteLine("552 Message exceeds allowed size",new SocketCallBack(this.EndSend)); } } #endregion #region method DATA #region method BeginDataCmd private void BeginDataCmd(string argsText) { /* RFC 2821 4.1.1 NOTE: Several commands (RSET, DATA, QUIT) are specified as not permitting parameters. In the absence of specific extensions offered by the server and accepted by the client, clients MUST NOT send such parameters and servers SHOULD reject commands containing them as having invalid syntax. */ if(argsText.Length > 0){ this.Socket.BeginWriteLine("500 Syntax error. Syntax:{DATA}",new SocketCallBack(this.EndSend)); return; } /* RFC 2821 4.1.1.4 DATA NOTE: If accepted, the SMTP server returns a 354 Intermediate reply and considers all succeeding lines up to but not including the end of mail data indicator to be the message text. When the end of text is successfully received and stored the SMTP-receiver sends a 250 OK reply. The mail data is terminated by a line containing only a period, that is, the character sequence "<CRLF>.<CRLF>" (see section 4.5.2). This is the end of mail data indication. When the SMTP server accepts a message either for relaying or for final delivery, it inserts a trace record (also referred to interchangeably as a "time stamp line" or "Received" line) at the top of the mail data. This trace record indicates the identity of the host that sent the message, the identity of the host that received the message (and is inserting this time stamp), and the date and time the message was received. Relayed messages will have multiple time stamp lines. Details for formation of these lines, including their syntax, is specified in section 4.4. */ /* RFC 2821 DATA NOTE: If there was no MAIL, or no RCPT, command, or all such commands were rejected, the server MAY return a "command out of sequence" (503) or "no valid recipients" (554) reply in response to the DATA command. */ if(!m_CmdValidator.MayHandle_DATA || m_BDat){ this.Socket.BeginWriteLine("503 Bad sequence of commands",new SocketCallBack(this.EndSend)); return; } if(m_Forward_path.Count == 0){ this.Socket.BeginWriteLine("554 no valid recipients given",new SocketCallBack(this.EndSend)); return; } // Get message store stream GetMessageStoreStream_eArgs eArgs = m_pServer.OnGetMessageStoreStream(this); m_pMsgStream = eArgs.StoreStream; // reply: 354 Start mail input this.Socket.WriteLine("354 Start mail input; end with <CRLF>.<CRLF>"); //---- Construct server headers for message----------------------------------------------------------------// string header = "Received: from " + Core.GetHostName(this.RemoteEndPoint.Address) + " (" + this.RemoteEndPoint.Address.ToString() + ")\r\n"; header += "\tby " + this.BindInfo.HostName + " with SMTP; " + DateTime.Now.ToUniversalTime().ToString("r",System.Globalization.DateTimeFormatInfo.InvariantInfo) + "\r\n"; byte[] headers = System.Text.Encoding.ASCII.GetBytes(header); m_pMsgStream.Write(headers,0,headers.Length); //---------------------------------------------------------------------------------------------------------// // Begin recieving data this.Socket.BeginReadPeriodTerminated(m_pMsgStream,m_pServer.MaxMessageSize,null,new SocketCallBack(this.EndDataCmd)); } #endregion #region method EndDataCmd /// <summary> /// Is called when DATA command is finnished. /// </summary> /// <param name="result"></param> /// <param name="count"></param> /// <param name="exception"></param> /// <param name="tag"></param> private void EndDataCmd(SocketCallBackResult result,long count,Exception exception,object tag) { try{ switch(result) { case SocketCallBackResult.Ok: // Notify Message stream owner that message storing completed ok. MessageStoringCompleted_eArgs oArg = m_pServer.OnMessageStoringCompleted(this,null,m_pMsgStream); if(oArg.ServerReply.ErrorReply){ this.Socket.BeginWriteLine(oArg.ServerReply.ToSmtpReply("500","Error storing message"),new SocketCallBack(this.EndSend)); } else{ this.Socket.BeginWriteLine(oArg.ServerReply.ToSmtpReply("250","OK"),new SocketCallBack(this.EndSend)); } break; case SocketCallBackResult.LengthExceeded: // We must call that method to notify Message stream owner to close/dispose that stream. m_pServer.OnMessageStoringCompleted(this,"Requested mail action aborted: exceeded storage allocation",m_pMsgStream); this.Socket.BeginWriteLine("552 Requested mail action aborted: exceeded storage allocation",new SocketCallBack(this.EndSend)); break; case SocketCallBackResult.SocketClosed: if(m_pMsgStream != null){ // We must call that method to notify Message stream owner to close/dispose that stream. m_pServer.OnMessageStoringCompleted(this,"SocketClosed",m_pMsgStream); m_pMsgStream = null; } // Stream is already closed, probably by the EndSession method, do nothing. //else{ //} EndSession(); break; case SocketCallBackResult.Exception: if(m_pMsgStream != null){ // We must call that method to notify Message stream owner to close/dispose that stream. m_pServer.OnMessageStoringCompleted(this,"Exception: " + exception.Message,m_pMsgStream); m_pMsgStream = null; } // Stream is already closed, probably by the EndSession method, do nothing. //else{ //} OnError(exception); break; } /* RFC 2821 4.1.1.4 DATA NOTE: Receipt of the end of mail data indication requires the server to process the stored mail transaction information. This processing consumes the information in the reverse-path buffer, the forward-path buffer, and the mail data buffer, and on the completion of this command these buffers are cleared. */ ResetState(); } catch(Exception x){ OnError(x); } } #endregion #endregion #region function BDAT #region method BeginBDATCmd private void BeginBDATCmd(string argsText) { /*RFC 3030 2 The BDAT verb takes two arguments.The first argument indicates the length, in octets, of the binary data chunk. The second optional argument indicates that the data chunk is the last. The message data is sent immediately after the trailing <CR> <LF> of the BDAT command line. Once the receiver-SMTP receives the specified number of octets, it will return a 250 reply code. The optional LAST parameter on the BDAT command indicates that this is the last chunk of message data to be sent. The last BDAT command MAY have a byte-count of zero indicating there is no additional data to be sent. Any BDAT command sent after the BDAT LAST is illegal and MUST be replied to with a 503 "Bad sequence of commands" reply code. The state resulting from this error is indeterminate. A RSET command MUST be sent to clear the transaction before continuing. A 250 response MUST be sent to each successful BDAT data block within a mail transaction. bdat-cmd ::= "BDAT" SP chunk-size [ SP end-marker ] CR LF chunk-size ::= 1*DIGIT end-marker ::= "LAST" */ if(!m_CmdValidator.MayHandle_BDAT){ this.Socket.BeginWriteLine("503 Bad sequence of commands",new SocketCallBack(this.EndSend)); return; } string[] param = argsText.Split(new char[]{' '}); if(param.Length > 0 && param.Length < 3){ if(Core.IsNumber(param[0])){ int countToRead = Convert.ToInt32(param[0]); // LAST specified bool lastChunk = false; if(param.Length == 2){ lastChunk = true; } // First BDAT command call. if(!m_BDat){ // Get message store stream GetMessageStoreStream_eArgs eArgs = m_pServer.OnGetMessageStoreStream(this); m_pMsgStream = eArgs.StoreStream; // Add header to first bdat block only //---- Construct server headers for message----------------------------------------------------------------// string header = "Received: from " + Core.GetHostName(this.RemoteEndPoint.Address) + " (" + this.RemoteEndPoint.Address.ToString() + ")\r\n"; header += "\tby " + this.BindInfo.HostName + " with SMTP; " + DateTime.Now.ToUniversalTime().ToString("r",System.Globalization.DateTimeFormatInfo.InvariantInfo) + "\r\n"; byte[] headers = System.Text.Encoding.ASCII.GetBytes(header); m_pMsgStream.Write(headers,0,headers.Length); //---------------------------------------------------------------------------------------------------------// } // Begin junking data, maximum allowed message size exceeded. // BDAT comman is dummy, after commandline binary data is at once follwed, // so server server must junk all data and then report error. if((m_BDAT_ReadedCount + countToRead) > m_pServer.MaxMessageSize){ this.Socket.BeginReadSpecifiedLength(new JunkingStream(),countToRead,lastChunk,new SocketCallBack(this.EndBDatCmd)); } // Begin reading data else{ this.Socket.BeginReadSpecifiedLength(m_pMsgStream,countToRead,lastChunk,new SocketCallBack(this.EndBDatCmd)); } m_BDat = true; } else{ this.Socket.BeginWriteLine("500 Syntax error. Syntax:{BDAT chunk-size [LAST]}",new SocketCallBack(this.EndSend)); } } else{ this.Socket.BeginWriteLine("500 Syntax error. Syntax:{BDAT chunk-size [LAST]}",new SocketCallBack(this.EndSend)); } } #endregion #region method EndBDatCmd private void EndBDatCmd(SocketCallBackResult result,long count,Exception exception,object tag) { try{ switch(result) { case SocketCallBackResult.Ok: m_BDAT_ReadedCount += count; // BDAT command completed, got all data junks if((bool)tag){ // Maximum allowed message size exceeded. if((m_BDAT_ReadedCount) > m_pServer.MaxMessageSize){ m_pServer.OnMessageStoringCompleted(this,"Requested mail action aborted: exceeded storage allocation",m_pMsgStream); this.Socket.BeginWriteLine("552 Requested mail action aborted: exceeded storage allocation",new SocketCallBack(this.EndSend)); } else{ // Notify Message stream owner that message storing completed ok. MessageStoringCompleted_eArgs oArg = m_pServer.OnMessageStoringCompleted(this,null,m_pMsgStream); if(oArg.ServerReply.ErrorReply){ this.Socket.BeginWriteLine(oArg.ServerReply.ToSmtpReply("500","Error storing message"),new SocketCallBack(this.EndSend)); } else{ this.Socket.BeginWriteLine(oArg.ServerReply.ToSmtpReply("250","Message(" + m_BDAT_ReadedCount + " bytes) stored ok."),new SocketCallBack(this.EndSend)); } } /* RFC 2821 4.1.1.4 DATA NOTE: Receipt of the end of mail data indication requires the server to process the stored mail transaction information. This processing consumes the information in the reverse-path buffer, the forward-path buffer, and the mail data buffer, and on the completion of this command these buffers are cleared. */ ResetState(); } // Got BDAT data block, BDAT must continue, that wasn't last data block. else{ // Maximum allowed message size exceeded. if((m_BDAT_ReadedCount) > m_pServer.MaxMessageSize){ this.Socket.BeginWriteLine("552 Requested mail action aborted: exceeded storage allocation",new SocketCallBack(this.EndSend)); } else{ this.Socket.BeginWriteLine("250 Data block of " + count + " bytes recieved OK.",new SocketCallBack(this.EndSend)); } } break; case SocketCallBackResult.SocketClosed: if(m_pMsgStream != null){ // We must call that method to notify Message stream owner to close/dispose that stream. m_pServer.OnMessageStoringCompleted(this,"SocketClosed",m_pMsgStream); m_pMsgStream = null; } // Stream is already closed, probably by the EndSession method, do nothing. //else{ //} EndSession(); return; case SocketCallBackResult.Exception: if(m_pMsgStream != null){ // We must call that method to notify Message stream owner to close/dispose that stream. m_pServer.OnMessageStoringCompleted(this,"Exception: " + exception.Message,m_pMsgStream); m_pMsgStream = null; } // Stream is already closed, probably by the EndSession method, do nothing. //else{ //} OnError(exception); return; } } catch(Exception x){ OnError(x); } } #endregion #endregion #region method RSET private void RSET(string argsText) { /* RFC 2821 4.1.1 NOTE: Several commands (RSET, DATA, QUIT) are specified as not permitting parameters. In the absence of specific extensions offered by the server and accepted by the client, clients MUST NOT send such parameters and servers SHOULD reject commands containing them as having invalid syntax. */ if(argsText.Length > 0){ this.Socket.BeginWriteLine("500 Syntax error. Syntax:{RSET}",new SocketCallBack(this.EndSend)); return; } /* RFC 2821 4.1.1.5 RESET (RSET) NOTE: This command specifies that the current mail transaction will be aborted. Any stored sender, recipients, and mail data MUST be discarded, and all buffers and state tables cleared. The receiver MUST send a "250 OK" reply to a RSET command with no arguments. */ try{ // Message storing aborted by RSET. // This can happen if BDAT -> RSET and LAST BDAT block wasn't sent. if(m_pMsgStream != null){ // We must call that method to notify Message stream owner to close/dispose that stream. m_pServer.OnMessageStoringCompleted(this,"Message storing aborted by RSET",m_pMsgStream); m_pMsgStream = null; } } catch{ } ResetState(); this.Socket.BeginWriteLine("250 OK",new SocketCallBack(this.EndSend)); } #endregion #region method VRFY private void VRFY() { /* RFC 821 VRFY Example: S: VRFY Lumi R: 250 <NAME> <<EMAIL>> S: VRFY lum R: 550 String does not match anything. */ // ToDo: Parse user, add new event for cheking user this.Socket.BeginWriteLine("502 Command not implemented",new SocketCallBack(this.EndSend)); } #endregion #region mehtod NOOP private void NOOP() { /* RFC 2821 4.1.1.9 NOOP (NOOP) NOTE: This command does not affect any parameters or previously entered commands. It specifies no action other than that the receiver send an OK reply. */ this.Socket.BeginWriteLine("250 OK",new SocketCallBack(this.EndSend)); } #endregion #region method QUIT private void QUIT(string argsText) { /* RFC 2821 4.1.1 NOTE: Several commands (RSET, DATA, QUIT) are specified as not permitting parameters. In the absence of specific extensions offered by the server and accepted by the client, clients MUST NOT send such parameters and servers SHOULD reject commands containing them as having invalid syntax. */ if(argsText.Length > 0){ this.Socket.BeginWriteLine("500 Syntax error. Syntax:<QUIT>",new SocketCallBack(this.EndSend)); return; } /* RFC 2821 4.1.1.10 QUIT (QUIT) NOTE: This command specifies that the receiver MUST send an OK reply, and then close the transmission channel. */ // reply: 221 - Close transmission cannel this.Socket.WriteLine("221 Service closing transmission channel"); // this.Socket.BeginSendLine("221 Service closing transmission channel",null); } #endregion //---- Optional commands #region function EXPN private void EXPN() { /* RFC 821 EXPN NOTE: This command asks the receiver to confirm that the argument identifies a mailing list, and if so, to return the membership of that list. The full name of the users (if known) and the fully specified mailboxes are returned in a multiline reply. Example: S: EXPN lsAll R: 250-ivar lumi <<EMAIL>> R: 250-<<EMAIL>> R: 250 <<EMAIL>> */ this.Socket.WriteLine("502 Command not implemented"); } #endregion #region function HELP private void HELP() { /* RFC 821 HELP NOTE: This command causes the receiver to send helpful information to the sender of the HELP command. The command may take an argument (e.g., any command name) and return more specific information as a response. */ this.Socket.WriteLine("502 Command not implemented"); } #endregion #region method ResetState private void ResetState() { //--- Reset variables m_BodyType = BodyType.x7_bit; m_Forward_path.Clear(); m_Reverse_path = ""; // m_Authenticated = false; // Keep AUTH m_CmdValidator.Reset(); m_CmdValidator.Helo_ok = true; m_pMsgStream = null; m_BDat = false; m_BDAT_ReadedCount = 0; } #endregion #region function EndSend /// <summary> /// Is called when asynchronous send completes. /// </summary> /// <param name="result">If true, then send was successfull.</param> /// <param name="count">Count sended.</param> /// <param name="exception">Exception happend on send. NOTE: available only is result=false.</param> /// <param name="tag">User data.</param> private void EndSend(SocketCallBackResult result,long count,Exception exception,object tag) { try{ switch(result) { case SocketCallBackResult.Ok: BeginRecieveCmd(); break; case SocketCallBackResult.SocketClosed: EndSession(); break; case SocketCallBackResult.Exception: OnError(exception); break; } } catch(Exception x){ OnError(x); } } #endregion #region Properties Implementation /// <summary> /// Gets client reported EHLO/HELO name. /// </summary> public string EhloName { get{ return m_EhloName; } } /// <summary> /// Gets body type. /// </summary> public BodyType BodyType { get{ return m_BodyType; } } /// <summary> /// Gets sender. /// </summary> public string MailFrom { get{ return m_Reverse_path; } } /// <summary> /// Gets recipients. /// </summary> public string[] MailTo { get{ string[] to = new string[m_Forward_path.Count]; m_Forward_path.Values.CopyTo(to,0); return to; } } #endregion } } <file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/TCP/TCP_Session.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.TCP { #region usings using System; using System.Net; using System.Security.Principal; using IO; #endregion /// <summary> /// This is base class for TCP_Client and TCP_ServerSession. /// </summary> public abstract class TCP_Session : IDisposable { #region Properties /// <summary> /// Gets session authenticated user identity , returns null if not authenticated. /// </summary> public virtual GenericIdentity AuthenticatedUserIdentity { get { return null; } } /// <summary> /// Gets the time when session was connected. /// </summary> public abstract DateTime ConnectTime { get; } /// <summary> /// Gets session ID. /// </summary> public abstract string ID { get; } /// <summary> /// Gets if this session is authenticated. /// </summary> public bool IsAuthenticated { get { return AuthenticatedUserIdentity != null; } } /// <summary> /// Gets if session is connected. /// </summary> public abstract bool IsConnected { get; } /// <summary> /// Gets if this session TCP connection is secure connection. /// </summary> public virtual bool IsSecureConnection { get { return false; } } /// <summary> /// Gets the last time when data was sent or received. /// </summary> public abstract DateTime LastActivity { get; } /// <summary> /// Gets session local IP end point. /// </summary> public abstract IPEndPoint LocalEndPoint { get; } /// <summary> /// Gets session remote IP end point. /// </summary> public abstract IPEndPoint RemoteEndPoint { get; } /// <summary> /// Gets TCP stream which must be used to send/receive data through this session. /// </summary> public abstract SmartStream TcpStream { get; } #endregion #region Methods /// <summary> /// Cleans up any resources being used. /// </summary> public abstract void Dispose(); /// <summary> /// Disconnects session. /// </summary> public abstract void Disconnect(); #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Autoreply/ApiService.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections.Generic; using System.Configuration; using System.IO; using System.Linq; using System.Net; using System.Net.Mime; using System.Text; using System.Web; using ASC.Common.Threading.Workers; using ASC.Core; using log4net; namespace ASC.Mail.Autoreply { internal class ApiService { private readonly ILog _log = LogManager.GetLogger(typeof(ApiService)); private readonly WorkerQueue<ApiRequest> _messageQueue = new WorkerQueue<ApiRequest>(4, TimeSpan.FromMinutes(5), 5, false); private readonly string _adressTemplate; public ApiService(bool https) { _adressTemplate = (https ? Uri.UriSchemeHttps : Uri.UriSchemeHttp) + Uri.SchemeDelimiter + "{{0}}{0}/{{1}}"; var baseDomain = CoreContext.Configuration.BaseDomain.TrimEnd('/'); if (baseDomain == "localhost") { baseDomain = string.Empty; } if (!string.IsNullOrEmpty(baseDomain) && baseDomain[0] != '.' && baseDomain[0] != '/') { baseDomain = '.' + baseDomain; } _adressTemplate = string.Format(_adressTemplate, baseDomain); } public void Start() { if (!_messageQueue.IsStarted) { _messageQueue.Start(SendMessage); } } public void Stop() { if (_messageQueue.IsStarted) { _messageQueue.Stop(); } } public void EnqueueRequest(ApiRequest request) { _log.DebugFormat("queue request \"{0}\"", request); _messageQueue.Add(request); } private void SendMessage(ApiRequest requestInfo) { try { _log.DebugFormat("begin send request {0}", requestInfo); CoreContext.TenantManager.SetCurrentTenant(requestInfo.Tenant); var authKey = SecurityContext.AuthenticateMe(requestInfo.User.ID); if (string.IsNullOrEmpty(authKey)) { _log.ErrorFormat("can't obtain authorization cookie for user {0}", requestInfo.User.ID); return; } var uri = BuildUri(requestInfo); _log.Debug(uri); _log.DebugFormat("builded uri for request {0}", uri); var request = (HttpWebRequest)WebRequest.Create(uri); request.Method = requestInfo.Method; request.AllowAutoRedirect = true; request.Headers["Authorization"] = authKey; using (var requestStream = request.GetRequestStream()) { if (requestInfo.FilesToPost != null && requestInfo.FilesToPost.Any()) { WriteMultipartRequest(request, requestStream, requestInfo); } else { WriteFormEncoded(request, requestStream, requestInfo, authKey); } } try { using (var response = request.GetResponse()) using (var responseStream = response.GetResponseStream()) { if (responseStream != null) { using (var readStream = new StreamReader(responseStream)) { _log.DebugFormat("response from server: {0}", readStream.ReadToEnd()); } } } } catch (Exception error) { _log.Error("error while getting the response", error); } _log.DebugFormat("end send request {0}", requestInfo); } catch (Exception x) { _log.Error("error while sending request", x); throw; } } private Uri BuildUri(ApiRequest requestInfo) { return new Uri(string.Format(_adressTemplate, requestInfo.Tenant.TenantAlias, requestInfo.Url.TrimStart('/'))); } private void WriteMultipartRequest(WebRequest request, Stream requestStream, ApiRequest requestInfo) { var boundaryId = DateTime.Now.Ticks.ToString("x"); var boundary = "\r\n--" + boundaryId + "\r\n"; var formdataTemplate = "\r\n--" + boundaryId + "\r\nContent-Disposition: form-data; name=\"{0}\";\r\n\r\n{1}"; if (requestInfo.Parameters != null && requestInfo.Parameters.Any()) { foreach (var parameter in requestInfo.Parameters.Where(x => x.Value != null)) { var formItem = string.Empty; if (parameter.Value is IEnumerable<object>) { foreach (var value in ((IEnumerable<object>)parameter.Value)) { formItem = string.Format(formdataTemplate, parameter.Name, value); } } else if (parameter.Value is DateTime) { formItem = string.Format(formdataTemplate, parameter.Name, ((DateTime)parameter.Value).ToString("s")); } else { formItem = string.Format(formdataTemplate, parameter.Name, parameter.Value); } if (!string.IsNullOrEmpty(formItem)) { _log.DebugFormat("writing form item boundary:{0}", formItem); WriteUtf8String(requestStream, formItem); } } } WriteUtf8String(requestStream, boundary); var files = requestInfo.FilesToPost.ToArray(); for (int i = 0; i < files.Length; i++) { WriteFile(requestStream, files[i]); if (i < files.Length - 1) WriteUtf8String(requestStream, boundary); else WriteUtf8String(requestStream, "\r\n--" + boundaryId + "--\r\n"); } request.ContentType = new ContentType("multipart/form-data") { Boundary = boundaryId }.ToString(); } private static void WriteFile(Stream requestStream, RequestFileInfo fileInfo) { var header = string.Format("Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\nContent-Transfer-Encoding: binary\r\n\r\n", Path.GetFileNameWithoutExtension(fileInfo.Name), Path.GetFileName(fileInfo.Name), fileInfo.ContentType ?? "application/octet-stream"); WriteUtf8String(requestStream, header); requestStream.Write(fileInfo.Body, 0, fileInfo.Body.Length); } private void WriteFormEncoded(WebRequest request, Stream requestStream, ApiRequest requestInfo, string authKey) { var stringBuilder = new StringBuilder(); if (requestInfo.Parameters != null && requestInfo.Parameters.Any()) { foreach (var parameter in requestInfo.Parameters.Where(x => x.Value != null)) { if (parameter.Value is IEnumerable<object>) { foreach (var value in ((IEnumerable<object>)parameter.Value)) { stringBuilder.AppendFormat("{0}[]={1}&", HttpUtility.UrlEncode(parameter.Name), HttpUtility.UrlEncode(value.ToString())); } } else if (parameter.Value is DateTime) { stringBuilder.AppendFormat("{0}={1}&", HttpUtility.UrlEncode(parameter.Name), HttpUtility.UrlEncode(((DateTime)parameter.Value).ToString("s"))); } else { stringBuilder.AppendFormat("{0}={1}&", HttpUtility.UrlEncode(parameter.Name), HttpUtility.UrlEncode(parameter.Value.ToString())); } } } stringBuilder.AppendFormat("asc_auth_key={0}", authKey); _log.DebugFormat("writing form data {0}", stringBuilder); WriteUtf8String(requestStream, stringBuilder.ToString()); request.ContentType = "application/x-www-form-urlencoded"; } private static void WriteUtf8String(Stream stream, string str) { byte[] headerbytes = Encoding.UTF8.GetBytes(str); stream.Write(headerbytes, 0, headerbytes.Length); } } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/SIP/Message/SIP_t_Info.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.SIP.Message { #region usings using System; using System.Text; #endregion /// <summary> /// Implements SIP "info" value. Defined in RFC 3261. /// </summary> /// <remarks> /// <code> /// RFC 3261 Syntax: /// info = LAQUOT absoluteURI RAQUOT *( SEMI info-param) /// info-param = ( "purpose" EQUAL ( "icon" / "info" / "card" / token ) ) / generic-param /// </code> /// </remarks> public class SIP_t_Info : SIP_t_ValueWithParams { #region Members private string m_Uri = ""; #endregion #region Properties /// <summary> /// Gets or sets 'purpose' parameter value. Value null means not specified. /// Known values: "icon","info","card". /// </summary> public string Purpose { get { SIP_Parameter parameter = Parameters["purpose"]; if (parameter != null) { return parameter.Value; } else { return null; } } set { if (string.IsNullOrEmpty(value)) { Parameters.Remove("purpose"); } else { Parameters.Set("purpose", value); } } } #endregion #region Methods /// <summary> /// Parses "info" from specified value. /// </summary> /// <param name="value">SIP "info" value.</param> /// <exception cref="ArgumentNullException">Raised when <b>value</b> is null.</exception> /// <exception cref="SIP_ParseException">Raised when invalid SIP message.</exception> public void Parse(string value) { if (value == null) { throw new ArgumentNullException("value"); } Parse(new StringReader(value)); } /// <summary> /// Parses "info" from specified reader. /// </summary> /// <param name="reader">Reader from where to parse.</param> /// <exception cref="ArgumentNullException">Raised when <b>reader</b> is null.</exception> /// <exception cref="SIP_ParseException">Raised when invalid SIP message.</exception> public override void Parse(StringReader reader) { /* Call-Info = "Call-Info" HCOLON info *(COMMA info) info = LAQUOT absoluteURI RAQUOT *( SEMI info-param) info-param = ( "purpose" EQUAL ( "icon" / "info" / "card" / token ) ) / generic-param */ if (reader == null) { throw new ArgumentNullException("reader"); } // Parse uri // Read to LAQUOT reader.QuotedReadToDelimiter('<'); if (!reader.StartsWith("<")) { throw new SIP_ParseException("Invalid Alert-Info value, Uri not between <> !"); } // Parse parameters ParseParameters(reader); } /// <summary> /// Converts this to valid "info" value. /// </summary> /// <returns>Returns "info" value.</returns> public override string ToStringValue() { StringBuilder retVal = new StringBuilder(); retVal.Append("<" + m_Uri + ">"); retVal.Append(ParametersToString()); return retVal.ToString(); } #endregion } }<file_sep>/module/ASC.Api/ASC.Api.Mail/MailApi.Alerts.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections.Generic; using ASC.Api.Attributes; using ASC.Mail.Data.Contracts; namespace ASC.Api.Mail { public partial class MailApi { /// <summary> /// Returns the list of alerts for the authenticated user /// </summary> /// <returns>Alerts list</returns> /// <short>Get alerts list</short> /// <category>Alerts</category> [Read(@"alert")] public IList<MailAlertData> GetAlerts() { return MailEngineFactory.AlertEngine.GetAlerts(); } /// <summary> /// Deletes the alert with the ID specified in the request /// </summary> /// <param name="id">Alert ID</param> /// <returns>Deleted alert id. Same as request parameter.</returns> /// <short>Delete alert by ID</short> /// <category>Alerts</category> [Delete(@"alert/{id}")] public long DeleteAlert(long id) { if(id < 0) throw new ArgumentException(@"Invalid alert id. Id must be positive integer.", "id"); var success = MailEngineFactory.AlertEngine.DeleteAlert(id); if(!success) throw new Exception("Delete failed"); return id; } } } <file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/SIP/Stack/SIP_UA_Registration.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.SIP.Stack { #region usings using System; using System.Net; using System.Timers; using Message; #endregion /// <summary> /// This class represent SIP UA registration. /// </summary> public class SIP_UA_Registration { #region Events /// <summary> /// This event is raised when registration has disposed. /// </summary> public event EventHandler Disposed = null; /// <summary> /// This event is raised when REGISTER/un-REGISTER has failed. /// </summary> public event EventHandler<SIP_ResponseReceivedEventArgs> Error = null; /// <summary> /// This event is raised when REGISTER has completed successfully. /// </summary> public event EventHandler Registered = null; /// <summary> /// This event is raised when registration state has changed. /// </summary> public event EventHandler StateChanged = null; /// <summary> /// This event is raised when un-REGISTER has completed successfully. /// </summary> public event EventHandler Unregistered = null; #endregion #region Members private readonly string m_AOR = ""; private readonly AbsoluteUri m_pContact; private readonly SIP_Uri m_pServer; private readonly int m_RefreshInterval = 300; private bool m_AutoDispose; private bool m_AutoRefresh = true; private bool m_IsDisposed; private SIP_Flow m_pFlow; private SIP_RequestSender m_pRegisterSender; private SIP_Stack m_pStack; private TimerEx m_pTimer; private SIP_RequestSender m_pUnregisterSender; private SIP_UA_RegistrationState m_State = SIP_UA_RegistrationState.Unregistered; #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="stack">Owner SIP stack.</param> /// <param name="server">Registrar server URI. For example: sip:domain.com.</param> /// <param name="aor">Address of record. For example: <EMAIL>.</param> /// <param name="contact">Contact URI.</param> /// <param name="expires">Gets after how many seconds reigisration expires.</param> /// <exception cref="ArgumentNullException">Is raised when <b>ua</b>,<b>server</b>,<b>transport</b>,<b>aor</b> or <b>contact</b> is null reference.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments contains invalid value.</exception> internal SIP_UA_Registration(SIP_Stack stack, SIP_Uri server, string aor, AbsoluteUri contact, int expires) { if (stack == null) { throw new ArgumentNullException("stack"); } if (server == null) { throw new ArgumentNullException("server"); } if (aor == null) { throw new ArgumentNullException("aor"); } if (aor == string.Empty) { throw new ArgumentException("Argument 'aor' value must be specified."); } if (contact == null) { throw new ArgumentNullException("contact"); } m_pStack = stack; m_pServer = server; m_AOR = aor; m_pContact = contact; m_RefreshInterval = expires; m_pTimer = new TimerEx((m_RefreshInterval - 15)*1000); m_pTimer.AutoReset = false; m_pTimer.Elapsed += m_pTimer_Elapsed; m_pTimer.Enabled = false; } #endregion #region Properties /// <summary> /// Gets registration address of record. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and and this property is accessed.</exception> public string AOR { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_AOR; } } /// <summary> /// If true and contact is different than received or rport, received and rport is used as contact. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and and this property is accessed.</exception> public bool AutoFixContact { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } // TODO: return false; } } /// <summary> /// Gets registration contact URI. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and and this property is accessed.</exception> public AbsoluteUri Contact { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_pContact; } } /// <summary> /// Gets after how many seconds contact expires. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and and this property is accessed.</exception> public int Expires { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return 3600; } } /// <summary> /// Gets if this object is disposed. /// </summary> public bool IsDisposed { get { return m_IsDisposed; } } /// <summary> /// Gets registration state. /// </summary> public SIP_UA_RegistrationState State { get { return m_State; } } #endregion #region Methods /// <summary> /// Cleans up any resources being used. /// </summary> public void Dispose() { if (m_IsDisposed) { return; } m_IsDisposed = true; m_pStack = null; m_pTimer.Dispose(); m_pTimer = null; SetState(SIP_UA_RegistrationState.Disposed); OnDisposed(); Registered = null; Unregistered = null; Error = null; Disposed = null; } /// <summary> /// Starts registering. /// </summary> /// <param name="autoRefresh">If true, registration takes care of refreshing itself to registrar server.</param> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and and this method is accessed.</exception> public void BeginRegister(bool autoRefresh) { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } // Fix ME: Stack not running, try register on next step. // In ideal solution we need to start registering when stack starts. if (!m_pStack.IsRunning) { m_pTimer.Enabled = true; return; } m_AutoRefresh = autoRefresh; SetState(SIP_UA_RegistrationState.Registering); /* RFC 3261 10.1 Constructing the REGISTER Request. Request-URI: The Request-URI names the domain of the location service for which the registration is meant (for example, "sip:chicago.com"). The "userinfo" and "@" components of the SIP URI MUST NOT be present. */ SIP_Request register = m_pStack.CreateRequest(SIP_Methods.REGISTER, new SIP_t_NameAddress(m_pServer.Scheme + ":" + m_AOR), new SIP_t_NameAddress(m_pServer.Scheme + ":" + m_AOR)); register.RequestLine.Uri = SIP_Uri.Parse(m_pServer.Scheme + ":" + m_AOR.Substring(m_AOR.IndexOf('@') + 1)); register.Route.Add(m_pServer.ToString()); register.Contact.Add("<" + Contact + ">;expires=" + m_RefreshInterval); m_pRegisterSender = m_pStack.CreateRequestSender(register, m_pFlow); m_pRegisterSender.ResponseReceived += m_pRegisterSender_ResponseReceived; m_pRegisterSender.Start(); } /// <summary> /// Starts unregistering. /// </summary> /// <param name="dispose">If true, registration will be disposed after unregister.</param> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and and this method is accessed.</exception> public void BeginUnregister(bool dispose) { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } m_AutoDispose = dispose; // Stop register timer, otherwise we may get register and unregister race condition. m_pTimer.Enabled = false; if (m_State == SIP_UA_RegistrationState.Registered) { /* RFC 3261 10.1 Constructing the REGISTER Request. Request-URI: The Request-URI names the domain of the location service for which the registration is meant (for example, "sip:chicago.com"). The "userinfo" and "@" components of the SIP URI MUST NOT be present. */ SIP_Request unregister = m_pStack.CreateRequest(SIP_Methods.REGISTER, new SIP_t_NameAddress(m_pServer.Scheme + ":" + m_AOR), new SIP_t_NameAddress(m_pServer.Scheme + ":" + m_AOR)); unregister.RequestLine.Uri = SIP_Uri.Parse(m_pServer.Scheme + ":" + m_AOR.Substring(m_AOR.IndexOf('@') + 1)); unregister.Route.Add(m_pServer.ToString()); unregister.Contact.Add("<" + Contact + ">;expires=0"); m_pUnregisterSender = m_pStack.CreateRequestSender(unregister, m_pFlow); m_pUnregisterSender.ResponseReceived += m_pUnregisterSender_ResponseReceived; m_pUnregisterSender.Start(); } else { SetState(SIP_UA_RegistrationState.Unregistered); OnUnregistered(); if (m_AutoDispose) { Dispose(); } m_pUnregisterSender = null; } } #endregion #region Utility methods /// <summary> /// This method is raised when registration needs to refresh server registration. /// </summary> /// <param name="sender">Sender.</param> /// <param name="e">Event data.</param> private void m_pTimer_Elapsed(object sender, ElapsedEventArgs e) { if (m_pStack.IsRunning) { BeginRegister(m_AutoRefresh); } } /// <summary> /// This method is called when REGISTER has finished. /// </summary> /// <param name="sender">Sender.</param> /// <param name="e">Event data.</param> private void m_pRegisterSender_ResponseReceived(object sender, SIP_ResponseReceivedEventArgs e) { m_pFlow = e.ClientTransaction.Flow; if (e.Response.StatusCodeType == SIP_StatusCodeType.Success) { SetState(SIP_UA_RegistrationState.Registered); OnRegistered(); m_pFlow.SendKeepAlives = true; } else { SetState(SIP_UA_RegistrationState.Error); OnError(e); } // REMOVE ME: if (AutoFixContact && (m_pContact is SIP_Uri)) { // If Via: received or rport paramter won't match to our sent-by, use received and rport to construct new contact value. SIP_Uri cContact = ((SIP_Uri) m_pContact); IPAddress cContactIP = Net_Utils.IsIPAddress(cContact.Host) ? IPAddress.Parse(cContact.Host) : null; SIP_t_ViaParm via = e.Response.Via.GetTopMostValue(); if (via != null && cContactIP != null) { IPEndPoint ep = new IPEndPoint(via.Received != null ? via.Received : cContactIP, via.RPort > 0 ? via.RPort : cContact.Port); if (!cContactIP.Equals(ep.Address) || cContact.Port != via.RPort) { // Unregister old contact. BeginUnregister(false); // Fix contact. cContact.Host = ep.Address.ToString(); cContact.Port = ep.Port; m_pRegisterSender.Dispose(); m_pRegisterSender = null; BeginRegister(m_AutoRefresh); return; } } } if (m_AutoRefresh) { // Set registration refresh timer. m_pTimer.Enabled = true; } m_pRegisterSender.Dispose(); m_pRegisterSender = null; } /// <summary> /// This method is called when un-REGISTER has finished. /// </summary> /// <param name="sender">Sender.</param> /// <param name="e">Event data.</param> private void m_pUnregisterSender_ResponseReceived(object sender, SIP_ResponseReceivedEventArgs e) { SetState(SIP_UA_RegistrationState.Unregistered); OnUnregistered(); if (m_AutoDispose) { Dispose(); } m_pUnregisterSender = null; } /// <summary> /// Changes current registration state. /// </summary> /// <param name="newState">New registration state.</param> private void SetState(SIP_UA_RegistrationState newState) { m_State = newState; OnStateChanged(); } /// <summary> /// Raises event <b>StateChanged</b>. /// </summary> private void OnStateChanged() { if (StateChanged != null) { StateChanged(this, new EventArgs()); } } /// <summary> /// Raises event <b>Registered</b>. /// </summary> private void OnRegistered() { if (Registered != null) { Registered(this, new EventArgs()); } } /// <summary> /// Raises event <b>Unregistered</b>. /// </summary> private void OnUnregistered() { if (Unregistered != null) { Unregistered(this, new EventArgs()); } } /// <summary> /// Raises event <b>Error</b>. /// </summary> /// <param name="e">Event data.</param> private void OnError(SIP_ResponseReceivedEventArgs e) { if (Error != null) { Error(this, e); } } /// <summary> /// Raises event <b>Disposed</b>. /// </summary> private void OnDisposed() { if (Disposed != null) { Disposed(this, new EventArgs()); } } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Autoreply/CooldownInspector.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections.Generic; using System.Linq; using System.Threading; using log4net; namespace ASC.Mail.Autoreply { internal class CooldownInspector { private readonly ILog _log = LogManager.GetLogger(typeof(CooldownInspector)); private readonly object _syncRoot = new object(); private readonly Dictionary<Guid, List<DateTime>> _lastUsagesByUser = new Dictionary<Guid, List<DateTime>>(); private readonly int _allowedRequests; private readonly TimeSpan _duringTime; private readonly TimeSpan _cooldownLength; private Timer _clearTimer; public CooldownInspector(CooldownConfigurationElement config) { _allowedRequests = config.AllowedRequests; _duringTime = config.DuringTimeInterval; _cooldownLength = config.Length; } public void Start() { if (!IsDisabled() && _clearTimer == null) { _clearTimer = new Timer(x => ClearExpiredRecords(), null, _cooldownLength, _cooldownLength); } } public void Stop() { if (_clearTimer != null) { _clearTimer.Change(Timeout.Infinite, Timeout.Infinite); _clearTimer.Dispose(); _clearTimer = null; _lastUsagesByUser.Clear(); } } public TimeSpan GetCooldownRemainigTime(Guid userId) { if (IsDisabled()) return TimeSpan.Zero; lock (_syncRoot) { var lastUsages = GetLastUsages(userId); return lastUsages.Count >= _allowedRequests ? _cooldownLength - (DateTime.UtcNow - lastUsages.Max()) : TimeSpan.Zero; } } public void RegisterServiceUsage(Guid userId) { if (IsDisabled()) return; lock (_syncRoot) { var lastUsages = GetLastUsages(userId); lastUsages.Add(DateTime.UtcNow); _lastUsagesByUser[userId] = lastUsages; } } private void ClearExpiredRecords() { lock (_syncRoot) { _log.Debug("start clearing expired usage records"); try { foreach (var userId in _lastUsagesByUser.Keys.ToList()) { _lastUsagesByUser[userId] = GetLastUsages(userId); if (_lastUsagesByUser[userId].Count == 0) _lastUsagesByUser.Remove(userId); } } catch (Exception error) { _log.Error("error while clearing expired usage records", error); } } } private List<DateTime> GetLastUsages(Guid userId) { if (!_lastUsagesByUser.ContainsKey(userId)) return new List<DateTime>(); return _lastUsagesByUser[userId] .Where(timestamp => timestamp > DateTime.UtcNow - _duringTime) .OrderByDescending(timestamp => timestamp) .Take(_allowedRequests) .ToList(); } private bool IsDisabled() { return _allowedRequests <= 0 || _duringTime <= TimeSpan.Zero || _cooldownLength <= TimeSpan.Zero; } } } <file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/SIP/Proxy/SIP_Registration.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.SIP.Proxy { #region usings using System; using System.Collections.Generic; using Message; using Stack; #endregion /// <summary> /// This class implements SIP registrar registration entry. Defined in RFC 3261 10.3. /// </summary> public class SIP_Registration { #region Members private readonly string m_AOR = ""; private readonly DateTime m_CreateTime; private readonly List<SIP_RegistrationBinding> m_pBindings; private readonly object m_pLock = new object(); private readonly string m_UserName = ""; #endregion #region Properties /// <summary> /// Gets time when this registration entry was created. /// </summary> public DateTime CreateTime { get { return m_CreateTime; } } /// <summary> /// Gets user name who owns this registration. /// </summary> public string UserName { get { return m_UserName; } } /// <summary> /// Gets registration address of record. /// </summary> public string AOR { get { return m_AOR; } } /// <summary> /// Gets this registration priority ordered bindings. /// </summary> public SIP_RegistrationBinding[] Bindings { get { SIP_RegistrationBinding[] retVal = m_pBindings.ToArray(); // Sort by qvalue, higer qvalue means higher priority. Array.Sort(retVal); return retVal; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="userName">User name who owns this registration.</param> /// <param name="aor">Address of record. For example: <EMAIL>.</param> /// <exception cref="ArgumentNullException">Is raised when <b>userName</b> or <b>aor</b> is null reference.</exception> public SIP_Registration(string userName, string aor) { if (userName == null) { throw new ArgumentNullException("userName"); } if (aor == null) { throw new ArgumentNullException("aor"); } if (aor == "") { throw new ArgumentException("Argument 'aor' value must be specified."); } m_UserName = userName; m_AOR = aor; m_CreateTime = DateTime.Now; m_pBindings = new List<SIP_RegistrationBinding>(); } #endregion #region Methods /// <summary> /// Gets matching binding. Returns null if no match. /// </summary> /// <param name="contactUri">URI to match.</param> /// <returns>Returns matching binding. Returns null if no match.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>contactUri</b> is null reference.</exception> public SIP_RegistrationBinding GetBinding(AbsoluteUri contactUri) { if (contactUri == null) { throw new ArgumentNullException("contactUri"); } lock (m_pLock) { foreach (SIP_RegistrationBinding binding in m_pBindings) { if (contactUri.Equals(binding.ContactURI)) { return binding; } } return null; } } /// <summary> /// Adds or updates matching bindings. /// </summary> /// <param name="flow">SIP data flow what updates this binding. This value is null if binding was not added through network or /// flow has disposed.</param> /// <param name="callID">Call-ID header field value.</param> /// <param name="cseqNo">CSeq header field sequence number value.</param> /// <param name="contacts">Contacts to add or update.</param> /// <exception cref="ArgumentNullException">Is raised when <b>callID</b> or <b>contacts</b> is null reference.</exception> public void AddOrUpdateBindings(SIP_Flow flow, string callID, int cseqNo, SIP_t_ContactParam[] contacts) { if (callID == null) { throw new ArgumentNullException("callID"); } if (cseqNo < 0) { throw new ArgumentException("Argument 'cseqNo' value must be >= 0."); } if (contacts == null) { throw new ArgumentNullException("contacts"); } lock (m_pLock) { foreach (SIP_t_ContactParam contact in contacts) { SIP_RegistrationBinding binding = GetBinding(contact.Address.Uri); // Add binding. if (binding == null) { binding = new SIP_RegistrationBinding(this, contact.Address.Uri); m_pBindings.Add(binding); } // Update binding. binding.Update(flow, contact.Expires == -1 ? 3600 : contact.Expires, contact.QValue == -1 ? 1.0 : contact.QValue, callID, cseqNo); } } } /// <summary> /// Removes specified binding. /// </summary> /// <param name="binding">Registration binding.</param> /// <exception cref="ArgumentNullException">Is raised when <b>binding</b> is null reference.</exception> public void RemoveBinding(SIP_RegistrationBinding binding) { if (binding == null) { throw new ArgumentNullException("binding"); } lock (m_pLock) { m_pBindings.Remove(binding); } } /// <summary> /// Removes all this registration bindings. /// </summary> public void RemoveAllBindings() { lock (m_pLock) { m_pBindings.Clear(); } } /// <summary> /// Removes all expired bindings. /// </summary> public void RemoveExpiredBindings() { lock (m_pLock) { for (int i = 0; i < m_pBindings.Count; i++) { if (m_pBindings[i].IsExpired) { m_pBindings.RemoveAt(i); i--; } } } } #endregion } }<file_sep>/module/ASC.Api/ASC.Api.Documents/PrivacyRoomApi.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System.Collections.Generic; using System.Web; using ASC.Api.Attributes; using ASC.Api.Interfaces; using ASC.Common.Logging; using ASC.Core; using ASC.Core.Billing; using ASC.Core.Users; using ASC.MessagingSystem; using ASC.Web.Files.Core.Entries; using ASC.Web.Studio.Core; using Resources; namespace ASC.Api.Documents { public class PrivacyRoomApi : IApiEntryPoint { public string Name { get { return "privacyroom"; } } /// <summary> /// /// </summary> /// <visible>false</visible> [Update("keys")] public object SetKeys(string publicKey, string privateKeyEnc) { SecurityContext.DemandPermissions(new UserSecurityProvider(SecurityContext.CurrentAccount.ID), Core.Users.Constants.Action_EditUser); if (!PrivacyRoomSettings.Enabled) throw new System.Security.SecurityException(); var keyPair = EncryptionKeyPair.GetKeyPair(); if (keyPair != null) { if (!string.IsNullOrEmpty(keyPair.PublicKey)) { return new { isset = true }; } LogManager.GetLogger("ASC.Api.Documents").InfoFormat("User {0} updates address", SecurityContext.CurrentAccount.ID); } EncryptionKeyPair.SetKeyPair(publicKey, privateKeyEnc); return new { isset = true }; } /// <summary> /// /// </summary> /// <visible>false</visible> [Read("access/{fileId}")] public IEnumerable<EncryptionKeyPair> GetPublicKeysWithAccess(string fileId) { if (!PrivacyRoomSettings.Enabled) throw new System.Security.SecurityException(); var fileKeyPair = EncryptionKeyPair.GetKeyPair(fileId); return fileKeyPair; } /// <summary> /// /// </summary> /// <returns></returns> /// <visible>false</visible> [Read("")] public bool PrivacyRoom() { SecurityContext.DemandPermissions(SecutiryConstants.EditPortalSettings); return PrivacyRoomSettings.Enabled; } /// <summary> /// /// </summary> /// <param name="enable"></param> /// <returns></returns> /// <visible>false</visible> [Update("")] public bool SetPrivacyRoom(bool enable) { SecurityContext.DemandPermissions(SecutiryConstants.EditPortalSettings); if (enable) { if (!PrivacyRoomSettings.Available) { throw new BillingException(Resource.ErrorNotAllowedOption, "PrivacyRoom"); } } PrivacyRoomSettings.Enabled = enable; MessageService.Send(HttpContext.Current.Request, enable ? MessageAction.PrivacyRoomEnable : MessageAction.PrivacyRoomDisable); return enable; } } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Autoreply/Utility/StringDistance.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; namespace ASC.Mail.Autoreply.Utility { public static class StringDistance { public static int LevenshteinDistance(string s, string t) { return LevenshteinDistance(s, t, true); } public static int LevenshteinDistance(string s, string t, bool ignoreCase) { if (String.IsNullOrEmpty(s)) { return String.IsNullOrEmpty(t) ? 0 : t.Length; } if (String.IsNullOrEmpty(t)) { return s.Length; } if (ignoreCase) { s = s.ToLowerInvariant(); t = t.ToLowerInvariant(); } int n = s.Length; int m = t.Length; var d = new int[n + 1, m + 1]; for (int i = 0; i <= n; d[i, 0] = i++) { } for (int j = 0; j <= m; d[0, j] = j++) { } for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { int cost = (t[j - 1] == s[i - 1]) ? 0 : 1; d[i, j] = Math.Min(Math.Min(d[i - 1, j] + 1, d[i, j - 1] + 1), d[i - 1, j - 1] + cost); } } return d[n, m]; } } } <file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/SIP/Message/SIP_t_LanguageTag.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.SIP.Message { #region usings using System; using System.Text; #endregion /// <summary> /// Implements SIP "language-tag" value. Defined in RFC 3261. /// </summary> /// <remarks> /// <code> /// RFC 3261 Syntax: /// language-tag = primary-tag *( "-" subtag ) /// primary-tag = 1*8ALPHA /// subtag = 1*8ALPHA /// </code> /// </remarks> public class SIP_t_LanguageTag : SIP_t_ValueWithParams { #region Members private string m_LanguageTag = ""; #endregion #region Properties /// <summary> /// Gets or sets language tag. /// </summary> public string LanguageTag { get { return m_LanguageTag; } set { if (string.IsNullOrEmpty(value)) { throw new ArgumentException("Property LanguageTag value can't be null or empty !"); } m_LanguageTag = value; } } #endregion #region Methods /// <summary> /// Parses "language-tag" from specified value. /// </summary> /// <param name="value">SIP "language-tag" value.</param> /// <exception cref="ArgumentNullException">Raised when <b>value</b> is null.</exception> /// <exception cref="SIP_ParseException">Raised when invalid SIP message.</exception> public void Parse(string value) { if (value == null) { throw new ArgumentNullException("value"); } Parse(new StringReader(value)); } /// <summary> /// Parses "language-tag" from specified reader. /// </summary> /// <param name="reader">Reader from where to parse.</param> /// <exception cref="ArgumentNullException">Raised when <b>reader</b> is null.</exception> /// <exception cref="SIP_ParseException">Raised when invalid SIP message.</exception> public override void Parse(StringReader reader) { /* Content-Language = "Content-Language" HCOLON language-tag *(COMMA language-tag) language-tag = primary-tag *( "-" subtag ) primary-tag = 1*8ALPHA subtag = 1*8ALPHA */ if (reader == null) { throw new ArgumentNullException("reader"); } // Parse content-coding string word = reader.ReadWord(); if (word == null) { throw new SIP_ParseException("Invalid Content-Language value, language-tag value is missing !"); } m_LanguageTag = word; // Parse parameters ParseParameters(reader); } /// <summary> /// Converts this to valid "language-tag" value. /// </summary> /// <returns>Returns "language-tag" value.</returns> public override string ToStringValue() { /* Content-Language = "Content-Language" HCOLON language-tag *(COMMA language-tag) language-tag = primary-tag *( "-" subtag ) primary-tag = 1*8ALPHA subtag = 1*8ALPHA */ StringBuilder retVal = new StringBuilder(); retVal.Append(m_LanguageTag); retVal.Append(ParametersToString()); return retVal.ToString(); } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/SIP/Stack/SIP_TransactionState.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.SIP.Stack { /// <summary> /// This enum holds SIP transaction states. Defined in RFC 3261. /// </summary> public enum SIP_TransactionState { /// <summary> /// Client transaction waits <b>Start</b> method to be called. /// </summary> WaitingToStart, /// <summary> /// Calling to recipient. This is used only by INVITE client transaction. /// </summary> Calling, /// <summary> /// This is transaction initial state. Used only in Non-INVITE transaction. /// </summary> Trying, /// <summary> /// This is INVITE server transaction initial state. Used only in INVITE server transaction. /// </summary> Proceeding, /// <summary> /// Transaction has got final response. /// </summary> Completed, /// <summary> /// Transation has got ACK from request maker. This is used only by INVITE server transaction. /// </summary> Confirmed, /// <summary> /// Transaction has terminated and waits disposing. /// </summary> Terminated, /// <summary> /// Transaction has disposed. /// </summary> Disposed, } }<file_sep>/module/ASC.Feed.Aggregator/Modules/Documents/DocumentsDbHelper.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using ASC.Common.Data.Sql; using ASC.Common.Data.Sql.Expressions; using ASC.Files.Core; namespace ASC.Feed.Aggregator.Modules.Documents { public class DocumentsDbHelper { public static SqlQuery GetRootFolderType(string parentFolderColumnName) { return new SqlQuery("files_folder d") .From("files_folder_tree t") .Select("concat(cast(d.folder_type as char), d.create_by, cast(d.id as char))") .Where(Exp.EqColumns("d.id", "t.parent_id") & Exp.EqColumns("t.folder_id", "f." + parentFolderColumnName)) .OrderBy("level", false) .SetMaxResults(1); } public static FolderType ParseRootFolderType(object v) { return v != null ? (FolderType)Enum.Parse(typeof(FolderType), v.ToString().Substring(0, 1)) : default(FolderType); } public static Guid ParseRootFolderCreator(object v) { return v != null ? new Guid(v.ToString().Substring(1, 36)) : default(Guid); } public static int ParseRootFolderId(object v) { return v != null ? int.Parse(v.ToString().Substring(1 + 36)) : default(int); } } }<file_sep>/module/ASC.Api/ASC.Api.CRM/CRMApi.CurrencyRates.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections.Generic; using System.Linq; using ASC.Api.Attributes; using ASC.CRM.Core; using ASC.MessagingSystem; using ASC.Web.CRM.Classes; using ASC.Web.CRM.Resources; namespace ASC.Api.CRM { public partial class CRMApi { //TABLE `crm_currency_rate` column `rate` DECIMAL(10,2) NOT NULL public const decimal MaxRateValue = (decimal) 99999999.99; /// <summary> /// Get the list of currency rates /// </summary> /// <short>Get currency rates list</short> /// <category>Common</category> /// <returns> /// List of currency rates /// </returns> [Read(@"currency/rates")] public IEnumerable<CurrencyRateWrapper> GetCurrencyRates() { return DaoFactory.CurrencyRateDao.GetAll().ConvertAll(ToCurrencyRateWrapper); } /// <summary> /// Get currency rate by id /// </summary> /// <short>Get currency rate</short> /// <category>Common</category> /// <returns> /// Currency rate /// </returns> /// <exception cref="ArgumentException"></exception> [Read(@"currency/rates/{id:[0-9]+}")] public CurrencyRateWrapper GetCurrencyRate(int id) { if (id <= 0) throw new ArgumentException(); var currencyRate = DaoFactory.CurrencyRateDao.GetByID(id); return ToCurrencyRateWrapper(currencyRate); } /// <summary> /// Get currency rate by currencies /// </summary> /// <short>Get currency rate</short> /// <category>Common</category> /// <returns> /// Currency rate /// </returns> /// <exception cref="ArgumentException"></exception> [Read(@"currency/rates/{fromCurrency}/{toCurrency}")] public CurrencyRateWrapper GetCurrencyRate(string fromCurrency, string toCurrency) { if (string.IsNullOrEmpty(fromCurrency) || string.IsNullOrEmpty(toCurrency)) throw new ArgumentException(); var currencyRate = DaoFactory.CurrencyRateDao.GetByCurrencies(fromCurrency, toCurrency); return ToCurrencyRateWrapper(currencyRate); } /// <summary> /// Create new currency rate object /// </summary> /// <short></short> /// <category>Common</category> /// <returns></returns> [Create(@"currency/rates")] public CurrencyRateWrapper CreateCurrencyRate(string fromCurrency, string toCurrency, decimal rate) { ValidateRate(rate); ValidateCurrencies(new[] {fromCurrency, toCurrency}); var currencyRate = new CurrencyRate { FromCurrency = fromCurrency, ToCurrency = toCurrency, Rate = rate }; currencyRate.ID = DaoFactory.CurrencyRateDao.SaveOrUpdate(currencyRate); MessageService.Send(Request, MessageAction.CurrencyRateUpdated, fromCurrency, toCurrency); return ToCurrencyRateWrapper(currencyRate); } /// <summary> /// Update currency rate object /// </summary> /// <short></short> /// <category>Common</category> /// <returns></returns> [Update(@"currency/rates/{id:[0-9]+}")] public CurrencyRateWrapper UpdateCurrencyRate(int id, string fromCurrency, string toCurrency, decimal rate) { if (id <= 0) throw new ArgumentException(); ValidateRate(rate); ValidateCurrencies(new[] {fromCurrency, toCurrency}); var currencyRate = DaoFactory.CurrencyRateDao.GetByID(id); if (currencyRate == null) throw new ArgumentException(); currencyRate.FromCurrency = fromCurrency; currencyRate.ToCurrency = toCurrency; currencyRate.Rate = rate; currencyRate.ID = DaoFactory.CurrencyRateDao.SaveOrUpdate(currencyRate); MessageService.Send(Request, MessageAction.CurrencyRateUpdated, fromCurrency, toCurrency); return ToCurrencyRateWrapper(currencyRate); } /// <summary> /// Set currency rates /// </summary> /// <short></short> /// <category>Common</category> /// <returns></returns> [Create(@"currency/setrates")] public List<CurrencyRateWrapper> SetCurrencyRates(String currency, List<CurrencyRate> rates) { if (!CRMSecurity.IsAdmin) throw CRMSecurity.CreateSecurityException(); if (string.IsNullOrEmpty(currency)) throw new ArgumentException(); ValidateCurrencyRates(rates); currency = currency.ToUpper(); if (Global.TenantSettings.DefaultCurrency.Abbreviation != currency) { var cur = CurrencyProvider.Get(currency); if (cur == null) throw new ArgumentException(); Global.SaveDefaultCurrencySettings(cur); MessageService.Send(Request, MessageAction.CrmDefaultCurrencyUpdated); } rates = DaoFactory.CurrencyRateDao.SetCurrencyRates(rates); foreach (var rate in rates) { MessageService.Send(Request, MessageAction.CurrencyRateUpdated, rate.FromCurrency, rate.ToCurrency); } return rates.Select(ToCurrencyRateWrapper).ToList(); } /// <summary> /// Add currency rates /// </summary> /// <short></short> /// <category>Common</category> /// <returns></returns> [Create(@"currency/addrates")] public List<CurrencyRateWrapper> AddCurrencyRates(List<CurrencyRate> rates) { if (!CRMSecurity.IsAdmin) throw CRMSecurity.CreateSecurityException(); ValidateCurrencyRates(rates); var existingRates = DaoFactory.CurrencyRateDao.GetAll(); foreach (var rate in rates) { var exist = false; foreach (var existingRate in existingRates) { if (rate.FromCurrency != existingRate.FromCurrency || rate.ToCurrency != existingRate.ToCurrency) continue; existingRate.Rate = rate.Rate; DaoFactory.CurrencyRateDao.SaveOrUpdate(existingRate); MessageService.Send(Request, MessageAction.CurrencyRateUpdated, rate.FromCurrency, rate.ToCurrency); exist = true; break; } if (exist) continue; rate.ID = DaoFactory.CurrencyRateDao.SaveOrUpdate(rate); MessageService.Send(Request, MessageAction.CurrencyRateUpdated, rate.FromCurrency, rate.ToCurrency); existingRates.Add(rate); } return existingRates.Select(ToCurrencyRateWrapper).ToList(); } /// <summary> /// Delete currency rate object /// </summary> /// <short></short> /// <category>Common</category> /// <returns></returns> [Delete(@"currency/rates/{id:[0-9]+}")] public CurrencyRateWrapper DeleteCurrencyRate(int id) { if (id <= 0) throw new ArgumentException(); var currencyRate = DaoFactory.CurrencyRateDao.GetByID(id); if (currencyRate == null) throw new ArgumentException(); DaoFactory.CurrencyRateDao.Delete(id); return ToCurrencyRateWrapper(currencyRate); } private static void ValidateCurrencyRates(IEnumerable<CurrencyRate> rates) { var currencies = new List<string>(); foreach (var rate in rates) { ValidateRate(rate.Rate); currencies.Add(rate.FromCurrency); currencies.Add(rate.ToCurrency); } ValidateCurrencies(currencies.ToArray()); } private static void ValidateCurrencies(string[] currencies) { if (currencies.Any(string.IsNullOrEmpty)) throw new ArgumentException(); var available = CurrencyProvider.GetAll().Select(x => x.Abbreviation); var unknown = currencies.Where(x => !available.Contains(x)).ToArray(); if (!unknown.Any()) return; throw new ArgumentException(string.Format(CRMErrorsResource.UnknownCurrency, string.Join(",", unknown))); } private static void ValidateRate(decimal rate) { if (rate < 0 || rate > MaxRateValue) throw new ArgumentException(string.Format(CRMErrorsResource.InvalidCurrencyRate, rate)); } private static CurrencyRateWrapper ToCurrencyRateWrapper(CurrencyRate currencyRate) { return new CurrencyRateWrapper(currencyRate); } } }<file_sep>/common/ASC.Data.Storage/SecureHelper.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Web; using ASC.Common.Logging; namespace ASC.Data.Storage { public static class SecureHelper { public static bool IsSecure() { try { return HttpContext.Current != null && Uri.UriSchemeHttps.Equals(HttpContext.Current.Request.GetUrlRewriter().Scheme, StringComparison.OrdinalIgnoreCase); } catch(Exception err) { LogManager.GetLogger("ASC.Data.Storage.SecureHelper").Error(err); return false; } } } }<file_sep>/common/ASC.Core.Common/Caching/CachedQuotaService.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using ASC.Common.Caching; using ASC.Core.Tenants; using System; using System.Collections.Generic; using System.Linq; namespace ASC.Core.Caching { public class CachedQuotaService : IQuotaService { private const string KEY_QUOTA = "quota"; private const string KEY_QUOTA_ROWS = "quotarows"; private readonly IQuotaService service; private readonly ICache cache; private readonly ICacheNotify cacheNotify; private readonly TrustInterval interval; public TimeSpan CacheExpiration { get; set; } public CachedQuotaService(IQuotaService service) { if (service == null) throw new ArgumentNullException("service"); this.service = service; cache = AscCache.Memory; interval = new TrustInterval(); CacheExpiration = TimeSpan.FromMinutes(10); cacheNotify = AscCache.Notify; cacheNotify.Subscribe<QuotaCacheItem>((i, a) => { if (i.Key == KEY_QUOTA_ROWS) { interval.Expire(); } else if (i.Key == KEY_QUOTA) { cache.Remove(KEY_QUOTA); } }); } public IEnumerable<TenantQuota> GetTenantQuotas() { var quotas = cache.Get<IEnumerable<TenantQuota>>(KEY_QUOTA); if (quotas == null) { cache.Insert(KEY_QUOTA, quotas = service.GetTenantQuotas(), DateTime.UtcNow.Add(CacheExpiration)); } return quotas; } public TenantQuota GetTenantQuota(int tenant) { return GetTenantQuotas().SingleOrDefault(q => q.Id == tenant); } public TenantQuota SaveTenantQuota(TenantQuota quota) { var q = service.SaveTenantQuota(quota); cacheNotify.Publish(new QuotaCacheItem { Key = KEY_QUOTA }, CacheNotifyAction.Remove); return q; } public void RemoveTenantQuota(int tenant) { throw new NotImplementedException(); } public void SetTenantQuotaRow(TenantQuotaRow row, bool exchange) { service.SetTenantQuotaRow(row, exchange); cacheNotify.Publish(new QuotaCacheItem { Key = KEY_QUOTA_ROWS }, CacheNotifyAction.InsertOrUpdate); } public IEnumerable<TenantQuotaRow> FindTenantQuotaRows(TenantQuotaRowQuery query) { if (query == null) throw new ArgumentNullException("query"); var rows = cache.Get<Dictionary<string, List<TenantQuotaRow>>>(KEY_QUOTA_ROWS); if (rows == null || interval.Expired) { var date = rows != null ? interval.StartTime : DateTime.MinValue; interval.Start(CacheExpiration); var changes = service.FindTenantQuotaRows(new TenantQuotaRowQuery(Tenant.DEFAULT_TENANT).WithLastModified(date)) .GroupBy(r => r.Tenant.ToString()) .ToDictionary(g => g.Key, g => g.ToList()); // merge changes from db to cache if (rows == null) { rows = changes; } else { lock (rows) { foreach (var p in changes) { if (rows.ContainsKey(p.Key)) { var cachedRows = rows[p.Key]; foreach (var r in p.Value) { cachedRows.RemoveAll(c => c.Path == r.Path); cachedRows.Add(r); } } else { rows[p.Key] = p.Value; } } } } cache.Insert(KEY_QUOTA_ROWS, rows, DateTime.UtcNow.Add(CacheExpiration)); } var quotaRows = cache.Get<Dictionary<string, List<TenantQuotaRow>>>(KEY_QUOTA_ROWS); if (quotaRows == null) { return Enumerable.Empty<TenantQuotaRow>(); } lock (quotaRows) { var list = quotaRows.ContainsKey(query.Tenant.ToString()) ? quotaRows[query.Tenant.ToString()] : new List<TenantQuotaRow>(); if (query != null && !string.IsNullOrEmpty(query.Path)) { return list.Where(r => query.Path == r.Path); } return list.ToList(); } } [Serializable] class QuotaCacheItem { public string Key { get; set; } } } } <file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/SIP/UA/SIP_UA_Call.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.SIP.UA { #region usings using System; using System.Collections.Generic; using System.Text; using Message; using SDP; using Stack; #endregion /// <summary> /// This class represent SIP UA call. /// </summary> public class SIP_UA_Call : IDisposable { #region Events /// <summary> /// Is raised when call state has changed. /// </summary> public event EventHandler StateChanged = null; #endregion #region Members private readonly List<SIP_Dialog> m_pEarlyDialogs; private readonly SIP_ServerTransaction m_pInitialInviteTransaction; private readonly SIP_Request m_pInvite; private readonly AbsoluteUri m_pLocalUri; private readonly AbsoluteUri m_pRemoteUri; private readonly SIP_UA m_pUA; private bool m_IsRedirected; private SIP_Dialog m_pDialog; private SIP_RequestSender m_pInitialInviteSender; private object m_pLock = ""; private SDP_Message m_pRemoteSDP; private DateTime m_StartTime; private SIP_UA_CallState m_State = SIP_UA_CallState.WaitingForStart; #endregion #region Constructor /// <summary> /// Default outgoing call constructor. /// </summary> /// <param name="ua">Owner UA.</param> /// <param name="invite">INVITE request.</param> /// <exception cref="ArgumentNullException">Is riased when <b>ua</b> or <b>invite</b> is null reference.</exception> /// <exception cref="ArgumentException">Is raised when any of the argumnets has invalid value.</exception> internal SIP_UA_Call(SIP_UA ua, SIP_Request invite) { if (ua == null) { throw new ArgumentNullException("ua"); } if (invite == null) { throw new ArgumentNullException("invite"); } if (invite.RequestLine.Method != SIP_Methods.INVITE) { throw new ArgumentException("Argument 'invite' is not INVITE request."); } m_pUA = ua; m_pInvite = invite; m_pLocalUri = invite.From.Address.Uri; m_pRemoteUri = invite.To.Address.Uri; m_State = SIP_UA_CallState.WaitingForStart; m_pEarlyDialogs = new List<SIP_Dialog>(); } /// <summary> /// Default incoming call constructor. /// </summary> /// <param name="ua">Owner UA.</param> /// <param name="invite">INVITE server transaction.</param> /// <exception cref="ArgumentNullException">Is riased when <b>ua</b> or <b>invite</b> is null reference.</exception> internal SIP_UA_Call(SIP_UA ua, SIP_ServerTransaction invite) { if (ua == null) { throw new ArgumentNullException("ua"); } if (invite == null) { throw new ArgumentNullException("invite"); } m_pUA = ua; m_pInitialInviteTransaction = invite; m_pLocalUri = invite.Request.To.Address.Uri; m_pRemoteUri = invite.Request.From.Address.Uri; m_pInitialInviteTransaction.Canceled += delegate { // If transaction canceled, terminate call. SetState(SIP_UA_CallState.Terminated); }; m_State = SIP_UA_CallState.WaitingToAccept; } #endregion #region Properties /// <summary> /// Gets call duration in seconds. /// </summary> public int Duration { get { return ((DateTime.Now - m_StartTime)).Seconds; // TODO: if terminated, we need static value here. } } /// <summary> /// Gets if this object is disposed. /// </summary> public bool IsDisposed { get { return m_State == SIP_UA_CallState.Disposed; } } /// <summary> /// Gets if call is on hold. /// </summary> public bool IsOnhold { // TODO: get { return false; } } /// <summary> /// Gets if call has been redirected by remote party. /// </summary> public bool IsRedirected { get { return m_IsRedirected; } } /// <summary> /// Gets call local party URI. /// </summary> public AbsoluteUri LocalUri { get { return m_pLocalUri; } } /// <summary> /// Gets remote SDP. /// </summary> public SDP_Message RemoteSDP { get { return m_pRemoteSDP; } } /// <summary> /// Gets call remote party URI. /// </summary> public AbsoluteUri RemoteUri { get { return m_pRemoteUri; } } /// <summary> /// Gets call start time. /// </summary> public DateTime StartTime { get { return m_StartTime; } } /// <summary> /// Gets current call state. /// </summary> public SIP_UA_CallState State { get { return m_State; } } /// <summary> /// Gets or sets user data. /// </summary> public object Tag { get; set; } #endregion #region Methods /// <summary> /// Cleans up any resource being used. /// </summary> public void Dispose() { lock (m_pLock) { if (m_State == SIP_UA_CallState.Disposed) { return; } SetState(SIP_UA_CallState.Disposed); // TODO: Clean up StateChanged = null; } } /// <summary> /// Starts terminating call. To get when call actually terminates, monitor <b>StateChanged</b> event. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and and this method is accessed.</exception> public void Terminate() { lock (m_pLock) { if (m_State == SIP_UA_CallState.Disposed) { throw new ObjectDisposedException(GetType().Name); } if (m_State == SIP_UA_CallState.Terminating || m_State == SIP_UA_CallState.Terminated) { return; } else if (m_State == SIP_UA_CallState.WaitingForStart) { SetState(SIP_UA_CallState.Terminated); } else if (m_State == SIP_UA_CallState.WaitingToAccept) { m_pInitialInviteTransaction.SendResponse( m_pUA.Stack.CreateResponse(SIP_ResponseCodes.x487_Request_Terminated, m_pInitialInviteTransaction.Request)); SetState(SIP_UA_CallState.Terminated); } else if (m_State == SIP_UA_CallState.Active) { m_pDialog.Terminate(); SetState(SIP_UA_CallState.Terminated); } else if (m_pInitialInviteSender != null) { /* RFC 3261 15. If we are caller and call is not active yet, we must do following actions: *) Send CANCEL, set call Terminating flag. *) If we get non 2xx final response, we are done. (Normally cancel causes '408 Request terminated') *) If we get 2xx response (2xx sent by remote party before our CANCEL reached), we must send BYE to active dialog. */ SetState(SIP_UA_CallState.Terminating); m_pInitialInviteSender.Cancel(); } } } /// <summary> /// Starts calling. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and and this method is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when call is not in valid state.</exception> public void Start() { lock (m_pLock) { if (m_State == SIP_UA_CallState.Disposed) { throw new ObjectDisposedException(GetType().Name); } if (m_State != SIP_UA_CallState.WaitingForStart) { throw new InvalidOperationException( "Start method can be called only in 'SIP_UA_CallState.WaitingForStart' state."); } SetState(SIP_UA_CallState.Calling); m_pInitialInviteSender = m_pUA.Stack.CreateRequestSender(m_pInvite); m_pInitialInviteSender.ResponseReceived += m_pInitialInviteSender_ResponseReceived; m_pInitialInviteSender.Start(); } } /// <summary> /// Accepts call. /// </summary> public void Accept() { if (m_State == SIP_UA_CallState.Disposed) { throw new ObjectDisposedException(GetType().Name); } if (m_State != SIP_UA_CallState.WaitingToAccept) { throw new InvalidOperationException( "Accept method can be called only in 'SIP_UA_CallState.WaitingToAccept' state."); } // TODO: We must add Contact header and SDP to response. SIP_Response response = m_pUA.Stack.CreateResponse(SIP_ResponseCodes.x200_Ok, m_pInitialInviteTransaction.Request, m_pInitialInviteTransaction.Flow); response.ContentType = "application/sdp"; response.Data = Encoding.Default.GetBytes("v=0\r\n" + "o=LSSIP 333 242452 IN IP4 192.168.1.70\r\n" + "s=SIP Call\r\n" + "c=IN IP4 192.168.1.70\r\n" + "t=0 0\r\n" + "m=audio 11000 RTP/AVP 0\r\n" + "a=rtpmap:0 PCMU/8000\r\n" + "a=sendrecv\r\n"); m_pInitialInviteTransaction.SendResponse(response); SetState(SIP_UA_CallState.Active); m_pDialog = m_pUA.Stack.TransactionLayer.GetOrCreateDialog(m_pInitialInviteTransaction, response); m_pDialog.StateChanged += m_pDialog_StateChanged; } /// <summary> /// Rejects incoming call. /// </summary> /// <param name="statusCode_reason">Status-code reasonText.</param> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and and this method is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when call is not in valid state and this method is called.</exception> /// <exception cref="ArgumentNullException">Is raised when <b>statusCode_reason</b> is null.</exception> public void Reject(string statusCode_reason) { lock (m_pLock) { if (State == SIP_UA_CallState.Disposed) { throw new ObjectDisposedException(GetType().Name); } if (State != SIP_UA_CallState.WaitingToAccept) { throw new InvalidOperationException("Call is not in valid state."); } if (statusCode_reason == null) { throw new ArgumentNullException("statusCode_reason"); } m_pInitialInviteTransaction.SendResponse(m_pUA.Stack.CreateResponse(statusCode_reason, m_pInitialInviteTransaction .Request)); SetState(SIP_UA_CallState.Terminated); } } /// <summary> /// Redirects incoming call to speified contact(s). /// </summary> /// <param name="contacts">Redirection targets.</param> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and and this method is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when call is not in valid state and this method is called.</exception> /// <exception cref="ArgumentNullException">Is raised when <b>contacts</b> is null.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> public void Redirect(SIP_t_ContactParam[] contacts) { lock (m_pLock) { if (State == SIP_UA_CallState.Disposed) { throw new ObjectDisposedException(GetType().Name); } if (State != SIP_UA_CallState.WaitingToAccept) { throw new InvalidOperationException("Call is not in valid state."); } if (contacts == null) { throw new ArgumentNullException("contacts"); } if (contacts.Length == 0) { throw new ArgumentException("Arguments 'contacts' must contain at least 1 value."); } // TODO: //m_pUA.Stack.CreateResponse(SIP_ResponseCodes.,m_pInitialInviteTransaction); throw new NotImplementedException(); } } #endregion #region Utility methods /// <summary> /// Is called when SIP dialog state has changed. /// </summary> /// <param name="sender">Sender.</param> /// <param name="e">Event data.</param> private void m_pDialog_StateChanged(object sender, EventArgs e) { if (State == SIP_UA_CallState.Terminated) { return; } if (m_pDialog.State == SIP_DialogState.Terminated) { SetState(SIP_UA_CallState.Terminated); m_pDialog.Dispose(); } } /// <summary> /// This method is called when initial INVITE sender got response. /// </summary> /// <param name="sender">Sender.</param> /// <param name="e">Event data.</param> private void m_pInitialInviteSender_ResponseReceived(object sender, SIP_ResponseReceivedEventArgs e) { lock (m_pLock) { // If remote party provided SDP, parse it. if (e.Response.ContentType != null && e.Response.ContentType.ToLower().IndexOf("application/sdp") > -1) { m_pRemoteSDP = SDP_Message.Parse(Encoding.UTF8.GetString(e.Response.Data)); // TODO: If parsing failed, end call. } if (e.Response.StatusCodeType == SIP_StatusCodeType.Provisional) { if (e.Response.StatusCode == 180) { SetState(SIP_UA_CallState.Ringing); } else if (e.Response.StatusCode == 182) { SetState(SIP_UA_CallState.Queued); } // We don't care other status responses. /* RFC 3261 13.2.2.1. Zero, one or multiple provisional responses may arrive before one or more final responses are received. Provisional responses for an INVITE request can create "early dialogs". If a provisional response has a tag in the To field, and if the dialog ID of the response does not match an existing dialog, one is constructed using the procedures defined in Section 12.1.2. */ if (e.Response.StatusCode > 100 && e.Response.To.Tag != null) { m_pEarlyDialogs.Add(m_pUA.Stack.TransactionLayer.GetOrCreateDialog( e.ClientTransaction, e.Response)); } } else if (e.Response.StatusCodeType == SIP_StatusCodeType.Success) { m_StartTime = DateTime.Now; SetState(SIP_UA_CallState.Active); m_pDialog = m_pUA.Stack.TransactionLayer.GetOrCreateDialog(e.ClientTransaction, e.Response); m_pDialog.StateChanged += m_pDialog_StateChanged; /* Exit all all other dialogs created by this call (due to forking). That is not defined in RFC but, since UAC can send BYE to early and confirmed dialogs, because of this all 100% valid. */ foreach (SIP_Dialog dialog in m_pEarlyDialogs.ToArray()) { if (!m_pDialog.Equals(dialog)) { dialog.Terminate("Another forking leg accepted.", true); } } } else { /* RFC 3261 13.2.2.3. All early dialogs are considered terminated upon reception of the non-2xx final response. */ foreach (SIP_Dialog dialog in m_pEarlyDialogs.ToArray()) { dialog.Terminate( "All early dialogs are considered terminated upon reception of the non-2xx final response. (RFC 3261 13.2.2.3)", false); } m_pEarlyDialogs.Clear(); Error(); SetState(SIP_UA_CallState.Terminated); } } } /// <summary> /// Changes call state. /// </summary> /// <param name="state">New call state.</param> private void SetState(SIP_UA_CallState state) { m_State = state; OnStateChanged(state); } /// <summary> /// Raises <b>StateChanged</b> event. /// </summary> /// <param name="state">New call state.</param> private void OnStateChanged(SIP_UA_CallState state) { if (StateChanged != null) { StateChanged(this, new EventArgs()); } } // public event EventHandler Error private void Error() {} #endregion } }<file_sep>/module/ASC.Api/ASC.Api.Calendar/Wrappers/CalendarWrapper.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections.Generic; using System.Runtime.Serialization; using ASC.Api.Calendar.BusinessObjects; using ASC.Core; using ASC.Core.Users; using ASC.Web.Core.Calendars; using ASC.Api.Calendar.ExternalCalendars; using ASC.Common.Security; namespace ASC.Api.Calendar.Wrappers { [DataContract(Name = "calendar", Namespace = "")] public class CalendarWrapper { public BaseCalendar UserCalendar{get; private set;} protected UserViewSettings _userViewSettings; protected Guid _userId; public CalendarWrapper(BaseCalendar calendar) : this(calendar, null){} public CalendarWrapper(BaseCalendar calendar, UserViewSettings userViewSettings) { _userViewSettings = userViewSettings; if (_userViewSettings == null && calendar is ASC.Api.Calendar.BusinessObjects.Calendar) { _userViewSettings = (calendar as ASC.Api.Calendar.BusinessObjects.Calendar) .ViewSettings.Find(s=> s.UserId == SecurityContext.CurrentAccount.ID); } if (_userViewSettings == null) { UserCalendar = calendar; _userId = SecurityContext.CurrentAccount.ID; } else { UserCalendar = calendar.GetUserCalendar(_userViewSettings); _userId = _userViewSettings.UserId; } } [DataMember(Name = "isSubscription", Order = 80)] public virtual bool IsSubscription { get { if (UserCalendar.IsiCalStream()) return true; if (UserCalendar.Id.Equals(SharedEventsCalendar.CalendarId, StringComparison.InvariantCultureIgnoreCase)) return true; if (UserCalendar.OwnerId.Equals(_userId)) return false; return true; } set { } } [DataMember(Name = "iCalUrl", Order = 230)] public virtual string iCalUrl { get { if (UserCalendar.IsiCalStream()) return (UserCalendar as BusinessObjects.Calendar).iCalUrl; return ""; } set { } } [DataMember(Name = "isiCalStream", Order = 220)] public virtual bool IsiCalStream { get { if (UserCalendar.IsiCalStream()) return true; return false; } set { } } [DataMember(Name = "isHidden", Order = 50)] public virtual bool IsHidden { get { return _userViewSettings != null ? _userViewSettings.IsHideEvents : false; } set { } } [DataMember(Name = "canAlertModify", Order = 200)] public virtual bool CanAlertModify { get { return UserCalendar.Context.CanChangeAlertType; } set { } } [DataMember(Name = "isShared", Order = 60)] public virtual bool IsShared { get { return UserCalendar.SharingOptions.SharedForAll || UserCalendar.SharingOptions.PublicItems.Count > 0; } set { } } [DataMember(Name = "permissions", Order = 70)] public virtual CalendarPermissions Permissions { get { var p = new CalendarPermissions() { Data = PublicItemCollection.GetForCalendar(UserCalendar) }; foreach (var item in UserCalendar.SharingOptions.PublicItems) { if (item.IsGroup) p.UserParams.Add(new UserParams() { Id = item.Id, Name = CoreContext.UserManager.GetGroupInfo(item.Id).Name }); else p.UserParams.Add(new UserParams() { Id = item.Id, Name = CoreContext.UserManager.GetUsers(item.Id).DisplayUserName() }); } return p; } set { } } [DataMember(Name = "isEditable", Order = 90)] public virtual bool IsEditable { get { if (UserCalendar.IsiCalStream()) return false; if (UserCalendar is ISecurityObject) return SecurityContext.PermissionResolver.Check(CoreContext.Authentication.GetAccountByID(_userId), (ISecurityObject)UserCalendar as ISecurityObject, null, CalendarAccessRights.FullAccessAction); return false; } set { } } [DataMember(Name = "textColor", Order = 30)] public string TextColor { get { return String.IsNullOrEmpty(UserCalendar.Context.HtmlTextColor)? BusinessObjects.Calendar.DefaultTextColor: UserCalendar.Context.HtmlTextColor; } set { } } [DataMember(Name = "backgroundColor", Order = 40)] public string BackgroundColor { get { return String.IsNullOrEmpty(UserCalendar.Context.HtmlBackgroundColor) ? BusinessObjects.Calendar.DefaultBackgroundColor : UserCalendar.Context.HtmlBackgroundColor; } set { } } [DataMember(Name = "description", Order = 20)] public string Description { get { return UserCalendar.Description; } set { } } [DataMember(Name = "title", Order = 30)] public string Title { get{return UserCalendar.Name;} set{} } [DataMember(Name = "objectId", Order = 0)] public string Id { get{return UserCalendar.Id;} set{} } [DataMember(Name = "isTodo", Order = 0)] public int IsTodo { get { if (UserCalendar.IsExistTodo()) return (UserCalendar as BusinessObjects.Calendar).IsTodo; return 0; } set { } } [DataMember(Name = "owner", Order = 120)] public UserParams Owner { get { var owner = new UserParams() { Id = UserCalendar.OwnerId , Name = ""}; if (UserCalendar.OwnerId != Guid.Empty) owner.Name = CoreContext.UserManager.GetUsers(UserCalendar.OwnerId).DisplayUserName(); return owner; } set { } } public bool IsAcceptedSubscription { get { return _userViewSettings == null || _userViewSettings.IsAccepted; } set { } } [DataMember(Name = "events", Order = 150)] public List<EventWrapper> Events { get; set; } [DataMember(Name = "todos", Order = 160)] public List<TodoWrapper> Todos { get; set; } [DataMember(Name = "defaultAlert", Order = 160)] public EventAlertWrapper DefaultAlertType { get{ return EventAlertWrapper.ConvertToTypeSurrogated(UserCalendar.EventAlertType); } set { } } [DataMember(Name = "timeZone", Order = 160)] public TimeZoneWrapper TimeZoneInfo { get { return new TimeZoneWrapper(UserCalendar.TimeZone); } set{} } [DataMember(Name = "canEditTimeZone", Order = 160)] public bool CanEditTimeZone { get { return UserCalendar.Context.CanChangeTimeZone;} set { } } public static object GetSample() { return new { canEditTimeZone = false, timeZone = TimeZoneWrapper.GetSample(), defaultAlert = EventAlertWrapper.GetSample(), events = new List<object>() { EventWrapper.GetSample() }, owner = UserParams.GetSample(), objectId = "1", title = "Calendar Name", description = "Calendar Description", backgroundColor = "#000000", textColor = "#ffffff", isEditable = true, permissions = CalendarPermissions.GetSample(), isShared = true, canAlertModify = true, isHidden = false, isiCalStream = false, isSubscription = false }; } } } <file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/RTP/RTP_MultimediaSession.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.RTP { #region usings using System; using System.Collections.Generic; #endregion /// <summary> /// This class represents RTP single-media and multimedia session. /// </summary> public class RTP_MultimediaSession : IDisposable { #region Events /// <summary> /// Is raised when unknown error has happened. /// </summary> public event EventHandler<ExceptionEventArgs> Error = null; /// <summary> /// Is raised when new remote participant has joined to session. /// </summary> public event EventHandler<RTP_ParticipantEventArgs> NewParticipant = null; /// <summary> /// Is raised when new session has created. /// </summary> public event EventHandler<EventArgs<RTP_Session>> SessionCreated = null; #endregion #region Members private bool m_IsDisposed; private RTP_Participant_Local m_pLocalParticipant; private Dictionary<string, RTP_Participant_Remote> m_pParticipants; private List<RTP_Session> m_pSessions; #endregion #region Properties /// <summary> /// Gets if this object is disposed. /// </summary> public bool IsDisposed { get { return m_IsDisposed; } } /// <summary> /// Gets media sessions. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public RTP_Session[] Sessions { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_pSessions.ToArray(); } } /// <summary> /// Gets local participant. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public RTP_Participant_Local LocalParticipant { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_pLocalParticipant; } } /// <summary> /// Gets session remote participants. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public RTP_Participant_Remote[] RemoteParticipants { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } lock (m_pParticipants) { RTP_Participant_Remote[] retVal = new RTP_Participant_Remote[m_pParticipants.Count]; m_pParticipants.Values.CopyTo(retVal, 0); return retVal; } } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="cname">Canonical name of participant. <seealso cref="RTP_Utils.GenerateCNAME"/>RTP_Utils.GenerateCNAME /// can be used to create this value.</param> /// <exception cref="ArgumentNullException">Is raised when <b>cname</b> is null reference.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> public RTP_MultimediaSession(string cname) { if (cname == null) { throw new ArgumentNullException("cname"); } if (cname == string.Empty) { throw new ArgumentException("Argument 'cname' value must be specified."); } m_pLocalParticipant = new RTP_Participant_Local(cname); m_pSessions = new List<RTP_Session>(); m_pParticipants = new Dictionary<string, RTP_Participant_Remote>(); } #endregion #region Methods /// <summary> /// Cleans up any resources being used. /// </summary> public void Dispose() { if (m_IsDisposed) { return; } foreach (RTP_Session session in m_pSessions.ToArray()) { session.Dispose(); } m_IsDisposed = true; m_pLocalParticipant = null; m_pSessions = null; m_pParticipants = null; NewParticipant = null; Error = null; } /// <summary> /// Closes RTP multimedia session, sends BYE with optional reason text to remote targets. /// </summary> /// <param name="closeReason">Close reason. Value null means not specified.</param> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this method is accessed.</exception> public void Close(string closeReason) { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } foreach (RTP_Session session in m_pSessions.ToArray()) { session.Close(closeReason); } Dispose(); } /// <summary> /// Starts session. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this method is accessed.</exception> public void Start() { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } // TODO: } /// <summary> /// Stops session. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this method is accessed.</exception> public void Stop() { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } // TODO: } /// <summary> /// Creates new RTP session. /// </summary> /// <param name="localEP">Local RTP end point.</param> /// <param name="clock">RTP media clock.</param> /// <returns>Returns created session.</returns> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this method is accessed.</exception> /// <exception cref="ArgumentNullException">Is raised when <b>localEP</b> or <b>clock</b> is null reference.</exception> public RTP_Session CreateSession(RTP_Address localEP, RTP_Clock clock) { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (localEP == null) { throw new ArgumentNullException("localEP"); } if (clock == null) { throw new ArgumentNullException("clock"); } RTP_Session session = new RTP_Session(this, localEP, clock); session.Disposed += delegate(object s, EventArgs e) { m_pSessions.Remove((RTP_Session) s); }; m_pSessions.Add(session); OnSessionCreated(session); return session; } #endregion #region Utility methods /// <summary> /// Raises <b>SessionCreated</b> event. /// </summary> /// <param name="session">RTP session.</param> private void OnSessionCreated(RTP_Session session) { if (session == null) { throw new ArgumentNullException("session"); } if (SessionCreated != null) { SessionCreated(this, new EventArgs<RTP_Session>(session)); } } /// <summary> /// Raises <b>NewParticipant</b> event. /// </summary> /// <param name="participant">New participant.</param> private void OnNewParticipant(RTP_Participant_Remote participant) { if (NewParticipant != null) { NewParticipant(this, new RTP_ParticipantEventArgs(participant)); } } #endregion #region Internal methods /// <summary> /// Gets or creates new participant if participant does not exist. /// </summary> /// <param name="cname">Participant canonical name.</param> /// <returns>Returns specified participant.</returns> internal RTP_Participant_Remote GetOrCreateParticipant(string cname) { if (cname == null) { throw new ArgumentNullException("cname"); } if (cname == string.Empty) { throw new ArgumentException("Argument 'cname' value must be specified."); } lock (m_pParticipants) { RTP_Participant_Remote participant = null; if (!m_pParticipants.TryGetValue(cname, out participant)) { participant = new RTP_Participant_Remote(cname); participant.Removed += delegate { m_pParticipants.Remove(participant.CNAME); }; m_pParticipants.Add(cname, participant); OnNewParticipant(participant); } return participant; } } /// <summary> /// Raises <b>Error</b> event. /// </summary> /// <param name="exception">Exception.</param> internal void OnError(Exception exception) { if (Error != null) { Error(this, new ExceptionEventArgs(exception)); } } #endregion } }<file_sep>/module/ASC.Api/ASC.Api.Community/Bookmarks/BookmarkApi.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections.Generic; using System.Linq; using ASC.Api.Attributes; using ASC.Api.Bookmarks; using ASC.Api.Collections; using ASC.Api.Exceptions; using ASC.Bookmarking.Business; using ASC.Bookmarking.Business.Permissions; using ASC.Bookmarking.Pojo; using ASC.Core; using ASC.Core.Tenants; using ASC.Web.Studio.UserControls.Common.Comments; using ASC.Web.Studio.Utility.HtmlUtility; using ASC.Web.UserControls.Bookmarking.Common.Presentation; using ASC.Web.UserControls.Bookmarking.Common.Util; namespace ASC.Api.Community { public partial class CommunityApi { private BookmarkingService _bookmarkingDao; private BookmarkingService BookmarkingDao { get { return _bookmarkingDao ?? (_bookmarkingDao = BookmarkingService.GetCurrentInstanse()); } } ///<summary> ///Returns the list of all bookmarks on the portal with the bookmark titles, date of creation and update, bookmark text and author ///</summary> ///<short> ///All bookmarks ///</short> ///<category>Bookmarks</category> ///<returns>List of all bookmarks</returns> [Read("bookmark")] public IEnumerable<BookmarkWrapper> GetBookmarks() { var bookmarks = BookmarkingDao.GetAllBookmarks((int)_context.StartIndex, (int)_context.Count); _context.SetDataPaginated(); return bookmarks.Select(x => new BookmarkWrapper(x)).ToSmartList(); } ///<summary> ///Returns the list of all bookmarks for the current user with the bookmark titles, date of creation and update, bookmark text and author ///</summary> ///<short> ///Added by me ///</short> ///<category>Bookmarks</category> ///<returns>List of bookmarks</returns> [Read("bookmark/@self")] public IEnumerable<BookmarkWrapper> GetMyBookmarks() { var bookmarks = BookmarkingDao.GetBookmarksCreatedByUser(SecurityContext.CurrentAccount.ID, (int)_context.StartIndex, (int)_context.Count); _context.SetDataPaginated(); return bookmarks.Select(x => new BookmarkWrapper(x)).ToSmartList(); } ///<summary> ///Returns a list of bookmarks matching the search query with the bookmark title, date of creation and update, bookmark description and author ///</summary> ///<short> ///Search ///</short> ///<category>Bookmarks</category> /// <param name="query">search query</param> ///<returns>List of bookmarks</returns> [Read("bookmark/@search/{query}")] public IEnumerable<BookmarkWrapper> SearchBookmarks(string query) { var bookmarks = BookmarkingDao.SearchBookmarks(new List<string> {query}, (int)_context.StartIndex, (int)_context.Count); _context.SetDataPaginated(); return bookmarks.Select(x => new BookmarkWrapper(x)).ToSmartList(); } ///<summary> ///Returns the list of favorite bookmarks for the current user with the bookmark titles, date of creation and update, bookmark text and author ///</summary> ///<short> ///My favorite ///</short> ///<category>Bookmarks</category> ///<returns>List of bookmarks</returns> [Read("bookmark/@favs")] public IEnumerable<BookmarkWrapper> GetFavsBookmarks() { var bookmarks = BookmarkingDao.GetFavouriteBookmarksSortedByDate((int)_context.StartIndex, (int)_context.Count); _context.SetDataPaginated(); return bookmarks.Select(x => new BookmarkWrapper(x)).ToSmartList(); } ///<summary> ///Returns a list of all tags used for bookmarks with the number showing the tag usage ///</summary> ///<short> ///All tags ///</short> ///<category>Bookmarks</category> ///<returns>List of tags</returns> [Read("bookmark/tag")] public IEnumerable<TagWrapper> GetBookmarksTags() { var bookmarks = BookmarkingDao.GetAllTags(); return bookmarks.Select(x => new TagWrapper(x)).ToSmartList(); } ///<summary> ///Returns the list of all bookmarks marked by the tag specified with the bookmark titles, date of creation and update, bookmark text and author ///</summary> ///<short> ///By tag ///</short> ///<category>Bookmarks</category> ///<param name="tag">tag</param> ///<returns>List of bookmarks</returns> [Read("bookmark/bytag")] public IEnumerable<BookmarkWrapper> GetBookmarksByTag(string tag) { var bookmarks = BookmarkingDao.SearchBookmarksByTag(tag, (int)_context.StartIndex, (int)_context.Count); _context.SetDataPaginated(); return bookmarks.Select(x => new BookmarkWrapper(x)).ToSmartList(); } ///<summary> ///Returns the list of recenty added bookmarks with the bookmark titles, date of creation and update, bookmark text and author ///</summary> ///<short> ///Recently added ///</short> ///<category>Bookmarks</category> ///<returns>List of bookmarks</returns> [Read("bookmark/top/recent")] public IEnumerable<BookmarkWrapper> GetRecentBookmarks() { var bookmarks = BookmarkingDao.GetMostRecentBookmarks((int)_context.StartIndex, (int)_context.Count); _context.SetDataPaginated(); return bookmarks.Select(x => new BookmarkWrapper(x)).ToSmartList(); } ///<summary> ///Returns the list of the bookmarks most popular on the current date with the bookmark titles, date of creation and update, bookmark text and author ///</summary> ///<short> ///Top of day ///</short> ///<category>Bookmarks</category> ///<returns>List of bookmarks</returns> [Read("bookmark/top/day")] public IEnumerable<BookmarkWrapper> GetTopDayBookmarks() { var bookmarks = BookmarkingDao.GetTopOfTheDay((int)_context.StartIndex, (int)_context.Count); _context.SetDataPaginated(); return bookmarks.Select(x => new BookmarkWrapper(x)).ToSmartList(); } ///<summary> ///Returns the list of the bookmarks most popular in the current month with the bookmark titles, date of creation and update, bookmark text and author ///</summary> ///<short> ///Top of month ///</short> ///<category>Bookmarks</category> ///<returns>List of bookmarks</returns> [Read("bookmark/top/month")] public IEnumerable<BookmarkWrapper> GetTopMonthBookmarks() { var bookmarks = BookmarkingDao.GetTopOfTheMonth((int)_context.StartIndex, (int)_context.Count); _context.SetDataPaginated(); return bookmarks.Select(x => new BookmarkWrapper(x)).ToSmartList(); } ///<summary> ///Returns the list of the bookmarks most popular on the current week with the bookmark titles, date of creation and update, bookmark text and author ///</summary> ///<short> ///Top of week ///</short> ///<category>Bookmarks</category> ///<returns>list of bookmarks</returns> [Read("bookmark/top/week")] public IEnumerable<BookmarkWrapper> GetTopWeekBookmarks() { var bookmarks = BookmarkingDao.GetTopOfTheWeek((int)_context.StartIndex, (int)_context.Count); _context.SetDataPaginated(); return bookmarks.Select(x => new BookmarkWrapper(x)).ToSmartList(); } ///<summary> ///Returns the list of the bookmarks most popular in the current year with the bookmark titles, date of creation and update, bookmark text and author ///</summary> ///<short> ///Top of year ///</short> ///<category>Bookmarks</category> ///<returns>list of bookmarks</returns> [Read("bookmark/top/year")] public IEnumerable<BookmarkWrapper> GetTopYearBookmarks() { var bookmarks = BookmarkingDao.GetTopOfTheYear((int)_context.StartIndex, (int)_context.Count); _context.SetDataPaginated(); return bookmarks.Select(x => new BookmarkWrapper(x)).ToSmartList(); } ///<summary> /// Returns the list of all comments to the bookmark with the specified ID ///</summary> ///<short> /// Get comments ///</short> ///<category>Bookmarks</category> ///<param name="id">Bookmark ID</param> ///<returns>list of bookmark comments</returns> [Read("bookmark/{id}/comment")] public IEnumerable<BookmarkCommentWrapper> GetBookmarkComments(long id) { var comments = BookmarkingDao.GetBookmarkComments(BookmarkingDao.GetBookmarkByID(id)); return comments.Select(x => new BookmarkCommentWrapper(x)).ToSmartList(); } ///<summary> /// Adds a comment to the bookmark with the specified ID. The parent bookmark ID can be also specified if needed. ///</summary> ///<short> /// Add comment ///</short> ///<param name="id">Bookmark ID</param> ///<param name="content">comment content</param> ///<param name="parentId">parent comment ID</param> ///<returns>list of bookmark comments</returns> /// <example> /// <![CDATA[ /// Sending data in application/json: /// /// { /// content:"My comment", /// parentId:"9924256A-739C-462b-AF15-E652A3B1B6EB" /// } /// /// Sending data in application/x-www-form-urlencoded /// content="My comment"&parentId="9924256A-739C-462b-AF15-E652A3B1B6EB" /// ]]> /// </example> /// <remarks> /// Send parentId=00000000-0000-0000-0000-000000000000 or don't send it at all if you want your comment to be on the root level /// </remarks> /// <category>Bookmarks</category> [Create("bookmark/{id}/comment")] public BookmarkCommentWrapper AddBookmarkComment(long id, string content, Guid parentId) { var bookmark = BookmarkingDao.GetBookmarkByID(id); if (bookmark == null) throw new ItemNotFoundException("bookmark not found"); var comment = new Comment { ID = Guid.NewGuid(), BookmarkID = id, Content = content, Datetime = DateTime.UtcNow, UserID = SecurityContext.CurrentAccount.ID, Parent = parentId.ToString() }; BookmarkingDao.AddComment(comment); return new BookmarkCommentWrapper(comment); } ///<summary> /// Returns a detailed information on the bookmark with the specified ID ///</summary> ///<short> /// Get bookmarks by ID ///</short> ///<param name="id">Bookmark ID</param> ///<returns>bookmark</returns> ///<category>Bookmarks</category> [Read("bookmark/{id}")] public BookmarkWrapper GetBookmarkById(long id) { return new BookmarkWrapper(BookmarkingDao.GetBookmarkByID(id)); } ///<summary> /// Adds a bookmark with a specified title, description and tags ///</summary> ///<short> /// Add bookmark ///</short> ///<param name="url">url of bookmarking page</param> ///<param name="title">title to show</param> ///<param name="description">description</param> ///<param name="tags">tags. separated by semicolon</param> ///<returns>newly added bookmark</returns> /// <example> /// <![CDATA[ /// Sending data in application/json: /// /// { /// url:"www.teamlab.com", /// title: "TeamLab", /// description: "best site i've ever seen", /// tags: "project management, collaboration" /// } /// /// Sending data in application/x-www-form-urlencoded /// url="www.teamlab.com"&title="TeamLab"&description="best site i've ever seen"&tags="project management, collaboration" /// ]]> /// </example> /// <category>Bookmarks</category> [Create("bookmark")] public BookmarkWrapper AddBookmark(string url, string title, string description, string tags) { var bookmark = new Bookmark(url, TenantUtil.DateTimeNow(), title, description) {UserCreatorID = SecurityContext.CurrentAccount.ID}; BookmarkingDao.AddBookmark(bookmark, !string.IsNullOrEmpty(tags) ? tags.Split(',').Select(x => new Tag {Name = x}).ToList() : new List<Tag>()); return new BookmarkWrapper(bookmark); } /// <summary> /// Get comment preview with the content specified in the request /// </summary> /// <short>Get comment preview</short> /// <section>Comments</section> /// <param name="commentid">Comment ID</param> /// <param name="htmltext">Comment content</param> /// <returns>Comment info</returns> /// <category>Bookmarks</category> [Create("bookmark/comment/preview")] public CommentInfo GetBookmarkCommentPreview(string commentid, string htmltext) { var comment = new Comment { Datetime = TenantUtil.DateTimeNow(), UserID = SecurityContext.CurrentAccount.ID }; if (!String.IsNullOrEmpty(commentid)) { comment = BookmarkingServiceHelper.GetCurrentInstanse().GetCommentById(commentid); comment.Parent = string.Empty; } comment.Content = htmltext; var ci = BookmarkingConverter.ConvertComment(comment, new List<Comment>()); ci.IsEditPermissions = false; ci.IsResponsePermissions = false; //var isRoot = string.IsNullOrEmpty(comment.Parent) || comment.Parent.Equals(Guid.Empty.ToString(), StringComparison.CurrentCultureIgnoreCase); return ci; } /// <summary> ///Remove comment with the id specified in the request /// </summary> /// <short>Remove comment</short> /// <section>Comments</section> /// <param name="commentid">Comment ID</param> /// <returns>Comment id</returns> /// <category>Bookmarks</category> [Delete("bookmark/comment/{commentid}")] public string RemoveBookmarkComment(string commentid) { var comment = BookmarkingServiceHelper.GetCurrentInstanse().GetCommentById(commentid); if (comment != null && BookmarkingPermissionsCheck.PermissionCheckEditComment(comment)) { BookmarkingServiceHelper.GetCurrentInstanse().RemoveComment(commentid); return commentid; } return null; } /// <category>Bookmarks</category> [Create("bookmark/comment")] public CommentInfo AddBookmarkComment(string parentcommentid, long entityid, string content) { var comment = new Comment { Content = content, Datetime = TenantUtil.DateTimeNow(), UserID = SecurityContext.CurrentAccount.ID }; var parentID = Guid.Empty; try { if (!string.IsNullOrEmpty(parentcommentid)) { parentID = new Guid(parentcommentid); } } catch { parentID = Guid.Empty; } comment.Parent = parentID.ToString(); comment.BookmarkID = entityid; comment.ID = Guid.NewGuid(); BookmarkingServiceHelper.GetCurrentInstanse().AddComment(comment); return BookmarkingConverter.ConvertComment(comment, new List<Comment>()); } /// <category>Bookmarks</category> [Update("bookmark/comment/{commentid}")] public string UpdateBookmarkComment(string commentid, string content) { var comment = BookmarkingServiceHelper.GetCurrentInstanse().GetCommentById(commentid); if (comment == null || !BookmarkingPermissionsCheck.PermissionCheckEditComment(comment)) throw new ArgumentException(); BookmarkingServiceHelper.GetCurrentInstanse().UpdateComment(commentid, content); return HtmlUtility.GetFull(content); } /// <summary> /// Removes bookmark from favourite. If after removing user bookmark raiting of this bookmark is 0, the bookmark will be removed completely. /// </summary> /// <short>Removes bookmark from favourite</short> /// <param name="id">Bookmark ID</param> /// <returns>bookmark</returns> /// <category>Bookmarks</category> [Delete("bookmark/@favs/{id}")] public BookmarkWrapper RemoveBookmarkFromFavourite(long id) { var bookmark = BookmarkingServiceHelper.GetCurrentInstanse().RemoveBookmarkFromFavourite(id); return bookmark == null ? null : new BookmarkWrapper(bookmark); } /// <summary> /// Removes bookmark /// </summary> /// <short>Removes bookmark</short> /// <param name="id">Bookmark ID</param> /// <category>Bookmarks</category> [Delete("bookmark/{id}")] public void RemoveBookmark(long id) { BookmarkingServiceHelper.GetCurrentInstanse().RemoveBookmark(id); } } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/_Obsolete/MIME/Mime.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.Mime { #region usings using System; using System.Collections.Generic; using System.IO; using System.Text; using IO; #endregion /// <summary> /// Class for creating,parsing,modifing rfc 2822 mime messages. /// </summary> /// <remarks> /// <code> /// /// Message examples: /// /// <B>Simple message:</B> /// /// //--- Beginning of message /// From: <EMAIL> /// To: <EMAIL> /// Subject: Message subject. /// Content-Type: text/plain /// /// Message body text. Bla blaa /// blaa,blaa. /// //--- End of message /// /// /// In simple message MainEntity is whole message. /// /// <B>Message with attachments:</B> /// /// //--- Beginning of message /// From: <EMAIL> /// To: <EMAIL> /// Subject: Message subject. /// Content-Type: multipart/mixed; boundary="multipart_mixed" /// /// --multipart_mixed /* text entity */ /// Content-Type: text/plain /// /// Message body text. Bla blaa /// blaa,blaa. /// --multipart_mixed /* attachment entity */ /// Content-Type: application/octet-stream /// /// attachment_data /// --multipart_mixed-- /// //--- End of message /// /// MainEntity is multipart_mixed entity and text and attachment entities are child entities of MainEntity. /// </code> /// </remarks> /// <example> /// <code> /// // Parsing example: /// Mime m = Mime.Parse("message.eml"); /// // Do your stuff with mime /// </code> /// <code> /// // Create simple message with simple way: /// AddressList from = new AddressList(); /// from.Add(new MailboxAddress("dispaly name","<EMAIL>")); /// AddressList to = new AddressList(); /// to.Add(new MailboxAddress("dispaly name","<EMAIL>")); /// /// Mime m = Mime.CreateSimple(from,to,"test subject","test body text",""); /// </code> /// <code> /// // Creating a new simple message /// Mime m = new Mime(); /// MimeEntity mainEntity = m.MainEntity; /// // Force to create From: header field /// mainEntity.From = new AddressList(); /// mainEntity.From.Add(new MailboxAddress("dispaly name","<EMAIL>")); /// // Force to create To: header field /// mainEntity.To = new AddressList(); /// mainEntity.To.Add(new MailboxAddress("dispaly name","<EMAIL>")); /// mainEntity.Subject = "subject"; /// mainEntity.ContentType = MediaType_enum.Text_plain; /// mainEntity.ContentTransferEncoding = ContentTransferEncoding_enum.QuotedPrintable; /// mainEntity.DataText = "Message body text."; /// /// m.ToFile("message.eml"); /// </code> /// <code> /// // Creating message with text and attachments /// Mime m = new Mime(); /// MimeEntity mainEntity = m.MainEntity; /// // Force to create From: header field /// mainEntity.From = new AddressList(); /// mainEntity.From.Add(new MailboxAddress("dispaly name","<EMAIL>")); /// // Force to create To: header field /// mainEntity.To = new AddressList(); /// mainEntity.To.Add(new MailboxAddress("dispaly name","<EMAIL>")); /// mainEntity.Subject = "subject"; /// mainEntity.ContentType = MediaType_enum.Multipart_mixed; /// /// MimeEntity textEntity = mainEntity.ChildEntities.Add(); /// textEntity.ContentType = MediaType_enum.Text_plain; /// textEntity.ContentTransferEncoding = ContentTransferEncoding_enum.QuotedPrintable; /// textEntity.DataText = "Message body text."; /// /// MimeEntity attachmentEntity = mainEntity.ChildEntities.Add(); /// attachmentEntity.ContentType = MediaType_enum.Application_octet_stream; /// attachmentEntity.ContentDisposition = ContentDisposition_enum.Attachment; /// attachmentEntity.ContentTransferEncoding = ContentTransferEncoding_enum.Base64; /// attachmentEntity.ContentDisposition_FileName = "yourfile.xxx"; /// attachmentEntity.DataFromFile("yourfile.xxx"); /// // or /// attachmentEntity.Data = your_attachment_data; /// </code> /// </example> [Obsolete("See LumiSoft.Net.MIME or LumiSoft.Net.Mail namepaces for replacement.")] public class Mime { #region Members private readonly MimeEntity m_pMainEntity; #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> public Mime() { m_pMainEntity = new MimeEntity(); // Add default header fields m_pMainEntity.MessageID = MimeUtils.CreateMessageID(); m_pMainEntity.Date = DateTime.Now; m_pMainEntity.MimeVersion = "1.0"; } #endregion #region Properties /// <summary> /// Gets attachment entities. Entity is considered as attachmnet if:<p/> /// *) Content-Disposition: attachment (RFC 2822 message)<p/> /// *) Content-Disposition: filename = "" is specified (RFC 2822 message)<p/> /// *) Content-Type: name = "" is specified (old RFC 822 message)<p/> /// </summary> public MimeEntity[] Attachments { get { List<MimeEntity> attachments = new List<MimeEntity>(); MimeEntity[] entities = MimeEntities; foreach (MimeEntity entity in entities) { if (entity.ContentDisposition == ContentDisposition_enum.Attachment) { attachments.Add(entity); } else if (entity.ContentType_Name != null) { attachments.Add(entity); } else if (entity.ContentDisposition_FileName != null) { attachments.Add(entity); } } return attachments.ToArray(); } } /* /// <summary> /// Gets body text mime entity. Returns null if no body body text entity. /// </summary> public MimeEntity BodyTextEntity { get{ if(this.MainEntity.ContentType == MediaType_enum.NotSpecified){ if(this.MainEntity.DataEncoded != null){ return this.MainEntity; } } else{ MimeEntity[] entities = this.MimeEntities; foreach(MimeEntity entity in entities){ if(entity.ContentType == MediaType_enum.Text_plain){ return entity; } } } return null; } } */ /// <summary> /// Gets message body html. Returns null if no body html text specified. /// </summary> public string BodyHtml { get { MimeEntity[] entities = MimeEntities; foreach (MimeEntity entity in entities) { if (entity.ContentType == MediaType_enum.Text_html) { return entity.DataText; } } return null; } } /// <summary> /// Gets message body text. Returns null if no body text specified. /// </summary> public string BodyText { get { /* RFC 2045 5.2 If content Content-Type: header field is missing, then it defaults to: Content-type: text/plain; charset=us-ascii */ if (MainEntity.ContentType == MediaType_enum.NotSpecified) { if (MainEntity.DataEncoded != null) { return Encoding.ASCII.GetString(MainEntity.Data); } } else { MimeEntity[] entities = MimeEntities; foreach (MimeEntity entity in entities) { if (entity.ContentType == MediaType_enum.Text_plain) { return entity.DataText; } } } return null; } } /// <summary> /// Message main(top-level) entity. /// </summary> public MimeEntity MainEntity { get { return m_pMainEntity; } } /// <summary> /// Gets all mime entities contained in message, including child entities. /// </summary> public MimeEntity[] MimeEntities { get { List<MimeEntity> allEntities = new List<MimeEntity>(); allEntities.Add(m_pMainEntity); GetEntities(m_pMainEntity.ChildEntities, allEntities); return allEntities.ToArray(); } } #endregion #region Methods /// <summary> /// Parses mime message from byte[] data. /// </summary> /// <param name="data">Mime message data.</param> /// <returns></returns> public static Mime Parse(byte[] data) { using (MemoryStream ms = new MemoryStream(data)) { return Parse(ms); } } /// <summary> /// Parses mime message from file. /// </summary> /// <param name="fileName">Mime message file.</param> /// <returns></returns> public static Mime Parse(string fileName) { using (FileStream fs = File.OpenRead(fileName)) { return Parse(fs); } } /// <summary> /// Parses mime message from stream. /// </summary> /// <param name="stream">Mime message stream.</param> /// <returns></returns> public static Mime Parse(Stream stream) { Mime mime = new Mime(); mime.MainEntity.Parse(new SmartStream(stream, false), null); return mime; } /// <summary> /// Creates simple mime message. /// </summary> /// <param name="from">Header field From: value.</param> /// <param name="to">Header field To: value.</param> /// <param name="subject">Header field Subject: value.</param> /// <param name="bodyText">Body text of message. NOTE: Pass null is body text isn't wanted.</param> /// <param name="bodyHtml">Body HTML text of message. NOTE: Pass null is body HTML text isn't wanted.</param> /// <returns></returns> public static Mime CreateSimple(AddressList from, AddressList to, string subject, string bodyText, string bodyHtml) { return CreateSimple(from, to, subject, bodyText, bodyHtml, null); } /// <summary> /// Creates simple mime message with attachments. /// </summary> /// <param name="from">Header field From: value.</param> /// <param name="to">Header field To: value.</param> /// <param name="subject">Header field Subject: value.</param> /// <param name="bodyText">Body text of message. NOTE: Pass null is body text isn't wanted.</param> /// <param name="bodyHtml">Body HTML text of message. NOTE: Pass null is body HTML text isn't wanted.</param> /// <param name="attachmentFileNames">Attachment file names. Pass null if no attachments. NOTE: File name must contain full path to file, for example: c:\test.pdf.</param> /// <returns></returns> public static Mime CreateSimple(AddressList from, AddressList to, string subject, string bodyText, string bodyHtml, string[] attachmentFileNames) { Mime m = new Mime(); MimeEntity mainEntity = m.MainEntity; mainEntity.From = from; mainEntity.To = to; mainEntity.Subject = subject; // There are no atachments if (attachmentFileNames == null || attachmentFileNames.Length == 0) { // If bodyText and bodyHtml both specified if (bodyText != null && bodyHtml != null) { mainEntity.ContentType = MediaType_enum.Multipart_alternative; MimeEntity textEntity = mainEntity.ChildEntities.Add(); textEntity.ContentType = MediaType_enum.Text_plain; textEntity.ContentTransferEncoding = ContentTransferEncoding_enum.QuotedPrintable; textEntity.DataText = bodyText; MimeEntity textHtmlEntity = mainEntity.ChildEntities.Add(); textHtmlEntity.ContentType = MediaType_enum.Text_html; textHtmlEntity.ContentTransferEncoding = ContentTransferEncoding_enum.QuotedPrintable; textHtmlEntity.DataText = bodyHtml; } // There is only body text else if (bodyText != null) { MimeEntity textEntity = mainEntity; textEntity.ContentType = MediaType_enum.Text_plain; textEntity.ContentTransferEncoding = ContentTransferEncoding_enum.QuotedPrintable; textEntity.DataText = bodyText; } // There is only body html text else if (bodyHtml != null) { MimeEntity textHtmlEntity = mainEntity; textHtmlEntity.ContentType = MediaType_enum.Text_html; textHtmlEntity.ContentTransferEncoding = ContentTransferEncoding_enum.QuotedPrintable; textHtmlEntity.DataText = bodyHtml; } } // There are attachments else { mainEntity.ContentType = MediaType_enum.Multipart_mixed; // If bodyText and bodyHtml both specified if (bodyText != null && bodyHtml != null) { MimeEntity multiPartAlternativeEntity = mainEntity.ChildEntities.Add(); multiPartAlternativeEntity.ContentType = MediaType_enum.Multipart_alternative; MimeEntity textEntity = multiPartAlternativeEntity.ChildEntities.Add(); textEntity.ContentType = MediaType_enum.Text_plain; textEntity.ContentTransferEncoding = ContentTransferEncoding_enum.QuotedPrintable; textEntity.DataText = bodyText; MimeEntity textHtmlEntity = multiPartAlternativeEntity.ChildEntities.Add(); textHtmlEntity.ContentType = MediaType_enum.Text_html; textHtmlEntity.ContentTransferEncoding = ContentTransferEncoding_enum.QuotedPrintable; textHtmlEntity.DataText = bodyHtml; } // There is only body text else if (bodyText != null) { MimeEntity textEntity = mainEntity.ChildEntities.Add(); textEntity.ContentType = MediaType_enum.Text_plain; textEntity.ContentTransferEncoding = ContentTransferEncoding_enum.QuotedPrintable; textEntity.DataText = bodyText; } // There is only body html text else if (bodyHtml != null) { MimeEntity textHtmlEntity = mainEntity.ChildEntities.Add(); textHtmlEntity.ContentType = MediaType_enum.Text_html; textHtmlEntity.ContentTransferEncoding = ContentTransferEncoding_enum.QuotedPrintable; textHtmlEntity.DataText = bodyHtml; } foreach (string fileName in attachmentFileNames) { MimeEntity attachmentEntity = mainEntity.ChildEntities.Add(); attachmentEntity.ContentType = MediaType_enum.Application_octet_stream; attachmentEntity.ContentDisposition = ContentDisposition_enum.Attachment; attachmentEntity.ContentTransferEncoding = ContentTransferEncoding_enum.Base64; attachmentEntity.ContentDisposition_FileName = Core.GetFileNameFromPath(fileName); attachmentEntity.DataFromFile(fileName); } } return m; } /// <summary> /// Stores mime message to string. /// </summary> /// <returns></returns> public string ToStringData() { return Encoding.Default.GetString(ToByteData()); } /// <summary> /// Stores mime message to byte[]. /// </summary> /// <returns></returns> public byte[] ToByteData() { using (MemoryStream ms = new MemoryStream()) { ToStream(ms); return ms.ToArray(); } } /// <summary> /// Stores mime message to specified file. /// </summary> /// <param name="fileName">File name.</param> public void ToFile(string fileName) { using (FileStream fs = File.Create(fileName)) { ToStream(fs); } } /// <summary> /// Stores mime message to specified stream. Stream position stays where mime writing ends. /// </summary> /// <param name="storeStream">Stream where to store mime message.</param> public void ToStream(Stream storeStream) { m_pMainEntity.ToStream(storeStream); } #endregion #region Utility methods /// <summary> /// Gets mime entities, including nested entries. /// </summary> /// <param name="entities"></param> /// <param name="allEntries"></param> private void GetEntities(MimeEntityCollection entities, List<MimeEntity> allEntries) { if (entities != null) { foreach (MimeEntity ent in entities) { allEntries.Add(ent); // Add child entities, if any if (ent.ChildEntities.Count > 0) { GetEntities(ent.ChildEntities, allEntries); } } } } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/EncodingTools.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections.Generic; using System.Text; using System.Runtime.InteropServices; using System.IO; namespace ASC.Mail.Net { public static class EncodingTools { // this only contains ascii, default windows code page and unicode public static int[] PreferedEncodingsForStream; // this contains all codepages, sorted by preference and byte usage public static int[] PreferedEncodings; // this contains all codepages, sorted by preference and byte usage public static int[] AllEncodings; public static Dictionary<string, string> encoding_aliases; /// <summary> /// Static constructor that fills the default preferred codepages /// </summary> static EncodingTools() { List<int> streamEcodings = new List<int>(); List<int> allEncodings = new List<int>(); List<int> mimeEcodings = new List<int>(); // asscii - most simple so put it in first place... streamEcodings.Add(Encoding.ASCII.CodePage); mimeEcodings.Add(Encoding.ASCII.CodePage); allEncodings.Add(Encoding.ASCII.CodePage); // add default 2nd for all encodings allEncodings.Add(Encoding.Default.CodePage); // default is single byte? if (Encoding.Default.IsSingleByte) { // put it in second place streamEcodings.Add(Encoding.Default.CodePage); mimeEcodings.Add(Encoding.Default.CodePage); } // prefer JIS over JIS-SHIFT (JIS is detected better than JIS-SHIFT) // this one does include cyrilic (strange but true) allEncodings.Add(50220); mimeEcodings.Add(50220); // always allow unicode flavours for streams (they all have a preamble) streamEcodings.Add(Encoding.Unicode.CodePage); foreach (EncodingInfo enc in Encoding.GetEncodings()) { if (!streamEcodings.Contains(enc.CodePage)) { Encoding encoding = Encoding.GetEncoding(enc.CodePage); if (encoding.GetPreamble().Length > 0) streamEcodings.Add(enc.CodePage); } } // stream is done here PreferedEncodingsForStream = streamEcodings.ToArray(); // all singlebyte encodings foreach (EncodingInfo enc in Encoding.GetEncodings()) { if (!enc.GetEncoding().IsSingleByte) continue; if (!allEncodings.Contains(enc.CodePage)) allEncodings.Add(enc.CodePage); // only add iso and IBM encodings to mime encodings if (enc.CodePage <= 1258) { mimeEcodings.Add(enc.CodePage); } } // add the rest (multibyte) foreach (EncodingInfo enc in Encoding.GetEncodings()) { if (!enc.GetEncoding().IsSingleByte) { if (!allEncodings.Contains(enc.CodePage)) allEncodings.Add(enc.CodePage); // only add iso and IBM encodings to mime encodings if (enc.CodePage <= 1258) { mimeEcodings.Add(enc.CodePage); } } } // add unicodes mimeEcodings.Add(Encoding.Unicode.CodePage); PreferedEncodings = mimeEcodings.ToArray(); AllEncodings = allEncodings.ToArray(); #region Fill in codepage aliases map encoding_aliases = new Dictionary<string, string>(); string[] known_aliases = new string[] { // first name is an alias. The second one is a registered in IANA name // All aliases (first column) must be in lower case // Please don't append aliases to aliases. This will lead to exception in GetEncodingByCodepageName() // It was investigated that only Java aliases are not present in Encoding class internal lists. // All windows aliases may be found here: http://www.lingoes.net/en/translator/codepage.htm // Java aliases have been obtained from here: http://docs.oracle.com/javase/1.4.2/docs/guide/intl/encoding.doc.html "cp1250", "windows-1250", // Windows Eastern European "cp-1250", "windows-1250", "cp1251", "windows-1251", // Windows Cyrillic "cp-1251", "windows-1251", "cp1252", "windows-1252", // Windows Latin-1 "cp-1252", "windows-1252", "cp1253", "windows-1253", // Windows Greek "cp-1253", "windows-1253", "cp1254", "windows-1254", // Windows Turkish "cp-1254", "windows-1254", "cp1257", "windows-1257", // Windows Baltic "cp-1257", "windows-1257", "iso8859_1", "iso-8859-1", // ISO 8859-1, Latin Alphabet No. 1 "iso8859_2", "iso-8859-2", // Latin Alphabet No. 2 "iso8859_4", "iso-8859-4", // Latin Alphabet No. 4 "iso8859_5", "iso-8859-5", // Latin/Cyrillic Alphabet "iso8859_7", "iso-8859-7", // Latin/Greek Alphabet "iso8859_9", "iso-8859-9", // Latin Alphabet No. 9 "iso8859_13", "iso-8859-13", // Latin Alphabet No. 13 "iso8859_15", "iso-8859-15", // Latin Alphabet No. 15 "koi8_r", "koi8-r", // KOI8-R, Russian "utf8", "utf-8", // Eight-bit UCS Transformation Format "utf16", "utf-16", // Sixteen-bit UCS Transformation Format, byte order identified by an optional byte-order mark "unicodebigunmarked", "utf-16be", // Sixteen-bit Unicode Transformation Format, big-endian byte order "unicodelittleunmarked", "utf-16le", // Sixteen-bit Unicode Transformation Format, little-endian byte order "cp1255", "windows-1255", // Windows Hebrew "cp-1255", "windows-1255", "cp1256", "windows-1256", // Windows Arabic "cp-1256", "windows-1256", "cp1258", "windows-1258", // Windows Vietnamese "cp-1258", "windows-1258", "iso8859_3", "iso-8859-3", // Latin Alphabet No. 3 "iso8859_6", "iso-8859-6", // Latin/Arabic Alphabet "iso8859_8", "iso-8859-8", // Latin/Hebrew Alphabet "ms932", "shift_jis", // Windows Japanese "windows-31j", "shift_jis", // Windows Japanese "euc_jp", "euc-jp", // JISX 0201, 0208 and 0212, EUC encoding Japanese "euc_jp_linux", "x-euc-jp-linux", // JISX 0201, 0208 , EUC encoding Japanese "iso2022jp", "iso-2022-jp", // JIS X 0201, 0208, in ISO 2022 form, Japanese "ms936", "x-mswin-936", // Windows Simplified Chinese "euc_cn", "x-euc-cn", // GB2312, EUC encoding, Simplified Chinese "iscii91", "iscii91", // Windows Japanese "ms949", "x-windows-949", // Windows Korean "iso2022kr", "iso-2022-kr", // ISO 2022 KR, Korean "ms950", "x-windows-950", // Windows Traditional Chinese "ms950_hkscs", "x-ms950-hkscs", // Windows Traditional Chinese with Hong Kong extensions "euc-tw", "x-euc-tw", // CNS11643 (Plane 1-3), EUC encoding, Traditional Chinese "tis620", "tis-620", // TIS620, Thai }; for (int i = 0; i < known_aliases.Length; i += 2) { encoding_aliases[known_aliases[i]] = known_aliases[i + 1]; } #endregion } /// <summary> /// Checks if specified string data is acii data. /// </summary> /// <param name="data"></param> /// <returns></returns> public static bool IsAscii(string data) { // assume empty string to be ascii if ((data == null) || (data.Length == 0)) return true; foreach (char c in data) { if ((int)c > 127) { return false; } } return true; } /// <summary> /// Gets the best Encoding for usage in mime encodings /// </summary> /// <param name="input">text to detect</param> /// <returns>the suggested encoding</returns> public static Encoding GetMostEfficientEncoding(string input) { return GetMostEfficientEncoding(input, PreferedEncodings); } /// <summary> /// Gets the best ISO Encoding for usage in a stream /// </summary> /// <param name="input">text to detect</param> /// <returns>the suggested encoding</returns> public static Encoding GetMostEfficientEncodingForStream(string input) { return GetMostEfficientEncoding(input, PreferedEncodingsForStream); } /// <summary> /// Gets the best fitting encoding from a list of possible encodings /// </summary> /// <param name="input">text to detect</param> /// <param name="preferedEncodings">an array of codepages</param> /// <returns>the suggested encoding</returns> public static Encoding GetMostEfficientEncoding(string input, int[] preferedEncodings) { Encoding enc = DetectOutgoingEncoding(input, preferedEncodings, true); // unicode.. hmmm... check for smallest encoding if (enc.CodePage == Encoding.Unicode.CodePage) { int byteCount = Encoding.UTF7.GetByteCount(input); enc = Encoding.UTF7; int bestByteCount = byteCount; // utf8 smaller? byteCount = Encoding.UTF8.GetByteCount(input); if (byteCount < bestByteCount) { enc = Encoding.UTF8; bestByteCount = byteCount; } // unicode smaller? byteCount = Encoding.Unicode.GetByteCount(input); if (byteCount < bestByteCount) { enc = Encoding.Unicode; bestByteCount = byteCount; } } else { } return enc; } public static Encoding DetectOutgoingEncoding(string input) { return DetectOutgoingEncoding(input, PreferedEncodings, true); } public static Encoding DetectOutgoingStreamEncoding(string input) { return DetectOutgoingEncoding(input, PreferedEncodingsForStream, true); } public static Encoding[] DetectOutgoingEncodings(string input) { return DetectOutgoingEncodings(input, PreferedEncodings, true); } public static Encoding[] DetectOutgoingStreamEncodings(string input) { return DetectOutgoingEncodings(input, PreferedEncodingsForStream, true); } private static Encoding DetectOutgoingEncoding(string input, int[] preferedEncodings, bool preserveOrder) { if (input == null) throw new ArgumentNullException("input"); // empty strings can always be encoded as ASCII if (input.Length == 0) return Encoding.ASCII; Encoding result = Encoding.ASCII; // get the IMultiLanguage3 interface MultiLanguage.IMultiLanguage3 multilang3 = new MultiLanguage.CMultiLanguageClass(); if (multilang3 == null) throw new System.Runtime.InteropServices.COMException("Failed to get IMultilang3"); try { int[] resultCodePages = new int[preferedEncodings != null ? preferedEncodings.Length : Encoding.GetEncodings().Length]; uint detectedCodepages = (uint)resultCodePages.Length; ushort specialChar = (ushort)'?'; // get unmanaged arrays IntPtr pPrefEncs = preferedEncodings == null ? IntPtr.Zero : Marshal.AllocCoTaskMem(sizeof(uint) * preferedEncodings.Length); IntPtr pDetectedEncs = Marshal.AllocCoTaskMem(sizeof(uint) * resultCodePages.Length); try { if (preferedEncodings != null) Marshal.Copy(preferedEncodings, 0, pPrefEncs, preferedEncodings.Length); Marshal.Copy(resultCodePages, 0, pDetectedEncs, resultCodePages.Length); MultiLanguage.MLCPF options = MultiLanguage.MLCPF.MLDETECTF_VALID_NLS; if (preserveOrder) options |= MultiLanguage.MLCPF.MLDETECTF_PRESERVE_ORDER; if (preferedEncodings != null) options |= MultiLanguage.MLCPF.MLDETECTF_PREFERRED_ONLY; multilang3.DetectOutboundCodePage(options, input, (uint)input.Length, pPrefEncs, (uint)(preferedEncodings == null ? 0 : preferedEncodings.Length), pDetectedEncs, ref detectedCodepages, ref specialChar); // get result if (detectedCodepages > 0) { int[] theResult = new int[detectedCodepages]; Marshal.Copy(pDetectedEncs, theResult, 0, theResult.Length); result = Encoding.GetEncoding(theResult[0]); } } finally { if (pPrefEncs != IntPtr.Zero) Marshal.FreeCoTaskMem(pPrefEncs); Marshal.FreeCoTaskMem(pDetectedEncs); } } finally { Marshal.FinalReleaseComObject(multilang3); } return result; } public static Encoding[] DetectOutgoingEncodings(string input, int[] preferedEncodings, bool preserveOrder) { if (input == null) throw new ArgumentNullException("input"); // empty strings can always be encoded as ASCII if (input.Length == 0) return new Encoding[] { Encoding.ASCII }; List<Encoding> result = new List<Encoding>(); // get the IMultiLanguage3 interface MultiLanguage.IMultiLanguage3 multilang3 = new MultiLanguage.CMultiLanguageClass(); if (multilang3 == null) throw new System.Runtime.InteropServices.COMException("Failed to get IMultilang3"); try { int[] resultCodePages = new int[preferedEncodings.Length]; uint detectedCodepages = (uint)resultCodePages.Length; ushort specialChar = (ushort)'?'; // get unmanaged arrays IntPtr pPrefEncs = Marshal.AllocCoTaskMem(sizeof(uint) * preferedEncodings.Length); IntPtr pDetectedEncs = preferedEncodings == null ? IntPtr.Zero : Marshal.AllocCoTaskMem(sizeof(uint) * resultCodePages.Length); try { if (preferedEncodings != null) Marshal.Copy(preferedEncodings, 0, pPrefEncs, preferedEncodings.Length); Marshal.Copy(resultCodePages, 0, pDetectedEncs, resultCodePages.Length); MultiLanguage.MLCPF options = MultiLanguage.MLCPF.MLDETECTF_VALID_NLS | MultiLanguage.MLCPF.MLDETECTF_PREFERRED_ONLY; if (preserveOrder) options |= MultiLanguage.MLCPF.MLDETECTF_PRESERVE_ORDER; if (preferedEncodings != null) options |= MultiLanguage.MLCPF.MLDETECTF_PREFERRED_ONLY; // finally... call to DetectOutboundCodePage multilang3.DetectOutboundCodePage(options, input, (uint)input.Length, pPrefEncs, (uint)(preferedEncodings == null ? 0 : preferedEncodings.Length), pDetectedEncs, ref detectedCodepages, ref specialChar); // get result if (detectedCodepages > 0) { int[] theResult = new int[detectedCodepages]; Marshal.Copy(pDetectedEncs, theResult, 0, theResult.Length); // get the encodings for the codepages for (int i = 0; i < detectedCodepages; i++) result.Add(Encoding.GetEncoding(theResult[i])); } } finally { if (pPrefEncs != IntPtr.Zero) Marshal.FreeCoTaskMem(pPrefEncs); Marshal.FreeCoTaskMem(pDetectedEncs); } } finally { Marshal.FinalReleaseComObject(multilang3); } // nothing found return result.ToArray(); } /// <summary> /// Detect the most probable codepage from an byte array /// </summary> /// <param name="input">array containing the raw data</param> /// <returns>the detected encoding or the default encoding if the detection failed</returns> public static Encoding DetectInputCodepage(byte[] input) { try { Encoding[] detected = DetectInputCodepages(input, 1); if (detected.Length > 0) return detected[0]; return Encoding.Default; } catch (COMException) { // return default codepage on error return Encoding.Default; } } /// <summary> /// Rerurns up to maxEncodings codpages that are assumed to be apropriate /// </summary> /// <param name="input">array containing the raw data</param> /// <param name="maxEncodings">maxiumum number of encodings to detect</param> /// <returns>an array of Encoding with assumed encodings</returns> public static Encoding[] DetectInputCodepages(byte[] input, int maxEncodings) { if (Path.DirectorySeparatorChar == '/') { // unix return new Encoding[0]; } if (maxEncodings < 1) throw new ArgumentOutOfRangeException("at least one encoding must be returend", "maxEncodings"); if (input == null) throw new ArgumentNullException("input"); // empty strings can always be encoded as ASCII if (input.Length == 0) return new Encoding[] { Encoding.ASCII }; // expand the string to be at least 256 bytes if (input.Length < 256) { byte[] newInput = new byte[256]; int steps = 256 / input.Length; for (int i = 0; i < steps; i++) Array.Copy(input, 0, newInput, input.Length * i, input.Length); int rest = 256 % input.Length; if (rest > 0) Array.Copy(input, 0, newInput, steps * input.Length, rest); input = newInput; } List<Encoding> result = new List<Encoding>(); // get the IMultiLanguage" interface MultiLanguage.IMultiLanguage2 multilang2 = new MultiLanguage.CMultiLanguageClass(); if (multilang2 == null) throw new System.Runtime.InteropServices.COMException("Failed to get IMultilang2"); try { MultiLanguage.DetectEncodingInfo[] detectedEncdings = new MultiLanguage.DetectEncodingInfo[maxEncodings]; int scores = detectedEncdings.Length; int srcLen = input.Length; // setup options (none) MultiLanguage.MLDETECTCP options = MultiLanguage.MLDETECTCP.MLDETECTCP_NONE; // finally... call to DetectInputCodepage multilang2.DetectInputCodepage(options, 0, ref input[0], ref srcLen, ref detectedEncdings[0], ref scores); // get result if (scores > 0) { for (int i = 0; i < scores; i++) { // add the result result.Add(Encoding.GetEncoding((int)detectedEncdings[i].nCodePage)); } } } finally { Marshal.FinalReleaseComObject(multilang2); } // nothing found return result.ToArray(); } /// <summary> /// Opens a text file and returns the content /// encoded in the most probable encoding /// </summary> /// <param name="path">path to the souce file</param> /// <returns>the text content of the file</returns> public static string ReadTextFile(string path) { if (path == null) throw new ArgumentNullException("path"); using (Stream fs = File.Open(path, FileMode.Open)) { byte[] rawData = new byte[fs.Length]; Encoding enc = DetectInputCodepage(rawData); return enc.GetString(rawData); } } /// <summary> /// Returns a stream reader for the given /// text file with the best encoding applied /// </summary> /// <param name="path">path to the file</param> /// <returns>a StreamReader for the file</returns> public static StreamReader OpenTextFile(string path) { if (path == null) throw new ArgumentNullException("path"); return OpenTextStream(File.Open(path, FileMode.Open)); } /// <summary> /// Creates a stream reader from a stream and detects /// the encoding form the first bytes in the stream /// </summary> /// <param name="stream">a stream to wrap</param> /// <returns>the newly created StreamReader</returns> public static StreamReader OpenTextStream(Stream stream) { // check stream parameter if (stream == null) throw new ArgumentNullException("stream"); if (!stream.CanSeek) throw new ArgumentException("the stream must support seek operations", "stream"); // assume default encoding at first place Encoding detectedEncoding = Encoding.Default; // seek to stream start stream.Seek(0, SeekOrigin.Begin); // buffer for preamble and up to 512b sample text for dection byte[] buf = new byte[System.Math.Min(stream.Length, 512)]; stream.Read(buf, 0, buf.Length); detectedEncoding = DetectInputCodepage(buf); // seek back to stream start stream.Seek(0, SeekOrigin.Begin); return new StreamReader(stream, detectedEncoding); } /// <summary> /// Create an Encoding instance by codepage name using additional jdk aliases /// Doesn't throw if codepage name is not supported /// </summary> /// <param name="codepage_name">codepage name</param> /// <returns>Created Encoding instance or null if codepage name is not supported</returns> public static Encoding GetEncodingByCodepageName(string codepage_name) { try { return GetEncodingByCodepageName_Throws(codepage_name); } catch (System.ArgumentException) { return null; } } /// <summary> /// Create an Encoding instance by codepage name using additional jdk aliases /// Throws if codepage name is not supported /// </summary> /// <param name="codepage_name">codepage name</param> /// <returns>Created Encoding instance</returns> /// <exception cref="System.ArgumentException">Throws if codepage name is not supported</exception> public static Encoding GetEncodingByCodepageName_Throws(string codepage_name) { string dealiased_name; if (!encoding_aliases.TryGetValue(codepage_name, out dealiased_name)) { dealiased_name = codepage_name; } return System.Text.Encoding.GetEncoding(dealiased_name); } } } <file_sep>/Roadmap.md # ONLYOFFICE Community Server roadmap This document provides the roadmap of the planned ONLYOFFICE Community Server changes. This is an updated and corrected version of the roadmap. We also reserve the right to change it when necessary. ## Version 11.0 ### General * Portal notifications via Telegram * Ability to make an addon (Mail, Chat, Calendar) a default portal page * Two scrolling areas on the page: navingation and content * New version of Elasticsearch - v.7.4 * New mechanics for displaying messages on authorization page * Update to Mono v6.10 ### Security * File encryption at rest * ONLYOFFICE Private Rooms support * Updates for password security (min length = 8 characters, complexity check on client-side, hashing when transmitting to server) ### Documents * Favorites folder, ability to add files to favorites * Recent folder * Custom Filter access rights for spreadsheets * Connecting kDrive via WebDav * Support for .webp images * New MailMerge API for the editors * Separate section for quick access to admin settings on the left panel ### CRM * `Make a VoIP call` action in the contact context menu * Bug fixes ### Control Panel * Control Panel is available in Community Edition * Advanced rebranding settings * Reindexing full-text search via Elasticsearch * Private Rooms enabling page * New Encryption block in the Storage section ## Project information Official website: [https://www.onlyoffice.com/](https://www.onlyoffice.com/) Code repository: <https://github.com/ONLYOFFICE/CommunityServer> Docker Image: <https://github.com/ONLYOFFICE/Docker-CommunityServer> License: [GNU GPL v3.0](https://www.gnu.org/copyleft/gpl.html) SaaS version: <https://www.onlyoffice.com/cloud-office.aspx> ## Support If you have any problems with ONLYOFFICE, please contact us on [developers' forum](https://dev.onlyoffice.org/). <file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/SIP/Message/SIP_t_SessionExpires.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.SIP.Message { #region usings using System; using System.Text; #endregion /// <summary> /// Implements SIP "Session-Expires" value. Defined in RFC 4028. /// </summary> /// <remarks> /// <code> /// RFC 4028 Syntax: /// Session-Expires = delta-seconds *(SEMI se-params) /// se-params = refresher-param / generic-param /// refresher-param = "refresher" EQUAL ("uas" / "uac") /// </code> /// </remarks> public class SIP_t_SessionExpires : SIP_t_ValueWithParams { #region Members private int m_Expires = 90; #endregion #region Properties /// <summary> /// Gets or sets after how many seconds session expires. /// </summary> /// <exception cref="ArgumentException">Is raised when value less than 90 is passed.</exception> public int Expires { get { return m_Expires; } set { if (m_Expires < 90) { throw new ArgumentException("Property Expires value must be >= 90 !"); } m_Expires = value; } } /// <summary> /// Gets or sets Session-Expires 'refresher' parameter. Normally this value is 'ua' or 'uas'. /// Value null means not specified. /// </summary> public string Refresher { get { SIP_Parameter parameter = Parameters["refresher"]; if (parameter != null) { return parameter.Value; } else { return null; } } set { if (value == null) { Parameters.Remove("refresher"); } else { Parameters.Set("refresher", value); } } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="value">Session-Expires value.</param> public SIP_t_SessionExpires(string value) { Parse(value); } /// <summary> /// Default constructor. /// </summary> /// <param name="expires">Specifies after many seconds session expires.</param> /// <param name="refresher">Specifies session refresher(uac/uas/null). Value null means not specified.</param> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> public SIP_t_SessionExpires(int expires, string refresher) { if (m_Expires < 90) { throw new ArgumentException("Argument 'expires' value must be >= 90 !"); } m_Expires = expires; Refresher = refresher; } #endregion #region Methods /// <summary> /// Parses "Session-Expires" from specified value. /// </summary> /// <param name="value">SIP "Session-Expires" value.</param> /// <exception cref="ArgumentNullException">Raised when <b>value</b> is null.</exception> /// <exception cref="SIP_ParseException">Raised when invalid SIP message.</exception> public void Parse(string value) { if (value == null) { throw new ArgumentNullException("value"); } Parse(new StringReader(value)); } /// <summary> /// Parses "Session-Expires" from specified reader. /// </summary> /// <param name="reader">Reader from where to parse.</param> /// <exception cref="ArgumentNullException">Raised when <b>reader</b> is null.</exception> /// <exception cref="SIP_ParseException">Raised when invalid SIP message.</exception> public override void Parse(StringReader reader) { /* Session-Expires = delta-seconds *(SEMI se-params) se-params = refresher-param / generic-param refresher-param = "refresher" EQUAL ("uas" / "uac") */ if (reader == null) { throw new ArgumentNullException("reader"); } // delta-seconds string word = reader.ReadWord(); if (word == null) { throw new SIP_ParseException("Session-Expires delta-seconds value is missing !"); } try { m_Expires = Convert.ToInt32(word); } catch { throw new SIP_ParseException("Invalid Session-Expires delta-seconds value !"); } // Parse parameters ParseParameters(reader); } /// <summary> /// Converts this to valid "Session-Expires" value. /// </summary> /// <returns>Returns "Session-Expires" value.</returns> public override string ToStringValue() { /* Session-Expires = delta-seconds *(SEMI se-params) se-params = refresher-param / generic-param refresher-param = "refresher" EQUAL ("uas" / "uac") */ StringBuilder retVal = new StringBuilder(); // delta-seconds retVal.Append(m_Expires.ToString()); // Add parameters retVal.Append(ParametersToString()); return retVal.ToString(); } #endregion } }<file_sep>/web/studio/ASC.Web.Studio/UserControls/Common/ckeditor/config.js /** * @license Copyright (c) 2003-2016, CKSource - <NAME>. All rights reserved. * For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.editorConfig = function( config ) { this.on("focus", function() { // hide all popup's jq(".studio-action-panel:not(.freeze-display)").hide(); jq(".advanced-selector-container").hide(); }); config.language = ASC.Resources.Master.TwoLetterISOLanguageName; config.enterMode = CKEDITOR.ENTER_P; config.shiftEnterMode = CKEDITOR.ENTER_BR; CKEDITOR.config.forcePasteAsPlainText = false; // default so content won't be manipulated on load CKEDITOR.config.basicEntities = true; CKEDITOR.config.entities = true; CKEDITOR.config.entities_latin = false; CKEDITOR.config.entities_greek = false; CKEDITOR.config.entities_processNumerical = false; CKEDITOR.config.fillEmptyBlocks = function () { return true; }; CKEDITOR.config.allowedContent = true; // don't filter my data //--------main settings config.skin = 'teamlab'; config.width = '100%'; config.height = '400px'; config.resize_dir = 'vertical'; config.filebrowserWindowWidth = '640px'; config.filebrowserWindowHeight = '480px'; config.pasteFromWordRemoveFontStyles = false; config.image_previewText = ' '; config.disableNativeSpellChecker = false; //--------toolbar settings this.getBaseConfig = function() { return [ { name: 'basic', items: ['Undo', 'Redo', '-', 'Font', 'FontSize', 'Bold', 'Italic', 'Underline', 'Strike', 'TextColor', 'BGColor'] }, { name: 'paragraph', items: ['JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock', 'NumberedList', 'BulletedList'] }, { name: 'insert', items: ['Image', 'Smiley', 'Link', 'Unlink', 'RemoveFormat'] } ]; }; config.toolbar_Basic = config.toolbar_CrmEmail = config.toolbar_CrmHistory = config.toolbar_ComNews = config.toolbar_ComForum = this.getBaseConfig(); config.toolbar_Comment = jq.map(this.getBaseConfig(), function (value) { if (value.name == "insert") { value.items.splice(5, 0, "Blockquote"); // Add 'Blockquote' value.items.splice(6, 0, "Source"); // Add 'Source' } return value; }); config.toolbar_Mail = jq.map(this.getBaseConfig(), function(value) { if (value.name == "paragraph") { value.items.splice(4, 0, 'Outdent', 'Indent'); // Add 'Outdent', 'Indent' } if (value.name == "insert") { value.items.splice(5, 0, "Source"); // Add 'Source' value.items.splice(4, 0, "Blockquote"); // Add 'Blockquote' } return value; }); config.toolbar_MailSignature = jq.map(this.getBaseConfig(), function(value) { if (value.name == "basic") { value.items.splice(0, 3); // Remove 'Undo', 'Redo', '-' } if (value.name == "paragraph") { value.items.splice(4, 2); // Remove 'NumberedList', 'BulletedList' } if (value.name == "insert") { value.items.splice(5, 0, "Source"); // Add 'Source' value.items.splice(1, 1); // Remove 'Smiley' } return value; }); config.toolbar_PrjMessage = config.toolbar_ComBlog = jq.map(this.getBaseConfig(), function(value) { if (value.name == "insert") { value.items.splice(5, 0, "Source"); // Add 'Source' value.items.splice(4, 0, 'TeamlabCut'); // Add 'TeamlabCut' } return value; }); //-------Full toolbar config.toolbar_Full = [ { name: 'document', items: ['Source', '-', 'Save', 'NewPage', 'DocProps', 'Preview', 'Print', '-', 'Templates'] }, { name: 'clipboard', items: ['Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord', '-', 'Undo', 'Redo'] }, { name: 'editing', items: ['Find', 'Replace', '-', 'SelectAll', '-', 'SpellChecker', 'Scayt'] }, { name: 'forms', items: ['Form', 'Checkbox', 'Radio', 'TextField', 'Textarea', 'Select', 'Button', 'ImageButton','HiddenField'] }, '/', { name: 'basicstyles', items: ['Bold', 'Italic', 'Underline', 'Strike', 'Subscript', 'Superscript', '-', 'RemoveFormat'] }, { name: 'paragraph', items: ['NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-', 'Blockquote', 'CreateDiv', '-', 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock', '-', 'BidiLtr', 'BidiRtl'] }, { name: 'links', items: ['Link', 'Unlink', 'Anchor'] }, { name: 'insert', items: ['Image', 'oembed', 'Flash', 'Table', 'HorizontalRule', 'Smiley', 'SpecialChar', 'PageBreak', 'Iframe'] }, '/', { name: 'styles', items: ['Styles', 'Format', 'Font', 'FontSize'] }, { name: 'colors', items: ['TextColor', 'BGColor'] }, { name: 'tools', items: ['Maximize', 'ShowBlocks', '-', 'About'] } ]; //--------extraPlugins settings config.extraPlugins = 'oembed,teamlabcut,teamlabquote,codemirror'; config.oembed_maxWidth = '640'; config.oembed_maxHeight = '480'; config.oembed_WrapperClass = 'embeded-content'; //--------teamlabcut settings config.teamlabcut_wrapTable = true; config.smiley_path = CKEDITOR.basePath + 'plugins/smiley/teamlab_images/', config.smiley_images = [ 'smile1.gif', 'smile2.gif', 'smile3.gif', 'smile4.gif', 'smile5.gif', 'smile6.gif', 'smile7.gif', 'smile8.gif', 'smile9.gif', 'smile10.gif', 'smile11.gif', 'smile12.gif', 'smile13.gif', 'smile14.gif', 'smile15.gif', 'smile16.gif', 'smile17.gif', 'smile18.gif', 'smile19.gif', 'smile20.gif', 'smile21.gif' ]; config.smiley_descriptions = [ ':-)', ';-)', ':-\\', ':-D', ':-(', '8-)', '*DANCE*', '[:-}', '*CRAZY*', '=-O', ':-P', ':\'(', ':-!', '*THUMBS UP*', '*SORRY*', '*YAHOO*', '*OK*', ']:->', '*HELP*', '*DRINK*', '@=' ]; config.smiley_columns = 5; var fonts = config.font_names.split(";"); fonts.push("Open Sans/Open Sans, sans-serif"); fonts.sort(); config.font_names = fonts.join(";"); config.font_defaultLabel = 'Open Sans'; config.fontSize_defaultLabel = '12'; };<file_sep>/web/studio/ASC.Web.Studio/Products/Files/Utils/FileShareLink.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Web; using ASC.Common.Utils; using ASC.Files.Core; using ASC.Web.Core.Files; using ASC.Web.Files.Classes; using ASC.Web.Studio.Utility; using File = ASC.Files.Core.File; using FileShare = ASC.Files.Core.Security.FileShare; namespace ASC.Web.Files.Utils { public static class FileShareLink { public static string GetLink(File file, bool withHash = true) { var url = file.DownloadUrl; if (FileUtility.CanWebView(file.Title)) url = FilesLinkUtility.GetFileWebPreviewUrl(file.Title, file.ID); if (withHash) { var linkParams = CreateKey(file.ID.ToString()); url += "&" + FilesLinkUtility.DocShareKey + "=" + HttpUtility.UrlEncode(linkParams); } return CommonLinkUtility.GetFullAbsolutePath(url); } public static string CreateKey(string fileId) { return Signature.Create(fileId, Global.GetDocDbKey()); } public static string Parse(string doc) { return Signature.Read<string>(doc ?? String.Empty, Global.GetDocDbKey()); } public static bool Check(string doc, bool checkRead, IFileDao fileDao, out File file) { var fileShare = Check(doc, fileDao, out file); return (!checkRead && (fileShare == FileShare.ReadWrite || fileShare == FileShare.CustomFilter || fileShare == FileShare.Review || fileShare == FileShare.FillForms || fileShare == FileShare.Comment)) || (checkRead && fileShare != FileShare.Restrict); } public static FileShare Check(string doc, IFileDao fileDao, out File file) { file = null; if (string.IsNullOrEmpty(doc)) return FileShare.Restrict; var fileId = Parse(doc); file = fileDao.GetFile(fileId); if (file == null) return FileShare.Restrict; var filesSecurity = Global.GetFilesSecurity(); if (filesSecurity.CanEdit(file, FileConstant.ShareLinkId)) return FileShare.ReadWrite; if (filesSecurity.CanCustomFilterEdit(file, FileConstant.ShareLinkId)) return FileShare.CustomFilter; if (filesSecurity.CanReview(file, FileConstant.ShareLinkId)) return FileShare.Review; if (filesSecurity.CanFillForms(file, FileConstant.ShareLinkId)) return FileShare.FillForms; if (filesSecurity.CanComment(file, FileConstant.ShareLinkId)) return FileShare.Comment; if (filesSecurity.CanRead(file, FileConstant.ShareLinkId)) return FileShare.Read; return FileShare.Restrict; } } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/IMAP/Server/IMAP_MessageCollection.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.IMAP.Server { #region usings using System; using System.Collections; using System.Collections.Generic; #endregion /// <summary> /// IMAP messages info collection. /// </summary> public class IMAP_MessageCollection : IEnumerable,IDisposable { #region Members private readonly SortedList<long, IMAP_Message> m_pMessages; #endregion #region Properties /// <summary> /// Gets number of messages in the collection. /// </summary> public int Count { get { return m_pMessages.Count; } } /// <summary> /// Gets a IMAP_Message object in the collection by index number. /// </summary> /// <param name="index">An Int32 value that specifies the position of the IMAP_Message object in the IMAP_MessageCollection collection.</param> public IMAP_Message this[int index] { get { return m_pMessages.Values[index]; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> public IMAP_MessageCollection() { m_pMessages = new SortedList<long, IMAP_Message>(); } #endregion #region Methods /// <summary> /// Adds new message info to the collection. /// </summary> /// <param name="id">Message ID.</param> /// <param name="uid">Message IMAP UID value.</param> /// <param name="internalDate">Message store date.</param> /// <param name="size">Message size in bytes.</param> /// <param name="flags">Message flags.</param> /// <returns>Returns added IMAp message info.</returns> public IMAP_Message Add(string id, long uid, DateTime internalDate, long size, IMAP_MessageFlags flags) { if (uid < 1) { throw new ArgumentException("Message UID value must be > 0 !"); } IMAP_Message message = new IMAP_Message(this, id, uid, internalDate, size, flags); m_pMessages.Add(uid, message); return message; } /// <summary> /// Removes specified IMAP message from the collection. /// </summary> /// <param name="message">IMAP message to remove.</param> public void Remove(IMAP_Message message) { m_pMessages.Remove(message.UID); } /// <summary> /// Gets collection contains specified message with specified UID. /// </summary> /// <param name="uid">Message UID.</param> /// <returns></returns> public bool ContainsUID(long uid) { return m_pMessages.ContainsKey(uid); } /// <summary> /// Gets index of specified message in the collection. /// </summary> /// <param name="message">Message indesx to get.</param> /// <returns>Returns index of specified message in the collection or -1 if message doesn't belong to this collection.</returns> public int IndexOf(IMAP_Message message) { return m_pMessages.IndexOfKey(message.UID); } /// <summary> /// Removes all messages from the collection. /// </summary> public void Clear() { m_pMessages.Clear(); } /// <summary> /// Gets messages which has specified flags set. /// </summary> /// <param name="flags">Flags to match.</param> /// <returns></returns> public IMAP_Message[] GetWithFlags(IMAP_MessageFlags flags) { List<IMAP_Message> retVal = new List<IMAP_Message>(); foreach (IMAP_Message message in m_pMessages.Values) { if ((message.Flags & flags) != 0) { retVal.Add(message); } } return retVal.ToArray(); } /// <summary> /// Gets enumerator. /// </summary> /// <returns></returns> public IEnumerator GetEnumerator() { return m_pMessages.Values.GetEnumerator(); } private bool isDisposed = false; public void Dispose() { if (!isDisposed) { isDisposed = true; if (m_pMessages!=null) { foreach (var imapMessage in m_pMessages) { imapMessage.Value.Dispose(); } } } } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/Multilang/tagMIMECONTF.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace MultiLanguage { using System; using System.Security; public enum tagMIMECONTF { MIMECONTF_BROWSER = 2, MIMECONTF_EXPORT = 0x400, MIMECONTF_IMPORT = 8, MIMECONTF_MAILNEWS = 1, MIMECONTF_MIME_IE4 = 0x10000000, MIMECONTF_MIME_LATEST = 0x20000000, MIMECONTF_MIME_REGISTRY = 0x40000000, MIMECONTF_MINIMAL = 4, MIMECONTF_PRIVCONVERTER = 0x10000, MIMECONTF_SAVABLE_BROWSER = 0x200, MIMECONTF_SAVABLE_MAILNEWS = 0x100, MIMECONTF_VALID = 0x20000, MIMECONTF_VALID_NLS = 0x40000 } } <file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/Mail/Mail_t_MailboxList.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.Mail { #region usings using System; using System.Collections; using System.Collections.Generic; using System.Text; #endregion /// <summary> /// This class represents <b>mailbox-list</b>. Defined in RFC 5322 3.4. /// </summary> public class Mail_t_MailboxList : IEnumerable { #region Members private readonly List<Mail_t_Mailbox> m_pList; private bool m_IsModified; #endregion #region Properties /// <summary> /// Gets if list has modified since it was loaded. /// </summary> public bool IsModified { get { return m_IsModified; } } /// <summary> /// Gets number of items in the collection. /// </summary> public int Count { get { return m_pList.Count; } } /// <summary> /// Gets the element at the specified index. /// </summary> /// <param name="index">The zero-based index of the element to get.</param> /// <returns>Returns the element at the specified index.</returns> /// <exception cref="ArgumentOutOfRangeException">Is raised when <b>index</b> is out of range.</exception> public Mail_t_Mailbox this[int index] { get { if (index < 0 || index >= m_pList.Count) { throw new ArgumentOutOfRangeException("index"); } return m_pList[index]; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> public Mail_t_MailboxList() { m_pList = new List<Mail_t_Mailbox>(); } #endregion #region Methods /// <summary> /// Inserts a address into the collection at the specified location. /// </summary> /// <param name="index">The location in the collection where you want to add the item.</param> /// <param name="value">Address to insert.</param> /// <exception cref="ArgumentOutOfRangeException">Is raised when <b>index</b> is out of range.</exception> /// <exception cref="ArgumentNullException">Is raised when <b>value</b> is null reference.</exception> public void Insert(int index, Mail_t_Mailbox value) { if (index < 0 || index > m_pList.Count) { throw new ArgumentOutOfRangeException("index"); } if (value == null) { throw new ArgumentNullException("value"); } m_pList.Insert(index, value); m_IsModified = true; } /// <summary> /// Adds specified address to the end of the collection. /// </summary> /// <param name="value">Address to add.</param> /// <exception cref="ArgumentNullException">Is raised when <b>value</b> is null reference value.</exception> public void Add(Mail_t_Mailbox value) { if (value == null) { throw new ArgumentNullException("value"); } m_pList.Add(value); m_IsModified = true; } /// <summary> /// Removes specified item from the collection. /// </summary> /// <param name="value">Address to remove.</param> /// <exception cref="ArgumentNullException">Is raised when <b>value</b> is null reference value.</exception> public void Remove(Mail_t_Mailbox value) { if (value == null) { throw new ArgumentNullException("value"); } m_pList.Remove(value); } /// <summary> /// Removes all items from the collection. /// </summary> public void Clear() { m_pList.Clear(); m_IsModified = true; } /// <summary> /// Copies addresses to new array. /// </summary> /// <returns>Returns addresses array.</returns> public Mail_t_Mailbox[] ToArray() { return m_pList.ToArray(); } /// <summary> /// Gets enumerator. /// </summary> /// <returns></returns> public IEnumerator GetEnumerator() { return m_pList.GetEnumerator(); } public override string ToString() { StringBuilder retVal = new StringBuilder(); for (int i = 0; i < m_pList.Count; i++) { if (i == (m_pList.Count - 1)) { retVal.Append(m_pList[i].ToString().Trim()); } else { retVal.Append(m_pList[i].ToString().Trim() + ","); } } return retVal.ToString(); } #endregion #region Internal methods /// <summary> /// Resets IsModified property to false. /// </summary> internal void AcceptChanges() { m_IsModified = false; } #endregion } }<file_sep>/module/ASC.AuditTrail/Mappers/SettingsActionMapper.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System.Collections.Generic; using ASC.MessagingSystem; namespace ASC.AuditTrail.Mappers { internal class SettingsActionsMapper { public static Dictionary<MessageAction, MessageMaps> GetMaps() { return new Dictionary<MessageAction, MessageMaps> { { MessageAction.LanguageSettingsUpdated, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "LanguageSettingsUpdated", ProductResourceName = "SettingsProduct", ModuleResourceName = "GeneralModule" } }, { MessageAction.TimeZoneSettingsUpdated, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "TimeZoneSettingsUpdated", ProductResourceName = "SettingsProduct", ModuleResourceName = "GeneralModule" } }, { MessageAction.DnsSettingsUpdated, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "DnsSettingsUpdated", ProductResourceName = "SettingsProduct", ModuleResourceName = "GeneralModule" } }, { MessageAction.TrustedMailDomainSettingsUpdated, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "TrustedMailDomainSettingsUpdated", ProductResourceName = "SettingsProduct", ModuleResourceName = "GeneralModule" } }, { MessageAction.PasswordStrengthSettingsUpdated, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "PasswordStrengthSettingsUpdated", ProductResourceName = "SettingsProduct", ModuleResourceName = "GeneralModule" } }, { MessageAction.TwoFactorAuthenticationSettingsUpdated, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "TwoFactorAuthenticationSettingsUpdated", ProductResourceName = "SettingsProduct", ModuleResourceName = "GeneralModule" } }, { MessageAction.TwoFactorAuthenticationDisabled, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "TwoFactorAuthenticationSettingsDisabled", ProductResourceName = "SettingsProduct", ModuleResourceName = "GeneralModule" } }, { MessageAction.TwoFactorAuthenticationEnabledBySms, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "TwoFactorAuthenticationSettingsEnabledBySms", ProductResourceName = "SettingsProduct", ModuleResourceName = "GeneralModule" } }, { MessageAction.TwoFactorAuthenticationEnabledByTfaApp, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "TwoFactorAuthenticationSettingsEnabledByTfaApp", ProductResourceName = "SettingsProduct", ModuleResourceName = "GeneralModule" } }, { MessageAction.AdministratorMessageSettingsUpdated, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "AdministratorMessageSettingsUpdated", ProductResourceName = "SettingsProduct", ModuleResourceName = "GeneralModule" } }, { MessageAction.DefaultStartPageSettingsUpdated, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "DefaultStartPageSettingsUpdated", ProductResourceName = "SettingsProduct", ModuleResourceName = "GeneralModule" } }, { MessageAction.ProductsListUpdated, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "ProductsListUpdated", ProductResourceName = "SettingsProduct", ModuleResourceName = "ProductsModule" } }, { MessageAction.OwnerUpdated, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "OwnerChanged", ProductResourceName = "SettingsProduct", ModuleResourceName = "ProductsModule" } }, { MessageAction.AdministratorAdded, new MessageMaps { ActionTypeTextResourceName = "CreateActionType", ActionTextResourceName = "AdministratorAdded", ProductResourceName = "SettingsProduct", ModuleResourceName = "ProductsModule" } }, { MessageAction.UsersOpenedProductAccess, new MessageMaps { ActionTypeTextResourceName = "UpdateAccessActionType", ActionTextResourceName = "ProductAccessOpenedForUsers", ProductResourceName = "SettingsProduct", ModuleResourceName = "ProductsModule" } }, { MessageAction.GroupsOpenedProductAccess, new MessageMaps { ActionTypeTextResourceName = "UpdateAccessActionType", ActionTextResourceName = "ProductAccessOpenedForGroups", ProductResourceName = "SettingsProduct", ModuleResourceName = "ProductsModule" } }, { MessageAction.ProductAccessOpened, new MessageMaps { ActionTypeTextResourceName = "UpdateAccessActionType", ActionTextResourceName = "ProductAccessOpened", ProductResourceName = "SettingsProduct", ModuleResourceName = "ProductsModule" } }, { MessageAction.ProductAccessRestricted, new MessageMaps { ActionTypeTextResourceName = "UpdateAccessActionType", ActionTextResourceName = "ProductAccessRestricted", ProductResourceName = "SettingsProduct", ModuleResourceName = "ProductsModule" } }, { MessageAction.ProductAddedAdministrator, new MessageMaps { ActionTypeTextResourceName = "CreateActionType", ActionTextResourceName = "ProductAddedAdministrator", ProductResourceName = "SettingsProduct", ModuleResourceName = "ProductsModule" } }, { MessageAction.ProductDeletedAdministrator, new MessageMaps { ActionTypeTextResourceName = "DeleteActionType", ActionTextResourceName = "ProductDeletedAdministrator", ProductResourceName = "SettingsProduct", ModuleResourceName = "ProductsModule" } }, { MessageAction.AdministratorDeleted, new MessageMaps { ActionTypeTextResourceName = "UpdateAccessActionType", ActionTextResourceName = "AdministratorDeleted", ProductResourceName = "SettingsProduct", ModuleResourceName = "ProductsModule" } }, { MessageAction.AdministratorOpenedFullAccess, new MessageMaps { ActionTypeTextResourceName = "UpdateAccessActionType", ActionTextResourceName = "AdministratorOpenedFullAccess", ProductResourceName = "SettingsProduct", ModuleResourceName = "ProductsModule" } }, { MessageAction.GreetingSettingsUpdated, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "GreetingSettingsUpdated", ProductResourceName = "SettingsProduct", ModuleResourceName = "ProductsModule" } }, { MessageAction.TeamTemplateChanged, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "TeamTemplateChanged", ProductResourceName = "SettingsProduct", ModuleResourceName = "ProductsModule" } }, { MessageAction.ColorThemeChanged, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "ColorThemeChanged", ProductResourceName = "SettingsProduct", ModuleResourceName = "ProductsModule" } }, { MessageAction.OwnerSentPortalDeactivationInstructions, new MessageMaps { ActionTypeTextResourceName = "SendActionType", ActionTextResourceName = "OwnerSentPortalDeactivationInstructions", ProductResourceName = "SettingsProduct", ModuleResourceName = "ProductsModule" } }, { MessageAction.OwnerSentPortalDeleteInstructions, new MessageMaps { ActionTypeTextResourceName = "SendActionType", ActionTextResourceName = "OwnerSentPortalDeleteInstructions", ProductResourceName = "SettingsProduct", ModuleResourceName = "ProductsModule" } }, { MessageAction.LoginHistoryReportDownloaded, new MessageMaps { ActionTypeTextResourceName = "DownloadActionType", ActionTextResourceName = "LoginHistoryReportDownloaded", ProductResourceName = "SettingsProduct", ModuleResourceName = "ProductsModule" } }, { MessageAction.AuditTrailReportDownloaded, new MessageMaps { ActionTypeTextResourceName = "DownloadActionType", ActionTextResourceName = "AuditTrailReportDownloaded", ProductResourceName = "SettingsProduct", ModuleResourceName = "ProductsModule" } }, { MessageAction.PortalDeactivated, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "PortalDeactivated", ProductResourceName = "SettingsProduct", ModuleResourceName = "ProductsModule" } }, { MessageAction.PortalDeleted, new MessageMaps { ActionTypeTextResourceName = "DeleteActionType", ActionTextResourceName = "PortalDeleted", ProductResourceName = "SettingsProduct", ModuleResourceName = "ProductsModule" } }, { MessageAction.OwnerSentChangeOwnerInstructions, new MessageMaps { ActionTypeTextResourceName = "SendActionType", ActionTextResourceName = "OwnerSentChangeOwnerInstructions", ProductResourceName = "SettingsProduct", ModuleResourceName = "ProductsModule" } }, { MessageAction.SSOEnabled, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "SSOEnabled", ProductResourceName = "SettingsProduct", ModuleResourceName = "ProductsModule" } }, { MessageAction.SSODisabled, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "SSODisabled", ProductResourceName = "SettingsProduct", ModuleResourceName = "ProductsModule" } }, { MessageAction.PortalAccessSettingsUpdated, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "PortalAccessSettingsUpdated", ProductResourceName = "SettingsProduct", ModuleResourceName = "ProductsModule" } }, { MessageAction.DocumentServiceLocationSetting, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "DocumentServiceLocationSetting", ProductResourceName = "SettingsProduct", ModuleResourceName = "ProductsModule" } }, { MessageAction.AuthorizationKeysSetting, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "AuthorizationKeysSetting", ProductResourceName = "SettingsProduct", ModuleResourceName = "ProductsModule" } }, { MessageAction.FullTextSearchSetting, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "FullTextSearchSetting", ProductResourceName = "SettingsProduct", ModuleResourceName = "ProductsModule" } }, { MessageAction.StartTransferSetting, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "StartTransferSetting", ProductResourceName = "SettingsProduct", ModuleResourceName = "ProductsModule" } }, { MessageAction.StartBackupSetting, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "StartBackupSetting", ProductResourceName = "SettingsProduct", ModuleResourceName = "ProductsModule" } }, { MessageAction.LicenseKeyUploaded, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "LicenseKeyUploaded", ProductResourceName = "SettingsProduct", ModuleResourceName = "ProductsModule" } }, { MessageAction.StartStorageEncryption, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "StartStorageEncryption", ProductResourceName = "SettingsProduct", ModuleResourceName = "ProductsModule" } }, { MessageAction.StartStorageDecryption, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "StartStorageDecryption", ProductResourceName = "SettingsProduct", ModuleResourceName = "ProductsModule" } }, { MessageAction.CookieSettingsUpdated, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "CookieSettingsUpdated", ProductResourceName = "SettingsProduct", ModuleResourceName = "ProductsModule" } }, { MessageAction.MailServiceSettingsUpdated, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "MailServiceSettingsUpdated", ProductResourceName = "SettingsProduct", ModuleResourceName = "ProductsModule" } }, { MessageAction.CustomNavigationSettingsUpdated, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "CustomNavigationSettingsUpdated", ProductResourceName = "SettingsProduct", ModuleResourceName = "ProductsModule" } }, { MessageAction.AuditSettingsUpdated, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "AuditSettingsUpdated", ProductResourceName = "SettingsProduct", ModuleResourceName = "ProductsModule" } }, { MessageAction.PrivacyRoomEnable, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "PrivacyRoomEnable", ProductResourceName = "SettingsProduct", ModuleResourceName = "ProductsModule" } }, { MessageAction.PrivacyRoomDisable, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "PrivacyRoomDisable", ProductResourceName = "SettingsProduct", ModuleResourceName = "ProductsModule" } } }; } } }<file_sep>/module/ASC.TelegramService/TelegramHandler.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections.Generic; using System.Net; using System.Linq; using System.Runtime.Caching; using ASC.Common.Logging; using ASC.Core.Common.Notify.Telegram; using ASC.Notify.Messages; using ASC.TelegramService.Core; using Telegram.Bot; using Telegram.Bot.Args; namespace ASC.TelegramService { public class TelegramHandler { private readonly Dictionary<int, TenantTgClient> clients; private readonly CommandModule command; private readonly ILog log; public TelegramHandler(CommandModule command, ILog log) { this.command = command; this.log = log; clients = new Dictionary<int, TenantTgClient>(); ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12 | SecurityProtocolType.Tls13; } public async void SendMessage(NotifyMessage msg) { if (string.IsNullOrEmpty(msg.To)) return; if (!clients.ContainsKey(msg.Tenant)) return; var client = clients[msg.Tenant].Client; try { var tgUser = CachedTelegramDao.Instance.GetUser(Guid.Parse(msg.To), msg.Tenant); if (tgUser == null) { log.DebugFormat("Couldn't find telegramId for user '{0}'", msg.To); return; } var chat = await client.GetChatAsync(tgUser.TelegramId); await client.SendTextMessageAsync(chat, msg.Content, Telegram.Bot.Types.Enums.ParseMode.Markdown); } catch (Exception e) { log.DebugFormat("Couldn't send message for user '{0}' got an '{1}'", msg.To, e.Message); } } public void DisableClient(int tenantId) { if (!clients.ContainsKey(tenantId)) return; var client = clients[tenantId]; client.Client.StopReceiving(); clients.Remove(tenantId); } public bool CreateOrUpdateClientForTenant(int tenantId, string token, int tokenLifespan, string proxy, bool force = false) { if (clients.ContainsKey(tenantId)) { var client = clients[tenantId]; client.TokenLifeSpan = tokenLifespan; if (token != client.Token || proxy != client.Proxy) { var newClient = InitClient(token, proxy); try { if (!newClient.TestApiAsync().GetAwaiter().GetResult()) return false; } catch (Exception e) { log.DebugFormat("Couldn't test api connection: {0}", e); return false; } client.Client.StopReceiving(); BindClient(newClient, tenantId); client.Client = newClient; client.Token = token; client.Proxy = proxy; } } else { var client = InitClient(token, proxy); if (!force) { try { if (!client.TestApiAsync().GetAwaiter().GetResult()) return false; } catch (Exception e) { log.DebugFormat("Couldn't test api connection: {0}", e); return false; } } BindClient(client, tenantId); clients.Add(tenantId, new TenantTgClient() { Token = token, Client = client, Proxy = proxy, TenantId = tenantId, TokenLifeSpan = tokenLifespan }); } return true; } public void RegisterUser(string userId, int tenantId, string token) { if (!clients.ContainsKey(tenantId)) return; var userKey = UserKey(userId, tenantId); var dateExpires = DateTimeOffset.Now.AddMinutes(clients[tenantId].TokenLifeSpan); MemoryCache.Default.Set(token, userKey, dateExpires); MemoryCache.Default.Set(string.Format(userKey), token, dateExpires); } public string CurrentRegistrationToken(string userId, int tenantId) { return (string)MemoryCache.Default.Get(UserKey(userId, tenantId)); } private async void OnMessage(object sender, MessageEventArgs e, TelegramBotClient client, int tenantId) { if (string.IsNullOrEmpty(e.Message.Text) || e.Message.Text[0] != '/') return; await command.HandleCommand(e.Message, client, tenantId); } private TelegramBotClient InitClient(string token, string proxy) { return string.IsNullOrEmpty(proxy) ? new TelegramBotClient(token) : new TelegramBotClient(token, new WebProxy(proxy)); } private void BindClient(TelegramBotClient client, int tenantId) { client.OnMessage += (sender, e) => { OnMessage(sender, e, client, tenantId); }; client.StartReceiving(); } private string UserKey(string userId, int tenantId) { return string.Format("{0}:{1}", userId, tenantId); } } } <file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/SDP/SDP_Time.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.SDP { #region usings using System; #endregion /// <summary> /// A SDP_Time represents an <B>t=</B> SDP message field. Defined in RFC 4566 5.9. Timing. /// </summary> public class SDP_Time { #region Members private long m_StartTime; private long m_StopTime; #endregion #region Properties /// <summary> /// Gets or sets start time when session must start. Network Time Protocol (NTP) time values in /// seconds since 1900. 0 value means not specified, if StopTime is also 0, then means infinite session. /// </summary> public long StartTime { get { return m_StartTime; } set { if (value < 0) { throw new ArgumentException("Property StartTime value must be >= 0 !"); } m_StopTime = value; } } /// <summary> /// Gets or sets stop time when session must end. Network Time Protocol (NTP) time values in /// seconds since 1900. 0 value means not specified, if StopTime is also 0, then means infinite session. /// </summary> public long StopTime { get { return m_StopTime; } set { if (value < 0) { throw new ArgumentException("Property StopTime value must be >= 0 !"); } m_StopTime = value; } } #endregion #region Methods /// <summary> /// Parses media from "t" SDP message field. /// </summary> /// <param name="tValue">"t" SDP message field.</param> /// <returns></returns> public static SDP_Time Parse(string tValue) { // t=<start-time> <stop-time> SDP_Time time = new SDP_Time(); // Remove t= StringReader r = new StringReader(tValue); r.QuotedReadToDelimiter('='); //--- <start-time> ------------------------------------------------------------ string word = r.ReadWord(); if (word == null) { throw new Exception("SDP message \"t\" field <start-time> value is missing !"); } time.m_StartTime = Convert.ToInt64(word); //--- <stop-time> ------------------------------------------------------------- word = r.ReadWord(); if (word == null) { throw new Exception("SDP message \"t\" field <stop-time> value is missing !"); } time.m_StopTime = Convert.ToInt64(word); return time; } /// <summary> /// Converts this to valid "t" string. /// </summary> /// <returns></returns> public string ToValue() { // t=<start-time> <stop-time> return "t=" + StartTime + " " + StopTime + "\r\n"; } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/vCard/DeliveryAddressType_enum.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.Mime.vCard { /// <summary> /// vCal delivery address type. Note this values may be flagged ! /// </summary> public enum DeliveryAddressType_enum { /// <summary> /// Delivery address type not specified. /// </summary> NotSpecified = 0, /// <summary> /// Preferred delivery address. /// </summary> Preferred = 1, /// <summary> /// Domestic delivery address. /// </summary> Domestic = 2, /// <summary> /// International delivery address. /// </summary> Ineternational = 4, /// <summary> /// Postal delivery address. /// </summary> Postal = 8, /// <summary> /// Parcel delivery address. /// </summary> Parcel = 16, /// <summary> /// Delivery address for a residence. /// </summary> Home = 32, /// <summary> /// Address for a place of work. /// </summary> Work = 64, } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/RTP/RTP_Utils.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.RTP { #region usings using System; using System.Net; #endregion /// <summary> /// This class provides utility methods for RTP. /// </summary> public class RTP_Utils { #region Methods /// <summary> /// Generates random SSRC value. /// </summary> /// <returns>Returns random SSRC value.</returns> public static uint GenerateSSRC() { return (uint) new Random().Next(100000, int.MaxValue); } /// <summary> /// Generates random CNAME value. /// </summary> /// <returns></returns> public static string GenerateCNAME() { // [email protected] return Environment.UserName + "@" + Dns.GetHostName() + "." + Guid.NewGuid().ToString().Substring(0, 8); } /// <summary> /// Converts specified DateTime value to short NTP time. Note: NTP time is in UTC. /// </summary> /// <param name="value">DateTime value to convert. This value must be in local time.</param> /// <returns>Returns NTP value.</returns> public static uint DateTimeToNTP32(DateTime value) { /* In some fields where a more compact representation is appropriate, only the middle 32 bits are used; that is, the low 16 bits of the integer part and the high 16 bits of the fractional part. The high 16 bits of the integer part must be determined independently. */ return (uint) ((DateTimeToNTP64(value) >> 16) & 0xFFFFFFFF); } /// <summary> /// Converts specified DateTime value to long NTP time. Note: NTP time is in UTC. /// </summary> /// <param name="value">DateTime value to convert. This value must be in local time.</param> /// <returns>Returns NTP value.</returns> public static ulong DateTimeToNTP64(DateTime value) { /* Wallclock time (absolute date and time) is represented using the timestamp format of the Network Time Protocol (NTP), which is in seconds relative to 0h UTC on 1 January 1900 [4]. The full resolution NTP timestamp is a 64-bit unsigned fixed-point number with the integer part in the first 32 bits and the fractional part in the last 32 bits. In some fields where a more compact representation is appropriate, only the middle 32 bits are used; that is, the low 16 bits of the integer part and the high 16 bits of the fractional part. The high 16 bits of the integer part must be determined independently. */ TimeSpan ts = ((value.ToUniversalTime() - new DateTime(1900, 1, 1, 0, 0, 0))); return ((ulong) (ts.TotalMilliseconds%1000) << 32) | (uint) (ts.Milliseconds << 22); } #endregion } }<file_sep>/web/studio/ASC.Web.Studio/Products/Files/Services/WCFService/FileOperations/FileDownloadOperation.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading; using ASC.Common.Security.Authentication; using ASC.Data.Storage; using ASC.Files.Core; using ASC.MessagingSystem; using ASC.Web.Core.Files; using ASC.Web.Files.Classes; using ASC.Web.Files.Helpers; using ASC.Web.Files.Resources; using ASC.Web.Files.Utils; using ASC.Web.Studio.Core; using File = ASC.Files.Core.File; namespace ASC.Web.Files.Services.WCFService.FileOperations { class FileDownloadOperation : FileOperation { private readonly Dictionary<object, string> files; private readonly Dictionary<string, string> headers; public override FileOperationType OperationType { get { return FileOperationType.Download; } } public FileDownloadOperation(Dictionary<object, string> folders, Dictionary<object, string> files, Dictionary<string, string> headers) : base(folders.Select(f => f.Key).ToList(), files.Select(f => f.Key).ToList()) { this.files = files; this.headers = headers; } protected override void Do() { var entriesPathId = GetEntriesPathId(); if (entriesPathId == null || entriesPathId.Count == 0) { if (0 < Files.Count) throw new FileNotFoundException(FilesCommonResource.ErrorMassage_FileNotFound); throw new DirectoryNotFoundException(FilesCommonResource.ErrorMassage_FolderNotFound); } ReplaceLongPath(entriesPathId); using (var stream = CompressToZip(entriesPathId)) { if (stream != null) { stream.Position = 0; const string fileName = FileConstant.DownloadTitle + ".zip"; var store = Global.GetStore(); store.Save( FileConstant.StorageDomainTmp, string.Format(@"{0}\{1}", ((IAccount)Thread.CurrentPrincipal.Identity).ID, fileName), stream, "application/zip", "attachment; filename=\"" + fileName + "\""); Status = string.Format("{0}?{1}=bulk", FilesLinkUtility.FileHandlerPath, FilesLinkUtility.Action); } } } private ItemNameValueCollection ExecPathFromFile(File file, string path) { FileMarker.RemoveMarkAsNew(file); var title = file.Title; if (files.ContainsKey(file.ID.ToString())) { var convertToExt = files[file.ID.ToString()]; if (!string.IsNullOrEmpty(convertToExt)) { title = FileUtility.ReplaceFileExtension(title, convertToExt); } } var entriesPathId = new ItemNameValueCollection(); entriesPathId.Add(path + title, file.ID.ToString()); return entriesPathId; } private ItemNameValueCollection GetEntriesPathId() { var entriesPathId = new ItemNameValueCollection(); if (0 < Files.Count) { var files = FileDao.GetFiles(Files.ToArray()); files = FilesSecurity.FilterRead(files).ToList(); files.ForEach(file => entriesPathId.Add(ExecPathFromFile(file, string.Empty))); } if (0 < Folders.Count) { FilesSecurity.FilterRead(FolderDao.GetFolders(Files.ToArray())).ToList().Cast<FileEntry>().ToList() .ForEach(folder => FileMarker.RemoveMarkAsNew(folder)); var filesInFolder = GetFilesInFolders(Folders, string.Empty); entriesPathId.Add(filesInFolder); } return entriesPathId; } private ItemNameValueCollection GetFilesInFolders(IEnumerable<object> folderIds, string path) { CancellationToken.ThrowIfCancellationRequested(); var entriesPathId = new ItemNameValueCollection(); foreach (var folderId in folderIds) { CancellationToken.ThrowIfCancellationRequested(); var folder = FolderDao.GetFolder(folderId); if (folder == null || !FilesSecurity.CanRead(folder)) continue; var folderPath = path + folder.Title + "/"; var files = FileDao.GetFiles(folder.ID, null, FilterType.None, false, Guid.Empty, string.Empty, true); files = FilesSecurity.FilterRead(files).ToList(); files.ForEach(file => entriesPathId.Add(ExecPathFromFile(file, folderPath))); FileMarker.RemoveMarkAsNew(folder); var nestedFolders = FolderDao.GetFolders(folder.ID); nestedFolders = FilesSecurity.FilterRead(nestedFolders).ToList(); if (files.Count == 0 && nestedFolders.Count == 0) { entriesPathId.Add(folderPath, String.Empty); } var filesInFolder = GetFilesInFolders(nestedFolders.ConvertAll(f => f.ID), folderPath); entriesPathId.Add(filesInFolder); } return entriesPathId; } private Stream CompressToZip(ItemNameValueCollection entriesPathId) { var stream = TempStream.Create(); using (var zip = new Ionic.Zip.ZipOutputStream(stream, true)) { zip.CompressionLevel = Ionic.Zlib.CompressionLevel.Level3; zip.AlternateEncodingUsage = Ionic.Zip.ZipOption.AsNecessary; zip.AlternateEncoding = Encoding.UTF8; foreach (var path in entriesPathId.AllKeys) { var counter = 0; foreach (var entryId in entriesPathId[path]) { if (CancellationToken.IsCancellationRequested) { zip.Dispose(); stream.Dispose(); CancellationToken.ThrowIfCancellationRequested(); } var newtitle = path; File file = null; var convertToExt = string.Empty; if (!string.IsNullOrEmpty(entryId)) { FileDao.InvalidateCache(entryId); file = FileDao.GetFile(entryId); if (file == null) { Error = FilesCommonResource.ErrorMassage_FileNotFound; continue; } if (file.ContentLength > SetupInfo.AvailableFileSize) { Error = string.Format(FilesCommonResource.ErrorMassage_FileSizeZip, FileSizeComment.FilesSizeToString(SetupInfo.AvailableFileSize)); continue; } if (files.ContainsKey(file.ID.ToString())) { convertToExt = files[file.ID.ToString()]; if (!string.IsNullOrEmpty(convertToExt)) { newtitle = FileUtility.ReplaceFileExtension(path, convertToExt); } } } if (0 < counter) { var suffix = " (" + counter + ")"; if (!string.IsNullOrEmpty(entryId)) { newtitle = 0 < newtitle.IndexOf('.') ? newtitle.Insert(newtitle.LastIndexOf('.'), suffix) : newtitle + suffix; } else { break; } } zip.PutNextEntry(newtitle); if (!string.IsNullOrEmpty(entryId) && file != null) { try { if (FileConverter.EnableConvert(file, convertToExt)) { //Take from converter using (var readStream = FileConverter.Exec(file, convertToExt)) { readStream.StreamCopyTo(zip); if (!string.IsNullOrEmpty(convertToExt)) { FilesMessageService.Send(file, headers, MessageAction.FileDownloadedAs, file.Title, convertToExt); } else { FilesMessageService.Send(file, headers, MessageAction.FileDownloaded, file.Title); } } } else { using (var readStream = FileDao.GetFileStream(file)) { readStream.StreamCopyTo(zip); FilesMessageService.Send(file, headers, MessageAction.FileDownloaded, file.Title); } } } catch (Exception ex) { Error = ex.Message; Logger.Error(Error, ex); } } counter++; } ProgressStep(); } } return stream; } private void ReplaceLongPath(ItemNameValueCollection entriesPathId) { foreach (var path in new List<string>(entriesPathId.AllKeys)) { CancellationToken.ThrowIfCancellationRequested(); if (200 >= path.Length || 0 >= path.IndexOf('/')) continue; var ids = entriesPathId[path]; entriesPathId.Remove(path); var newtitle = "LONG_FOLDER_NAME" + path.Substring(path.LastIndexOf('/')); entriesPathId.Add(newtitle, ids); } } class ItemNameValueCollection { private readonly Dictionary<string, List<string>> dic = new Dictionary<string, List<string>>(); public IEnumerable<string> AllKeys { get { return dic.Keys; } } public IEnumerable<string> this[string name] { get { return dic[name].ToArray(); } } public int Count { get { return dic.Count; } } public void Add(string name, string value) { if (!dic.ContainsKey(name)) { dic.Add(name, new List<string>()); } dic[name].Add(value); } public void Add(ItemNameValueCollection collection) { foreach (var key in collection.AllKeys) { foreach (var value in collection[key]) { Add(key, value); } } } public void Add(string name, IEnumerable<string> values) { if (!dic.ContainsKey(name)) { dic.Add(name, new List<string>()); } dic[name].AddRange(values); } public void Remove(string name) { dic.Remove(name); } } } }<file_sep>/module/ASC.Api/ASC.Api.Documents/DocumentsApi.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Net; using System.Net.Mime; using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Web; using ASC.Api.Attributes; using ASC.Api.Collections; using ASC.Api.Exceptions; using ASC.Api.Impl; using ASC.Api.Utils; using ASC.Core; using ASC.Core.Users; using ASC.FederatedLogin.Helpers; using ASC.FederatedLogin.LoginProviders; using ASC.Files.Core; using ASC.MessagingSystem; using ASC.Web.Core.Files; using ASC.Web.Files.Classes; using ASC.Web.Files.Helpers; using ASC.Web.Files.HttpHandlers; using ASC.Web.Files.Services.DocumentService; using ASC.Web.Files.Services.WCFService; using ASC.Web.Files.Services.WCFService.FileOperations; using ASC.Web.Files.Utils; using ASC.Web.Studio.Utility; using Newtonsoft.Json.Linq; using FileShare = ASC.Files.Core.Security.FileShare; using FilesNS = ASC.Web.Files.Services.WCFService; using MimeMapping = ASC.Common.Web.MimeMapping; using SortedByType = ASC.Files.Core.SortedByType; namespace ASC.Api.Documents { /// <summary> /// Provides access to documents /// </summary> public class DocumentsApi : Interfaces.IApiEntryPoint { private readonly ApiContext _context; private readonly IFileStorageService _fileStorageService; /// <summary> /// </summary> public string Name { get { return "files"; } } /// <summary> /// </summary> /// <param name="context"></param> /// <param name="fileStorageService"></param> public DocumentsApi(ApiContext context, IFileStorageService fileStorageService) { _context = context; _fileStorageService = fileStorageService; } /// <summary> /// Returns the detailed list of files and folders located in the current user My section /// </summary> /// <short>Section My</short> /// <category>Folders</category> /// <returns>My folder contents</returns> [Read("@my")] public FolderContentWrapper GetMyFolder(Guid userIdOrGroupId, FilterType filterType) { return ToFolderContentWrapper(Global.FolderMy, userIdOrGroupId, filterType); } /// <summary> /// Returns the detailed list of files and folders located in the current user Projects section /// </summary> /// <short>Section Projects</short> /// <category>Folders</category> /// <returns>Projects folder contents</returns> [Read("@projects")] public FolderContentWrapper GetProjectsFolder(Guid userIdOrGroupId, FilterType filterType) { return ToFolderContentWrapper(Global.FolderProjects, userIdOrGroupId, filterType); } /// <summary> /// Returns the detailed list of files and folders located in the Common section /// </summary> /// <short>Section Common</short> /// <category>Folders</category> /// <returns>Common folder contents</returns> [Read("@common")] public FolderContentWrapper GetCommonFolder(Guid userIdOrGroupId, FilterType filterType) { return ToFolderContentWrapper(Global.FolderCommon, userIdOrGroupId, filterType); } /// <summary> /// Returns the detailed list of files and folders located in the Shared with Me section /// </summary> /// <short>Section Shared</short> /// <category>Folders</category> /// <returns>Shared folder contents</returns> [Read("@share")] public FolderContentWrapper GetShareFolder(Guid userIdOrGroupId, FilterType filterType) { return ToFolderContentWrapper(Global.FolderShare, userIdOrGroupId, filterType); } /// <summary> /// Returns the detailed list of recent files /// </summary> /// <short>Section Recent</short> /// <category>Folders</category> /// <returns>Recent contents</returns> [Read("@recent")] public FolderContentWrapper GetRecentFolder(Guid userIdOrGroupId, FilterType filterType) { return ToFolderContentWrapper(Global.FolderRecent, userIdOrGroupId, filterType); } /// <summary> /// Returns the detailed list of favorites files /// </summary> /// <short>Section Favorite</short> /// <category>Folders</category> /// <returns>Favorites contents</returns> [Read("@favorites")] public FolderContentWrapper GetFavoritesFolder(Guid userIdOrGroupId, FilterType filterType) { return ToFolderContentWrapper(Global.FolderFavorites, userIdOrGroupId, filterType); } /// <summary> /// Returns the detailed list of templates files /// </summary> /// <short>Section Template</short> /// <category>Folders</category> /// <returns>Templates contents</returns> [Read("@templates")] public FolderContentWrapper GetTemplatesFolder(Guid userIdOrGroupId, FilterType filterType) { return ToFolderContentWrapper(Global.FolderTemplates, userIdOrGroupId, filterType); } /// <summary> /// Returns the detailed list of files and folders located in the Recycle Bin /// </summary> /// <short>Section Trash</short> /// <category>Folders</category> /// <returns>Trash folder contents</returns> [Read("@trash")] public FolderContentWrapper GetTrashFolder(Guid userIdOrGroupId, FilterType filterType) { return ToFolderContentWrapper(Global.FolderTrash, userIdOrGroupId, filterType); } /// <summary> /// Returns the detailed list of files and folders located in the folder with the ID specified in the request /// </summary> /// <short> /// Folder by ID /// </short> /// <category>Folders</category> /// <param name="folderId">Folder ID</param> /// <param name="userIdOrGroupId" optional="true">User or group ID</param> /// <param name="filterType" optional="true" remark="Allowed values: None (0), FilesOnly (1), FoldersOnly (2), DocumentsOnly (3), PresentationsOnly (4), SpreadsheetsOnly (5) or ImagesOnly (7)">Filter type</param> /// <returns>Folder contents</returns> [Read("{folderId}")] public FolderContentWrapper GetFolder(String folderId, Guid userIdOrGroupId, FilterType filterType) { return ToFolderContentWrapper(folderId, userIdOrGroupId, filterType).NotFoundIfNull(); } /// <summary> /// Uploads the file specified with single file upload or standart multipart/form-data method to My section /// </summary> /// <short>Upload to My</short> /// <category>Uploads</category> /// <remarks> /// <![CDATA[ /// Upload can be done in 2 different ways: /// <ol> /// <li>Single file upload. You should set Content-Type &amp; Content-Disposition header to specify filename and content type, and send file in request body</li> /// <li>Using standart multipart/form-data method</li> /// </ol>]]> /// </remarks> /// <param name="file" visible="false">Request Input stream</param> /// <param name="contentType" visible="false">Content-Type Header</param> /// <param name="contentDisposition" visible="false">Content-Disposition Header</param> /// <param name="files" visible="false">List of files when posted as multipart/form-data</param> /// <returns>Uploaded file</returns> [Create("@my/upload")] public object UploadFileToMy(Stream file, ContentType contentType, ContentDisposition contentDisposition, IEnumerable<HttpPostedFileBase> files) { return UploadFile(Global.FolderMy.ToString(), file, contentType, contentDisposition, files, false, null); } /// <summary> /// Uploads the file specified with single file upload or standart multipart/form-data method to Common section /// </summary> /// <short>Upload to Common</short> /// <category>Uploads</category> /// <remarks> /// <![CDATA[ /// Upload can be done in 2 different ways: /// <ol> /// <li>Single file upload. You should set Content-Type &amp; Content-Disposition header to specify filename and content type, and send file in request body</li> /// <li>Using standart multipart/form-data method</li> /// </ol>]]> /// </remarks> /// <param name="file" visible="false">Request Input stream</param> /// <param name="contentType" visible="false">Content-Type Header</param> /// <param name="contentDisposition" visible="false">Content-Disposition Header</param> /// <param name="files" visible="false">List of files when posted as multipart/form-data</param> /// <returns>Uploaded file</returns> [Create("@common/upload")] public object UploadFileToCommon(Stream file, ContentType contentType, ContentDisposition contentDisposition, IEnumerable<HttpPostedFileBase> files) { return UploadFile(Global.FolderCommon.ToString(), file, contentType, contentDisposition, files, false, null); } /// <summary> /// Uploads the file specified with single file upload or standart multipart/form-data method to the selected folder /// </summary> /// <short>Upload file</short> /// <category>Uploads</category> /// <remarks> /// <![CDATA[ /// Upload can be done in 2 different ways: /// <ol> /// <li>Single file upload. You should set Content-Type &amp; Content-Disposition header to specify filename and content type, and send file in request body</li> /// <li>Using standart multipart/form-data method</li> /// </ol>]]> /// </remarks> /// <param name="folderId">Folder ID to upload to</param> /// <param name="file" visible="false">Request Input stream</param> /// <param name="contentType" visible="false">Content-Type Header</param> /// <param name="contentDisposition" visible="false">Content-Disposition Header</param> /// <param name="files" visible="false">List of files when posted as multipart/form-data</param> /// <param name="createNewIfExist" visible="false">Create New If Exist</param> /// <param name="storeOriginalFileFlag" visible="false">If True, upload documents in original formats as well</param> /// <param name="keepConvertStatus" visible="false">Keep status conversation after finishing</param> /// <returns>Uploaded file</returns> [Create("{folderId}/upload")] public object UploadFile(string folderId, Stream file, ContentType contentType, ContentDisposition contentDisposition, IEnumerable<HttpPostedFileBase> files, bool? createNewIfExist, bool? storeOriginalFileFlag, bool keepConvertStatus = false) { if (storeOriginalFileFlag.HasValue) { FilesSettings.StoreOriginalFiles = storeOriginalFileFlag.Value; } if (files != null && files.Any()) { if (files.Count() == 1) { //Only one file. return it var postedFile = files.First(); return InsertFile(folderId, postedFile.InputStream, postedFile.FileName, createNewIfExist, keepConvertStatus); } //For case with multiple files return files.Select(postedFile => InsertFile(folderId, postedFile.InputStream, postedFile.FileName, createNewIfExist, keepConvertStatus)).ToList(); } if (file != null) { var fileName = "file" + MimeMapping.GetExtention(contentType.MediaType); if (contentDisposition != null) { fileName = contentDisposition.FileName; } return InsertFile(folderId, file, fileName, createNewIfExist, keepConvertStatus); } throw new InvalidOperationException("No input files"); } /// <summary> /// Uploads the file specified with single file upload to Common section /// </summary> /// <short>Insert to My</short> /// <param name="file" visible="false">Request Input stream</param> /// <param name="title">Name of file which has to be uploaded</param> /// <param name="createNewIfExist" visible="false">Create New If Exist</param> /// <param name="keepConvertStatus" visible="false">Keep status conversation after finishing</param> /// <category>Uploads</category> /// <returns></returns> [Create("@my/insert")] public FileWrapper InsertFileToMy(Stream file, string title, bool? createNewIfExist, bool keepConvertStatus = false) { return InsertFile(Global.FolderMy.ToString(), file, title, createNewIfExist, keepConvertStatus); } /// <summary> /// Uploads the file specified with single file upload to Common section /// </summary> /// <short>Insert to Common</short> /// <param name="file" visible="false">Request Input stream</param> /// <param name="title">Name of file which has to be uploaded</param> /// <param name="createNewIfExist" visible="false">Create New If Exist</param> /// <param name="keepConvertStatus" visible="false">Keep status conversation after finishing</param> /// <category>Uploads</category> /// <returns></returns> [Create("@common/insert")] public FileWrapper InsertFileToCommon(Stream file, string title, bool? createNewIfExist, bool keepConvertStatus = false) { return InsertFile(Global.FolderCommon.ToString(), file, title, createNewIfExist, keepConvertStatus); } /// <summary> /// Uploads the file specified with single file upload /// </summary> /// <param name="folderId">Folder ID to upload to</param> /// <param name="file" visible="false">Request Input stream</param> /// <param name="title">Name of file which has to be uploaded</param> /// <param name="createNewIfExist" visible="false">Create New If Exist</param> /// <param name="keepConvertStatus" visible="false">Keep status conversation after finishing</param> /// <category>Uploads</category> /// <returns></returns> [Create("{folderId}/insert")] public FileWrapper InsertFile(string folderId, Stream file, string title, bool? createNewIfExist, bool keepConvertStatus = false) { try { var resultFile = FileUploader.Exec(folderId, title, file.Length, file, createNewIfExist.HasValue ? createNewIfExist.Value : !FilesSettings.UpdateIfExist, !keepConvertStatus); return new FileWrapper(resultFile); } catch (FileNotFoundException e) { throw new ItemNotFoundException("File not found", e); } catch (DirectoryNotFoundException e) { throw new ItemNotFoundException("Folder not found", e); } } /// <summary> /// Update file content /// </summary> /// <category>Files</category> /// <param name="file">Stream of file</param> /// <param name="fileId">File ID</param> /// <param name="encrypted" visible="false"></param> /// <param name="forcesave" visible="false"></param> [Update("{fileId}/update")] public FileWrapper UpdateFileStream(Stream file, string fileId, bool encrypted = false, bool forcesave = false) { try { var resultFile = _fileStorageService.UpdateFileStream(fileId, file, encrypted, forcesave); return new FileWrapper(resultFile); } catch (FileNotFoundException e) { throw new ItemNotFoundException("File not found", e); } } /// <summary> /// Save file /// </summary> /// <short>Editing save</short> /// <param name="fileId">File ID</param> /// <param name="fileExtension"></param> /// <param name="downloadUri"></param> /// <param name="stream"></param> /// <param name="doc"></param> /// <param name="forcesave"></param> /// <category>Files</category> /// <returns></returns> [Update("file/{fileId}/saveediting")] public FileWrapper SaveEditing(String fileId, string fileExtension, string downloadUri, Stream stream, String doc, bool forcesave) { return new FileWrapper(_fileStorageService.SaveEditing(fileId, fileExtension, downloadUri, stream, doc, forcesave)); } /// <summary> /// Lock file when editing /// </summary> /// <short>Editing start</short> /// <param name="fileId">File ID</param> /// <param name="editingAlone" visible="false"></param> /// <param name="doc" visible="false"></param> /// <category>Files</category> /// <returns>File key for Document Service</returns> [Create("file/{fileId}/startedit")] public string StartEdit(String fileId, bool editingAlone, String doc) { return _fileStorageService.StartEdit(fileId, editingAlone, doc); } /// <summary> /// Continue to lock file when editing /// </summary> /// <short>Editing track</short> /// <param name="fileId">File ID</param> /// <param name="tabId" visible="false"></param> /// <param name="docKeyForTrack" visible="false"></param> /// <param name="doc" visible="false"></param> /// <param name="isFinish">for unlock</param> /// <category>Files</category> /// <returns></returns> [Read("file/{fileId}/trackeditfile")] public KeyValuePair<bool, String> TrackEditFile(String fileId, Guid tabId, String docKeyForTrack, String doc, bool isFinish) { return _fileStorageService.TrackEditFile(fileId, tabId, docKeyForTrack, doc, isFinish); } /// <summary> /// Get initialization configuration for open editor /// </summary> /// <short>Editing open</short> /// <param name="fileId">File ID</param> /// <param name="version">File version</param> /// <param name="doc" visible="false"></param> /// <category>Files</category> /// <returns>Configuration</returns> [Read("file/{fileId}/openedit")] public Configuration OpenEdit(String fileId, int version, String doc) { Configuration configuration; DocumentServiceHelper.GetParams(fileId, version, doc, true, true, true, out configuration); configuration.Type = Configuration.EditorType.External; configuration.Token = DocumentServiceHelper.GetSignature(configuration); return configuration; } /// <summary> /// Creates session to upload large files in multiple chunks. /// </summary> /// <short>Chunked upload</short> /// <category>Uploads</category> /// <param name="folderId">Id of the folder in which file will be uploaded</param> /// <param name="fileName">Name of file which has to be uploaded</param> /// <param name="fileSize">Length in bytes of file which has to be uploaded</param> /// <param name="relativePath">Relative folder from folderId</param> /// <param name="encrypted" visible="false"></param> /// <remarks> /// <![CDATA[ /// Each chunk can have different length but its important what length is multiple of <b>512</b> and greater or equal than <b>5 mb</b>. Last chunk can have any size. /// After initial request respond with status 200 OK you must obtain value of 'location' field from the response. Send all your chunks to that location. /// Each chunk must be sent in strict order in which chunks appears in file. /// After receiving each chunk if no errors occured server will respond with current information about upload session. /// When number of uploaded bytes equal to the number of bytes you send in initial request server will respond with 201 Created and will send you info about uploaded file. /// ]]> /// </remarks> /// <returns> /// <![CDATA[ /// Information about created session. Which includes: /// <ul> /// <li><b>id:</b> unique id of this upload session</li> /// <li><b>created:</b> UTC time when session was created</li> /// <li><b>expired:</b> UTC time when session will be expired if no chunks will be sent until that time</li> /// <li><b>location:</b> URL to which you must send your next chunk</li> /// <li><b>bytes_uploaded:</b> If exists contains number of bytes uploaded for specific upload id</li> /// <li><b>bytes_total:</b> Number of bytes which has to be uploaded</li> /// </ul> /// ]]> /// </returns> [Create("{folderId}/upload/create_session")] public object CreateUploadSession(string folderId, string fileName, long fileSize, string relativePath, bool encrypted) { var file = FileUploader.VerifyChunkedUpload(folderId, fileName, fileSize, FilesSettings.UpdateIfExist, relativePath); if (FilesLinkUtility.IsLocalFileUploader) { var session = FileUploader.InitiateUpload(file.FolderID.ToString(), (file.ID ?? "").ToString(), file.Title, file.ContentLength, encrypted); var response = ChunkedUploaderHandler.ToResponseObject(session, true); return new { success = true, data = response }; } var createSessionUrl = FilesLinkUtility.GetInitiateUploadSessionUrl(file.FolderID, file.ID, file.Title, file.ContentLength, encrypted); var request = (HttpWebRequest)WebRequest.Create(createSessionUrl); request.Method = "POST"; request.ContentLength = 0; // hack for uploader.onlyoffice.com in api requests var rewriterHeader = _context.RequestContext.HttpContext.Request.Headers[HttpRequestExtensions.UrlRewriterHeader]; if (!string.IsNullOrEmpty(rewriterHeader)) { request.Headers[HttpRequestExtensions.UrlRewriterHeader] = rewriterHeader; } // hack. http://ubuntuforums.org/showthread.php?t=1841740 if (WorkContext.IsMono) { ServicePointManager.ServerCertificateValidationCallback += (s, ce, ca, p) => true; } using (var response = request.GetResponse()) using (var responseStream = response.GetResponseStream()) { return JObject.Parse(new StreamReader(responseStream).ReadToEnd()); //result is json string } } /// <summary> /// Creates a text (.txt) file in My section with the title and contents sent in the request /// </summary> /// <short>Create txt in My</short> /// <category>Files</category> /// <param name="title">File title</param> /// <param name="content">File contents</param> /// <returns>Folder contents</returns> /// <visible>false</visible> [Create("@my/text")] public FileWrapper CreateTextFileInMy(string title, string content) { return CreateTextFile(Global.FolderMy.ToString(), title, content); } /// <summary> /// Creates a text (.txt) file in Common Documents section with the title and contents sent in the request /// </summary> /// <short>Create txt in Common</short> /// <category>Files</category> /// <param name="title">File title</param> /// <param name="content">File contents</param> /// <returns>Folder contents</returns> /// <visible>false</visible> [Create("@common/text")] public FileWrapper CreateTextFileInCommon(string title, string content) { return CreateTextFile(Global.FolderCommon.ToString(), title, content); } /// <summary> /// Creates a text (.txt) file in the selected folder with the title and contents sent in the request /// </summary> /// <short>Create txt</short> /// <category>Files</category> /// <param name="folderId">Folder ID</param> /// <param name="title">File title</param> /// <param name="content">File contents</param> /// <returns>Folder contents</returns> /// <visible>false</visible> [Create("{folderId}/text")] public FileWrapper CreateTextFile(string folderId, string title, string content) { if (title == null) throw new ArgumentNullException("title"); //Try detect content var extension = ".txt"; if (!string.IsNullOrEmpty(content)) { if (Regex.IsMatch(content, @"<([^\s>]*)(\s[^<]*)>")) { extension = ".html"; } } return CreateFile(folderId, title, content, extension); } private static FileWrapper CreateFile(string folderId, string title, string content, string extension) { using (var memStream = new MemoryStream(Encoding.UTF8.GetBytes(content))) { var file = FileUploader.Exec(folderId, title.EndsWith(extension, StringComparison.OrdinalIgnoreCase) ? title : (title + extension), memStream.Length, memStream); return new FileWrapper(file); } } /// <summary> /// Creates an html (.html) file in the selected folder with the title and contents sent in the request /// </summary> /// <short>Create html</short> /// <category>Files</category> /// <param name="folderId">Folder ID</param> /// <param name="title">File title</param> /// <param name="content">File contents</param> /// <returns>Folder contents</returns> /// <visible>false</visible> [Create("{folderId}/html")] public FileWrapper CreateHtmlFile(string folderId, string title, string content) { if (title == null) throw new ArgumentNullException("title"); return CreateFile(folderId, title, content, ".html"); } /// <summary> /// Creates an html (.html) file in My section with the title and contents sent in the request /// </summary> /// <short>Create html in My</short> /// <category>Files</category> /// <param name="title">File title</param> /// <param name="content">File contents</param> /// <returns>Folder contents</returns> /// <visible>false</visible> [Create("@my/html")] public FileWrapper CreateHtmlFileInMy(string title, string content) { return CreateHtmlFile(Global.FolderMy.ToString(), title, content); } /// <summary> /// Creates an html (.html) file in Common section with the title and contents sent in the request /// </summary> /// <short>Create html in Common</short> /// <category>Files</category> /// <param name="title">File title</param> /// <param name="content">File contents</param> /// <returns>Folder contents</returns> /// <visible>false</visible> [Create("@common/html")] public FileWrapper CreateHtmlFileInCommon(string title, string content) { return CreateHtmlFile(Global.FolderCommon.ToString(), title, content); } /// <summary> /// Creates a new folder with the title sent in the request. The ID of a parent folder can be also specified. /// </summary> /// <short> /// Create folder /// </short> /// <category>Folders</category> /// <param name="folderId">Parent folder ID</param> /// <param name="title">Title of new folder</param> /// <returns>New folder contents</returns> [Create("folder/{folderId}")] public FolderWrapper CreateFolder(string folderId, string title) { var folder = _fileStorageService.CreateNewFolder(folderId, title); return new FolderWrapper(folder); } /// <summary> /// Creates a new file in the My section with the title sent in the request /// </summary> /// <short>Create file in My</short> /// <category>Files</category> /// <param name="title" remark="Allowed values: the file must have one of the following extensions: DOCX, XLSX, PPTX">File title</param> /// <remarks>In case the extension for the file title differs from DOCX/XLSX/PPTX and belongs to one of the known text, spreadsheet or presentation formats, it will be changed to DOCX/XLSX/PPTX accordingly. If the file extension is not set or is unknown, the DOCX extension will be added to the file title.</remarks> /// <returns>New file info</returns> [Create("@my/file")] public FileWrapper CreateFile(string title) { return CreateFile(Global.FolderMy.ToString(), title, null); } /// <summary> /// Creates a new file in the specified folder with the title sent in the request /// </summary> /// <short>Create file</short> /// <category>Files</category> /// <param name="folderId">Folder ID</param> /// <param name="title" remark="Allowed values: the file must have one of the following extensions: DOCX, XLSX, PPTX">File title</param> /// <param name="templateId">File ID for using as template</param> /// <remarks>In case the extension for the file title differs from DOCX/XLSX/PPTX and belongs to one of the known text, spreadsheet or presentation formats, it will be changed to DOCX/XLSX/PPTX accordingly. If the file extension is not set or is unknown, the DOCX extension will be added to the file title.</remarks> /// <returns>New file info</returns> [Create("{folderId}/file")] public FileWrapper CreateFile(string folderId, string title, string templateId) { var file = _fileStorageService.CreateNewFile(folderId, title, templateId); return new FileWrapper(file); } /// <summary> /// Renames the selected folder to the new title specified in the request /// </summary> /// <short> /// Rename folder /// </short> /// <category>Folders</category> /// <param name="folderId">Folder ID</param> /// <param name="title">New title</param> /// <returns>Folder contents</returns> [Update("folder/{folderId}")] public FolderWrapper RenameFolder(string folderId, string title) { var folder = _fileStorageService.FolderRename(folderId, title); return new FolderWrapper(folder); } /// <summary> /// Returns a detailed information about the folder with the ID specified in the request /// </summary> /// <short>Folder information</short> /// <category>Folders</category> /// <returns>Folder info</returns> [Read("folder/{folderId}")] public FolderWrapper GetFolderInfo(string folderId) { var folder = _fileStorageService.GetFolder(folderId).NotFoundIfNull("Folder not found"); return new FolderWrapper(folder); } /// <summary> /// Returns parent folders /// </summary> /// <short>Folder path</short> /// <param name="folderId"></param> /// <category>Folders</category> /// <returns>Parent folders</returns> [Read("folder/{folderId}/path")] public IEnumerable<FolderWrapper> GetFolderPath(string folderId) { return EntryManager.GetBreadCrumbs(folderId).Select(f => new FolderWrapper(f)).ToSmartList(); } /// <summary> /// Returns a detailed information about the file with the ID specified in the request /// </summary> /// <short>File information</short> /// <category>Files</category> /// <returns>File info</returns> [Read("file/{fileId}")] public FileWrapper GetFileInfo(string fileId, int version = -1) { var file = _fileStorageService.GetFile(fileId, version).NotFoundIfNull("File not found"); return new FileWrapper(file); } /// <summary> /// Updates the information of the selected file with the parameters specified in the request /// </summary> /// <short>Update file info</short> /// <category>Files</category> /// <param name="fileId">File ID</param> /// <param name="title">New title</param> /// <param name="lastVersion">File last version number</param> /// <returns>File info</returns> [Update("file/{fileId}")] public FileWrapper UpdateFile(String fileId, String title, int lastVersion) { if (!String.IsNullOrEmpty(title)) _fileStorageService.FileRename(fileId.ToString(CultureInfo.InvariantCulture), title); if (lastVersion > 0) _fileStorageService.UpdateToVersion(fileId.ToString(CultureInfo.InvariantCulture), lastVersion); return GetFileInfo(fileId); } /// <summary> /// Deletes the file with the ID specified in the request /// </summary> /// <short>Delete file</short> /// <category>Operations</category> /// <param name="fileId">File ID</param> /// <param name="deleteAfter">Delete after finished</param> /// <param name="immediately">Don't move to the Recycle Bin</param> /// <returns>Operation result</returns> [Delete("file/{fileId}")] public IEnumerable<FileOperationWraper> DeleteFile(String fileId, bool deleteAfter, bool immediately) { return DeleteBatchItems(null, new[] { fileId }, deleteAfter, immediately); } /// <summary> /// Start conversion operation /// </summary> /// <short>Convert start</short> /// <category>Operations</category> /// <param name="fileId"></param> /// <returns>Operation result</returns> [Update("file/{fileId}/checkconversion")] public IEnumerable<ConversationResult> StartConversion(String fileId) { return CheckConversion(fileId, true); } /// <summary> /// Check conversion status /// </summary> /// <short>Convert status</short> /// <category>Operations</category> /// <param name="fileId"></param> /// <param name="start"></param> /// <returns>Operation result</returns> [Read("file/{fileId}/checkconversion")] public IEnumerable<ConversationResult> CheckConversion(String fileId, bool start) { return _fileStorageService.CheckConversion(new FilesNS.ItemList<FilesNS.ItemList<string>> { new FilesNS.ItemList<string> { fileId, "0", start.ToString() } }) .Select(r => { var o = new ConversationResult { Id = r.Id, Error = r.Error, OperationType = r.OperationType, Processed = r.Processed, Progress = r.Progress, Source = r.Source, }; if (!string.IsNullOrEmpty(r.Result)) { var jResult = JObject.Parse(r.Result); o.File = GetFileInfo(jResult.Value<string>("id"), jResult.Value<int>("version")); } return o; }); } /// <summary> /// Deletes the folder with the ID specified in the request /// </summary> /// <short>Delete folder</short> /// <category>Operations</category> /// <param name="folderId">Folder ID</param> /// <param name="deleteAfter">Delete after finished</param> /// <param name="immediately">Don't move to the Recycle Bin</param> /// <returns>Operation result</returns> [Delete("folder/{folderId}")] public IEnumerable<FileOperationWraper> DeleteFolder(String folderId, bool deleteAfter, bool immediately) { return DeleteBatchItems(new[] { folderId }, null, deleteAfter, immediately); } /// <summary> /// Checking for conflicts /// </summary> /// <category>Operations</category> /// <param name="destFolderId">Destination folder ID</param> /// <param name="folderIds">Folder ID list</param> /// <param name="fileIds">File ID list</param> /// <returns>Conflicts file ids</returns> [Read("fileops/move")] public IEnumerable<FileWrapper> MoveOrCopyBatchCheck(String destFolderId, IEnumerable<String> folderIds, IEnumerable<String> fileIds) { var itemList = new Web.Files.Services.WCFService.ItemList<String>(); itemList.AddRange((folderIds ?? new List<String>()).Select(x => "folder_" + x)); itemList.AddRange((fileIds ?? new List<String>()).Select(x => "file_" + x)); var ids = _fileStorageService.MoveOrCopyFilesCheck(itemList, destFolderId).Keys.Select(id => "file_" + id); var entries = _fileStorageService.GetItems(new Web.Files.Services.WCFService.ItemList<string>(ids), FilterType.FilesOnly, false, "", ""); return entries.Select(x => new FileWrapper((Files.Core.File)x)).ToSmartList(); } /// <summary> /// Moves all the selected files and folders to the folder with the ID specified in the request /// </summary> /// <short>Move to folder</short> /// <category>Operations</category> /// <param name="destFolderId">Destination folder ID</param> /// <param name="folderIds">Folder ID list</param> /// <param name="fileIds">File ID list</param> /// <param name="conflictResolveType">Overwriting behavior: skip(0), overwrite(1) or duplicate(2)</param> /// <param name="deleteAfter">Delete after finished</param> /// <returns>Operation result</returns> [Update("fileops/move")] public IEnumerable<FileOperationWraper> MoveBatchItems(String destFolderId, IEnumerable<String> folderIds, IEnumerable<String> fileIds, FileConflictResolveType conflictResolveType, bool deleteAfter) { var itemList = new Web.Files.Services.WCFService.ItemList<String>(); itemList.AddRange((folderIds ?? new List<String>()).Select(x => "folder_" + x)); itemList.AddRange((fileIds ?? new List<String>()).Select(x => "file_" + x)); return _fileStorageService.MoveOrCopyItems(itemList, destFolderId, conflictResolveType, false, deleteAfter).Select(o => new FileOperationWraper(o)); } /// <summary> /// Copies all the selected files and folders to the folder with the ID specified in the request /// </summary> /// <short>Copy to folder</short> /// <category>Operations</category> /// <param name="destFolderId">Destination folder ID</param> /// <param name="folderIds">Folder ID list</param> /// <param name="fileIds">File ID list</param> /// <param name="conflictResolveType">Overwriting behavior: skip(0), overwrite(1) or duplicate(2)</param> /// <param name="deleteAfter">Delete after finished</param> /// <returns>Operation result</returns> [Update("fileops/copy")] public IEnumerable<FileOperationWraper> CopyBatchItems(String destFolderId, IEnumerable<String> folderIds, IEnumerable<String> fileIds, FileConflictResolveType conflictResolveType, bool deleteAfter) { var itemList = new Web.Files.Services.WCFService.ItemList<String>(); itemList.AddRange((folderIds ?? new List<String>()).Select(x => "folder_" + x)); itemList.AddRange((fileIds ?? new List<String>()).Select(x => "file_" + x)); return _fileStorageService.MoveOrCopyItems(itemList, destFolderId, conflictResolveType, true, deleteAfter).Select(o => new FileOperationWraper(o)); } /// <summary> /// Marks all files and folders as read /// </summary> /// <short>Mark as read</short> /// <category>Operations</category> /// <returns>Operation result</returns> [Update("fileops/markasread")] public IEnumerable<FileOperationWraper> MarkAsRead(IEnumerable<String> folderIds, IEnumerable<String> fileIds) { var itemList = new Web.Files.Services.WCFService.ItemList<String>(); itemList.AddRange((folderIds ?? new List<String>()).Select(x => "folder_" + x)); itemList.AddRange((fileIds ?? new List<String>()).Select(x => "file_" + x)); return _fileStorageService.MarkAsRead(itemList).Select(o => new FileOperationWraper(o)); } /// <summary> /// Finishes all the active Operations /// </summary> /// <short>Finish all</short> /// <category>Operations</category> /// <returns>Operation result</returns> [Update("fileops/terminate")] public IEnumerable<FileOperationWraper> TerminateTasks() { return _fileStorageService.TerminateTasks().Select(o => new FileOperationWraper(o)); } /// <summary> /// Returns the list of all active Operations /// </summary> /// <short>Operations list</short> /// <category>Operations</category> /// <returns>Operation result</returns> [Read("fileops")] public IEnumerable<FileOperationWraper> GetOperationStatuses() { return _fileStorageService.GetTasksStatuses().Select(o => new FileOperationWraper(o)); } /// <summary> /// Start downlaod process of files and folders with ID /// </summary> /// <short>Finish Operations</short> /// <param name="fileConvertIds" visible="false">File ID list for download with convert to format</param> /// <param name="fileIds">File ID list</param> /// <param name="folderIds">Folder ID list</param> /// <category>Operations</category> /// <returns>Operation result</returns> [Update("fileops/bulkdownload")] public IEnumerable<FileOperationWraper> BulkDownload( IEnumerable<ItemKeyValuePair<String, String>> fileConvertIds, IEnumerable<String> fileIds, IEnumerable<String> folderIds) { var itemList = new Dictionary<String, String>(); foreach (var fileId in fileConvertIds.Where(fileId => !itemList.ContainsKey(fileId.Key))) { itemList.Add("file_" + fileId.Key, fileId.Value); } foreach (var fileId in fileIds.Where(fileId => !itemList.ContainsKey(fileId))) { itemList.Add("file_" + fileId, string.Empty); } foreach (var folderId in folderIds.Where(folderId => !itemList.ContainsKey(folderId))) { itemList.Add("folder_" + folderId, String.Empty); } return _fileStorageService.BulkDownload(itemList).Select(o => new FileOperationWraper(o)); } /// <summary> /// Deletes the files and folders with the IDs specified in the request /// </summary> /// <param name="folderIds">Folder ID list</param> /// <param name="fileIds">File ID list</param> /// <param name="deleteAfter">Delete after finished</param> /// <param name="immediately">Don't move to the Recycle Bin</param> /// <short>Delete files and folders</short> /// <category>Operations</category> /// <returns>Operation result</returns> [Update("fileops/delete")] public IEnumerable<FileOperationWraper> DeleteBatchItems(IEnumerable<String> folderIds, IEnumerable<String> fileIds, bool deleteAfter, bool immediately) { var itemList = new Web.Files.Services.WCFService.ItemList<String>(); itemList.AddRange((folderIds ?? new List<String>()).Select(x => "folder_" + x)); itemList.AddRange((fileIds ?? new List<String>()).Select(x => "file_" + x)); return _fileStorageService.DeleteItems("delete", itemList, false, deleteAfter, immediately).Select(o => new FileOperationWraper(o)); } /// <summary> /// Deletes all files and folders from the recycle bin /// </summary> /// <short>Clear recycle bin</short> /// <category>Operations</category> /// <returns>Operation result</returns> [Update("fileops/emptytrash")] public IEnumerable<FileOperationWraper> EmptyTrash() { return _fileStorageService.EmptyTrash().Select(o => new FileOperationWraper(o)); } /// <summary> /// Returns the detailed information about all the available file versions with the ID specified in the request /// </summary> /// <short>File versions</short> /// <category>Files</category> /// <param name="fileId">File ID</param> /// <returns>File information</returns> [Read("file/{fileId}/history")] public IEnumerable<FileWrapper> GetFileVersionInfo(string fileId) { var files = _fileStorageService.GetFileHistory(fileId); return files.Select(x => new FileWrapper(x)).ToSmartList(); } /// <summary> /// Change version history /// </summary> /// <param name="fileId">File ID</param> /// <param name="version">Version of history</param> /// <param name="continueVersion">Mark as version or revision</param> /// <category>Files</category> /// <returns></returns> [Update("file/{fileId}/history")] public IEnumerable<FileWrapper> ChangeHistory(string fileId, int version, bool continueVersion) { var history = _fileStorageService.CompleteVersion(fileId, version, continueVersion).Value; return history.Select(x => new FileWrapper(x)).ToSmartList(); } /// <summary> /// Returns the detailed information about shared file with the ID specified in the request /// </summary> /// <short>File sharing</short> /// <category>Sharing</category> /// <param name="fileId">File ID</param> /// <returns>Shared file information</returns> [Read("file/{fileId}/share")] public IEnumerable<FileShareWrapper> GetFileSecurityInfo(string fileId) { var fileShares = _fileStorageService.GetSharedInfo(new Web.Files.Services.WCFService.ItemList<string> { String.Format("file_{0}", fileId) }); return fileShares.Select(x => new FileShareWrapper(x)).ToSmartList(); } /// <summary> /// Returns the detailed information about shared folder with the ID specified in the request /// </summary> /// <short>Folder sharing</short> /// <param name="folderId">Folder ID</param> /// <category>Sharing</category> /// <returns>Shared folder information</returns> [Read("folder/{folderId}/share")] public IEnumerable<FileShareWrapper> GetFolderSecurityInfo(string folderId) { var fileShares = _fileStorageService.GetSharedInfo(new Web.Files.Services.WCFService.ItemList<string> { String.Format("folder_{0}", folderId) }); return fileShares.Select(x => new FileShareWrapper(x)).ToSmartList(); } /// <summary> /// Sets sharing settings for the file with the ID specified in the request /// </summary> /// <param name="fileId">File ID</param> /// <param name="share">Collection of sharing rights</param> /// <param name="notify">Should notify people</param> /// <param name="sharingMessage">Sharing message to send when notifying</param> /// <short>Share file</short> /// <category>Sharing</category> /// <remarks> /// Each of the FileShareParams must contain two parameters: 'ShareTo' - ID of the user with whom we want to share and 'Access' - access type which we want to grant to the user (Read, ReadWrite, etc) /// </remarks> /// <returns>Shared file information</returns> [Update("file/{fileId}/share")] public IEnumerable<FileShareWrapper> SetFileSecurityInfo(string fileId, IEnumerable<FileShareParams> share, bool notify, string sharingMessage) { if (share != null && share.Any()) { var list = new Web.Files.Services.WCFService.ItemList<AceWrapper>(share.Select(x => x.ToAceObject())); var aceCollection = new AceCollection { Entries = new Web.Files.Services.WCFService.ItemList<string> { "file_" + fileId }, Aces = list, Message = sharingMessage }; _fileStorageService.SetAceObject(aceCollection, notify); } return GetFileSecurityInfo(fileId); } /// <summary> /// Sets sharing settings for the folder with the ID specified in the request /// </summary> /// <short>Share folder</short> /// <param name="folderId">Folder ID</param> /// <param name="share">Collection of sharing rights</param> /// <param name="notify">Should notify people</param> /// <param name="sharingMessage">Sharing message to send when notifying</param> /// <remarks> /// Each of the FileShareParams must contain two parameters: 'ShareTo' - ID of the user with whom we want to share and 'Access' - access type which we want to grant to the user (Read, ReadWrite, etc) /// </remarks> /// <category>Sharing</category> /// <returns>Shared folder information</returns> [Update("folder/{folderId}/share")] public IEnumerable<FileShareWrapper> SetFolderSecurityInfo(string folderId, IEnumerable<FileShareParams> share, bool notify, string sharingMessage) { if (share != null && share.Any()) { var list = new Web.Files.Services.WCFService.ItemList<AceWrapper>(share.Select(x => x.ToAceObject())); var aceCollection = new AceCollection { Entries = new Web.Files.Services.WCFService.ItemList<string> { "folder_" + folderId }, Aces = list, Message = sharingMessage }; _fileStorageService.SetAceObject(aceCollection, notify); } return GetFolderSecurityInfo(folderId); } /// <summary> /// Removes sharing rights for the group with the ID specified in the request /// </summary> /// <param name="folderIds">Folders ID</param> /// <param name="fileIds">Files ID</param> /// <short>Remove group sharing rights</short> /// <category>Sharing</category> /// <returns>Shared file information</returns> [Delete("share")] public bool RemoveSecurityInfo(IEnumerable<String> folderIds, IEnumerable<String> fileIds) { var itemList = new Web.Files.Services.WCFService.ItemList<String>(); itemList.AddRange((folderIds ?? new List<String>()).Select(x => "folder_" + x)); itemList.AddRange((fileIds ?? new List<String>()).Select(x => "file_" + x)); _fileStorageService.RemoveAce(itemList); return true; } /// <summary> /// Returns the external link to the shared file with the ID specified in the request /// </summary> /// <short>Shared link</short> /// <param name="fileId">File ID</param> /// <param name="share">Access right</param> /// <category>Sharing</category> /// <returns>Shared file link</returns> [Update("{fileId}/sharedlink")] public string GenerateSharedLink(string fileId, FileShare share) { var file = GetFileInfo(fileId); var objectId = "file_" + file.Id; var sharedInfo = _fileStorageService.GetSharedInfo(new Web.Files.Services.WCFService.ItemList<string> { objectId }).Find(r => r.SubjectId == FileConstant.ShareLinkId); if (sharedInfo == null || sharedInfo.Share != share) { var list = new Web.Files.Services.WCFService.ItemList<AceWrapper> { new AceWrapper { SubjectId = FileConstant.ShareLinkId, SubjectGroup = true, Share = share } }; var aceCollection = new AceCollection { Entries = new Web.Files.Services.WCFService.ItemList<string> { objectId }, Aces = list }; _fileStorageService.SetAceObject(aceCollection, false); sharedInfo = _fileStorageService.GetSharedInfo(new Web.Files.Services.WCFService.ItemList<string> { objectId }).Find(r => r.SubjectId == FileConstant.ShareLinkId); } return sharedInfo.Link; } /// <summary> /// Get a list of available providers /// </summary> /// <category>Third-Party Integration</category> /// <returns>List of provider key</returns> /// <remarks>List of provider key: <KEY>, Box, WebDav, Yandex, OneDrive, SharePoint, GoogleDrive</remarks> /// <returns></returns> [Read("thirdparty/capabilities")] public List<List<string>> Capabilities() { var result = new List<List<string>>(); if (CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID).IsVisitor() || (!FilesSettings.EnableThirdParty && !CoreContext.Configuration.Personal)) { return result; } if (ThirdpartyConfiguration.SupportBoxInclusion) { result.Add(new List<string> { "Box", BoxLoginProvider.Instance.ClientID, BoxLoginProvider.Instance.RedirectUri }); } if (ThirdpartyConfiguration.SupportDropboxInclusion) { result.Add(new List<string> { "DropboxV2", DropboxLoginProvider.Instance.ClientID, DropboxLoginProvider.Instance.RedirectUri }); } if (ThirdpartyConfiguration.SupportGoogleDriveInclusion) { result.Add(new List<string> { "GoogleDrive", GoogleLoginProvider.Instance.ClientID, GoogleLoginProvider.Instance.RedirectUri }); } if (ThirdpartyConfiguration.SupportOneDriveInclusion) { result.Add(new List<string> { "OneDrive", OneDriveLoginProvider.Instance.ClientID, OneDriveLoginProvider.Instance.RedirectUri }); } if (ThirdpartyConfiguration.SupportSharePointInclusion) { result.Add(new List<string> { "SharePoint" }); } if (ThirdpartyConfiguration.SupportkDriveInclusion) { result.Add(new List<string> { "kDrive" }); } if (ThirdpartyConfiguration.SupportYandexInclusion) { result.Add(new List<string> { "Yandex" }); } if (ThirdpartyConfiguration.SupportWebDavInclusion) { result.Add(new List<string> { "WebDav" }); } //Obsolete BoxNet, DropBox, Google, SkyDrive, return result; } /// <summary> /// Saves the third party file storage service account /// </summary> /// <short>Save third party account</short> /// <param name="url">Connection url for SharePoint</param> /// <param name="login">Login</param> /// <param name="password">Password</param> /// <param name="token">Authentication token</param> /// <param name="isCorporate"></param> /// <param name="customerTitle">Title</param> /// <param name="providerKey">Provider Key</param> /// <param name="providerId">Provider ID</param> /// <category>Third-Party Integration</category> /// <returns>Folder contents</returns> /// <remarks>List of provider key: DropboxV2, Box, WebDav, Yandex, OneDrive, SharePoint, GoogleDrive</remarks> /// <exception cref="ArgumentException"></exception> [Create("thirdparty")] public FolderWrapper SaveThirdParty( String url, String login, String password, String token, bool isCorporate, String customerTitle, String providerKey, String providerId) { var thirdPartyParams = new ThirdPartyParams { AuthData = new AuthData(url, login, password, token), Corporate = isCorporate, CustomerTitle = customerTitle, ProviderId = providerId, ProviderKey = providerKey, }; var folder = _fileStorageService.SaveThirdParty(thirdPartyParams); return new FolderWrapper(folder); } /// <summary> /// Returns the list of all connected third party services /// </summary> /// <category>Third-Party Integration</category> /// <short>Third party list</short> /// <returns>Connected providers</returns> [Read("thirdparty")] public IEnumerable<ThirdPartyParams> GetThirdPartyAccounts() { return _fileStorageService.GetThirdParty(); } /// <summary> /// Returns the list of third party services connected in the Common section /// </summary> /// <category>Third-Party Integration</category> /// <short>Third party folder</short> /// <returns>Connected providers folder</returns> [Read("thirdparty/common")] public IEnumerable<Folder> GetCommonThirdPartyFolders() { var parent = _fileStorageService.GetFolder(Global.FolderCommon.ToString()); return EntryManager.GetThirpartyFolders(parent); } /// <summary> /// Removes the third party file storage service account with the ID specified in the request /// </summary> /// <param name="providerId">Provider ID. Provider id is part of folder id. /// Example, folder id is "sbox-123", then provider id is "123" /// </param> /// <short>Remove third party account</short> /// <category>Third-Party Integration</category> /// <returns>Folder id</returns> ///<exception cref="ArgumentException"></exception> [Delete("thirdparty/{providerId:[0-9]+}")] public object DeleteThirdParty(int providerId) { return _fileStorageService.DeleteThirdParty(providerId.ToString(CultureInfo.InvariantCulture)); } /// <summary> /// Search files /// </summary> /// <param name="query">Queary string</param> /// <returns>Files and folders</returns> [Read(@"@search/{query}")] public IEnumerable<FileEntryWrapper> Search(string query) { var searcher = new Web.Files.Configuration.SearchHandler(); var files = searcher.SearchFiles(query).Select(r => (FileEntryWrapper)new FileWrapper(r)); var folders = searcher.SearchFolders(query).Select(f => (FileEntryWrapper)new FolderWrapper(f)); return files.Concat(folders); } /// <summary> /// Adding files to favorite list /// </summary> /// <short>Favorite add</short> /// <category>Files</category> /// <param name="folderIds" visible="false"></param> /// <param name="fileIds">File IDs</param> /// <returns></returns> [Create("favorites")] public bool AddFavorites(IEnumerable<String> folderIds, IEnumerable<String> fileIds) { var list = _fileStorageService.AddToFavorites(new FilesNS.ItemList<string>(folderIds), new FilesNS.ItemList<string>(fileIds)); return true; } /// <summary> /// Removing files from favorite list /// </summary> /// <short>Favorite delete</short> /// <category>Files</category> /// <param name="folderIds" visible="false"></param> /// <param name="fileIds">File IDs</param> /// <returns></returns> [Delete("favorites")] public bool DeleteFavorites(IEnumerable<String> folderIds, IEnumerable<String> fileIds) { var list = _fileStorageService.DeleteFavorites(new FilesNS.ItemList<string>(folderIds), new FilesNS.ItemList<string>(fileIds)); return true; } /// <summary> /// Adding files to template list /// </summary> /// <short>Template add</short> /// <category>Files</category> /// <param name="fileIds">File IDs</param> /// <returns></returns> [Create("templates")] public bool AddTemplates(IEnumerable<String> fileIds) { var list = _fileStorageService.AddToTemplates(new FilesNS.ItemList<string>(fileIds)); return true; } /// <summary> /// Removing files from template list /// </summary> /// <short>Template delete</short> /// <category>Files</category> /// <param name="fileIds">File IDs</param> /// <returns></returns> [Delete("templates")] public bool DeleteTemplates(IEnumerable<String> fileIds) { var list = _fileStorageService.DeleteTemplates(new FilesNS.ItemList<string>(fileIds)); return true; } /// <summary> /// Store file in original formats when upload and convert /// </summary> /// <param name="set"></param> /// <category>Settings</category> /// <returns></returns> [Update(@"storeoriginal")] public bool StoreOriginal(bool set) { return _fileStorageService.StoreOriginal(set); } /// <summary> /// Do not show the confirmation dialog /// </summary> /// <param name="save"></param> /// <category>Settings</category> /// <visible>false</visible> /// <returns></returns> [Update(@"hideconfirmconvert")] public bool HideConfirmConvert(bool save) { return _fileStorageService.HideConfirmConvert(save); } /// <summary> /// Update the file version if the same name is exist /// </summary> /// <param name="set"></param> /// <category>Settings</category> /// <returns></returns> [Update(@"updateifexist")] public bool UpdateIfExist(bool set) { return _fileStorageService.UpdateIfExist(set); } /// <summary> /// Display recent folder /// </summary> /// <param name="set"></param> /// <category>Settings</category> /// <returns></returns> [Update(@"displayRecent")] public bool DisplayRecent(bool set) { return _fileStorageService.DisplayRecent(set); } /// <summary> /// Display favorite folder /// </summary> /// <param name="set"></param> /// <category>Settings</category> /// <returns></returns> [Update(@"settings/favorites")] public bool DisplayFavorite(bool set) { return _fileStorageService.DisplayFavorite(set); } /// <summary> /// Display template folder /// </summary> /// <param name="set"></param> /// <category>Settings</category> /// <returns></returns> [Update(@"settings/templates")] public bool DisplayTemplates(bool set) { return _fileStorageService.DisplayTemplates(set); } /// <summary> /// Checking document service location /// </summary> /// <param name="docServiceUrl">Document editing service Domain</param> /// <param name="docServiceUrlInternal">Document command service Domain</param> /// <param name="docServiceUrlPortal">Community Server Address</param> /// <category>Settings</category> /// <returns></returns> [Update("docservice")] public IEnumerable<string> CheckDocServiceUrl(string docServiceUrl, string docServiceUrlInternal, string docServiceUrlPortal) { FilesLinkUtility.DocServiceUrl = docServiceUrl; FilesLinkUtility.DocServiceUrlInternal = docServiceUrlInternal; FilesLinkUtility.DocServicePortalUrl = docServiceUrlPortal; MessageService.Send(HttpContext.Current.Request, MessageAction.DocumentServiceLocationSetting); var https = new Regex(@"^https://", RegexOptions.IgnoreCase); var http = new Regex(@"^http://", RegexOptions.IgnoreCase); if (https.IsMatch(CommonLinkUtility.GetFullAbsolutePath("")) && http.IsMatch(FilesLinkUtility.DocServiceUrl)) { throw new Exception("Mixed Active Content is not allowed. HTTPS address for Document Server is required."); } DocumentServiceConnector.CheckDocServiceUrl(); return new[] { FilesLinkUtility.DocServiceUrl, FilesLinkUtility.DocServiceUrlInternal, FilesLinkUtility.DocServicePortalUrl }; } /// <summary> /// Get the address of connected editors /// </summary> /// <category>Settings</category> /// <param name="version" visible="false"></param> /// <returns>Address</returns> [Read("docservice")] public object GetDocServiceUrl(bool version) { var url = CommonLinkUtility.GetFullAbsolutePath(FilesLinkUtility.DocServiceApiUrl); if (!version) { return url; } var dsVersion = DocumentServiceConnector.GetVersion(); return new { version = dsVersion, docServiceUrlApi = url, }; } private FolderContentWrapper ToFolderContentWrapper(object folderId, Guid userIdOrGroupId, FilterType filterType) { SortedByType sortBy; if (!Enum.TryParse(_context.SortBy, true, out sortBy)) sortBy = SortedByType.AZ; var startIndex = Convert.ToInt32(_context.StartIndex); return new FolderContentWrapper(_fileStorageService.GetFolderItems(folderId.ToString(), startIndex, Convert.ToInt32(_context.Count) - 1, //NOTE: in ApiContext +1 filterType, filterType == FilterType.ByUser, userIdOrGroupId.ToString(), _context.FilterValue, false, false, new OrderBy(sortBy, !_context.SortDescending)), startIndex); } #region wordpress /// <visible>false</visible> [Read("wordpress-info")] public object GetWordpressInfo() { var token = WordpressToken.GetToken(); if (token != null) { var meInfo = WordpressHelper.GetWordpressMeInfo(token.AccessToken); var blogId = JObject.Parse(meInfo).Value<string>("token_site_id"); var wordpressUserName = JObject.Parse(meInfo).Value<string>("username"); var blogInfo = RequestHelper.PerformRequest(WordpressLoginProvider.WordpressSites + blogId, "", "GET", ""); var jsonBlogInfo = JObject.Parse(blogInfo); jsonBlogInfo.Add("username", wordpressUserName); blogInfo = jsonBlogInfo.ToString(); return new { success = true, data = blogInfo }; } return new { success = false }; } /// <visible>false</visible> [Read("wordpress-delete")] public object DeleteWordpressInfo() { var token = WordpressToken.GetToken(); if (token != null) { WordpressToken.DeleteToken(token); return new { success = true }; } return new { success = false }; } /// <visible>false</visible> [Create("wordpress-save")] public object WordpressSave(string code) { if (code == "") { return new { success = false }; } try { var token = OAuth20TokenHelper.GetAccessToken<WordpressLoginProvider>(code); WordpressToken.SaveToken(token); var meInfo = WordpressHelper.GetWordpressMeInfo(token.AccessToken); var blogId = JObject.Parse(meInfo).Value<string>("token_site_id"); var wordpressUserName = JObject.Parse(meInfo).Value<string>("username"); var blogInfo = RequestHelper.PerformRequest(WordpressLoginProvider.WordpressSites + blogId, "", "GET", ""); var jsonBlogInfo = JObject.Parse(blogInfo); jsonBlogInfo.Add("username", wordpressUserName); blogInfo = jsonBlogInfo.ToString(); return new { success = true, data = blogInfo }; } catch (Exception) { return new { success = false }; } } /// <visible>false</visible> [Create("wordpress")] public bool CreateWordpressPost(string code, string title, string content, int status) { try { var token = WordpressToken.GetToken(); var meInfo = WordpressHelper.GetWordpressMeInfo(token.AccessToken); var parser = JObject.Parse(meInfo); if (parser == null) return false; var blogId = parser.Value<string>("token_site_id"); if (blogId != null) { var createPost = WordpressHelper.CreateWordpressPost(title, content, status, blogId, token); return createPost; } return false; } catch (Exception) { return false; } } #endregion #region easybib /// <visible>false</visible> [Read("easybib-citation-list")] public object GetEasybibCitationList(int source, string data) { try { var citationList = EasyBibHelper.GetEasyBibCitationsList(source, data); return new { success = true, citations = citationList }; } catch (Exception) { return new { success = false }; } } /// <visible>false</visible> [Read("easybib-styles")] public object GetEasybibStyles() { try { var data = EasyBibHelper.GetEasyBibStyles(); return new { success = true, styles = data }; } catch (Exception) { return new { success = false }; } } /// <visible>false</visible> [Create("easybib-citation")] public object EasyBibCitationBook(string citationData) { try { var citat = EasyBibHelper.GetEasyBibCitation(citationData); if (citat != null) { return new { success = true, citation = citat }; } else { return new { success = false }; } } catch (Exception) { return new { success = false }; } } #endregion /// <summary> /// Result of file conversation operation. /// </summary> [DataContract(Name = "operation_result", Namespace = "")] public class ConversationResult { /// <summary> /// Operation Id. /// </summary> [DataMember(Name = "id")] public string Id { get; set; } /// <summary> /// Operation type. /// </summary> [DataMember(Name = "operation")] public FileOperationType OperationType { get; set; } /// <summary> /// Operation progress. /// </summary> [DataMember(Name = "progress")] public int Progress { get; set; } /// <summary> /// Source files for operation. /// </summary> [DataMember(Name = "source")] public string Source { get; set; } /// <summary> /// Result file of operation. /// </summary> [DataMember(Name = "result")] public FileWrapper File { get; set; } /// <summary> /// Error during conversation. /// </summary> [DataMember(Name = "error")] public string Error { get; set; } /// <summary> /// Is operation processed. /// </summary> [DataMember(Name = "processed")] public string Processed { get; set; } } } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/SIP/Proxy/SIP_AuthenticateEventArgs.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.SIP.Proxy { #region usings using AUTH; #endregion /// <summary> /// This class provides data for SIP_ProxyCore.Authenticate event. /// </summary> public class SIP_AuthenticateEventArgs { #region Members private readonly Auth_HttpDigest m_pAuth; #endregion #region Properties /// <summary> /// Gets authentication context. /// </summary> public Auth_HttpDigest AuthContext { get { return m_pAuth; } } /// <summary> /// Gets or sets if specified request is authenticated. /// </summary> public bool Authenticated { get; set; } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="auth">Authentication context.</param> public SIP_AuthenticateEventArgs(Auth_HttpDigest auth) { m_pAuth = auth; } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/RTP/RTCP_Report_Sender.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.RTP { #region usings using System; #endregion /// <summary> /// This class holds sender report info. /// </summary> public class RTCP_Report_Sender { #region Members private readonly ulong m_NtpTimestamp; private readonly uint m_RtpTimestamp; private readonly uint m_SenderOctetCount; private readonly uint m_SenderPacketCount; #endregion #region Properties /// <summary> /// Gets the wallclock time (see Section 4) when this report was sent. /// </summary> public ulong NtpTimestamp { get { return m_NtpTimestamp; } } /// <summary> /// Gets RTP timestamp. /// </summary> public uint RtpTimestamp { get { return m_RtpTimestamp; } } /// <summary> /// Gets how many packets sender has sent. /// </summary> public uint SenderPacketCount { get { return m_SenderPacketCount; } } /// <summary> /// Gets how many bytes sender has sent. /// </summary> public uint SenderOctetCount { get { return m_SenderOctetCount; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="sr">RTCP SR report.</param> /// <exception cref="ArgumentNullException">Is raised when <b>sr</b> is null reference.</exception> internal RTCP_Report_Sender(RTCP_Packet_SR sr) { if (sr == null) { throw new ArgumentNullException("sr"); } m_NtpTimestamp = sr.NtpTimestamp; m_RtpTimestamp = sr.RtpTimestamp; m_SenderPacketCount = sr.SenderPacketCount; m_SenderOctetCount = sr.SenderOctetCount; } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/FTP/Server/FTP_Server.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.FTP.Server { #region usings using System; using System.IO; using System.Net; using System.Net.Sockets; #endregion #region Event delegates /// <summary> /// Represents the method that will handle the AuthUser event for FTP_Server. /// </summary> /// <param name="sender">The source of the event. </param> /// <param name="e">A AuthUser_EventArgs that contains the event data.</param> public delegate void AuthUserEventHandler(object sender, AuthUser_EventArgs e); /// <summary> /// Represents the method that will handle the filsystem rerlated events for FTP_Server. /// </summary> public delegate void FileSysEntryEventHandler(object sender, FileSysEntry_EventArgs e); #endregion /// <summary> /// FTP Server component. /// </summary> public class FTP_Server : SocketServer { #region Events /// <summary> /// Occurs when connected user tryes to authenticate. /// </summary> public event AuthUserEventHandler AuthUser = null; /// <summary> /// Occurs when server needs needs to create directory. /// </summary> public event FileSysEntryEventHandler CreateDir = null; /// <summary> /// Occurs when server needs needs to delete directory. /// </summary> public event FileSysEntryEventHandler DeleteDir = null; /// <summary> /// Occurs when server needs needs to delete file. /// </summary> public event FileSysEntryEventHandler DeleteFile = null; /// <summary> /// Occurs when server needs to validatee directory. /// </summary> public event FileSysEntryEventHandler DirExists = null; /// <summary> /// Occurs when server needs needs validate file. /// </summary> public event FileSysEntryEventHandler FileExists = null; /// <summary> /// Occurs when server needs directory info (directories,files in deirectory). /// </summary> public event FileSysEntryEventHandler GetDirInfo = null; /// <summary> /// Occurs when server needs needs to get file. /// </summary> public event FileSysEntryEventHandler GetFile = null; /// <summary> /// Occurs when server needs needs to rname directory or file. /// </summary> public event FileSysEntryEventHandler RenameDirFile = null; /// <summary> /// Occurs when POP3 session has finished and session log is available. /// </summary> public event LogEventHandler SessionLog = null; /// <summary> /// Occurs when server needs needs to store file. /// </summary> public event FileSysEntryEventHandler StoreFile = null; /// <summary> /// Occurs when new computer connected to FTP server. /// </summary> public event ValidateIPHandler ValidateIPAddress = null; #endregion #region Members private int m_PassiveStartPort = 20000; #endregion #region Properties /// <summary> /// Gets active sessions. /// </summary> public new FTP_Session[] Sessions { get { SocketServerSession[] sessions = base.Sessions; FTP_Session[] ftpSessions = new FTP_Session[sessions.Length]; sessions.CopyTo(ftpSessions, 0); return ftpSessions; } } /// <summary> /// Gets or sets passive mode public IP address what is reported to clients. /// This property is manly needed if FTP server is running behind NAT. /// Value null means not spcified. /// </summary> public IPAddress PassivePublicIP { get; set; } /// <summary> /// Gets or sets passive mode start port form which server starts using ports. /// </summary> /// <exception cref="ArgumentException">Is raised when ivalid value is passed.</exception> public int PassiveStartPort { get { return m_PassiveStartPort; } set { if (value < 1) { throw new ArgumentException("Valu must be > 0 !"); } m_PassiveStartPort = value; } } #endregion #region Constructor /// <summary> /// Defalut constructor. /// </summary> public FTP_Server() { BindInfo = new[] {new IPBindInfo("", IPAddress.Any, 21, SslMode.None, null)}; } #endregion #region Overrides /// <summary> /// Initialize and start new session here. Session isn't added to session list automatically, /// session must add itself to server session list by calling AddSession(). /// </summary> /// <param name="socket">Connected client socket.</param> /// <param name="bindInfo">BindInfo what accepted socket.</param> protected override void InitNewSession(Socket socket, IPBindInfo bindInfo) { string sessionID = Guid.NewGuid().ToString(); SocketEx socketEx = new SocketEx(socket); if (LogCommands) { socketEx.Logger = new SocketLogger(socket, SessionLog); socketEx.Logger.SessionID = sessionID; } FTP_Session session = new FTP_Session(sessionID, socketEx, bindInfo, this); } #endregion #region Virtual methods /// <summary> /// Raises event ValidateIP event. /// </summary> /// <param name="localEndPoint">Server IP.</param> /// <param name="remoteEndPoint">Connected client IP.</param> /// <returns>Returns true if connection allowed.</returns> internal virtual bool OnValidate_IpAddress(IPEndPoint localEndPoint, IPEndPoint remoteEndPoint) { ValidateIP_EventArgs oArg = new ValidateIP_EventArgs(localEndPoint, remoteEndPoint); if (ValidateIPAddress != null) { ValidateIPAddress(this, oArg); } return oArg.Validated; } /// <summary> /// Authenticates user. /// </summary> /// <param name="session">Reference to current pop3 session.</param> /// <param name="userName">User name.</param> /// <param name="passwData"></param> /// <param name="data"></param> /// <param name="authType"></param> /// <returns></returns> internal virtual bool OnAuthUser(FTP_Session session, string userName, string passwData, string data, AuthType authType) { AuthUser_EventArgs oArg = new AuthUser_EventArgs(session, userName, passwData, data, authType); if (AuthUser != null) { AuthUser(this, oArg); } return oArg.Validated; } #endregion #region Internal methods internal FileSysEntry_EventArgs OnGetDirInfo(FTP_Session session, string dir) { FileSysEntry_EventArgs oArg = new FileSysEntry_EventArgs(session, dir, ""); if (GetDirInfo != null) { GetDirInfo(this, oArg); } return oArg; } internal bool OnDirExists(FTP_Session session, string dir) { FileSysEntry_EventArgs oArg = new FileSysEntry_EventArgs(session, dir, ""); if (DirExists != null) { DirExists(this, oArg); } return oArg.Validated; } internal bool OnCreateDir(FTP_Session session, string dir) { FileSysEntry_EventArgs oArg = new FileSysEntry_EventArgs(session, dir, ""); if (CreateDir != null) { CreateDir(this, oArg); } return oArg.Validated; } internal bool OnDeleteDir(FTP_Session session, string dir) { FileSysEntry_EventArgs oArg = new FileSysEntry_EventArgs(session, dir, ""); if (DeleteDir != null) { DeleteDir(this, oArg); } return oArg.Validated; } internal bool OnRenameDirFile(FTP_Session session, string from, string to) { FileSysEntry_EventArgs oArg = new FileSysEntry_EventArgs(session, from, to); if (RenameDirFile != null) { RenameDirFile(this, oArg); } return oArg.Validated; } internal bool OnFileExists(FTP_Session session, string file) { // Remove last / file = file.Substring(0, file.Length - 1); FileSysEntry_EventArgs oArg = new FileSysEntry_EventArgs(session, file, ""); if (FileExists != null) { FileExists(this, oArg); } return oArg.Validated; } internal Stream OnGetFile(FTP_Session session, string file) { FileSysEntry_EventArgs oArg = new FileSysEntry_EventArgs(session, file, ""); if (GetFile != null) { GetFile(this, oArg); } return oArg.FileStream; } internal Stream OnStoreFile(FTP_Session session, string file) { FileSysEntry_EventArgs oArg = new FileSysEntry_EventArgs(session, file, ""); if (StoreFile != null) { StoreFile(this, oArg); } return oArg.FileStream; } internal bool OnDeleteFile(FTP_Session session, string file) { FileSysEntry_EventArgs oArg = new FileSysEntry_EventArgs(session, file, ""); if (DeleteFile != null) { DeleteFile(this, oArg); } return oArg.Validated; } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/Multilang/IMLangLineBreakConsole.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace MultiLanguage { using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Security; [ComImport, InterfaceType((short) 1), Guid("F5BE2EE1-BFD7-11D0-B188-00AA0038C969")] public interface IMLangLineBreakConsole { [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void BreakLineML([In, MarshalAs(UnmanagedType.Interface)] CMLangString pSrcMLStr, [In] int lSrcPos, [In] int lSrcLen, [In] int cMinColumns, [In] int cMaxColumns, out int plLineLen, out int plSkipLen); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void BreakLineW([In] uint locale, [In] ref ushort pszSrc, [In] int cchSrc, [In] int cMaxColumns, out int pcchLine, out int pcchSkip); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void BreakLineA([In] uint locale, [In] uint uCodePage, [In] ref sbyte pszSrc, [In] int cchSrc, [In] int cMaxColumns, out int pcchLine, out int pcchSkip); } } <file_sep>/module/ASC.Api/ASC.Api.Mail/MailApi.Settings.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using ASC.Api.Attributes; using ASC.Mail.Data.Contracts; namespace ASC.Api.Mail { public partial class MailApi { /// <summary> /// Returns Common Settings /// </summary> /// <returns>MailCommonSettings object</returns> /// <short>Get common settings</short> /// <category>Settings</category> [Read(@"settings")] public MailCommonSettings GetCommonSettings() { var commonSettings = MailCommonSettings.LoadForCurrentUser(); return commonSettings; } /// <summary> /// Returns EnableConversations flag /// </summary> /// <returns>boolean</returns> /// <short>Get EnableConversations flag</short> /// <category>Settings</category> [Read(@"settings/conversationsEnabled")] public bool GetEnableConversationFlag() { var value = MailCommonSettings.EnableConversations; return value; } /// <summary> /// Set EnableConversations flag /// </summary> /// <param name="enabled">True or False value</param> /// <short>Set EnableConversations flag</short> /// <category>Settings</category> [Update(@"settings/conversationsEnabled")] public void SetEnableConversationFlag(bool enabled) { MailCommonSettings.EnableConversations = enabled; } /// <summary> /// Returns AlwaysDisplayImages flag /// </summary> /// <returns>boolean</returns> /// <short>Get AlwaysDisplayImages flag</short> /// <category>Settings</category> [Read(@"settings/alwaysDisplayImages")] public bool GetAlwaysDisplayImagesFlag() { var value = MailCommonSettings.AlwaysDisplayImages; return value; } /// <summary> /// Set AlwaysDisplayImages flag /// </summary> /// <param name="enabled">True or False value</param> /// <short>Set AlwaysDisplayImages flag</short> /// <category>Settings</category> [Update(@"settings/alwaysDisplayImages")] public void SetAlwaysDisplayImagesFlag(bool enabled) { MailCommonSettings.AlwaysDisplayImages = enabled; } /// <summary> /// Returns CacheUnreadMessages flag /// </summary> /// <returns>boolean</returns> /// <short>Get CacheUnreadMessages flag</short> /// <category>Settings</category> [Read(@"settings/cacheMessagesEnabled")] public bool GetCacheUnreadMessagesFlag() { //TODO: Change cache algoritnm and restore it back /*var value = MailCommonSettings.CacheUnreadMessages; return value;*/ return false; } /// <summary> /// Set CacheUnreadMessages flag /// </summary> /// <param name="enabled">True or False value</param> /// <short>Set CacheUnreadMessages flag</short> /// <category>Settings</category> [Update(@"settings/cacheMessagesEnabled")] public void SetCacheUnreadMessagesFlag(bool enabled) { MailCommonSettings.CacheUnreadMessages = enabled; } /// <summary> /// Returns GoNextAfterMove flag /// </summary> /// <returns>boolean</returns> /// <short>Get GoNextAfterMove flag</short> /// <category>Settings</category> [Read(@"settings/goNextAfterMoveEnabled")] public bool GetEnableGoNextAfterMoveFlag() { var value = MailCommonSettings.GoNextAfterMove; return value; } /// <summary> /// Set GoNextAfterMove flag /// </summary> /// <param name="enabled">True or False value</param> /// <short>Set GoNextAfterMove flag</short> /// <category>Settings</category> [Update(@"settings/goNextAfterMoveEnabled")] public void SetEnableGoNextAfterMoveFlag(bool enabled) { MailCommonSettings.GoNextAfterMove = enabled; } /// <summary> /// Returns ReplaceMessageBody flag /// </summary> /// <returns>boolean</returns> /// <short>Get ReplaceMessageBody flag</short> /// <category>Settings</category> [Read(@"settings/replaceMessageBody")] public bool GetEnableReplaceMessageBodyFlag() { var value = MailCommonSettings.ReplaceMessageBody; return value; } /// <summary> /// Set ReplaceMessageBody flag /// </summary> /// <param name="enabled">True or False value</param> /// <short>Set ReplaceMessageBody flag</short> /// <category>Settings</category> [Update(@"settings/replaceMessageBody")] public void SetEnableReplaceMessageBodyFlag(bool enabled) { MailCommonSettings.ReplaceMessageBody = enabled; } } } <file_sep>/common/ASC.Data.Backup/Storage/ConsumerBackupStorage.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections.Generic; using System.IO; using System.Linq; using ASC.Data.Storage; using ASC.Data.Storage.Configuration; namespace ASC.Data.Backup.Storage { internal class ConsumerBackupStorage : IBackupStorage { private readonly IDataStore store; private const string Domain = "backup"; public ConsumerBackupStorage(IReadOnlyDictionary<string, string> storageParams) { var settings = new StorageSettings { Module = storageParams["module"], Props = storageParams.Where(r => r.Key != "module").ToDictionary(r => r.Key, r => r.Value) }; store = settings.DataStore; } public string Upload(string storageBasePath, string localPath, Guid userId) { using (var stream = File.OpenRead(localPath)) { var storagePath = Path.GetFileName(localPath); store.Save(Domain, storagePath, stream, ACL.Private); return storagePath; } } public void Download(string storagePath, string targetLocalPath) { using (var source = store.GetReadStream(Domain, storagePath)) using (var destination = File.OpenWrite(targetLocalPath)) { source.CopyTo(destination); } } public void Delete(string storagePath) { if (store.IsFile(Domain, storagePath)) { store.Delete(Domain, storagePath); } } public bool IsExists(string storagePath) { return store.IsFile(Domain, storagePath); } public string GetPublicLink(string storagePath) { return store.GetInternalUri(Domain, storagePath, TimeSpan.FromDays(1), null).AbsoluteUri; } } } <file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/_Obsolete/SocketEx.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net { #region usings using System; using System.IO; using System.Net; using System.Net.Security; using System.Net.Sockets; using System.Security.Cryptography.X509Certificates; using System.Text; #endregion /// <summary> /// This class implements extended socket, provides usefull methods for reading and writing data to socket. /// </summary> public class SocketEx : IDisposable { #region Nested type: _BeginWritePeriodTerminated_State /// <summary> /// BeginWritePeriodTerminated state obejct. /// </summary> private struct _BeginWritePeriodTerminated_State { #region Members private readonly SocketCallBack m_Callback; private readonly bool m_CloseStream; private readonly Stream m_Stream; private readonly object m_Tag; private int m_CountSent; private bool m_HasCRLF; private int m_LastByte; #endregion #region Properties /// <summary> /// Gets source stream. /// </summary> public Stream Stream { get { return m_Stream; } } /// <summary> /// Gets if stream must be closed if reading completed. /// </summary> public bool CloseStream { get { return m_CloseStream; } } /// <summary> /// Gets user data. /// </summary> public object Tag { get { return m_Tag; } } /// <summary> /// Gets callback what must be called if asynchronous write ends. /// </summary> public SocketCallBack Callback { get { return m_Callback; } } /// <summary> /// Gets or sets if last sent data ends with CRLF. /// </summary> public bool HasCRLF { get { return m_HasCRLF; } set { m_HasCRLF = value; } } /// <summary> /// Gets or sets what is last sent byte. /// </summary> public int LastByte { get { return m_LastByte; } set { m_LastByte = value; } } /// <summary> /// Gets or sets how many bytes has written to socket. /// </summary> public int CountSent { get { return m_CountSent; } set { m_CountSent = value; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="stream">Source stream.</param> /// <param name="closeStream">Specifies if stream must be closed after reading is completed.</param> /// <param name="tag">User data.</param> /// <param name="callback">Callback what to call if asynchronous data writing completes.</param> public _BeginWritePeriodTerminated_State(Stream stream, bool closeStream, object tag, SocketCallBack callback) { m_Stream = stream; m_CloseStream = closeStream; m_Tag = tag; m_Callback = callback; m_HasCRLF = false; m_LastByte = -1; m_CountSent = 0; } #endregion } #endregion #region Nested type: BufferDataBlockCompleted private delegate void BufferDataBlockCompleted(Exception x, object tag); #endregion #region Members private readonly byte[] m_Buffer; private int m_AvailableInBuffer; private string m_Host = ""; private DateTime m_LastActivityDate; private int m_OffsetInBuffer; private Encoding m_pEncoding; private SocketLogger m_pLogger; private Socket m_pSocket; private NetworkStream m_pSocketStream; private SslStream m_pSslStream; private long m_ReadedCount; private bool m_SSL; private long m_WrittenCount; #endregion #region Properties /// <summary> /// Gets or sets socket default encoding. /// </summary> public Encoding Encoding { get { return m_pEncoding; } set { if (m_pEncoding == null) { throw new ArgumentNullException("Encoding"); } m_pEncoding = value; } } /// <summary> /// Gets or sets logging source. If this is setted, reads/writes are logged to it. /// </summary> public SocketLogger Logger { get { return m_pLogger; } set { m_pLogger = value; } } /// <summary> /// Gets raw uderlaying socket. /// </summary> public Socket RawSocket { get { return m_pSocket; } } /// <summary> /// Gets if socket is connected. /// </summary> public bool Connected { get { return m_pSocket != null && m_pSocket.Connected; } } /// <summary> /// Gets the local endpoint. /// </summary> public EndPoint LocalEndPoint { get { if (m_pSocket == null) { return null; } else { return m_pSocket.LocalEndPoint; } } } /// <summary> /// Gets the remote endpoint. /// </summary> public EndPoint RemoteEndPoint { get { if (m_pSocket == null) { return null; } else { return m_pSocket.RemoteEndPoint; } } } /// <summary> /// Gets if socket is connected via SSL. /// </summary> public bool SSL { get { return m_SSL; } } /// <summary> /// Gets how many bytes are readed through this socket. /// </summary> public long ReadedCount { get { return m_ReadedCount; } } /// <summary> /// Gets how many bytes are written through this socket. /// </summary> public long WrittenCount { get { return m_WrittenCount; } } /// <summary> /// Gets when was last socket(read or write) activity. /// </summary> public DateTime LastActivity { get { return m_LastActivityDate; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> public SocketEx() { m_Buffer = new byte[8000]; m_pEncoding = Encoding.UTF8; m_LastActivityDate = DateTime.Now; m_pSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); m_pSocket.ReceiveTimeout = 60000; m_pSocket.SendTimeout = 60000; } /// <summary> /// Socket wrapper. NOTE: You must pass connected socket here ! /// </summary> /// <param name="socket">Socket.</param> public SocketEx(Socket socket) { m_Buffer = new byte[8000]; m_pEncoding = Encoding.UTF8; m_LastActivityDate = DateTime.Now; m_pSocket = socket; if (socket.ProtocolType == ProtocolType.Tcp) { m_pSocketStream = new NetworkStream(socket, false); } m_pSocket.ReceiveTimeout = 60000; m_pSocket.SendTimeout = 60000; } #endregion #region Methods /// <summary> /// Clean up any resouces being used. /// </summary> public void Dispose() { Disconnect(); } /// <summary> /// Connects to the specified host. /// </summary> /// <param name="endpoint">IP endpoint where to connect.</param> public void Connect(IPEndPoint endpoint) { Connect(endpoint.Address.ToString(), endpoint.Port, false); } /// <summary> /// Connects to the specified host. /// </summary> /// <param name="endpoint">IP endpoint where to connect.</param> /// <param name="ssl">Specifies if to connected via SSL.</param> public void Connect(IPEndPoint endpoint, bool ssl) { Connect(endpoint.Address.ToString(), endpoint.Port, ssl); } /// <summary> /// Connects to the specified host. /// </summary> /// <param name="host">Host name or IP where to connect.</param> /// <param name="port">TCP port number where to connect.</param> public void Connect(string host, int port) { Connect(host, port, false); } /// <summary> /// Connects to the specified host. /// </summary> /// <param name="host">Host name or IP where to connect.</param> /// <param name="port">TCP port number where to connect.</param> /// <param name="ssl">Specifies if to connected via SSL.</param> public void Connect(string host, int port, bool ssl) { m_pSocket.Connect(new IPEndPoint(System.Net.Dns.GetHostAddresses(host)[0], port)); // mono won't support it //m_pSocket.Connect(host,port); m_Host = host; m_pSocketStream = new NetworkStream(m_pSocket, false); if (ssl) { SwitchToSSL_AsClient(); } } /// <summary> /// Disconnects socket. /// </summary> public void Disconnect() { lock (this) { if (m_pSocket != null) { m_pSocket.Close(); } m_SSL = false; m_pSocketStream = null; m_pSslStream = null; m_pSocket = null; m_OffsetInBuffer = 0; m_AvailableInBuffer = 0; m_Host = ""; m_ReadedCount = 0; m_WrittenCount = 0; } } /// <summary> /// Shutdowns socket. /// </summary> /// <param name="how"></param> public void Shutdown(SocketShutdown how) { m_pSocket.Shutdown(how); } /// <summary> /// Associates a Socket with a local endpoint. /// </summary> /// <param name="loaclEP"></param> public void Bind(EndPoint loaclEP) { m_pSocket.Bind(loaclEP); } /// <summary> /// Places a Socket in a listening state. /// </summary> /// <param name="backlog">The maximum length of the pending connections queue. </param> public void Listen(int backlog) { m_pSocket.Listen(backlog); } /// <summary> /// TODO: /// </summary> /// <param name="ssl"></param> /// <returns></returns> public SocketEx Accept(bool ssl) { Socket s = m_pSocket.Accept(); return new SocketEx(s); } /// <summary> /// Switches socket to SSL mode. Throws excpetion is socket is already in SSL mode. /// </summary> /// <param name="certificate">Certificate to use for SSL.</param> public void SwitchToSSL(X509Certificate certificate) { if (m_SSL) { throw new Exception("Error can't switch to SSL, socket is already in SSL mode !"); } SslStream sslStream = new SslStream(m_pSocketStream); sslStream.AuthenticateAsServer(certificate); m_SSL = true; m_pSslStream = sslStream; } /// <summary> /// Switches socket to SSL mode. Throws excpetion is socket is already in SSL mode. /// </summary> public void SwitchToSSL_AsClient() { if (m_SSL) { throw new Exception("Error can't switch to SSL, socket is already in SSL mode !"); } SslStream sslStream = new SslStream(m_pSocketStream, true, RemoteCertificateValidationCallback); sslStream.AuthenticateAsClient(m_Host); m_SSL = true; m_pSslStream = sslStream; } /// <summary> /// Reads byte from socket. Returns readed byte or -1 if socket is shutdown and tehre is no more data available. /// </summary> /// <returns>Returns readed byte or -1 if socket is shutdown and tehre is no more data available.</returns> public int ReadByte() { BufferDataBlock(); // Socket is shutdown if (m_AvailableInBuffer == 0) { m_OffsetInBuffer = 0; m_AvailableInBuffer = 0; return -1; } m_OffsetInBuffer++; m_AvailableInBuffer--; return m_Buffer[m_OffsetInBuffer - 1]; } /// <summary> /// Reads line from socket. Maximum line length is 4000 bytes. NOTE: CRLF isn't written to destination stream. /// If maximum allowed line length is exceeded line is read to end, but isn't stored to buffer and exception /// is thrown after line reading. /// </summary> /// <returns>Returns readed line.</returns> public string ReadLine() { return ReadLine(4000); } /// <summary> /// Reads line from socket.NOTE: CRLF isn't written to destination stream. /// If maximum allowed line length is exceeded line is read to end, but isn't stored to buffer and exception /// is thrown after line reading. /// </summary> /// <param name="maxLineLength">Maximum line length in bytes.</param> /// <returns>Returns readed line.</returns> public string ReadLine(int maxLineLength) { return m_pEncoding.GetString(ReadLineByte(maxLineLength)); } /// <summary> /// Reads line from socket.NOTE: CRLF isn't written to destination stream. /// If maximum allowed line length is exceeded line is read to end, but isn't stored to buffer and exception /// is thrown after line reading. /// </summary> /// <param name="maxLineLength">Maximum line length in bytes.</param> /// <returns>Returns readed line.</returns> public byte[] ReadLineByte(int maxLineLength) { MemoryStream strmLineBuf = new MemoryStream(); ReadLine(strmLineBuf, maxLineLength); return strmLineBuf.ToArray(); } /// <summary> /// Reads line from socket and stores it to specified stream. NOTE: CRLF isn't written to destination stream. /// If maximum allowed line length is exceeded line is read to end, but isn't stored to buffer and exception /// is thrown after line reading. /// </summary> /// <param name="stream">Stream where to store readed line.</param> /// <param name="maxLineLength">Maximum line length in bytes.</param> public void ReadLine(Stream stream, int maxLineLength) { // Delay last byte writing, this is because CR, if next is LF, then skip CRLF and terminate reading. int lastByte = ReadByte(); int currentByte = ReadByte(); int readedCount = 2; while (currentByte > -1) { // We got line if (lastByte == (byte) '\r' && currentByte == (byte) '\n') { // Logging stuff if (m_pLogger != null) { if (stream.CanSeek && stream.Length < 200) { byte[] readedData = new byte[stream.Length]; stream.Position = 0; stream.Read(readedData, 0, readedData.Length); m_pLogger.AddReadEntry(m_pEncoding.GetString(readedData), readedCount); } else { m_pLogger.AddReadEntry("Big binary line, readed " + readedCount + " bytes.", readedCount); } } stream.Flush(); // Maximum allowed length exceeded if (readedCount > maxLineLength) { throw new ReadException(ReadReplyCode.LengthExceeded, "Maximum allowed line length exceeded !"); } return; } else { // Maximum allowed length exceeded, just don't store data. if (readedCount < maxLineLength) { stream.WriteByte((byte) lastByte); } lastByte = currentByte; } // Read next byte currentByte = ReadByte(); readedCount++; } // We should not reach there, if so then socket closed // Logging stuff if (m_pLogger != null) { m_pLogger.AddTextEntry("Remote host closed socket !"); } throw new ReadException(ReadReplyCode.SocketClosed, "Connected host closed socket, read line terminated unexpectedly !"); } /// <summary> /// Reads specified length of data from socket and store to specified stream. /// </summary> /// <param name="lengthToRead">Specifies how much data to read from socket.</param> /// <param name="storeStream">Stream where to store data.</param> public void ReadSpecifiedLength(int lengthToRead, Stream storeStream) { while (lengthToRead > 0) { BufferDataBlock(); // Socket is shutdown if (m_AvailableInBuffer == 0) { m_OffsetInBuffer = 0; m_AvailableInBuffer = 0; // Logging stuff if (m_pLogger != null) { m_pLogger.AddTextEntry("Remote host closed socket, all data wans't readed !"); } throw new Exception("Remote host closed socket, all data wans't readed !"); } // We have all data in buffer what we need. if (m_AvailableInBuffer >= lengthToRead) { storeStream.Write(m_Buffer, m_OffsetInBuffer, lengthToRead); storeStream.Flush(); m_OffsetInBuffer += lengthToRead; m_AvailableInBuffer -= lengthToRead; lengthToRead = 0; // Logging stuff if (m_pLogger != null) { if (storeStream.CanSeek && storeStream.Length < 200) { byte[] readedData = new byte[storeStream.Length]; storeStream.Position = 0; storeStream.Read(readedData, 0, readedData.Length); m_pLogger.AddReadEntry(m_pEncoding.GetString(readedData), lengthToRead); } else { m_pLogger.AddReadEntry("Big binary data, readed " + lengthToRead + " bytes.", lengthToRead); } } } // We need more data than buffer has,read all buffer data. else { storeStream.Write(m_Buffer, m_OffsetInBuffer, m_AvailableInBuffer); storeStream.Flush(); lengthToRead -= m_AvailableInBuffer; m_OffsetInBuffer = 0; m_AvailableInBuffer = 0; } } } /// <summary> /// Reads period terminated string. The data is terminated by a line containing only a period, that is, /// the character sequence "&lt;CRLF&gt;.&lt;CRLF&gt;". /// When a line of text is received, it checks the line. If the line is composed of a single period, /// it is treated as the end of data indicator. If the first character is a period and there are /// other characters on the line, the first character is deleted. /// If maximum allowed data length is exceeded data is read to end, but isn't stored to buffer and exception /// is thrown after data reading. /// </summary> /// <param name="maxLength">Maximum data length in bytes.</param> /// <returns></returns> public string ReadPeriodTerminated(int maxLength) { MemoryStream ms = new MemoryStream(); ReadPeriodTerminated(ms, maxLength); return m_pEncoding.GetString(ms.ToArray()); } /// <summary> /// Reads period terminated data. The data is terminated by a line containing only a period, that is, /// the character sequence "&lt;CRLF&gt;.&lt;CRLF&gt;". /// When a line of text is received, it checks the line. If the line is composed of a single period, /// it is treated as the end of data indicator. If the first character is a period and there are /// other characters on the line, the first character is deleted. /// If maximum allowed data length is exceeded data is read to end, but isn't stored to stream and exception /// is thrown after data reading. /// </summary> /// <param name="stream">Stream where to store readed data.</param> /// <param name="maxLength">Maximum data length in bytes.</param> public void ReadPeriodTerminated(Stream stream, int maxLength) { /* When a line of text is received by the server, it checks the line. If the line is composed of a single period, it is treated as the end of data indicator. If the first character is a period and there are other characters on the line, the first character is deleted. */ // Delay last byte writing, this is because CR, if next is LF, then last byte isn't written. byte[] buffer = new byte[8000]; int positionInBuffer = 0; int lastByte = ReadByte(); int currentByte = ReadByte(); int readedCount = 2; bool lineBreak = false; bool expectCRLF = false; while (currentByte > -1) { // We got <CRLF> + 1 char, we must skip that char if it is '.'. if (lineBreak) { lineBreak = false; // We must skip that char if it is '.' if (currentByte == '.') { expectCRLF = true; currentByte = ReadByte(); } } // We got <CRLF> else if (lastByte == (byte) '\r' && currentByte == (byte) '\n') { lineBreak = true; // We have <CRLF>.<CRLF>, skip last <CRLF>. if (expectCRLF) { // There is data in buffer, flush it if (positionInBuffer > 0) { stream.Write(buffer, 0, positionInBuffer); positionInBuffer = 0; } // Logging stuff if (m_pLogger != null) { if (stream.CanSeek && stream.Length < 200) { byte[] readedData = new byte[stream.Length]; stream.Position = 0; stream.Read(readedData, 0, readedData.Length); m_pLogger.AddReadEntry(m_pEncoding.GetString(readedData), readedCount); } else { m_pLogger.AddReadEntry("Big binary data, readed " + readedCount + " bytes.", readedCount); } } // Maximum allowed length exceeded if (readedCount > maxLength) { throw new ReadException(ReadReplyCode.LengthExceeded, "Maximum allowed line length exceeded !"); } return; } } // current char isn't CRLF part, so it isn't <CRLF>.<CRLF> terminator. if (expectCRLF && !(currentByte == (byte) '\r' || currentByte == (byte) '\n')) { expectCRLF = false; } // Maximum allowed length exceeded, just don't store data. if (readedCount < maxLength) { // Buffer is filled up, write buffer to stream if (positionInBuffer > (buffer.Length - 2)) { stream.Write(buffer, 0, positionInBuffer); positionInBuffer = 0; } buffer[positionInBuffer] = (byte) lastByte; positionInBuffer++; } // Read next byte lastByte = currentByte; currentByte = ReadByte(); readedCount++; } // We never should reach there, only if data isn't <CRLF>.<CRLF> terminated. // Logging stuff if (m_pLogger != null) { m_pLogger.AddTextEntry("Remote host closed socket and data wasn't <CRLF>.<CRLF> terminated !"); } throw new Exception("Remote host closed socket and data wasn't <CRLF>.<CRLF> terminated !"); } /// <summary> /// Writes specified data to socket. /// </summary> /// <param name="data">Data to write to socket.</param> public void Write(string data) { if (Logger != null) { Logger.AddSendEntry(data, data.Length); } Write(new MemoryStream(m_pEncoding.GetBytes(data))); } /// <summary> /// Writes specified data to socket. /// </summary> /// <param name="data">Data to to wite to socket.</param> public void Write(byte[] data) { Write(new MemoryStream(data)); } /// <summary> /// Writes specified data to socket. /// </summary> /// <param name="data">Data to to wite to socket.</param> /// <param name="offset">Offset in data from where to start sending data.</param> /// <param name="length">Lengh of data to send.</param> public void Write(byte[] data, int offset, int length) { MemoryStream ms = new MemoryStream(data); ms.Position = offset; Write(ms, length); } /// <summary> /// Writes specified data to socket. /// </summary> /// <param name="stream">Stream which data to write to socket. Reading starts from stream current position and will be readed to EOS.</param> public void Write(Stream stream) { m_pSocket.NoDelay = false; byte[] buffer = new byte[4000]; int sentCount = 0; int readedCount = stream.Read(buffer, 0, buffer.Length); while (readedCount > 0) { if (m_SSL) { m_pSslStream.Write(buffer, 0, readedCount); m_pSslStream.Flush(); } else { m_pSocketStream.Write(buffer, 0, readedCount); } sentCount += readedCount; m_WrittenCount += readedCount; m_LastActivityDate = DateTime.Now; readedCount = stream.Read(buffer, 0, buffer.Length); } // Logging stuff if (m_pLogger != null) { if (sentCount < 200) { m_pLogger.AddSendEntry(m_pEncoding.GetString(buffer, 0, sentCount), sentCount); } else { m_pLogger.AddSendEntry("Big binary data, sent " + sentCount + " bytes.", sentCount); } } } /// <summary> /// Writes specified data to socket. /// </summary> /// <param name="stream">Stream which data to write to socket. Reading starts from stream current position and specified count will be readed.</param> /// <param name="count">Number of bytes to read from stream and write to socket.</param> public void Write(Stream stream, long count) { m_pSocket.NoDelay = false; byte[] buffer = new byte[4000]; int sentCount = 0; int readedCount = 0; if ((count - sentCount) > buffer.Length) { readedCount = stream.Read(buffer, 0, buffer.Length); } else { readedCount = stream.Read(buffer, 0, (int) (count - sentCount)); } while (sentCount < count) { if (m_SSL) { m_pSslStream.Write(buffer, 0, readedCount); m_pSslStream.Flush(); } else { m_pSocketStream.Write(buffer, 0, readedCount); } sentCount += readedCount; m_WrittenCount += readedCount; m_LastActivityDate = DateTime.Now; if ((count - sentCount) > buffer.Length) { readedCount = stream.Read(buffer, 0, buffer.Length); } else { readedCount = stream.Read(buffer, 0, (int) (count - sentCount)); } } // Logging stuff if (m_pLogger != null) { if (sentCount < 200) { m_pLogger.AddSendEntry(m_pEncoding.GetString(buffer, 0, sentCount), sentCount); } else { m_pLogger.AddSendEntry("Big binary data, sent " + sentCount + " bytes.", sentCount); } } } /// <summary> /// Writes specified line to socket. If line isn't CRLF terminated, CRLF is added automatically. /// </summary> /// <param name="line">Line to write to socket.</param> public void WriteLine(string line) { if (Logger != null) { Logger.AddSendEntry(line, line.Length); } WriteLine(m_pEncoding.GetBytes(line)); } /// <summary> /// Writes specified line to socket. If line isn't CRLF terminated, CRLF is added automatically. /// </summary> /// <param name="line">Line to write to socket.</param> public void WriteLine(byte[] line) { // Don't allow to wait after we send data, because there won't no more data m_pSocket.NoDelay = true; // <CRF> is missing, add it if (line.Length < 2 || (line[line.Length - 2] != (byte) '\r' && line[line.Length - 1] != (byte) '\n')) { byte[] newLine = new byte[line.Length + 2]; Array.Copy(line, newLine, line.Length); newLine[newLine.Length - 2] = (byte) '\r'; newLine[newLine.Length - 1] = (byte) '\n'; line = newLine; } if (m_SSL) { m_pSslStream.Write(line); } else { m_pSocketStream.Write(line, 0, line.Length); } m_WrittenCount += line.Length; m_LastActivityDate = DateTime.Now; // Logging stuff if (m_pLogger != null) { if (line.Length < 200) { m_pLogger.AddSendEntry(m_pEncoding.GetString(line), line.Length); } else { m_pLogger.AddSendEntry("Big binary line, sent " + line.Length + " bytes.", line.Length); } } } /// <summary> /// Writes period terminated string to socket. The data is terminated by a line containing only a period, that is, /// the character sequence "&lt;CRLF&gt;.&lt;CRLF&gt;". Before sending a line of text, check the first /// character of the line.If it is a period, one additional period is inserted at the beginning of the line. /// </summary> /// <param name="data">String data to write.</param> public void WritePeriodTerminated(string data) { WritePeriodTerminated(new MemoryStream(m_pEncoding.GetBytes(data))); } /// <summary> /// Writes period terminated data to socket. The data is terminated by a line containing only a period, that is, /// the character sequence "&lt;CRLF&gt;.&lt;CRLF&gt;". Before sending a line of text, check the first /// character of the line.If it is a period, one additional period is inserted at the beginning of the line. /// </summary> /// <param name="stream">Stream which data to write. Reading begins from stream current position and is readed to EOS.</param> public void WritePeriodTerminated(Stream stream) { /* Before sending a line of text, check the first character of the line. If it is a period, one additional period is inserted at the beginning of the line. */ int countSent = 0; byte[] buffer = new byte[4000]; int positionInBuffer = 0; bool CRLF = false; int lastByte = -1; int currentByte = stream.ReadByte(); while (currentByte > -1) { // We have CRLF, mark it up if (lastByte == '\r' && currentByte == '\n') { CRLF = true; } // There is CRLF + current byte else if (CRLF) { // If it is a period, one additional period is inserted at the beginning of the line. if (currentByte == '.') { buffer[positionInBuffer] = (byte) '.'; positionInBuffer++; } // CRLF handled, reset it CRLF = false; } buffer[positionInBuffer] = (byte) currentByte; positionInBuffer++; lastByte = currentByte; // Buffer is filled up, write buffer to socket. if (positionInBuffer > (4000 - 10)) { if (m_SSL) { m_pSslStream.Write(buffer, 0, positionInBuffer); } else { m_pSocketStream.Write(buffer, 0, positionInBuffer); } countSent += positionInBuffer; m_WrittenCount += positionInBuffer; m_LastActivityDate = DateTime.Now; positionInBuffer = 0; } currentByte = stream.ReadByte(); } // We have readed all data, write budder data + .<CRLF> or <CRLF>.<CRLF> if data not <CRLF> terminated. if (!CRLF) { buffer[positionInBuffer] = (byte) '\r'; positionInBuffer++; buffer[positionInBuffer] = (byte) '\n'; positionInBuffer++; } buffer[positionInBuffer] = (byte) '.'; positionInBuffer++; buffer[positionInBuffer] = (byte) '\r'; positionInBuffer++; buffer[positionInBuffer] = (byte) '\n'; positionInBuffer++; if (m_SSL) { m_pSslStream.Write(buffer, 0, positionInBuffer); } else { m_pSocketStream.Write(buffer, 0, positionInBuffer); } countSent += positionInBuffer; m_WrittenCount += positionInBuffer; m_LastActivityDate = DateTime.Now; //-------------------------------------------------------------------------------------// // Logging stuff if (m_pLogger != null) { if (countSent < 200) { m_pLogger.AddSendEntry(m_pEncoding.GetString(buffer), buffer.Length); } else { m_pLogger.AddSendEntry("Binary data, sent " + countSent + " bytes.", countSent); } } } /// <summary> /// Begins reading line from socket asynchrounously. /// If maximum allowed line length is exceeded line is read to end, but isn't stored to buffer and exception /// is thrown after line reading. /// </summary> /// <param name="stream">Stream where to store readed line.</param> /// <param name="maxLineLength">Maximum line length in bytes.</param> /// <param name="tag">User data.</param> /// <param name="callback">The method to be called when the asynchronous line read operation is completed.</param> public void BeginReadLine(Stream stream, int maxLineLength, object tag, SocketCallBack callback) { TryToReadLine(callback, tag, stream, maxLineLength, -1, 0); } /// <summary> /// Begins reading specified amount of data from socket asynchronously. /// </summary> /// <param name="stream">Stream where to store readed data.</param> /// <param name="lengthToRead">Specifies number of bytes to read from socket.</param> /// <param name="tag">User data.</param> /// <param name="callback">The method to be called when the asynchronous read operation is completed.</param> public void BeginReadSpecifiedLength(Stream stream, int lengthToRead, object tag, SocketCallBack callback) { TryToReadReadSpecifiedLength(stream, lengthToRead, tag, callback, 0); } /// <summary> /// Begins reading period terminated data. The data is terminated by a line containing only a period, that is, /// the character sequence "&lt;CRLF&gt;.&lt;CRLF&gt;". /// When a line of text is received, it checks the line. If the line is composed of a single period, /// it is treated as the end of data indicator. If the first character is a period and there are /// other characters on the line, the first character is deleted. /// If maximum allowed data length is exceeded data is read to end, but isn't stored to stream and exception /// is thrown after data reading. /// </summary> /// <param name="stream">Stream where to store readed data.</param> /// <param name="maxLength">Maximum data length in bytes.</param> /// <param name="tag">User data.</param> /// <param name="callback">The method to be called when the asynchronous read operation is completed.</param> public void BeginReadPeriodTerminated(Stream stream, int maxLength, object tag, SocketCallBack callback) { TryToReadPeriodTerminated(callback, tag, stream, maxLength, -1, 0, false, false); } /// <summary> /// Begins writing specified data to socket. /// </summary> /// <param name="stream">Stream which data to write to socket. Reading starts from stream current position and will be readed to EOS.</param> /// <param name="tag">User data.</param> /// <param name="callback">The method to be called when the asynchronous write operation is completed.</param> public void BeginWrite(Stream stream, object tag, SocketCallBack callback) { // Allow socket to optimise sends m_pSocket.NoDelay = false; BeginProcessingWrite(stream, tag, callback, 0); } /// <summary> /// Begins specified line sending to socket asynchronously. /// </summary> /// <param name="line">Line to send.</param> /// <param name="callback">The method to be called when the asynchronous line write operation is completed.</param> public void BeginWriteLine(string line, SocketCallBack callback) { // Don't allow to wait after we send data, because there won't no more data m_pSocket.NoDelay = true; BeginWriteLine(line, null, callback); } /// <summary> /// Begins specified line sending to socket asynchronously. /// </summary> /// <param name="line">Line to send.</param> /// <param name="tag">User data.</param> /// <param name="callback">The method to be called when the asynchronous line write operation is completed.</param> public void BeginWriteLine(string line, object tag, SocketCallBack callback) { // Don't allow to wait after we send data, because there won't no more data m_pSocket.NoDelay = true; if (!line.EndsWith("\r\n")) { line += "\r\n"; } byte[] lineBytes = m_pEncoding.GetBytes(line); if (m_SSL) { m_pSslStream.BeginWrite(lineBytes, 0, lineBytes.Length, OnBeginWriteLineCallback, new[] {tag, callback, lineBytes}); } else { m_pSocketStream.BeginWrite(lineBytes, 0, lineBytes.Length, OnBeginWriteLineCallback, new[] {tag, callback, lineBytes}); } } /// <summary> /// Begins writing period terminated data to socket. The data is terminated by a line containing only a period, that is, /// the character sequence "&lt;CRLF&gt;.&lt;CRLF&gt;". Before sending a line of text, check the first /// character of the line.If it is a period, one additional period is inserted at the beginning of the line. /// </summary> /// <param name="stream">Stream which data to write. Reading begins from stream current position and is readed to EOS.</param> /// <param name="tag">User data.</param> /// <param name="callback">The method to be called when the asynchronous write operation is completed.</param> public void BeginWritePeriodTerminated(Stream stream, object tag, SocketCallBack callback) { BeginWritePeriodTerminated(stream, false, tag, callback); } /// <summary> /// Begins writing period terminated data to socket. The data is terminated by a line containing only a period, that is, /// the character sequence "&lt;CRLF&gt;.&lt;CRLF&gt;". Before sending a line of text, check the first /// character of the line.If it is a period, one additional period is inserted at the beginning of the line. /// </summary> /// <param name="stream">Stream which data to write. Reading begins from stream current position and is readed to EOS.</param> /// <param name="closeStream">Specifies if stream is closed after write operation has completed.</param> /// <param name="tag">User data.</param> /// <param name="callback">The method to be called when the asynchronous write operation is completed.</param> public void BeginWritePeriodTerminated(Stream stream, bool closeStream, object tag, SocketCallBack callback) { // Allow socket to optimise sends m_pSocket.NoDelay = false; _BeginWritePeriodTerminated_State state = new _BeginWritePeriodTerminated_State(stream, closeStream, tag, callback); BeginProcessingWritePeriodTerminated(state); } /// <summary> /// Sends data to the specified end point. /// </summary> /// <param name="data">Data to send.</param> /// <param name="remoteEP">Remote endpoint where to send data.</param> /// <returns>Returns number of bytes actualy sent.</returns> public int SendTo(byte[] data, EndPoint remoteEP) { return m_pSocket.SendTo(data, remoteEP); } #endregion #region Utility methods private bool RemoteCertificateValidationCallback(Object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { if (sslPolicyErrors == SslPolicyErrors.None || sslPolicyErrors == SslPolicyErrors.RemoteCertificateNameMismatch) { return true; } // Do not allow this client to communicate with unauthenticated servers. return false; } /// <summary> /// Tries to read line from socket data buffer. If buffer doesn't contain line, /// next buffer data block is getted asynchronously and this method is called again. /// </summary> /// <param name="callback">The method to be called when the asynchronous line read operation is completed.</param> /// <param name="tag">User data.</param> /// <param name="stream">Stream where to store readed data.</param> /// <param name="maxLineLength">Specifies maximum line legth.</param> /// <param name="lastByte">Last byte what was readed pevious method call or -1 if first method call.</param> /// <param name="readedCount">Specifies count of bytes readed.</param> private void TryToReadLine(SocketCallBack callback, object tag, Stream stream, int maxLineLength, int lastByte, int readedCount) { // There is no data in buffer, buffer next block asynchronously. if (m_AvailableInBuffer == 0) { BeginBufferDataBlock(OnBeginReadLineBufferingCompleted, new[] {callback, tag, stream, maxLineLength, lastByte, readedCount}); return; } // Delay last byte writing, this is because CR, if next is LF, then skip CRLF and terminate reading. // This is first method call, buffer 1 byte if (lastByte == -1) { lastByte = ReadByte(); readedCount++; // We use last byte, buffer next block asynchronously. if (m_AvailableInBuffer == 0) { BeginBufferDataBlock(OnBeginReadLineBufferingCompleted, new[] {callback, tag, stream, maxLineLength, lastByte, readedCount}); return; } } int currentByte = ReadByte(); readedCount++; while (currentByte > -1) { // We got line if (lastByte == (byte) '\r' && currentByte == (byte) '\n') { // Logging stuff if (m_pLogger != null) { if (stream.CanSeek && stream.Length < 200) { byte[] readedData = new byte[stream.Length]; stream.Position = 0; stream.Read(readedData, 0, readedData.Length); m_pLogger.AddReadEntry(m_pEncoding.GetString(readedData), readedCount); } else { m_pLogger.AddReadEntry("Big binary line, readed " + readedCount + " bytes.", readedCount); } } // Maximum allowed length exceeded if (readedCount > maxLineLength) { if (callback != null) { callback(SocketCallBackResult.LengthExceeded, 0, new ReadException(ReadReplyCode.LengthExceeded, "Maximum allowed data length exceeded !"), tag); } } // Line readed ok, call callback. if (callback != null) { callback(SocketCallBackResult.Ok, readedCount, null, tag); } return; } else { // Maximum allowed length exceeded, just don't store data. if (readedCount < maxLineLength) { stream.WriteByte((byte) lastByte); } } // Read next byte lastByte = currentByte; if (m_AvailableInBuffer > 0) { currentByte = ReadByte(); readedCount++; } // We have use all data in the buffer, buffer next block asynchronously. else { BeginBufferDataBlock(OnBeginReadLineBufferingCompleted, new[] {callback, tag, stream, maxLineLength, lastByte, readedCount}); return; } } // We should not reach there, if so then socket closed // Logging stuff if (m_pLogger != null) { m_pLogger.AddTextEntry("Remote host closed socket !"); } if (callback != null) { callback(SocketCallBackResult.SocketClosed, 0, new ReadException(ReadReplyCode.SocketClosed, "Connected host closed socket, read line terminated unexpectedly !"), tag); } } /// <summary> /// This method is called after asynchronous data buffering is completed. /// </summary> /// <param name="x">Exception what happened on method execution or null, if operation completed sucessfully.</param> /// <param name="tag">User data.</param> private void OnBeginReadLineBufferingCompleted(Exception x, object tag) { object[] param = (object[]) tag; SocketCallBack callback = (SocketCallBack) param[0]; object callbackTag = param[1]; Stream stream = (Stream) param[2]; int maxLineLength = (int) param[3]; int lastByte = (int) param[4]; int readedCount = (int) param[5]; if (x == null) { // We didn't get data, this can only happen if socket closed. if (m_AvailableInBuffer == 0) { // Logging stuff if (m_pLogger != null) { m_pLogger.AddTextEntry("Remote host closed socket !"); } callback(SocketCallBackResult.SocketClosed, 0, null, callbackTag); } else { TryToReadLine(callback, callbackTag, stream, maxLineLength, lastByte, readedCount); } } else { callback(SocketCallBackResult.Exception, 0, x, callbackTag); } } /// <summary> /// Tries to read specified length of data from socket data buffer. If buffer doesn't contain data, /// next buffer data block is getted asynchronously and this method is called again. /// </summary> /// <param name="stream">Stream where to store readed data.</param> /// <param name="lengthToRead">Specifies number of bytes to read from socket.</param> /// <param name="tag">User data.</param> /// <param name="callback">The method to be called when the asynchronous read operation is completed.</param> /// <param name="readedCount">Specifies count of bytes readed.</param> private void TryToReadReadSpecifiedLength(Stream stream, int lengthToRead, object tag, SocketCallBack callback, int readedCount) { if (lengthToRead == 0) { // Data readed ok, call callback. if (callback != null) { callback(SocketCallBackResult.Ok, readedCount, null, tag); } return; } // There is no data in buffer, buffer next block asynchronously. if (m_AvailableInBuffer == 0) { BeginBufferDataBlock(OnBeginReadSpecifiedLengthBufferingCompleted, new[] {callback, tag, stream, lengthToRead, readedCount}); return; } // Buffer has less data than that we need int lengthLeftForReading = lengthToRead - readedCount; if (lengthLeftForReading > m_AvailableInBuffer) { stream.Write(m_Buffer, m_OffsetInBuffer, m_AvailableInBuffer); stream.Flush(); readedCount += m_AvailableInBuffer; // We used buffer directly, sync buffer info !!! m_OffsetInBuffer = 0; m_AvailableInBuffer = 0; BeginBufferDataBlock(OnBeginReadSpecifiedLengthBufferingCompleted, new[] {callback, tag, stream, lengthToRead, readedCount}); } // Buffer contains all data we need else { stream.Write(m_Buffer, m_OffsetInBuffer, lengthLeftForReading); stream.Flush(); readedCount += lengthLeftForReading; // We used buffer directly, sync buffer info !!! m_OffsetInBuffer += lengthLeftForReading; m_AvailableInBuffer -= lengthLeftForReading; // Logging stuff if (m_pLogger != null) { if (stream.CanSeek && stream.Length < 200) { byte[] readedData = new byte[stream.Length]; stream.Position = 0; stream.Read(readedData, 0, readedData.Length); m_pLogger.AddReadEntry(m_pEncoding.GetString(readedData), lengthToRead); } else { m_pLogger.AddReadEntry("Big binary data, readed " + readedCount + " bytes.", readedCount); } } // Data readed ok, call callback. if (callback != null) { callback(SocketCallBackResult.Ok, readedCount, null, tag); } } } /// <summary> /// This method is called after asynchronous data buffering is completed. /// </summary> /// <param name="x">Exception what happened on method execution or null, if operation completed sucessfully.</param> /// <param name="tag">User data.</param> private void OnBeginReadSpecifiedLengthBufferingCompleted(Exception x, object tag) { object[] param = (object[]) tag; SocketCallBack callback = (SocketCallBack) param[0]; object callbackTag = param[1]; Stream stream = (Stream) param[2]; int lengthToRead = (int) param[3]; int readedCount = (int) param[4]; if (x == null) { // We didn't get data, this can only happen if socket closed. if (m_AvailableInBuffer == 0) { // Logging stuff if (m_pLogger != null) { m_pLogger.AddTextEntry("Remote host closed socket !"); } callback(SocketCallBackResult.SocketClosed, 0, null, callbackTag); } else { TryToReadReadSpecifiedLength(stream, lengthToRead, callbackTag, callback, readedCount); } } else { callback(SocketCallBackResult.Exception, 0, x, callbackTag); } } /// <summary> /// Tries to read period terminated data from socket data buffer. If buffer doesn't contain /// period terminated data,next buffer data block is getted asynchronously and this method is called again. /// </summary> /// <param name="callback">The method to be called when the asynchronous period terminated read operation is completed.</param> /// <param name="tag">User data.</param> /// <param name="stream">Stream where to store readed data.</param> /// <param name="maxLength">Specifies maximum data legth in bytes.</param> /// <param name="readedCount">Specifies count of bytes readed.</param> /// <param name="lastByte">Last byte what was readed pevious method call or -1 if first method call.</param> /// <param name="lineBreak">Specifies if there is active line break.</param> /// <param name="expectCRLF">Specifies if terminating CRLF is expected.</param> private void TryToReadPeriodTerminated(SocketCallBack callback, object tag, Stream stream, int maxLength, int lastByte, int readedCount, bool lineBreak, bool expectCRLF) { /* When a line of text is received by the server, it checks the line. If the line is composed of a single period, it is treated as the end of data indicator. If the first character is a period and there are other characters on the line, the first character is deleted. */ // There is no data in buffer, buffer next block asynchronously. if (m_AvailableInBuffer == 0) { BeginBufferDataBlock(OnBeginReadPeriodTerminatedBufferingCompleted, new[] { callback, tag, stream, maxLength, lastByte, readedCount, lineBreak, expectCRLF }); return; } // Delay last byte writing, this is because CR, if next is LF, then last byte isn't written. // This is first method call, buffer 1 byte if (lastByte == -1) { lastByte = ReadByte(); readedCount++; // We used last byte, buffer next block asynchronously. if (m_AvailableInBuffer == 0) { BeginBufferDataBlock(OnBeginReadPeriodTerminatedBufferingCompleted, new[] { callback, tag, stream, maxLength, lastByte, readedCount, lineBreak, expectCRLF }); return; } } byte[] buffer = new byte[8000]; int positionInBuffer = 0; int currentByte = ReadByte(); readedCount++; while (currentByte > -1) { // We got <CRLF> + 1 char, we must skip that char if it is '.'. if (lineBreak) { lineBreak = false; // We must skip this char if it is '.' if (currentByte == '.') { expectCRLF = true; // Read next byte if (m_AvailableInBuffer > 0) { currentByte = ReadByte(); readedCount++; } // We have use all data in the buffer, buffer next block asynchronously. else { // There is data in buffer, flush it if (positionInBuffer > 0) { stream.Write(buffer, 0, positionInBuffer); positionInBuffer = 0; } BeginBufferDataBlock(OnBeginReadPeriodTerminatedBufferingCompleted, new[] { callback, tag, stream, maxLength, lastByte, readedCount, lineBreak, expectCRLF }); return; } } } // We got <CRLF> else if (lastByte == (byte) '\r' && currentByte == (byte) '\n') { lineBreak = true; // We have <CRLF>.<CRLF>, skip last <CRLF>. if (expectCRLF) { // There is data in buffer, flush it if (positionInBuffer > 0) { stream.Write(buffer, 0, positionInBuffer); positionInBuffer = 0; } // Logging stuff if (m_pLogger != null) { if (stream.CanSeek && stream.Length < 200) { byte[] readedData = new byte[stream.Length]; stream.Position = 0; stream.Read(readedData, 0, readedData.Length); m_pLogger.AddReadEntry(m_pEncoding.GetString(readedData), readedCount); } else { m_pLogger.AddReadEntry("Big binary data, readed " + readedCount + " bytes.", readedCount); } } // Maximum allowed length exceeded if (readedCount > maxLength) { if (callback != null) { callback(SocketCallBackResult.LengthExceeded, 0, new ReadException(ReadReplyCode.LengthExceeded, "Maximum allowed data length exceeded !"), tag); } return; } // Data readed ok, call callback. if (callback != null) { callback(SocketCallBackResult.Ok, readedCount, null, tag); } return; } } // current char isn't CRLF part, so it isn't <CRLF>.<CRLF> terminator. if (expectCRLF && !(currentByte == (byte) '\r' || currentByte == (byte) '\n')) { expectCRLF = false; } // Maximum allowed length exceeded, just don't store data. if (readedCount < maxLength) { // Buffer is filled up, write buffer to stream if (positionInBuffer > (buffer.Length - 2)) { stream.Write(buffer, 0, positionInBuffer); positionInBuffer = 0; } buffer[positionInBuffer] = (byte) lastByte; positionInBuffer++; } // Read next byte lastByte = currentByte; if (m_AvailableInBuffer > 0) { currentByte = ReadByte(); readedCount++; } // We have use all data in the buffer, buffer next block asynchronously. else { // There is data in buffer, flush it if (positionInBuffer > 0) { stream.Write(buffer, 0, positionInBuffer); positionInBuffer = 0; } BeginBufferDataBlock(OnBeginReadPeriodTerminatedBufferingCompleted, new[] { callback, tag, stream, maxLength, lastByte, readedCount, lineBreak, expectCRLF }); return; } } // We should never reach here. if (callback != null) { callback(SocketCallBackResult.Exception, 0, new Exception( "Never should reach there ! method TryToReadPeriodTerminated out of while loop."), tag); } } /// <summary> /// This method is called after asynchronous data buffering is completed. /// </summary> /// <param name="x">Exception what happened on method execution or null, if operation completed sucessfully.</param> /// <param name="tag">User data.</param> private void OnBeginReadPeriodTerminatedBufferingCompleted(Exception x, object tag) { object[] param = (object[]) tag; SocketCallBack callback = (SocketCallBack) param[0]; object callbackTag = param[1]; Stream stream = (Stream) param[2]; int maxLength = (int) param[3]; int lastByte = (int) param[4]; int readedCount = (int) param[5]; bool lineBreak = (bool) param[6]; bool expectCRLF = (bool) param[7]; if (x == null) { // We didn't get data, this can only happen if socket closed. if (m_AvailableInBuffer == 0) { // Logging stuff if (m_pLogger != null) { m_pLogger.AddTextEntry("Remote host closed socket !"); } callback(SocketCallBackResult.SocketClosed, 0, null, callbackTag); } else { TryToReadPeriodTerminated(callback, callbackTag, stream, maxLength, lastByte, readedCount, lineBreak, expectCRLF); } } else { callback(SocketCallBackResult.Exception, 0, x, callbackTag); } } /// <summary> /// Starts sending data block to socket. /// </summary> /// <param name="stream">Stream which data to write.</param> /// <param name="tag">User data.</param> /// <param name="callback">The method to be called when the asynchronous write operation is completed</param> /// <param name="countSent">Specifies how many data is sent.</param> private void BeginProcessingWrite(Stream stream, object tag, SocketCallBack callback, int countSent) { byte[] buffer = new byte[4000]; int readedCount = stream.Read(buffer, 0, buffer.Length); // There data to send if (readedCount > 0) { countSent += readedCount; m_WrittenCount += readedCount; if (m_SSL) { m_pSslStream.BeginWrite(buffer, 0, readedCount, OnBeginWriteCallback, new[] {stream, tag, callback, countSent}); } else { m_pSocketStream.BeginWrite(buffer, 0, readedCount, OnBeginWriteCallback, new[] {stream, tag, callback, countSent}); } } // We have sent all data else { // Logging stuff if (m_pLogger != null) { if (stream.CanSeek && stream.Length < 200) { byte[] sentData = new byte[stream.Length]; stream.Position = 0; stream.Read(sentData, 0, sentData.Length); m_pLogger.AddSendEntry(m_pEncoding.GetString(sentData), countSent); } else { m_pLogger.AddSendEntry("Big binary data, sent " + countSent + " bytes.", countSent); } } // Line sent ok, call callback. if (callback != null) { callback(SocketCallBackResult.Ok, countSent, null, tag); } } } /// <summary> /// This method is called after asynchronous datablock send is completed. /// </summary> /// <param name="ar"></param> private void OnBeginWriteCallback(IAsyncResult ar) { object[] param = (object[]) ar.AsyncState; Stream stream = (Stream) param[0]; object tag = param[1]; SocketCallBack callBack = (SocketCallBack) param[2]; int countSent = (int) param[3]; try { if (m_SSL) { m_pSslStream.EndWrite(ar); } else { m_pSocketStream.EndWrite(ar); } m_LastActivityDate = DateTime.Now; BeginProcessingWrite(stream, tag, callBack, countSent); } catch (Exception x) { if (callBack != null) { callBack(SocketCallBackResult.Exception, 0, x, tag); } } } /// <summary> /// This method is called after asynchronous WriteLine is completed. /// </summary> /// <param name="ar"></param> private void OnBeginWriteLineCallback(IAsyncResult ar) { object[] param = (object[]) ar.AsyncState; object tag = param[0]; SocketCallBack callBack = (SocketCallBack) param[1]; byte[] lineBytes = (byte[]) param[2]; try { if (m_SSL) { m_pSslStream.EndWrite(ar); } else { m_pSocketStream.EndWrite(ar); } m_WrittenCount += lineBytes.Length; m_LastActivityDate = DateTime.Now; // Logging stuff if (m_pLogger != null) { if (lineBytes.Length < 200) { m_pLogger.AddSendEntry(m_pEncoding.GetString(lineBytes), lineBytes.Length); } else { m_pLogger.AddSendEntry("Big binary line, sent " + lineBytes.Length + " bytes.", lineBytes.Length); } } // Line sent ok, call callback. if (callBack != null) { callBack(SocketCallBackResult.Ok, lineBytes.Length, null, tag); } } catch (Exception x) { if (callBack != null) { callBack(SocketCallBackResult.Exception, 0, x, tag); } } } /// <summary> /// Reads data block from state.Stream and begins writing it to socket. /// This method is looped while all data has been readed from state.Stream, then sate.Callback is called. /// </summary> /// <param name="state">State info.</param> private void BeginProcessingWritePeriodTerminated(_BeginWritePeriodTerminated_State state) { /* Before sending a line of text, check the first character of the line. If it is a period, one additional period is inserted at the beginning of the line. */ byte[] buffer = new byte[4000]; int positionInBuffer = 0; int currentByte = state.Stream.ReadByte(); while (currentByte > -1) { // We have CRLF, mark it up if (state.LastByte == '\r' && currentByte == '\n') { state.HasCRLF = true; } // There is CRLF + current byte else if (state.HasCRLF) { // If it is a period, one additional period is inserted at the beginning of the line. if (currentByte == '.') { buffer[positionInBuffer] = (byte) '.'; positionInBuffer++; } // CRLF handled, reset it state.HasCRLF = false; } buffer[positionInBuffer] = (byte) currentByte; positionInBuffer++; state.LastByte = currentByte; // Buffer is filled up, begin writing buffer to socket. if (positionInBuffer > (4000 - 10)) { state.CountSent += positionInBuffer; m_WrittenCount += positionInBuffer; if (m_SSL) { m_pSslStream.BeginWrite(buffer, 0, positionInBuffer, OnBeginWritePeriodTerminatedCallback, state); } else { m_pSocketStream.BeginWrite(buffer, 0, positionInBuffer, OnBeginWritePeriodTerminatedCallback, state); } return; } currentByte = state.Stream.ReadByte(); } // We have readed all data, write .<CRLF> or <CRLF>.<CRLF> if data not <CRLF> terminated. if (!state.HasCRLF) { buffer[positionInBuffer] = (byte) '\r'; positionInBuffer++; buffer[positionInBuffer] = (byte) '\n'; positionInBuffer++; } buffer[positionInBuffer] = (byte) '.'; positionInBuffer++; buffer[positionInBuffer] = (byte) '\r'; positionInBuffer++; buffer[positionInBuffer] = (byte) '\n'; positionInBuffer++; if (m_SSL) { m_pSslStream.Write(buffer, 0, positionInBuffer); } else { m_pSocketStream.Write(buffer, 0, positionInBuffer); } state.CountSent += positionInBuffer; m_WrittenCount += positionInBuffer; m_LastActivityDate = DateTime.Now; //-------------------------------------------------------------------------------------// // Logging stuff if (m_pLogger != null) { if (state.CountSent < 200) { m_pLogger.AddSendEntry(m_pEncoding.GetString(buffer), buffer.Length); } else { m_pLogger.AddSendEntry("Binary data, sent " + state.CountSent + " bytes.", state.CountSent); } } // We don't need stream any more, close it if (state.CloseStream) { try { state.Stream.Close(); } catch {} } // Data sent ok, call callback. if (state.Callback != null) { state.Callback(SocketCallBackResult.Ok, state.CountSent, null, state.Tag); } } /// <summary> /// This method is called after asynchronous datablock send is completed. /// </summary> /// <param name="ar"></param> private void OnBeginWritePeriodTerminatedCallback(IAsyncResult ar) { _BeginWritePeriodTerminated_State state = (_BeginWritePeriodTerminated_State) ar.AsyncState; try { if (m_SSL) { m_pSslStream.EndWrite(ar); } else { m_pSocketStream.EndWrite(ar); } m_LastActivityDate = DateTime.Now; BeginProcessingWritePeriodTerminated(state); } catch (Exception x) { // We don't need stream any more, close it if (state.CloseStream) { try { state.Stream.Close(); } catch {} } if (state.Callback != null) { state.Callback(SocketCallBackResult.Exception, 0, x, state.Tag); } } } /// <summary> /// Buffers data from socket if needed. If there is data in buffer, no buffering is done. /// </summary> private void BufferDataBlock() { lock (this) { // There is no data in buffer, buffer next data block if (m_AvailableInBuffer == 0) { m_OffsetInBuffer = 0; if (m_SSL) { m_AvailableInBuffer = m_pSslStream.Read(m_Buffer, 0, m_Buffer.Length); } else { m_AvailableInBuffer = m_pSocket.Receive(m_Buffer); } m_ReadedCount += m_AvailableInBuffer; m_LastActivityDate = DateTime.Now; } } } /// <summary> /// Start buffering data from socket asynchronously. /// </summary> /// <param name="callback">The method to be called when the asynchronous data buffering operation is completed.</param> /// <param name="tag">User data.</param> private void BeginBufferDataBlock(BufferDataBlockCompleted callback, object tag) { if (m_AvailableInBuffer == 0) { m_OffsetInBuffer = 0; if (m_SSL) { m_pSslStream.BeginRead(m_Buffer, 0, m_Buffer.Length, OnBeginBufferDataBlockCallback, new[] {callback, tag}); } else { m_pSocket.BeginReceive(m_Buffer, 0, m_Buffer.Length, SocketFlags.None, OnBeginBufferDataBlockCallback, new[] {callback, tag}); } } } /// <summary> /// This method is called after asynchronous BeginBufferDataBlock is completed. /// </summary> /// <param name="ar"></param> private void OnBeginBufferDataBlockCallback(IAsyncResult ar) { object[] param = (object[]) ar.AsyncState; BufferDataBlockCompleted callback = (BufferDataBlockCompleted) param[0]; object tag = param[1]; try { // Socket closed by this.Disconnect() or closed by remote host. if (m_pSocket == null || !m_pSocket.Connected) { m_AvailableInBuffer = 0; } else { if (m_SSL) { m_AvailableInBuffer = m_pSslStream.EndRead(ar); } else { m_AvailableInBuffer = m_pSocket.EndReceive(ar); } } m_ReadedCount += m_AvailableInBuffer; m_LastActivityDate = DateTime.Now; if (callback != null) { callback(null, tag); } } catch (Exception x) { if (callback != null) { callback(x, tag); } } } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/_Obsolete/StreamLineReader.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net { #region usings using System; using System.IO; #endregion /// <summary> /// Stream line reader. /// </summary> //[Obsolete("Use StreamHelper instead !")] public class StreamLineReader { #region Members private readonly byte[] m_Buffer = new byte[1024]; private readonly Stream m_StrmSource; private bool m_CRLF_LinesOnly = true; private string m_Encoding = ""; private int m_ReadBufferSize = 1024; #endregion #region Properties /// <summary> /// Gets or sets charset encoding to use for string based methods. Default("") encoding is system default encoding. /// </summary> public string Encoding { get { return m_Encoding; } set { // Check if encoding is valid System.Text.Encoding.GetEncoding(value); m_Encoding = value; } } /// <summary> /// Gets or sets if lines must be CRLF terminated or may be only LF terminated too. /// </summary> public bool CRLF_LinesOnly { get { return m_CRLF_LinesOnly; } set { m_CRLF_LinesOnly = value; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="strmSource">Source stream from where to read data. Reading begins from stream current position.</param> public StreamLineReader(Stream strmSource) { m_StrmSource = strmSource; } #endregion #region Methods /// <summary> /// Reads byte[] line from stream. NOTE: Returns null if end of stream reached. /// </summary> /// <returns>Return null if end of stream reached.</returns> public byte[] ReadLine() { // TODO: Allow to buffer source stream reads byte[] buffer = m_Buffer; int posInBuffer = 0; int prevByte = m_StrmSource.ReadByte(); int currByteInt = m_StrmSource.ReadByte(); while (prevByte > -1) { // CRLF line found if ((prevByte == (byte) '\r' && (byte) currByteInt == (byte) '\n')) { byte[] retVal = new byte[posInBuffer]; Array.Copy(buffer, retVal, posInBuffer); return retVal; } // LF line found and only LF lines allowed else if (!m_CRLF_LinesOnly && currByteInt == '\n') { byte[] retVal = new byte[posInBuffer + 1]; Array.Copy(buffer, retVal, posInBuffer + 1); retVal[posInBuffer] = (byte) prevByte; return retVal; } // Buffer is full, add addition m_ReadBufferSize bytes if (posInBuffer == buffer.Length) { byte[] newBuffer = new byte[buffer.Length + m_ReadBufferSize]; Array.Copy(buffer, newBuffer, buffer.Length); buffer = newBuffer; } buffer[posInBuffer] = (byte) prevByte; posInBuffer++; prevByte = currByteInt; // Read next byte currByteInt = m_StrmSource.ReadByte(); } // Line isn't terminated with <CRLF> and has some bytes left, return them. if (posInBuffer > 0) { byte[] retVal = new byte[posInBuffer]; Array.Copy(buffer, retVal, posInBuffer); return retVal; } return null; } /// <summary> /// Reads string line from stream. String is converted with specified Encoding property from byte[] line. NOTE: Returns null if end of stream reached. /// </summary> /// <returns></returns> public string ReadLineString() { byte[] line = ReadLine(); if (line != null) { if (m_Encoding == null || m_Encoding == "") { return System.Text.Encoding.Default.GetString(line); } else { return System.Text.Encoding.GetEncoding(m_Encoding).GetString(line); } } else { return null; } } #endregion } }<file_sep>/common/ASC.Data.Backup/BackupManager.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Xml; using System.Xml.Linq; namespace ASC.Data.Backup { public class BackupManager { private const string ROOT = "backup"; private const string XML_NAME = "backupinfo.xml"; private IDictionary<string, IBackupProvider> providers; private readonly string backup; private readonly string[] configs; public event EventHandler<ProgressChangedEventArgs> ProgressChanged; public BackupManager(string backup) : this(backup, null) { } public BackupManager(string backup, params string[] configs) { this.backup = backup; this.configs = configs ?? new string[0]; providers = new Dictionary<string, IBackupProvider>(); AddBackupProvider(new DbBackupProvider()); AddBackupProvider(new FileBackupProvider()); } public void AddBackupProvider(IBackupProvider provider) { providers.Add(provider.Name, provider); provider.ProgressChanged += OnProgressChanged; } public void RemoveBackupProvider(string name) { if (providers.ContainsKey(name)) { providers[name].ProgressChanged -= OnProgressChanged; providers.Remove(name); } } public void Save(int tenant) { using (var backupWriter = new ZipWriteOperator(backup)) { var doc = new XDocument(new XElement(ROOT, new XAttribute("tenant", tenant))); foreach (var provider in providers.Values) { var elements = provider.GetElements(tenant, configs, backupWriter); if (elements != null) { doc.Root.Add(new XElement(provider.Name, elements)); } } backupWriter.WriteEntry(XML_NAME, doc.ToString(SaveOptions.None)); } ProgressChanged(this, new ProgressChangedEventArgs(string.Empty, 100, true)); } public void Load() { using (var reader = new ZipReadOperator(backup)) using (var stream = reader.GetEntry(XML_NAME)) using (var xml = XmlReader.Create(stream)) { var root = XDocument.Load(xml).Element(ROOT); if (root == null) return; var tenant = int.Parse(root.Attribute("tenant").Value); foreach (var provider in providers.Values) { var element = root.Element(provider.Name); provider.LoadFrom(element != null ? element.Elements() : new XElement[0], tenant, configs, reader); } } ProgressChanged(this, new ProgressChangedEventArgs(string.Empty, 100, true)); } private void OnProgressChanged(object sender, ProgressChangedEventArgs e) { if (ProgressChanged != null) ProgressChanged(this, e); } } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/vCard/Item.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.Mime.vCard { #region usings using System; using System.Text; #endregion /// <summary> /// vCard structure item. /// </summary> public class Item { #region Members private readonly string m_Name = ""; private string m_Parameters = ""; private string m_Value = ""; #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="name">Item name.</param> /// <param name="parameters">Item parameters.</param> /// <param name="value">Item encoded value value.</param> internal Item(string name, string parameters, string value) { m_Name = name; m_Parameters = parameters; m_Value = value; } #endregion #region Properties /// <summary> /// Gets item decoded value. If param string specifies Encoding and/or Charset, /// item.Value will be decoded accordingly. /// </summary> public string DecodedValue { /* RFC 2426 vCrad 5. Differences From vCard v2.1 The CRLF character sequence in a text type value is specified with the backslash character sequence "\n" or "\N". Any COMMA or SEMICOLON in a text type value must be backslash escaped. */ get { string data = m_Value; string encoding = null; string charset = null; string[] parameters = m_Parameters.ToLower().Split(';'); foreach (string parameter in parameters) { string[] name_value = parameter.Split('='); if (name_value[0] == "encoding" && name_value.Length > 1) { encoding = name_value[1]; } else if (name_value[0] == "charset" && name_value.Length > 1) { charset = name_value[1]; } } // Encoding specified, decode data. if (encoding != null) { if (encoding == "quoted-printable") { data = Core.QuotedPrintableDecode(data,Encoding.Default); } else if (encoding == "b") { data = Encoding.Default.GetString(Core.Base64Decode(Encoding.Default.GetBytes(data))); } else { throw new Exception("Unknown data encoding '" + encoding + "' !"); } } // Charset specified, convert data to specified charset. if (charset != null) { data = Encoding.GetEncoding(charset).GetString(Encoding.Default.GetBytes(data)); } // FIX ME: this must be done with structured fields //data = data.Replace("\\n","\r\n"); //data = TextUtils.UnEscapeString(data); Messes up structured fields return data; } } /// <summary> /// Gest item name. /// </summary> public string Name { get { return m_Name; } } /// <summary> /// Gets or sets item parameters. /// </summary> public string ParametersString { get { return m_Parameters; } set { m_Parameters = value; } } /// <summary> /// Gets or sets item encoded value. NOTE: If you set this property value, you must encode data /// by yourself and also set right ENCODING=encoding; and CHARSET=charset; prameter in item.ParametersString !!! /// Normally use method item.SetDecodedStringValue method instead, this does all you need. /// </summary> public string Value { get { return m_Value; } set { m_Value = value; } } #endregion #region Methods /// <summary> /// Sets item decoded value. Value will be encoded as needed and stored to item.Value property. /// Also property item.ParametersString is updated to reflect right encoding(always base64, required by rfc) and charset (utf-8). /// </summary> /// <param name="value"></param> public void SetDecodedValue(string value) { /* RFC 2426 vCrad 5. Differences From vCard v2.1 The QUOTED-PRINTABLE inline encoding has been eliminated. Only the "B" encoding of [RFC 2047] is an allowed value for the ENCODING parameter. The CRLF character sequence in a text type value is specified with the backslash character sequence "\n" or "\N". Any COMMA or SEMICOLON in a text type value must be backslash escaped. */ // FIX ME: this must be done with structured fields //value = value.Replace("\r\n","\n").Replace("\n","\\n"); //value = TextUtils.EscapeString(value,new char[]{',',';'}); bool needEncode = false; if (!Core.IsAscii(value)) { needEncode = true; } if (needEncode) { // Remove encoding and charset parameters string newParmString = ""; string[] parameters = m_Parameters.ToLower().Split(';'); foreach (string parameter in parameters) { string[] name_value = parameter.Split('='); if (name_value[0] == "encoding" || name_value[0] == "charset") {} else if (parameter.Length > 0) { newParmString += parameter + ";"; } } // Add encoding parameter newParmString += "ENCODING=b;CHARSET=utf-8"; ParametersString = newParmString; Value = Convert.ToBase64String(Encoding.UTF8.GetBytes(value)); } else { Value = value; } } #endregion #region Internal methods /// <summary> /// Converts item to vCal item string. /// </summary> /// <returns></returns> internal string ToItemString() { if (m_Parameters.Length > 0) { return m_Name + ";" + m_Parameters + ":" + MimeUtils.FoldData(m_Value); } else { return m_Name + ":" + MimeUtils.FoldData(m_Value); } } #endregion } }<file_sep>/module/ASC.Api/ASC.Api.Community/Blogs/BlogApi.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections.Generic; using System.Linq; using System.Security; using ASC.Api.Attributes; using ASC.Api.Blogs; using ASC.Api.Collections; using ASC.Api.Exceptions; using ASC.Api.Utils; using ASC.Blogs.Core; using ASC.Blogs.Core.Domain; using ASC.Core; using ASC.Web.Community.Product; using ASC.Web.Core.Users; using ASC.Web.Studio.UserControls.Common.Comments; using ASC.Web.Studio.Utility; using ASC.Web.Studio.Utility.HtmlUtility; using SecurityContext = ASC.Core.SecurityContext; namespace ASC.Api.Community { public partial class CommunityApi { private BlogsEngine _blogEngine; protected internal BlogsEngine BlogEngine { get { if (_blogEngine == null) { _blogEngine = BlogsEngine.GetEngine(CoreContext.TenantManager.GetCurrentTenant().TenantId); } return _blogEngine; } } ///<summary> /// Returns the list of all posts in blogs on the portal with the post title, date of creation and update, post text and author ID and display name ///</summary> ///<short>All posts</short> ///<returns>List of all posts</returns> ///<category>Blogs</category> [Read("blog")] public IEnumerable<BlogPostWrapperSummary> GetPosts() { return BlogEngine.SelectPosts(GetQuery()).Select(x => new BlogPostWrapperSummary(x)).ToSmartList(); } ///<summary> ///Creates a blog post with the specified title, content, tags and subscription to comments defined in the request body ///</summary> ///<short>Create post</short> ///<param name="title">New post title</param> ///<param name="content">New post text</param> ///<param name="tags">Tag list separated with ','</param> ///<param name="subscribeComments">Subscribe to post comments</param> ///<returns>Newly created post</returns> ///<example> ///<![CDATA[Sending data in application/json: /// ///{ /// title:"My post", /// content:"Post content", /// tags:"Me,Post,News", /// subscribeComments: "true" ///} /// ///Sending data in application/x-www-form-urlencoded ///title="My post"&content="Post content"&tags="Me,Post,News"&subscribeComments="true"]]> ///</example> ///<exception cref="ItemNotFoundException"></exception> ///<category>Blogs</category> [Create("blog")] public BlogPostWrapperFull CreatePost(string title, string content, string tags, bool subscribeComments) { var newPost = new Post { Content = content, Datetime = Core.Tenants.TenantUtil.DateTimeNow(), Title = title,/*TODO: maybe we should trim this */ UserID = SecurityContext.CurrentAccount.ID, TagList = !string.IsNullOrEmpty(tags) ? tags.Split(',').Distinct().Select(x => new Tag() { Content = x }).ToList() : new List<Tag>() }; BlogEngine.SavePost(newPost, true, subscribeComments); return new BlogPostWrapperFull(newPost); } ///<summary> ///Updates the specified post changing the post title, content or/and tags specified ///</summary> ///<short>Update post</short> ///<param name="postid">post ID</param> ///<param name="title">new title</param> ///<param name="content">new post text</param> ///<param name="tags">tag list separated with ','</param> ///<returns>Updated post</returns> ///<example> ///<![CDATA[ ///Sending data in application/json: ///{ /// title:"My post", /// content:"Post content", /// tags:"Me,Post,News" ///} /// ///Sending data in application/x-www-form-urlencoded ///title="My post"&content="Post content"&tags="Me,Post,News" ///]]> /// ///</example> ///<exception cref="ItemNotFoundException"></exception> ///<category>Blogs</category> [Update("blog/{postid}")] public BlogPostWrapperFull UpdatePost(Guid postid, string title, string content, string tags) { var post = BlogEngine.GetPostById(postid).NotFoundIfNull(); post.Content = content; post.Title = title; if (tags != null) post.TagList = tags.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Distinct().Select(x => new Tag() { Content = x }).ToList(); BlogEngine.SavePost(post, false, false); return new BlogPostWrapperFull(post); } ///<summary> ///Deletes the selected post from blogs ///</summary> ///<short>Delete post</short> ///<param name="postid">post ID to delete</param> ///<returns>Nothing</returns> ///<exception cref="ItemNotFoundException"></exception> ///<category>Blogs</category> [Delete("blog/{postid}")] public BlogPostWrapperFull DeletePost(Guid postid) { var post = BlogEngine.GetPostById(postid).NotFoundIfNull(); if (!CommunitySecurity.CheckPermissions(post, ASC.Blogs.Core.Constants.Action_EditRemovePost)) throw new SecurityException("Access denied."); BlogEngine.DeletePost(post); return null; } ///<summary> ///Returns the list of all blog posts for the current user with the post title, date of creation and update, post text and author ID and display name ///</summary> ///<category>Blogs</category> ///<short>My posts</short> ///<returns>My post list</returns> [Read("blog/@self")] public IEnumerable<BlogPostWrapperSummary> GetMyPosts() { return BlogEngine.SelectPosts(GetQuery().SetUser(SecurityContext.CurrentAccount.ID)).Select(x => new BlogPostWrapperSummary(x)).ToSmartList(); } ///<summary> ///Returns a list of blog posts matching the search query with the post title, date of creation and update, post text and author ///</summary> ///<category>Blogs</category> ///<short> ///Search posts ///</short> /// <param name="query">search query</param> ///<returns>Found post list</returns> [Read("blog/@search/{query}")] public IEnumerable<BlogPostWrapperSummary> GetSearchPosts(string query) { return BlogEngine.SelectPosts(GetQuery().SetSearch(query)).Select(x => new BlogPostWrapperSummary(x)).ToSmartList(); } ///<summary> ///Returns a list of blog posts of the specified user with the post title, date of creation and update and post text ///</summary> ///<short>User posts</short> ///<category>Blogs</category> ///<param name="username" remark="You can retrieve username through 'people' api">Username</param> ///<returns>List of user posts</returns> [Read("blog/user/{username}")] public IEnumerable<BlogPostWrapperSummary> GetUserPosts(string username) { var userid = CoreContext.UserManager.GetUserByUserName(username).ID; return BlogEngine.SelectPosts(GetQuery().SetUser(userid)).Select(x => new BlogPostWrapperSummary(x)).ToSmartList(); } ///<summary> ///Returns a list of blog posts containing the specified tag with the post title, date of creation and update, post text and author ///</summary> ///<short>By tag</short> ///<category>Blogs</category> ///<param name="tag">tag name</param> ///<returns>List of posts tagged with tag name</returns> [Read("blog/tag/{tag}")] public IEnumerable<BlogPostWrapperSummary> GetPostsByTag(string tag) { return BlogEngine.SelectPosts(GetQuery().SetTag(tag)).Select(x => new BlogPostWrapperSummary(x)).ToSmartList(); } ///<summary> ///Returns a list of all tags used with blog posts with the post title, date of creation and update, post text, author and all the tags used ///</summary> /// <category>Blogs</category> /// <short>Tags</short> ///<returns>List of tags</returns> [Read("blog/tag")] public IEnumerable<BlogTagWrapper> GetTags() { var result = BlogEngine.GetTopTagsList((int)_context.Count).Select(x => new BlogTagWrapper(x)); _context.SetDataPaginated(); return result.ToSmartList(); } ///<summary> /// Returns the detailed information for the blog post with the ID specified in the request ///</summary> ///<short>Specific post</short> ///<category>Blogs</category> ///<param name="postid">post ID</param> ///<returns>post</returns> [Read("blog/{postid}")] public BlogPostWrapperFull GetPost(Guid postid) { return new BlogPostWrapperFull(BlogEngine.GetPostById(postid).NotFoundIfNull()); } ///<summary> /// Returns the list of all the comments for the blog post with the ID specified in the request ///</summary> ///<category>Blogs</category> /// <short>Get comments</short> ///<param name="postid">post ID (GUID)</param> ///<returns>list of post comments</returns> [Read("blog/{postid}/comment")] public IEnumerable<BlogPostCommentWrapper> GetComments(Guid postid) { return BlogEngine.GetPostComments(postid).Where(x => !x.Inactive).Select(x => new BlogPostCommentWrapper(x)).ToSmartList(); } ///<summary> /// Adds a comment to the specified post with the comment text specified. The parent comment ID can be also specified if needed. ///</summary> /// <short>Add comment</short> /// <category>Blogs</category> ///<param name="postid">post ID</param> ///<param name="content">comment text</param> ///<param name="parentId">parent comment ID</param> ///<returns>List of post comments</returns> /// <example> /// <![CDATA[ /// Sending data in application/json: /// /// { /// content:"My comment", /// parentId:"9924256A-739C-462b-AF15-E652A3B1B6EB" /// } /// /// Sending data in application/x-www-form-urlencoded /// content="My comment"&parentId="9924256A-739C-462b-AF15-E652A3B1B6EB" /// ]]> /// </example> /// <remarks> /// Send parentId=00000000-0000-0000-0000-000000000000 or don't send it at all if you want your comment to be on the root level /// </remarks> [Create("blog/{postid}/comment")] public BlogPostCommentWrapper AddComment(Guid postid, string content, Guid parentId) { var post = BlogEngine.GetPostById(postid).NotFoundIfNull(); var newComment = new Comment { PostId = postid, Content = content, Datetime = DateTime.UtcNow, UserID = SecurityContext.CurrentAccount.ID }; if (parentId != Guid.Empty) newComment.ParentId = parentId; BlogEngine.SaveComment(newComment, post); return new BlogPostCommentWrapper(newComment); } /// <summary> /// Get comment preview with the content specified in the request /// </summary> /// <short>Get comment preview</short> /// <section>Comments</section> /// <param name="commentid">Comment ID</param> /// <param name="htmltext">Comment content</param> /// <returns>Comment info</returns> /// <category>Blogs</category> [Create("blog/comment/preview")] public CommentInfo GetBlogCommentPreview(string commentid, string htmltext) { var comment = new Comment { Datetime = ASC.Core.Tenants.TenantUtil.DateTimeNow(), UserID = SecurityContext.CurrentAccount.ID }; if (!String.IsNullOrEmpty(commentid)) { comment = BlogEngine.GetCommentById(new Guid(commentid)); } comment.Content = htmltext; return GetCommentInfo(comment, true); } /// <summary> ///Remove comment with the id specified in the request /// </summary> /// <short>Remove comment</short> /// <section>Comments</section> /// <param name="commentid">Comment ID</param> /// <returns>Comment id</returns> /// <category>Blogs</category> [Delete("blog/comment/{commentid}")] public string RemoveBlogComment(string commentid) { Guid? id = null; try { if (!String.IsNullOrEmpty(commentid)) id = new Guid(commentid); } catch { return commentid; } var comment = BlogEngine.GetCommentById(id.Value); if (comment == null) throw new ApplicationException("Comment not found"); CommunitySecurity.DemandPermissions(comment, ASC.Blogs.Core.Constants.Action_EditRemoveComment); comment.Inactive = true; var post = BlogEngine.GetPostById(comment.PostId); BlogEngine.RemoveComment(comment, post); return commentid; } /// <category>Blogs</category> [Create("blog/comment")] public CommentInfo AddBlogComment(string parentcommentid, string entityid, string content) { Guid postId; Guid? parentId = null; postId = new Guid(entityid); if (!String.IsNullOrEmpty(parentcommentid)) parentId = new Guid(parentcommentid); var post = BlogEngine.GetPostById(postId); if (post == null) { throw new Exception("postDeleted"); } CommunitySecurity.DemandPermissions(post, ASC.Blogs.Core.Constants.Action_AddComment); var newComment = new Comment { PostId = postId, Content = content, Datetime = ASC.Core.Tenants.TenantUtil.DateTimeNow(), UserID = SecurityContext.CurrentAccount.ID }; if (parentId.HasValue) newComment.ParentId = parentId.Value; BlogEngine.SaveComment(newComment, post); //mark post as seen for the current user BlogEngine.SavePostReview(post, SecurityContext.CurrentAccount.ID); return GetCommentInfo(newComment, false); } /// <category>Blogs</category> [Update("blog/comment/{commentid}")] public string UpdateBlogComment(string commentid, string content) { Guid? id = null; if (!String.IsNullOrEmpty(commentid)) id = new Guid(commentid); var comment = BlogEngine.GetCommentById(id.Value); if (comment == null) throw new Exception("Comment not found"); CommunitySecurity.DemandPermissions(comment, ASC.Blogs.Core.Constants.Action_EditRemoveComment); comment.Content = content; var post = BlogEngine.GetPostById(comment.PostId); BlogEngine.UpdateComment(comment, post); return HtmlUtility.GetFull(content); } private static CommentInfo GetCommentInfo(Comment comment, bool isPreview) { var info = new CommentInfo { CommentID = comment.ID.ToString(), UserID = comment.UserID, TimeStamp = comment.Datetime, TimeStampStr = comment.Datetime.Ago(), IsRead = true, Inactive = comment.Inactive, CommentBody = HtmlUtility.GetFull(comment.Content), UserFullName = DisplayUserSettings.GetFullUserName(comment.UserID), UserProfileLink = CommonLinkUtility.GetUserProfile(comment.UserID), UserAvatarPath = UserPhotoManager.GetBigPhotoURL(comment.UserID), UserPost = CoreContext.UserManager.GetUsers(comment.UserID).Title }; if (!isPreview) { info.IsEditPermissions = CommunitySecurity.CheckPermissions(comment, ASC.Blogs.Core.Constants.Action_EditRemoveComment); info.IsResponsePermissions = CommunitySecurity.CheckPermissions(comment.Post, ASC.Blogs.Core.Constants.Action_AddComment); } return info; } private PostsQuery GetQuery() { var query = new PostsQuery().SetOffset((int)_context.StartIndex).SetCount((int)_context.Count); _context.SetDataPaginated(); return query; } } } <file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/SIP/Proxy/SIP_ProxyTarget.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.SIP.Proxy { #region usings using System; using Stack; #endregion /// <summary> /// Represents SIP proxy target in the SIP proxy "target set". Defined in RFC 3261 16. /// </summary> public class SIP_ProxyTarget { #region Members private readonly SIP_Flow m_pFlow; private readonly SIP_Uri m_pTargetUri; #endregion #region Properties /// <summary> /// Gets target URI. /// </summary> public SIP_Uri TargetUri { get { return m_pTargetUri; } } /// <summary> /// Gets data flow. Value null means that new flow must created. /// </summary> public SIP_Flow Flow { get { return m_pFlow; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="targetUri">Target request-URI.</param> /// <exception cref="ArgumentNullException">Is raised when <b>targetUri</b> is null reference.</exception> public SIP_ProxyTarget(SIP_Uri targetUri) : this(targetUri, null) {} /// <summary> /// Default constructor. /// </summary> /// <param name="targetUri">Target request-URI.</param> /// <param name="flow">Data flow to try for forwarding..</param> /// <exception cref="ArgumentNullException">Is raised when <b>targetUri</b> is null reference.</exception> public SIP_ProxyTarget(SIP_Uri targetUri, SIP_Flow flow) { if (targetUri == null) { throw new ArgumentNullException("targetUri"); } m_pTargetUri = targetUri; m_pFlow = flow; } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/SIP/Proxy/SIP_Gateway.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.SIP.Proxy { #region usings using System; using Stack; #endregion /// <summary> /// This class represents SIP gateway to other system. /// </summary> public class SIP_Gateway { #region Members private string m_Host = ""; private string m_Password = ""; private int m_Port = 5060; private string m_Realm = ""; private string m_Transport = SIP_Transport.UDP; private string m_UserName = ""; #endregion #region Properties /// <summary> /// Gets or sets transport. /// </summary> /// <exception cref="ArgumentException">Is raised when invalid value passed.</exception> public string Transport { get { return m_Transport; } set { if (string.IsNullOrEmpty(value)) { throw new ArgumentException("Value cant be null or empty !"); } m_Transport = value; } } /// <summary> /// Gets or sets remote gateway host name or IP address. /// </summary> /// <exception cref="ArgumentException">Is raised when invalid value passed.</exception> public string Host { get { return m_Host; } set { if (string.IsNullOrEmpty(value)) { throw new ArgumentException("Value cant be null or empty !"); } m_Host = value; } } /// <summary> /// Gets or sets remote gateway port. /// </summary> /// <exception cref="ArgumentException">Is raised when invalid value passed.</exception> public int Port { get { return m_Port; } set { if (value < 1) { throw new ArgumentException("Value must be >= 1 !"); } m_Port = value; } } /// <summary> /// Gets or sets remote gateway realm(domain). /// </summary> public string Realm { get { return m_Realm; } set { if (value == null) { m_Realm = ""; } m_Realm = value; } } /// <summary> /// Gets or sets remote gateway user name. /// </summary> public string UserName { get { return m_UserName; } set { if (value == null) { m_UserName = ""; } m_UserName = value; } } /// <summary> /// Gets or sets remote gateway password. /// </summary> public string Password { get { return m_Password; } set { if (value == null) { m_Password = ""; } m_Password = value; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="transport">Transport to use.</param> /// <param name="host">Remote gateway host name or IP address.</param> /// <param name="port">Remote gateway port.</param> public SIP_Gateway(string transport, string host, int port) : this(transport, host, port, "", "", "") {} /// <summary> /// Default constructor. /// </summary> /// <param name="transport">Transport to use.</param> /// <param name="host">Remote gateway host name or IP address.</param> /// <param name="port">Remote gateway port.</param> /// <param name="realm">Remote gateway realm.</param> /// <param name="userName">Remote gateway user name.</param> /// <param name="password">Remote gateway password.</param> public SIP_Gateway(string transport, string host, int port, string realm, string userName, string password) { Transport = transport; Host = host; Port = port; Realm = realm; UserName = userName; Password = <PASSWORD>; } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/MIME/MIME_EntityCollection.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.MIME { #region usings using System; using System.Collections; using System.Collections.Generic; #endregion /// <summary> /// Represents MIME child entity collection in multipart/xxx entity. /// </summary> public class MIME_EntityCollection : IEnumerable { #region Members private readonly List<MIME_Entity> m_pCollection; private bool m_IsModified; #endregion #region Properties /// <summary> /// Gets if enity collection has modified. /// </summary> public bool IsModified { get { if (m_IsModified) { return true; } foreach (MIME_Entity entity in m_pCollection) { if (entity.IsModified) { return true; } } return false; } } /// <summary> /// Gets number of items in the collection. /// </summary> public int Count { get { return m_pCollection.Count; } } /// <summary> /// Gets MIME entity at the specified index. /// </summary> /// <param name="index">MIME entity zero-based index.</param> /// <returns>Returns MIME entity.</returns> public MIME_Entity this[int index] { get { return m_pCollection[index]; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> internal MIME_EntityCollection() { m_pCollection = new List<MIME_Entity>(); } #endregion #region Methods /// <summary> /// Adds specified MIME enity to the collection. /// </summary> /// <param name="entity">MIME entity.</param> /// <exception cref="ArgumentNullException">Is raised when <b>entity</b> is null reference.</exception> public void Add(MIME_Entity entity) { if (entity == null) { throw new ArgumentNullException("entity"); } m_pCollection.Add(entity); m_IsModified = true; } /// <summary> /// Inserts a new MIME entity into the collection at the specified location. /// </summary> /// <param name="index">The location in the collection where you want to add the MIME entity.</param> /// <param name="entity">MIME entity.</param> /// <exception cref="IndexOutOfRangeException">Is raised when <b>index</b> is out of range.</exception> /// <exception cref="ArgumentNullException">Is raised when <b>entity</b> is null reference.</exception> public void Insert(int index, MIME_Entity entity) { if (entity == null) { throw new ArgumentNullException("entity"); } m_pCollection.Insert(index, entity); m_IsModified = true; } /// <summary> /// Removes specified MIME entity from the collection. /// </summary> /// <param name="entity">MIME entity.</param> /// <exception cref="ArgumentNullException">Is raised when <b>field</b> is null reference.</exception> public void Remove(MIME_Entity entity) { if (entity == null) { throw new ArgumentNullException("field"); } m_pCollection.Remove(entity); m_IsModified = true; } /// <summary> /// Removes MIME entity at the specified index from the collection. /// </summary> /// <param name="index">The index of the MIME entity to remove.</param> /// <exception cref="IndexOutOfRangeException">Is raised when <b>index</b> is out of range.</exception> public void Remove(int index) { m_pCollection.RemoveAt(index); m_IsModified = true; } /// <summary> /// Removes all items from the collection. /// </summary> public void Clear() { m_pCollection.Clear(); m_IsModified = true; } /// <summary> /// Gets if the collection contains specified MIME entity. /// </summary> /// <param name="entity">MIME entity.</param> /// <returns>Returns true if the specified MIME entity exists in the collection, otherwise false.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>entity</b> is null.</exception> public bool Contains(MIME_Entity entity) { if (entity == null) { throw new ArgumentNullException("entity"); } return m_pCollection.Contains(entity); } /// <summary> /// Gets enumerator. /// </summary> /// <returns>Returns IEnumerator interface.</returns> public IEnumerator GetEnumerator() { return m_pCollection.GetEnumerator(); } #endregion } }<file_sep>/common/ASC.Data.Backup/Storage/DataStoreBackupStorage.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.IO; using ASC.Data.Storage; namespace ASC.Data.Backup.Storage { internal class DataStoreBackupStorage : IBackupStorage { private readonly string webConfigPath; private readonly int _tenant; public DataStoreBackupStorage(int tenant, string webConfigPath) { this.webConfigPath = webConfigPath; _tenant = tenant; } public string Upload(string storageBasePath, string localPath, Guid userId) { using (var stream = File.OpenRead(localPath)) { var storagePath = Path.GetFileName(localPath); GetDataStore().Save("", storagePath, stream); return storagePath; } } public void Download(string storagePath, string targetLocalPath) { using (var source = GetDataStore().GetReadStream("", storagePath)) using (var destination = File.OpenWrite(targetLocalPath)) { source.StreamCopyTo(destination); } } public void Delete(string storagePath) { var dataStore = GetDataStore(); if (dataStore.IsFile("", storagePath)) { dataStore.Delete("", storagePath); } } public bool IsExists(string storagePath) { return GetDataStore().IsFile("", storagePath); } public string GetPublicLink(string storagePath) { return GetDataStore().GetPreSignedUri("", storagePath, TimeSpan.FromDays(1), null).ToString(); } protected virtual IDataStore GetDataStore() { return StorageFactory.GetStorage(webConfigPath, _tenant.ToString(), "backup", null); } } } <file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/IMAP/Server/SharedRootFolders_EventArgs.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.IMAP.Server { /// <summary> /// Summary description for SharedRootFolders_EventArgs. /// </summary> public class SharedRootFolders_EventArgs { #region Members private readonly IMAP_Session m_pSession; #endregion #region Properties /// <summary> /// Gets reference to smtp session. /// </summary> public IMAP_Session Session { get { return m_pSession; } } /// <summary> /// Gets or sets users shared root folders. Ususaly there is only one root folder 'Shared Folders'. /// </summary> public string[] SharedRootFolders { get; set; } /// <summary> /// Gets or sets public root folders. Ususaly there is only one root folder 'Public Folders'. /// </summary> public string[] PublicRootFolders { get; set; } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> public SharedRootFolders_EventArgs(IMAP_Session session) { m_pSession = session; } #endregion } }<file_sep>/module/ASC.Api/ASC.Api.Community/Forums/ForumCategoryWrapper.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using ASC.Forum; using ASC.Specific; namespace ASC.Api.Forums { [DataContract(Name = "category", Namespace = "")] public class ForumCategoryWrapper : IApiSortableDate { [DataMember(Order = 0)] public int Id { get; set; } [DataMember(Order = 1)] public string Title { get; set; } [DataMember(Order = 2)] public ApiDateTime Created { get; set; } [DataMember(Order = 3)] public ApiDateTime Updated { get; set; } [DataMember(Order = 10)] public string Description { get; set; } public ForumCategoryWrapper(ThreadCategory category, IEnumerable<Thread> threads) { Id = category.ID; Title = category.Title; Updated = Created = (ApiDateTime)category.CreateDate; Description = category.Description; Threads = (from thread in threads where thread.IsApproved select new ForumThreadWrapper(thread)).ToList(); } private ForumCategoryWrapper() { } [DataMember(Order = 100)] public List<ForumThreadWrapper> Threads { get; set; } public static ForumCategoryWrapper GetSample() { return new ForumCategoryWrapper() { Id = 0, Created = ApiDateTime.GetSample(), Description = "Sample category", Title = "Sample title", Updated = ApiDateTime.GetSample(), Threads = new List<ForumThreadWrapper> { ForumThreadWrapper.GetSample()} }; } } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/SIP/Message/SIP_t_Timestamp.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.SIP.Message { #region usings using System; #endregion /// <summary> /// Implements SIP "Timestamp" value. Defined in RFC 3261. /// </summary> /// <remarks> /// <code> /// RFC 3261 Syntax: /// Timestamp = 1*(DIGIT) [ "." *(DIGIT) ] [ LWS delay ] /// delay = *(DIGIT) [ "." *(DIGIT) ] /// </code> /// </remarks> public class SIP_t_Timestamp : SIP_t_Value { #region Members private decimal m_Delay; private decimal m_Time; #endregion #region Properties /// <summary> /// Gets or sets time in seconds when request was sent. /// </summary> public decimal Time { get { return m_Time; } set { m_Time = value; } } /// <summary> /// Gets or sets delay time in seconds. Delay specifies the time between the UAS received /// the request and generated response. /// </summary> public decimal Delay { get { return m_Delay; } set { m_Delay = value; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="value">Timestamp: header field value.</param> public SIP_t_Timestamp(string value) { Parse(new StringReader(value)); } /// <summary> /// Default constructor. /// </summary> /// <param name="time">Time in seconds when request was sent.</param> /// <param name="delay">Delay time in seconds.</param> public SIP_t_Timestamp(decimal time, decimal delay) { m_Time = time; m_Delay = delay; } #endregion #region Methods /// <summary> /// Parses "Timestamp" from specified value. /// </summary> /// <param name="value">SIP "Timestamp" value.</param> /// <exception cref="ArgumentNullException">Raised when <b>reader</b> is null.</exception> /// <exception cref="SIP_ParseException">Raised when invalid SIP message.</exception> public void Parse(string value) { if (value == null) { throw new ArgumentNullException("reader"); } Parse(new StringReader(value)); } /// <summary> /// Parses "Timestamp" from specified reader. /// </summary> /// <param name="reader">Reader from where to parse.</param> /// <exception cref="ArgumentNullException">Raised when <b>reader</b> is null.</exception> /// <exception cref="SIP_ParseException">Raised when invalid SIP message.</exception> public override void Parse(StringReader reader) { /* RFC 3261. Timestamp = "Timestamp" HCOLON 1*(DIGIT) [ "." *(DIGIT) ] [ LWS delay ] delay = *(DIGIT) [ "." *(DIGIT) ] */ if (reader == null) { throw new ArgumentNullException("reader"); } // Get time string word = reader.ReadWord(); if (word == null) { throw new SIP_ParseException("Invalid 'Timestamp' value, time is missing !"); } m_Time = Convert.ToDecimal(word); // Get optional delay word = reader.ReadWord(); if (word != null) { m_Delay = Convert.ToDecimal(word); } else { m_Delay = 0; } } /// <summary> /// Converts this to valid "Timestamp" value. /// </summary> /// <returns>Returns "accept-range" value.</returns> public override string ToStringValue() { /* RFC 3261. Timestamp = "Timestamp" HCOLON 1*(DIGIT) [ "." *(DIGIT) ] [ LWS delay ] delay = *(DIGIT) [ "." *(DIGIT) ] */ if (m_Delay > 0) { return m_Time + " " + m_Delay; } else { return m_Time.ToString(); } } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/Data/lsDB_FixedLengthTable.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Data.lsDB { #region usings using System; using System.IO; using System.Threading; #endregion /// <summary> /// Table what all columns are with fixed length. /// </summary> public class lsDB_FixedLengthTable : IDisposable { #region Members private readonly LDB_DataColumnCollection m_pColumns; private long m_ColumnsStartOffset = -1; private string m_DbFileName = ""; private long m_FileLength; private long m_FilePosition; private lsDB_FixedLengthRecord m_pCurrentRecord; private FileStream m_pDbFile; private byte[] m_RowDataBuffer; private int m_RowLength = -1; private long m_RowsStartOffset = -1; private bool m_TableLocked; #endregion #region Properties /// <summary> /// Gets if there is active database file. /// </summary> public bool IsDatabaseOpen { get { return m_pDbFile != null; } } /// <summary> /// Gets open database file name. Throws exception if database isn't open. /// </summary> public string FileName { get { if (!IsDatabaseOpen) { throw new Exception("Database isn't open, please open database first !"); } return m_DbFileName; } } /// <summary> /// Gets table columns. Throws exception if database isn't open. /// </summary> public LDB_DataColumnCollection Columns { get { if (!IsDatabaseOpen) { throw new Exception("Database isn't open, please open database first !"); } return m_pColumns; } } /// <summary> /// Gets current record. Returns null if there isn't current record. /// </summary> public lsDB_FixedLengthRecord CurrentRecord { get { return m_pCurrentRecord; } } /// <summary> /// Gets table is locked. /// </summary> public bool TableLocked { get { return m_TableLocked; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> public lsDB_FixedLengthTable() { m_pColumns = new LDB_DataColumnCollection(this); } #endregion #region Methods /// <summary> /// Clean up any resources being used. /// </summary> public void Dispose() { Close(); } /// <summary> /// Opens specified data file. /// </summary> /// <param name="fileName">File name.</param> public void Open(string fileName) { Open(fileName, 0); } /// <summary> /// Opens specified data file. /// </summary> /// <param name="fileName">File name.</param> /// <param name="waitTime">If data base file is exclusively locked, then how many seconds to wait file to unlock before raising a error.</param> public void Open(string fileName, int waitTime) { DateTime lockExpireTime = DateTime.Now.AddSeconds(waitTime); while (true) { try { m_pDbFile = File.Open(fileName, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite); break; } catch (IOException x) { if (!File.Exists(fileName)) { throw new Exception("Specified database file '" + fileName + "' does not exists !"); } // Make this because to get rid of "The variable 'x' is declared but never used" string dummy = x.Message; Thread.Sleep(15); // Lock wait time timed out if (DateTime.Now > lockExpireTime) { throw new Exception("Database file is locked and lock wait time expired !"); } } } /* Table structure: 50 bytes - version 2 bytes - CRLF 4 bytes - Free rows count 2 bytes - CRLF 100 x 500 bytes - 100 columns info store 2 bytes - CRLF ... data pages */ m_DbFileName = fileName; // TODO: check if LDB file // Read version line (50 bytes + CRLF) byte[] version = new byte[52]; ReadFromFile(0, version, 0, version.Length); // Read free rows count byte[] freeRows = new byte[6]; ReadFromFile(0, freeRows, 0, freeRows.Length); long currentColumnOffset = 58; // Read 100 column lines (500 + CRLF bytes each) for (int i = 0; i < 100; i++) { byte[] columnInfo = new byte[102]; if (ReadFromFile(currentColumnOffset, columnInfo, 0, columnInfo.Length) != columnInfo.Length) { throw new Exception("Invalid columns data area length !"); } if (columnInfo[0] != '\0') { m_pColumns.Parse(columnInfo); } currentColumnOffset += 102; } // Header terminator \0 m_pDbFile.Position++; // No we have rows start offset m_RowsStartOffset = m_pDbFile.Position; // Store file length and position m_FileLength = m_pDbFile.Length; m_FilePosition = m_pDbFile.Position; // Calculate row length m_RowLength = 1 + 2; for (int i = 0; i < m_pColumns.Count; i++) { m_RowLength += m_pColumns[i].ColumnSize; } m_RowDataBuffer = new byte[m_RowLength]; } /// <summary> /// Closes database file. /// </summary> public void Close() { if (m_pDbFile != null) { m_pDbFile.Close(); m_pDbFile = null; m_DbFileName = ""; m_FileLength = 0; m_FilePosition = 0; m_RowLength = 0; m_ColumnsStartOffset = 0; m_RowsStartOffset = 0; m_TableLocked = false; m_RowDataBuffer = null; m_pCurrentRecord = null; } } /// <summary> /// Creates new database file. /// </summary> /// <param name="fileName">File name.</param> public void Create(string fileName) { m_pDbFile = new FileStream(fileName, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.None); /* Table structure: 50 bytes - version 2 bytes - CRLF 4 bytes - Free rows count 2 bytes - CRLF 100 x 500 bytes - 100 columns info store 2 bytes - CRLF ... data pages */ // Version 50 + CRLF bytes byte[] versionData = new byte[52]; versionData[0] = (byte) '1'; versionData[1] = (byte) '.'; versionData[2] = (byte) '0'; versionData[50] = (byte) '\r'; versionData[51] = (byte) '\n'; m_pDbFile.Write(versionData, 0, versionData.Length); // Free rows count byte[] freeRows = new byte[6]; freeRows[4] = (byte) '\r'; freeRows[5] = (byte) '\n'; m_pDbFile.Write(freeRows, 0, freeRows.Length); m_ColumnsStartOffset = m_pDbFile.Position; // 100 x 100 + CRLF bytes header lines for (int i = 0; i < 100; i++) { byte[] data = new byte[100]; m_pDbFile.Write(data, 0, data.Length); m_pDbFile.Write(new byte[] {(int) '\r', (int) '\n'}, 0, 2); } // Headers terminator char(0) m_pDbFile.WriteByte((int) '\0'); // Rows start pointer m_RowsStartOffset = m_pDbFile.Position - 1; m_DbFileName = fileName; // Store file length and position m_FileLength = m_pDbFile.Length; m_FilePosition = m_pDbFile.Position; // Calculate row length m_RowLength = 1 + 2; for (int i = 0; i < m_pColumns.Count; i++) { m_RowLength += m_pColumns[i].ColumnSize; } m_RowDataBuffer = new byte[m_RowLength]; } /// <summary> /// Locks table. /// </summary> /// <param name="waitTime">If table is locked, then how many sconds to wait table to unlock, before teturning error.</param> public void LockTable(int waitTime) { if (!IsDatabaseOpen) { throw new Exception("Database isn't open, please open database first !"); } // Table is locked already, just skip locking if (m_TableLocked) { return; } DateTime lockExpireTime = DateTime.Now.AddSeconds(waitTime); while (true) { try { // We just lock first byte m_pDbFile.Lock(0, 1); m_TableLocked = true; break; } // Catch the IOException generated if the // specified part of the file is locked. catch (IOException x) { // Make this because to get rid of "The variable 'x' is declared but never used" string dummy = x.Message; Thread.Sleep(15); // Lock wait time timed out if (DateTime.Now > lockExpireTime) { throw new Exception("Table is locked and lock wait time expired !"); } } } } /// <summary> /// Unlock table. /// </summary> public void UnlockTable() { if (!IsDatabaseOpen) { throw new Exception("Database isn't open, please open database first !"); } if (m_TableLocked) { // We just unlock first byte m_pDbFile.Unlock(0, 1); } } /// <summary> /// Moves to first record. /// </summary> public void MoveFirstRecord() { m_pCurrentRecord = null; // NextRecord(); } /// <summary> /// Gets next record. Returns true if end of file reached and there are no more records. /// </summary> /// <returns>Returns true if end of file reached and there are no more records.</returns> public bool NextRecord() { if (!IsDatabaseOpen) { throw new Exception("Database isn't open, please open database first !"); } //--- Find next record ---------------------------------------------------// long nextRowStartOffset = 0; if (m_pCurrentRecord == null) { nextRowStartOffset = m_RowsStartOffset; } else { nextRowStartOffset = m_pCurrentRecord.Pointer + m_RowLength; } while (true) { if (m_FileLength > nextRowStartOffset) { ReadFromFile(nextRowStartOffset, m_RowDataBuffer, 0, m_RowLength); // We want used row if (m_RowDataBuffer[0] == 'u') { if (m_pCurrentRecord == null) { m_pCurrentRecord = new lsDB_FixedLengthRecord(this, nextRowStartOffset, m_RowDataBuffer); } else { m_pCurrentRecord.ReuseRecord(this, nextRowStartOffset, m_RowDataBuffer); } break; } } else { return true; } nextRowStartOffset += m_RowLength; } //-------------------------------------------------------------------------// return false; } /// <summary> /// Appends new record to table. /// </summary> public void AppendRecord(object[] values) { if (!IsDatabaseOpen) { throw new Exception("Database isn't open, please open database first !"); } if (m_pColumns.Count != values.Length) { throw new Exception("Each column must have corresponding value !"); } bool unlock = true; // Table is already locked, don't lock it if (TableLocked) { unlock = false; } else { LockTable(15); } /* Fixed record structure: 1 byte - specified is row is used or free space u - used f - free space x bytes - columns data 2 bytes - CRLF */ int rowLength = 1 + 2; for (int i = 0; i < m_pColumns.Count; i++) { rowLength += m_pColumns[i].ColumnSize; } int position = 1; byte[] record = new byte[rowLength]; record[0] = (int) 'u'; record[rowLength - 2] = (int) '\r'; record[rowLength - 1] = (int) '\n'; for (int i = 0; i < values.Length; i++) { byte[] columnData = LDB_Record.ConvertToInternalData(m_pColumns[i], values[i]); // Check that column won't exceed maximum length. if (columnData.Length > m_pColumns[i].ColumnSize) { throw new Exception("Column '" + m_pColumns[i] + "' exceeds maximum value length !"); } Array.Copy(columnData, 0, record, position, columnData.Length); position += columnData.Length; } // Find free row byte[] freeRowsBuffer = new byte[4]; ReadFromFile(52, freeRowsBuffer, 0, freeRowsBuffer.Length); int freeRows = ldb_Utils.ByteToInt(freeRowsBuffer, 0); // There are plenty free rows, find first if (freeRows > 100) { //--- Find free record ---------------------------------------------------// long nextRowStartOffset = m_RowsStartOffset; long rowOffset = 0; byte[] rowData = new byte[m_RowLength]; while (true) { ReadFromFile(nextRowStartOffset, rowData, 0, m_RowLength); // We want used row if (rowData[0] == 'f') { rowOffset = nextRowStartOffset; break; } nextRowStartOffset += m_RowLength; } //-------------------------------------------------------------------------// // Write new record to file WriteToFile(rowOffset, record, 0, record.Length); // Update free rows count WriteToFile(52, ldb_Utils.IntToByte(freeRows - 1), 0, 4); } // There are few empty rows, just append it else { AppendToFile(record, 0, record.Length); } if (unlock) { UnlockTable(); } } /// <summary> /// Deletes current record. /// </summary> public void DeleteCurrentRecord() { if (!IsDatabaseOpen) { throw new Exception("Database isn't open, please open database first !"); } if (m_pCurrentRecord == null) { throw new Exception("There is no current record !"); } bool unlock = true; // Table is already locked, don't lock it if (TableLocked) { unlock = false; } else { LockTable(15); } byte[] data = new byte[m_RowLength]; data[0] = (byte) 'f'; data[m_RowLength - 2] = (byte) '\r'; data[m_RowLength - 1] = (byte) '\n'; WriteToFile(m_pCurrentRecord.Pointer, data, 0, data.Length); // Update free rows count byte[] freeRowsBuffer = new byte[4]; ReadFromFile(52, freeRowsBuffer, 0, freeRowsBuffer.Length); int freeRows = ldb_Utils.ByteToInt(freeRowsBuffer, 0); WriteToFile(52, ldb_Utils.IntToByte(freeRows + 1), 0, 4); if (unlock) { UnlockTable(); } // Activate next record **** Change it ??? NextRecord(); } #endregion #region Utility methods /// <summary> /// Sets file position. /// </summary> /// <param name="position">Position in file.</param> private void SetFilePosition(long position) { if (m_FilePosition != position) { m_pDbFile.Position = position; m_FilePosition = position; } } #endregion #region Internal methods /// <summary> /// Adds column to db file. /// </summary> /// <param name="column"></param> internal void AddColumn(LDB_DataColumn column) { if (column.ColumnSize < 1) { throw new Exception("Invalid column size '" + column.ColumnSize + "' for column '" + column.ColumnName + "' !"); } // Find free column data area long currentColumnOffset = m_ColumnsStartOffset; long freeColumnPosition = -1; // Loop all columns data areas, see it there any free left for (int i = 0; i < 100; i++) { byte[] columnInfo = new byte[102]; if (ReadFromFile(currentColumnOffset, columnInfo, 0, columnInfo.Length) != columnInfo.Length) { throw new Exception("Invalid columns data area length !"); } // We found unused column data area if (columnInfo[0] == '\0') { freeColumnPosition = currentColumnOffset - 102; break; } currentColumnOffset += 102; } if (freeColumnPosition != -1) { // TODO: If there is data ??? // Store column byte[] columnData = column.ToColumnInfo(); WriteToFile(currentColumnOffset, columnData, 0, columnData.Length); } else { throw new Exception("Couldn't find free column space ! "); } } /// <summary> /// Removes specified column from database file. /// </summary> /// <param name="column"></param> internal void RemoveColumn(LDB_DataColumn column) { throw new Exception("TODO:"); } /// <summary> /// Reads data from file. /// </summary> /// <param name="readOffset">Offset in database file from where to start reading data.</param> /// <param name="data">Buffer where to store readed data.</param> /// <param name="offset">Offset in array to where to start storing readed data.</param> /// <param name="count">Number of bytes to read.</param> /// <returns></returns> internal int ReadFromFile(long readOffset, byte[] data, int offset, int count) { SetFilePosition(readOffset); int readed = m_pDbFile.Read(data, offset, count); m_FilePosition += readed; return readed; } /// <summary> /// Writes data to file. /// </summary> /// <param name="writeOffset">Offset in database file from where to start writing data.</param> /// <param name="data">Data to write.</param> /// <param name="offset">Offset in array from where to start writing data.</param> /// <param name="count">Number of bytes to write.</param> /// <returns></returns> internal void WriteToFile(long writeOffset, byte[] data, int offset, int count) { SetFilePosition(writeOffset); m_pDbFile.Write(data, offset, count); m_FilePosition += count; } /// <summary> /// Appends specified data at the end of file. /// </summary> /// <param name="data">Data to write.</param> /// <param name="offset">Offset in array from where to start writing data.</param> /// <param name="count">Number of bytes to write.</param> internal void AppendToFile(byte[] data, int offset, int count) { m_pDbFile.Position = m_pDbFile.Length; m_pDbFile.Write(data, offset, count); m_FileLength = m_pDbFile.Length; m_FilePosition = m_pDbFile.Position; } /// <summary> /// Gets current position in file. /// </summary> /// <returns></returns> internal long GetFilePosition() { return m_FilePosition; } #endregion } }<file_sep>/web/studio/ASC.Web.Studio/Products/Community/Modules/Wiki/WikiUC/fckeditor/editor/plugins/ascuser/lang/lv.js  FCKLang.AscUserDlgTitle = "Lietotāju saraksts"; FCKLang.AscUserBtn = "Ievietot/Rediģēt saiti uz lietotāju"; FCKLang.AscUserOwnerAlert = "Lūdzu, izvēlieties lietotāju"; FCKLang.AscUserSearchLnkName ="Meklēt vārdu:"; FCKLang.AscUserList = "Lietotāju saraksts:";<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/SIP/Stack/SIP_ServerTransaction.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.SIP.Stack { #region usings using System; using System.Timers; using Message; #endregion /// <summary> /// Implements SIP server transaction. Defined in rfc 3261 17.2. /// </summary> public class SIP_ServerTransaction : SIP_Transaction { #region Events /// <summary> /// Is raised when transaction has canceled. /// </summary> public event EventHandler Canceled = null; /// <summary> /// Is raised when transaction has sent response to remote party. /// </summary> public event EventHandler<SIP_ResponseSentEventArgs> ResponseSent = null; #endregion #region Members private TimerEx m_pTimer100; private TimerEx m_pTimerG; private TimerEx m_pTimerH; private TimerEx m_pTimerI; private TimerEx m_pTimerJ; #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="stack">Owner SIP stack.</param> /// <param name="flow">SIP data flow which received request.</param> /// <param name="request">SIP request that transaction will handle.</param> /// <exception cref="ArgumentNullException">Is raised when <b>stack</b>,<b>flow</b> or <b>request</b> is null reference.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> public SIP_ServerTransaction(SIP_Stack stack, SIP_Flow flow, SIP_Request request) : base(stack, flow, request) { // Log if (Stack.Logger != null) { Stack.Logger.AddText(ID, "Transaction [branch='" + ID + "';method='" + Method + "';IsServer=true] created."); } Start(); } #endregion #region Methods /// <summary> /// Cleans up any resources being used. /// </summary> public override void Dispose() { lock (SyncRoot) { if (m_pTimer100 != null) { m_pTimer100.Dispose(); m_pTimer100 = null; } if (m_pTimerG != null) { m_pTimerG.Dispose(); m_pTimerG = null; } if (m_pTimerH != null) { m_pTimerH.Dispose(); m_pTimerH = null; } if (m_pTimerI != null) { m_pTimerI.Dispose(); m_pTimerI = null; } if (m_pTimerJ != null) { m_pTimerJ.Dispose(); m_pTimerJ = null; } } } /// <summary> /// Sends specified response to remote party. /// </summary> /// <param name="response">SIP response to send.</param> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this method is accessed.</exception> /// <exception cref="ArgumentNullException">Is raised when <b>response</b> is null reference.</exception> public void SendResponse(SIP_Response response) { lock (SyncRoot) { if (State == SIP_TransactionState.Disposed) { throw new ObjectDisposedException(GetType().Name); } if (response == null) { throw new ArgumentNullException("response"); } try { #region INVITE /* RFC 3261 17.2.1. |INVITE |pass INV to TU INVITE V send 100 if TU won't in 200ms send response+-----------+ +--------| |--------+101-199 from TU | | Proceeding| |send response +------->| |<-------+ | | Transport Err. | | Inform TU | |--------------->+ +-----------+ | 300-699 from TU | |2xx from TU | send response | |send response | | +------------------>+ | | INVITE V Timer G fires | send response+-----------+ send response | +--------| |--------+ | | | Completed | | | +------->| |<-------+ | +-----------+ | | | | ACK | | | - | +------------------>+ | Timer H fires | V or Transport Err.| +-----------+ Inform TU | | | | | Confirmed | | | | | +-----------+ | | | |Timer I fires | |- | | | V | +-----------+ | | | | | Terminated|<---------------+ | | +-----------+ */ if (Method == SIP_Methods.INVITE) { #region Proceeding if (State == SIP_TransactionState.Proceeding) { AddResponse(response); // 1xx if (response.StatusCodeType == SIP_StatusCodeType.Provisional) { Stack.TransportLayer.SendResponse(this, response); OnResponseSent(response); } // 2xx else if (response.StatusCodeType == SIP_StatusCodeType.Success) { Stack.TransportLayer.SendResponse(this, response); OnResponseSent(response); SetState(SIP_TransactionState.Terminated); } // 3xx - 6xx else { Stack.TransportLayer.SendResponse(this, response); OnResponseSent(response); SetState(SIP_TransactionState.Completed); /* RFC 3261 17.2.1. For unreliable transports, timer G is set to fire in T1 seconds, and is not set to fire for reliable transports. */ if (!Flow.IsReliable) { m_pTimerG = new TimerEx(SIP_TimerConstants.T1, false); m_pTimerG.Elapsed += m_pTimerG_Elapsed; m_pTimerG.Enabled = true; // Log if (Stack.Logger != null) { Stack.Logger.AddText(ID, "Transaction [branch='" + ID + "';method='" + Method + "';IsServer=true] timer G(INVITE response(3xx - 6xx) retransmission) started, will triger after " + m_pTimerG.Interval + "."); } } /* RFC 3261 17.2.1. When the "Completed" state is entered, timer H MUST be set to fire in 64*T1 seconds for all transports. */ m_pTimerH = new TimerEx(64*SIP_TimerConstants.T1); m_pTimerH.Elapsed += m_pTimerH_Elapsed; m_pTimerH.Enabled = true; // Log if (Stack.Logger != null) { Stack.Logger.AddText(ID, "Transaction [branch='" + ID + "';method='" + Method + "';IsServer=true] timer H(INVITE ACK wait) started, will triger after " + m_pTimerH.Interval + "."); } } } #endregion #region Completed else if (State == SIP_TransactionState.Completed) { // We do nothing here, we just wait ACK to arrive. } #endregion #region Confirmed else if (State == SIP_TransactionState.Confirmed) { // We do nothing, just wait ACK retransmissions. } #endregion #region Terminated else if (State == SIP_TransactionState.Terminated) { // We should never rreach here, but if so, skip it. } #endregion } #endregion #region Non-INVITE /* RFC 3261 17.2.2. |Request received |pass to TU V +-----------+ | | | Trying |-------------+ | | | +-----------+ |200-699 from TU | |send response |1xx from TU | |send response | | | Request V 1xx from TU | send response+-----------+send response| +--------| |--------+ | | | Proceeding| | | +------->| |<-------+ | +<--------------| | | |Trnsprt Err +-----------+ | |Inform TU | | | | | | |200-699 from TU | | |send response | | Request V | | send response+-----------+ | | +--------| | | | | | Completed |<------------+ | +------->| | +<--------------| | |Trnsprt Err +-----------+ |Inform TU | | |Timer J fires | |- | | | V | +-----------+ | | | +-------------->| Terminated| | | +-----------+ */ else { #region Trying if (State == SIP_TransactionState.Trying) { AddResponse(response); // 1xx if (response.StatusCodeType == SIP_StatusCodeType.Provisional) { Stack.TransportLayer.SendResponse(this, response); OnResponseSent(response); SetState(SIP_TransactionState.Proceeding); } // 2xx - 6xx else { Stack.TransportLayer.SendResponse(this, response); OnResponseSent(response); SetState(SIP_TransactionState.Completed); /* RFC 3261 17.2.2. When the server transaction enters the "Completed" state, it MUST set Timer J to fire in 64*T1 seconds for unreliable transports, and zero seconds for reliable transports. */ m_pTimerJ = new TimerEx(64*SIP_TimerConstants.T1, false); m_pTimerJ.Elapsed += m_pTimerJ_Elapsed; m_pTimerJ.Enabled = true; // Log if (Stack.Logger != null) { Stack.Logger.AddText(ID, "Transaction [branch='" + ID + "';method='" + Method + "';IsServer=true] timer J(Non-INVITE request retransmission wait) started, will triger after " + m_pTimerJ.Interval + "."); } } } #endregion #region Proceeding else if (State == SIP_TransactionState.Proceeding) { AddResponse(response); // 1xx if (response.StatusCodeType == SIP_StatusCodeType.Provisional) { Stack.TransportLayer.SendResponse(this, response); OnResponseSent(response); } // 2xx - 6xx else { Stack.TransportLayer.SendResponse(this, response); OnResponseSent(response); SetState(SIP_TransactionState.Completed); /* RFC 3261 17.2.2. When the server transaction enters the "Completed" state, it MUST set Timer J to fire in 64*T1 seconds for unreliable transports, and zero seconds for reliable transports. */ m_pTimerJ = new TimerEx(64*SIP_TimerConstants.T1, false); m_pTimerJ.Elapsed += m_pTimerJ_Elapsed; m_pTimerJ.Enabled = true; // Log if (Stack.Logger != null) { Stack.Logger.AddText(ID, "Transaction [branch='" + ID + "';method='" + Method + "';IsServer=true] timer J(Non-INVITE request retransmission wait) started, will triger after " + m_pTimerJ.Interval + "."); } } } #endregion #region Completed else if (State == SIP_TransactionState.Completed) { // Do nothing. } #endregion #region Terminated else if (State == SIP_TransactionState.Terminated) { // Do nothing. } #endregion } #endregion } catch (SIP_TransportException x) { // Log if (Stack.Logger != null) { Stack.Logger.AddText(ID, "Transaction [branch='" + ID + "';method='" + Method + "';IsServer=true] transport exception: " + x.Message); } OnTransportError(x); SetState(SIP_TransactionState.Terminated); } } } /// <summary> /// Cancels current transaction processing and sends '487 Request Terminated'. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this method is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when final response is sent and Cancel method is called after it.</exception> public override void Cancel() { lock (SyncRoot) { if (State == SIP_TransactionState.Disposed) { throw new ObjectDisposedException(GetType().Name); } if (FinalResponse != null) { throw new InvalidOperationException("Final response is already sent, CANCEL not allowed."); } try { SIP_Response response = Stack.CreateResponse(SIP_ResponseCodes.x487_Request_Terminated, Request); Stack.TransportLayer.SendResponse(this, response); OnCanceled(); } catch (SIP_TransportException x) { // Log if (Stack.Logger != null) { Stack.Logger.AddText(ID, "Transaction [branch='" + ID + "';method='" + Method + "';IsServer=true] transport exception: " + x.Message); } OnTransportError(x); SetState(SIP_TransactionState.Terminated); } } } #endregion #region Internal methods /// <summary> /// Processes specified request through this transaction. /// </summary> /// <param name="flow">SIP data flow.</param> /// <param name="request">SIP request.</param> /// <exception cref="ArgumentNullException">Is raised when <b>flow</b> or <b>request</b> is null reference.</exception> internal void ProcessRequest(SIP_Flow flow, SIP_Request request) { if (flow == null) { throw new ArgumentNullException("flow"); } if (request == null) { throw new ArgumentNullException("request"); } lock (SyncRoot) { if (State == SIP_TransactionState.Disposed) { return; } try { // Log if (Stack.Logger != null) { byte[] requestData = request.ToByteData(); Stack.Logger.AddRead(Guid.NewGuid().ToString(), null, 0, "Request [transactionID='" + ID + "'; method='" + request.RequestLine.Method + "'; cseq='" + request.CSeq.SequenceNumber + "'; " + "transport='" + flow.Transport + "'; size='" + requestData.Length + "'; received '" + flow.LocalEP + "' <- '" + flow.RemoteEP + "'.", flow.LocalEP, flow.RemoteEP, requestData); } #region INVITE if (Method == SIP_Methods.INVITE) { #region INVITE if (request.RequestLine.Method == SIP_Methods.INVITE) { if (State == SIP_TransactionState.Proceeding) { /* RFC 3261 17.2.1. If a request retransmission is received while in the "Proceeding" state, the most recent provisional response that was received from the TU MUST be passed to the transport layer for retransmission. */ SIP_Response response = LastProvisionalResponse; if (response != null) { Stack.TransportLayer.SendResponse(this, response); } } else if (State == SIP_TransactionState.Completed) { /* RFC 3261 17.2.1. While in the "Completed" state, if a request retransmission is received, the server SHOULD pass the response to the transport for retransmission. */ Stack.TransportLayer.SendResponse(this, FinalResponse); } } #endregion #region ACK else if (request.RequestLine.Method == SIP_Methods.ACK) { /* RFC 3261 17.2.1 If an ACK is received while the server transaction is in the "Completed" state, the server transaction MUST transition to the "Confirmed" state. As Timer G is ignored in this state, any retransmissions of the response will cease. When this state is entered, timer I is set to fire in T4 seconds for unreliable transports, and zero seconds for reliable transports. */ if (State == SIP_TransactionState.Completed) { SetState(SIP_TransactionState.Confirmed); // Stop timers G,H if (m_pTimerG != null) { m_pTimerG.Dispose(); m_pTimerG = null; // Log if (Stack.Logger != null) { Stack.Logger.AddText(ID, "Transaction [branch='" + ID + "';method='" + Method + "';IsServer=true] timer G(INVITE response(3xx - 6xx) retransmission) stoped."); } } if (m_pTimerH != null) { m_pTimerH.Dispose(); m_pTimerH = null; // Log if (Stack.Logger != null) { Stack.Logger.AddText(ID, "Transaction [branch='" + ID + "';method='" + Method + "';IsServer=true] timer H(INVITE ACK wait) stoped."); } } // Start timer I. m_pTimerI = new TimerEx((flow.IsReliable ? 0 : SIP_TimerConstants.T4), false); m_pTimerI.Elapsed += m_pTimerI_Elapsed; // Log if (Stack.Logger != null) { Stack.Logger.AddText(ID, "Transaction [branch='" + ID + "';method='" + Method + "';IsServer=true] timer I(INVITE ACK retransission wait) started, will triger after " + m_pTimerI.Interval + "."); } m_pTimerI.Enabled = true; } } #endregion } #endregion #region Non-INVITE else { // Non-INVITE transaction may have only request retransmission requests. if (Method == request.RequestLine.Method) { if (State == SIP_TransactionState.Proceeding) { /* RFC 3261 17.2.2. If a retransmission of the request is received while in the "Proceeding" state, the most recently sent provisional response MUST be passed to the transport layer for retransmission. */ Stack.TransportLayer.SendResponse(this, LastProvisionalResponse); } else if (State == SIP_TransactionState.Completed) { /* RFC 3261 17.2.2. While in the "Completed" state, the server transaction MUST pass the final response to the transport layer for retransmission whenever a retransmission of the request is received. */ Stack.TransportLayer.SendResponse(this, FinalResponse); } } } #endregion } catch (SIP_TransportException x) { // Log if (Stack.Logger != null) { Stack.Logger.AddText(ID, "Transaction [branch='" + ID + "';method='" + Method + "';IsServer=true] transport exception: " + x.Message); } OnTransportError(x); SetState(SIP_TransactionState.Terminated); } } } #endregion #region Utility methods /// <summary> /// Is raised when INVITE 100 (Trying) response must be sent if no response sent by transaction user. /// </summary> /// <param name="sender">Sender.</param> /// <param name="e">Event data.</param> private void m_pTimer100_Elapsed(object sender, ElapsedEventArgs e) { lock (SyncRoot) { // RFC 3261 17.2.1. TU didn't generate response in 200 ms, send '100 Trying' to stop request retransmission. if (State == SIP_TransactionState.Proceeding && Responses.Length == 0) { /* RFC 3261 17.2.1. The 100 (Trying) response is constructed according to the procedures in Section 8.2.6, except that the insertion of tags in the To header field of the response (when none was present in the request) is downgraded from MAY to SHOULD NOT. * RFC 3261 8.2.6. When a 100 (Trying) response is generated, any Timestamp header field present in the request MUST be copied into this 100 (Trying) response. If there is a delay in generating the response, the UAS SHOULD add a delay value into the Timestamp value in the response. This value MUST contain the difference between the time of sending of the response and receipt of the request, measured in seconds. */ SIP_Response tryingResponse = Stack.CreateResponse(SIP_ResponseCodes.x100_Trying, Request); if (Request.Timestamp != null) { tryingResponse.Timestamp = new SIP_t_Timestamp(Request.Timestamp.Time, (DateTime.Now - CreateTime).Seconds); } try { Stack.TransportLayer.SendResponse(this, tryingResponse); } catch (Exception x) { OnTransportError(x); SetState(SIP_TransactionState.Terminated); return; } } if (m_pTimer100 != null) { m_pTimer100.Dispose(); m_pTimer100 = null; } } } /// <summary> /// Is raised when INVITE timer G triggered. /// </summary> /// <param name="sender">Sender.</param> /// <param name="e">Event data.</param> private void m_pTimerG_Elapsed(object sender, ElapsedEventArgs e) { /* RFC 3261 17.2.1. If timer G fires, the response is passed to the transport layer once more for retransmission, and timer G is set to fire in MIN(2*T1, T2) seconds. From then on, when timer G fires, the response is passed to the transport again for transmission, and timer G is reset with a value that doubles, unless that value exceeds T2, in which case it is reset with the value of T2. */ lock (SyncRoot) { if (State == SIP_TransactionState.Completed) { // Log if (Stack.Logger != null) { Stack.Logger.AddText(ID, "Transaction [branch='" + ID + "';method='" + Method + "';IsServer=true] timer G(INVITE response(3xx - 6xx) retransmission) triggered."); } try { Stack.TransportLayer.SendResponse(this, FinalResponse); // Update(double current) next transmit time. m_pTimerG.Interval *= Math.Min(m_pTimerG.Interval*2, SIP_TimerConstants.T2); m_pTimerG.Enabled = true; // Log if (Stack.Logger != null) { Stack.Logger.AddText(ID, "Transaction [branch='" + ID + "';method='" + Method + "';IsServer=false] timer G(INVITE response(3xx - 6xx) retransmission) updated, will triger after " + m_pTimerG.Interval + "."); } } catch (Exception x) { OnTransportError(x); SetState(SIP_TransactionState.Terminated); } } } } /// <summary> /// Is raised when INVITE timer H triggered. /// </summary> /// <param name="sender">Sender.</param> /// <param name="e">Event data.</param> private void m_pTimerH_Elapsed(object sender, ElapsedEventArgs e) { /* RFC 3261 17.2.1. If timer H fires while in the "Completed" state, it implies that the ACK was never received. In this case, the server transaction MUST transition to the "Terminated" state, and MUST indicate to the TU that a transaction failure has occurred. */ lock (SyncRoot) { if (State == SIP_TransactionState.Completed) { // Log if (Stack.Logger != null) { Stack.Logger.AddText(ID, "Transaction [branch='" + ID + "';method='" + Method + "';IsServer=true] timer H(INVITE ACK wait) triggered."); } OnTransactionError("ACK was never received."); SetState(SIP_TransactionState.Terminated); } } } /// <summary> /// Is raised when INVITE timer I triggered. /// </summary> /// <param name="sender">Sender.</param> /// <param name="e">Event data.</param> private void m_pTimerI_Elapsed(object sender, ElapsedEventArgs e) { /* RFC 3261 17.2.1. Once timer I fires, the server MUST transition to the "Terminated" state. */ lock (SyncRoot) { // Log if (Stack.Logger != null) { Stack.Logger.AddText(ID, "Transaction [branch='" + ID + "';method='" + Method + "';IsServer=true] timer I(INVITE ACK retransmission wait) triggered."); } SetState(SIP_TransactionState.Terminated); } } /// <summary> /// Is raised when INVITE timer J triggered. /// </summary> /// <param name="sender">Sender.</param> /// <param name="e">Event data.</param> private void m_pTimerJ_Elapsed(object sender, ElapsedEventArgs e) { /* RFC 3261 172.2.2. Timer J fires, at which point it MUST transition to the "Terminated" state. */ lock (SyncRoot) { // Log if (Stack.Logger != null) { Stack.Logger.AddText(ID, "Transaction [branch='" + ID + "';method='" + Method + "';IsServer=true] timer I(Non-INVITE request retransmission wait) triggered."); } SetState(SIP_TransactionState.Terminated); } } /// <summary> /// Starts transaction processing. /// </summary> private void Start() { #region INVITE if (Method == SIP_Methods.INVITE) { /* RFC 3261 17.2.1. When a server transaction is constructed for a request, it enters the "Proceeding" state. The server transaction MUST generate a 100 (Trying) response unless it knows that the TU will generate a provisional or final response within 200 ms, in which case it MAY generate a 100 (Trying) response. */ SetState(SIP_TransactionState.Proceeding); m_pTimer100 = new TimerEx(200, false); m_pTimer100.Elapsed += m_pTimer100_Elapsed; m_pTimer100.Enabled = true; } #endregion #region Non-INVITE else { // RFC 3261 17.2.2. The state machine is initialized in the "Trying" state. SetState(SIP_TransactionState.Trying); } #endregion } /// <summary> /// Raises <b>ResponseSent</b> event. /// </summary> /// <param name="response">SIP response.</param> private void OnResponseSent(SIP_Response response) { if (ResponseSent != null) { ResponseSent(this, new SIP_ResponseSentEventArgs(this, response)); } } /// <summary> /// Raises <b>Canceled</b> event. /// </summary> private void OnCanceled() { if (Canceled != null) { Canceled(this, new EventArgs()); } } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/SIP/Stack/SIP_ResponseSentEventArgs.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.SIP.Stack { #region usings using System; #endregion /// <summary> /// This class provides data for <b>SIP_ServerTransaction.ResponseSent</b> method. /// </summary> public class SIP_ResponseSentEventArgs : EventArgs { #region Members private readonly SIP_Response m_pResponse; private readonly SIP_ServerTransaction m_pTransaction; #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="transaction">Server transaction.</param> /// <param name="response">SIP response.</param> /// <exception cref="ArgumentNullException">Is raised when any of the arguments is null.</exception> public SIP_ResponseSentEventArgs(SIP_ServerTransaction transaction, SIP_Response response) { if (transaction == null) { throw new ArgumentNullException("transaction"); } if (response == null) { throw new ArgumentNullException("response"); } m_pTransaction = transaction; m_pResponse = response; } #endregion #region Properties /// <summary> /// Gets response which was sent. /// </summary> public SIP_Response Response { get { return m_pResponse; } } /// <summary> /// Gets server transaction which sent response. /// </summary> public SIP_ServerTransaction ServerTransaction { get { return m_pTransaction; } } #endregion } }<file_sep>/module/ASC.Socket.IO/app/controllers/counters.js module.exports = (counters) => { const router = require('express').Router(); router .post("/sendUnreadUsers", (req, res) => { counters.sendUnreadUsers(req.body); res.end(); }) .post("/sendUnreadCounts", (req, res) => { counters.sendUnreadCounts(req.body); res.end(); }); return router; }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/SIP/Proxy/SIP_B2BUA_Call.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.SIP.Proxy { #region usings using System; using Message; using Stack; #endregion /// <summary> /// This class represents B2BUA call. /// </summary> public class SIP_B2BUA_Call { #region Members private readonly string m_CallID = ""; private readonly SIP_B2BUA m_pOwner; private readonly DateTime m_StartTime; private bool m_IsTerminated; private SIP_Dialog m_pCallee; private SIP_Dialog m_pCaller; #endregion #region Properties /// <summary> /// Gets call start time. /// </summary> public DateTime StartTime { get { return m_StartTime; } } /// <summary> /// Gets current call ID. /// </summary> public string CallID { get { return m_CallID; } } /// <summary> /// Gets caller SIP dialog. /// </summary> public SIP_Dialog CallerDialog { get { return m_pCaller; } } /// <summary> /// Gets callee SIP dialog. /// </summary> public SIP_Dialog CalleeDialog { get { return m_pCallee; } } /// <summary> /// Gets if call has timed out and needs to be terminated. /// </summary> public bool IsTimedOut { // TODO: get { return false; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="owner">Owner B2BUA server.</param> /// <param name="caller">Caller side dialog.</param> /// <param name="callee">Callee side dialog.</param> internal SIP_B2BUA_Call(SIP_B2BUA owner, SIP_Dialog caller, SIP_Dialog callee) { m_pOwner = owner; m_pCaller = caller; m_pCallee = callee; m_StartTime = DateTime.Now; m_CallID = Guid.NewGuid().ToString().Replace("-", ""); //m_pCaller.RequestReceived += new SIP_RequestReceivedEventHandler(m_pCaller_RequestReceived); //m_pCaller.Terminated += new EventHandler(m_pCaller_Terminated); //m_pCallee.RequestReceived += new SIP_RequestReceivedEventHandler(m_pCallee_RequestReceived); //m_pCallee.Terminated += new EventHandler(m_pCallee_Terminated); } #endregion #region Methods /// <summary> /// Terminates call. /// </summary> public void Terminate() { if (m_IsTerminated) { return; } m_IsTerminated = true; m_pOwner.RemoveCall(this); if (m_pCaller != null) { //m_pCaller.Terminate(); m_pCaller.Dispose(); m_pCaller = null; } if (m_pCallee != null) { //m_pCallee.Terminate(); m_pCallee.Dispose(); m_pCallee = null; } m_pOwner.OnCallTerminated(this); } #endregion #region Utility methods /// <summary> /// Is called when caller sends new request. /// </summary> /// <param name="e">Event data.</param> private void m_pCaller_RequestReceived(SIP_RequestReceivedEventArgs e) { // TODO: If we get UPDATE, but callee won't support it ? generate INVITE instead ? /* SIP_Request request = m_pCallee.CreateRequest(e.Request.RequestLine.Method); CopyMessage(e.Request,request,new string[]{"Via:","Call-Id:","To:","From:","CSeq:","Contact:","Route:","Record-Route:","Max-Forwards:","Allow:","Require:","Supported:"}); // Remove our Authentication header if it's there. foreach(SIP_SingleValueHF<SIP_t_Credentials> header in request.ProxyAuthorization.HeaderFields){ try{ Auth_HttpDigest digest = new Auth_HttpDigest(header.ValueX.AuthData,request.RequestLine.Method); if(m_pOwner.Stack.Realm == digest.Realm){ request.ProxyAuthorization.Remove(header); } } catch{ // We don't care errors here. This can happen if remote server xxx auth method here and // we don't know how to parse it, so we leave it as is. } } SIP_ClientTransaction clientTransaction = m_pCallee.CreateTransaction(request); clientTransaction.ResponseReceived += new EventHandler<SIP_ResponseReceivedEventArgs>(m_pCallee_ResponseReceived); clientTransaction.Tag = e.ServerTransaction; clientTransaction.Start();*/ } /// <summary> /// This method is called when caller dialog has terminated, normally this happens /// when dialog gets BYE request. /// </summary> /// <param name="sender">Sender.</param> /// <param name="e">Event data.</param> private void m_pCaller_Terminated(object sender, EventArgs e) { Terminate(); } /// <summary> /// This method is called when callee dialog client transaction receives response. /// </summary> /// <param name="sender">Sender.</param> /// <param name="e">Event data.</param> private void m_pCallee_ResponseReceived(object sender, SIP_ResponseReceivedEventArgs e) { SIP_ServerTransaction serverTransaction = (SIP_ServerTransaction) e.ClientTransaction.Tag; //SIP_Response response = serverTransaction.Request.CreateResponse(e.Response.StatusCode_ReasonPhrase); //CopyMessage(e.Response,response,new string[]{"Via:","Call-Id:","To:","From:","CSeq:","Contact:","Route:","Record-Route:","Allow:","Supported:"}); //serverTransaction.SendResponse(response); } /// <summary> /// Is called when callee sends new request. /// </summary> /// <param name="e">Event data.</param> private void m_pCallee_RequestReceived(SIP_RequestReceivedEventArgs e) { /* SIP_Request request = m_pCaller.CreateRequest(e.Request.RequestLine.Method); CopyMessage(e.Request,request,new string[]{"Via:","Call-Id:","To:","From:","CSeq:","Contact:","Route:","Record-Route:","Max-Forwards:","Allow:","Require:","Supported:"}); // Remove our Authentication header if it's there. foreach(SIP_SingleValueHF<SIP_t_Credentials> header in request.ProxyAuthorization.HeaderFields){ try{ Auth_HttpDigest digest = new Auth_HttpDigest(header.ValueX.AuthData,request.RequestLine.Method); if(m_pOwner.Stack.Realm == digest.Realm){ request.ProxyAuthorization.Remove(header); } } catch{ // We don't care errors here. This can happen if remote server xxx auth method here and // we don't know how to parse it, so we leave it as is. } } SIP_ClientTransaction clientTransaction = m_pCaller.CreateTransaction(request); clientTransaction.ResponseReceived += new EventHandler<SIP_ResponseReceivedEventArgs>(m_pCaller_ResponseReceived); clientTransaction.Tag = e.ServerTransaction; clientTransaction.Start();*/ } /// <summary> /// This method is called when callee dialog has terminated, normally this happens /// when dialog gets BYE request. /// </summary> /// <param name="sender">Sender.</param> /// <param name="e">Event data.</param> private void m_pCallee_Terminated(object sender, EventArgs e) { Terminate(); } /// <summary> /// This method is called when caller dialog client transaction receives response. /// </summary> /// <param name="sender">Sender.</param> /// <param name="e">Event data.</param> private void m_pCaller_ResponseReceived(object sender, SIP_ResponseReceivedEventArgs e) { SIP_ServerTransaction serverTransaction = (SIP_ServerTransaction) e.ClientTransaction.Tag; //SIP_Response response = serverTransaction.Request.CreateResponse(e.Response.StatusCode_ReasonPhrase); //CopyMessage(e.Response,response,new string[]{"Via:","Call-Id:","To:","From:","CSeq:","Contact:","Route:","Record-Route:","Allow:","Supported:"}); //serverTransaction.SendResponse(response); } /* /// <summary> /// Transfers call to specified recipient. /// </summary> /// <param name="to">Address where to transfer call.</param> public void CallTransfer(string to) { throw new NotImplementedException(); }*/ /// <summary> /// Copies header fileds from 1 message to antother. /// </summary> /// <param name="source">Source message.</param> /// <param name="destination">Destination message.</param> /// <param name="exceptHeaders">Header fields not to copy.</param> private void CopyMessage(SIP_Message source, SIP_Message destination, string[] exceptHeaders) { foreach (SIP_HeaderField headerField in source.Header) { bool copy = true; foreach (string h in exceptHeaders) { if (h.ToLower() == headerField.Name.ToLower()) { copy = false; break; } } if (copy) { destination.Header.Add(headerField.Name, headerField.Value); } } destination.Data = source.Data; } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/IMAP/IMAP_ACL_Flags.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.IMAP { /// <summary> /// IMAP ACL(access control list) rights. /// </summary> public enum IMAP_ACL_Flags { /// <summary> /// No permissions at all. /// </summary> None = 0, /// <summary> /// Lookup (mailbox is visible to LIST/LSUB commands). /// </summary> l = 1, /// <summary> /// Read (SELECT the mailbox, perform CHECK, FETCH, PARTIAL,SEARCH, COPY from mailbox). /// </summary> r = 2, /// <summary> /// Keep seen/unseen information across sessions (STORE SEEN flag). /// </summary> s = 4, /// <summary> /// Write (STORE flags other than SEEN and DELETED). /// </summary> w = 8, /// <summary> /// Insert (perform APPEND, COPY into mailbox). /// </summary> i = 16, /// <summary> /// Post (send mail to submission address for mailbox,not enforced by IMAP4 itself). /// </summary> p = 32, /// <summary> /// Create (CREATE new sub-mailboxes in any implementation-defined hierarchy). /// </summary> c = 64, /// <summary> /// Delete (STORE DELETED flag, perform EXPUNGE). /// </summary> d = 128, /// <summary> /// Administer (perform SETACL). /// </summary> a = 256, /// <summary> /// All permissions /// </summary> All = 0xFFFF, } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/Mail/Mail_t_TcpInfo.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.Mail { #region usings using System; using System.Net; #endregion /// <summary> /// Represents Received: header "TCP-info" value. Defined in RFC 5321. 4.4. /// </summary> /// <remarks> /// <code> /// RFC 5321 4.4. /// TCP-info = address-literal / ( Domain FWS address-literal ) /// address-literal = "[" ( IPv4-address-literal / IPv6-address-literal / General-address-literal ) "]" /// </code> /// </remarks> public class Mail_t_TcpInfo { #region Members private readonly string m_HostName; private readonly IPAddress m_pIP; #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="ip">IP address.</param> /// <param name="hostName">Host name.</param> /// <exception cref="ArgumentNullException">Is raised when <b>ip</b> is null reference.</exception> public Mail_t_TcpInfo(IPAddress ip, string hostName) { if (ip == null) { throw new ArgumentNullException("ip"); } m_pIP = ip; m_HostName = hostName; } #endregion #region Properties /// <summary> /// Gets host value. Value null means not specified. /// </summary> public string HostName { get { return m_HostName; } } /// <summary> /// Gets IP address. /// </summary> public IPAddress IP { get { return m_pIP; } } #endregion #region Methods /// <summary> /// Returns this as string. /// </summary> /// <returns>Returns this as string.</returns> public override string ToString() { if (string.IsNullOrEmpty(m_HostName)) { return "[" + m_pIP + "]"; } else { return m_HostName + " [" + m_pIP + "]"; } } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/SIP/Message/SIP_t_RValue.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.SIP.Message { #region usings using System; #endregion /// <summary> /// Implements SIP "r-value" value. Defined in RFC 4412. /// </summary> /// <remarks> /// <code> /// RFC 4412 Syntax: /// r-value = namespace "." r-priority /// namespace = token-nodot /// r-priority = token-nodot /// </code> /// </remarks> public class SIP_t_RValue : SIP_t_Value { #region Members private string m_Namespace = ""; private string m_Priority = ""; #endregion #region Properties /// <summary> /// Gets or sets Namespace. /// </summary> /// <exception cref="ArgumentNullException">Is raised when null value passed.</exception> /// <exception cref="ArgumentException">Is raised when invalid Namespace value passed.</exception> public string Namespace { get { return m_Namespace; } set { if (value == null) { throw new ArgumentNullException("Namespace"); } if (value == "") { throw new ArgumentException("Property Namespace value may not be '' !"); } if (!TextUtils.IsToken(value)) { throw new ArgumentException("Property Namespace value must be 'token' !"); } m_Namespace = value; } } /// <summary> /// Gets or sets priority. /// </summary> /// <exception cref="ArgumentNullException">Is raised when null value passed.</exception> /// <exception cref="ArgumentException">Is raised when invalid Priority value passed.</exception> public string Priority { get { return m_Priority; } set { if (value == null) { throw new ArgumentNullException("Priority"); } if (value == "") { throw new ArgumentException("Property Priority value may not be '' !"); } if (!TextUtils.IsToken(value)) { throw new ArgumentException("Property Priority value must be 'token' !"); } m_Priority = value; } } #endregion #region Methods /// <summary> /// Parses "r-value" from specified value. /// </summary> /// <param name="value">SIP "r-value" value.</param> /// <exception cref="ArgumentNullException">Raised when <b>value</b> is null.</exception> /// <exception cref="SIP_ParseException">Raised when invalid SIP message.</exception> public void Parse(string value) { if (value == null) { throw new ArgumentNullException("value"); } Parse(new StringReader(value)); } /// <summary> /// Parses "r-value" from specified reader. /// </summary> /// <param name="reader">Reader from where to parse.</param> /// <exception cref="ArgumentNullException">Raised when <b>reader</b> is null.</exception> /// <exception cref="SIP_ParseException">Raised when invalid SIP message.</exception> public override void Parse(StringReader reader) { /* r-value = namespace "." r-priority namespace = token-nodot r-priority = token-nodot */ if (reader == null) { throw new ArgumentNullException("reader"); } // namespace "." r-priority string word = reader.ReadWord(); if (word == null) { throw new SIP_ParseException( "Invalid 'r-value' value, 'namespace \".\" r-priority' is missing !"); } string[] namespace_priority = word.Split('.'); if (namespace_priority.Length != 2) { throw new SIP_ParseException("Invalid r-value !"); } m_Namespace = namespace_priority[0]; m_Priority = namespace_priority[1]; } /// <summary> /// Converts this to valid "r-value" value. /// </summary> /// <returns>Returns "r-value" value.</returns> public override string ToStringValue() { /* r-value = namespace "." r-priority namespace = token-nodot r-priority = token-nodot */ return m_Namespace + "." + m_Priority; } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/IMAP/Server/IMAP_MessageItems_enum.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.IMAP.Server { /// <summary> /// Specifies message itmes. /// </summary> public enum IMAP_MessageItems_enum { /// <summary> /// None. /// </summary> None = 0, /// <summary> /// Message main header. /// </summary> Header = 2, /// <summary> /// IMAP ENVELOPE structure. /// </summary> Envelope = 4, /// <summary> /// IMAP BODYSTRUCTURE structure. /// </summary> BodyStructure = 8, /// <summary> /// Full message. /// </summary> Message = 16, } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/SIP/Proxy/SIP_Presence.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.SIP.Proxy { #region usings using Stack; #endregion /// <summary> /// This class implements SIP presence server. /// </summary> public class SIP_Presence { #region Internal methods /// <summary> /// Handles SUBSCRIBE method. /// </summary> /// <param name="e">Request event arguments.</param> internal void Subscribe(SIP_RequestReceivedEventArgs e) {} /// <summary> /// Handles NOTIFY method. /// </summary> /// <param name="e">Request event arguments.</param> internal void Notify(SIP_RequestReceivedEventArgs e) {} #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/SMTP/Server/SMTP_MailFrom.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.SMTP.Server { #region usings using System; #endregion /// <summary> /// This class holds MAIL FROM: command value. /// </summary> public class SMTP_MailFrom { #region Members private readonly string m_Body; private readonly string m_ENVID; private readonly string m_Mailbox = ""; private readonly string m_RET; private readonly int m_Size = -1; #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="mailbox">Mailbox value.</param> /// <param name="size">SIZE parameter value.</param> /// <param name="body">BODY parameter value.</param> /// <param name="ret">DSN RET parameter value.</param> /// <param name="envid">DSN ENVID parameter value.</param> /// <exception cref="ArgumentNullException">Is raised when <b>mailbox</b> is null reference.</exception> public SMTP_MailFrom(string mailbox, int size, string body, string ret, string envid) { if (mailbox == null) { throw new ArgumentNullException("mailbox"); } m_Mailbox = mailbox; m_Size = size; m_Body = body; m_RET = ret; m_ENVID = envid; } #endregion #region Properties /// <summary> /// Gets MAIL FROM: BODY parameter value. Value null means not specified. /// Defined in RFC 1652. /// </summary> public string Body { get { return m_Body; } } /// <summary> /// Gets DSN ENVID parameter value. Value null means not specified. /// Defined in RFC 1891. /// </summary> public string ENVID { get { return m_ENVID; } } /// <summary> /// Gets SMTP "mailbox" value. Actually this is just email address. /// This value can be "" if "null reverse-path". /// </summary> public string Mailbox { get { return m_Mailbox; } } /// <summary> /// Gets DSN RET parameter value. Value null means not specified. /// RET specifies whether message or headers should be included in any failed DSN issued for message transmission. /// Defined in RFC 1891. /// </summary> public string RET { get { return m_RET; } } /// <summary> /// Gets MAIL FROM: SIZE parameter value. Value -1 means not specified. /// Defined in RFC 1870. /// </summary> public int Size { get { return m_Size; } } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/SIP/Stack/SIP_Request.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.SIP.Stack { #region usings using System; using System.IO; using System.Net; using System.Text; using Message; #endregion /// <summary> /// SIP server request. Related RFC 3261. /// </summary> public class SIP_Request : SIP_Message { #region Members private readonly SIP_RequestLine m_pRequestLine; private SIP_Flow m_pFlow; private IPEndPoint m_pLocalEP; private IPEndPoint m_pRemoteEP; #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="method">SIP request method.</param> /// <exception cref="ArgumentNullException">Is raised when <b>method</b> is null reference.</exception> public SIP_Request(string method) { if (method == null) { throw new ArgumentNullException("method"); } m_pRequestLine = new SIP_RequestLine(method, new AbsoluteUri()); } #endregion #region Properties /// <summary> /// Gets request-line. /// </summary> public SIP_RequestLine RequestLine { get { return m_pRequestLine; } } /// <summary> /// Gets or sets flow what received or sent this request. Returns null if this request isn't sent or received. /// </summary> internal SIP_Flow Flow { get { return m_pFlow; } set { m_pFlow = value; } } /// <summary> /// Gets or sets local end point what sent/received this request. Returns null if this request isn't sent or received. /// </summary> internal IPEndPoint LocalEndPoint { get { return m_pLocalEP; } set { m_pLocalEP = value; } } /// <summary> /// Gets or sets remote end point what sent/received this request. Returns null if this request isn't sent or received. /// </summary> internal IPEndPoint RemoteEndPoint { get { return m_pRemoteEP; } set { m_pRemoteEP = value; } } #endregion #region Methods /// <summary> /// Parses SIP_Request from byte array. /// </summary> /// <param name="data">Valid SIP request data.</param> /// <returns>Returns parsed SIP_Request obeject.</returns> /// <exception cref="ArgumentNullException">Raised when <b>data</b> is null.</exception> /// <exception cref="SIP_ParseException">Raised when invalid SIP message.</exception> public static SIP_Request Parse(byte[] data) { if (data == null) { throw new ArgumentNullException("data"); } return Parse(new MemoryStream(data)); } /// <summary> /// Parses SIP_Request from stream. /// </summary> /// <param name="stream">Stream what contains valid SIP request.</param> /// <returns>Returns parsed SIP_Request obeject.</returns> /// <exception cref="ArgumentNullException">Raised when <b>stream</b> is null.</exception> /// <exception cref="SIP_ParseException">Raised when invalid SIP message.</exception> public static SIP_Request Parse(Stream stream) { /* Syntax: SIP-Method SIP-URI SIP-Version SIP-Message */ if (stream == null) { throw new ArgumentNullException("stream"); } // Parse Response-line StreamLineReader r = new StreamLineReader(stream); r.Encoding = "utf-8"; string[] method_uri_version = r.ReadLineString().Split(' '); if (method_uri_version.Length != 3) { throw new Exception( "Invalid SIP request data ! Method line doesn't contain: SIP-Method SIP-URI SIP-Version."); } SIP_Request retVal = new SIP_Request(method_uri_version[0]); retVal.RequestLine.Uri = AbsoluteUri.Parse(method_uri_version[1]); retVal.RequestLine.Version = method_uri_version[2]; // Parse SIP message retVal.InternalParse(stream); return retVal; } /// <summary> /// Clones this request. /// </summary> /// <returns>Returns new cloned request.</returns> public SIP_Request Copy() { SIP_Request retVal = Parse(ToByteData()); retVal.Flow = m_pFlow; retVal.LocalEndPoint = m_pLocalEP; retVal.RemoteEndPoint = m_pRemoteEP; return retVal; } /// <summary> /// Checks if SIP request has all required values as request line,header fields and their values. /// Throws Exception if not valid SIP request. /// </summary> public void Validate() { // Request SIP version // Via: + branch prameter // To: // From: // CallID: // CSeq // Max-Forwards RFC 3261 8.1.1. if (!RequestLine.Version.ToUpper().StartsWith("SIP/2.0")) { throw new SIP_ParseException("Not supported SIP version '" + RequestLine.Version + "' !"); } if (Via.GetTopMostValue() == null) { throw new SIP_ParseException("Via: header field is missing !"); } if (Via.GetTopMostValue().Branch == null) { throw new SIP_ParseException("Via: header field branch parameter is missing !"); } if (To == null) { throw new SIP_ParseException("To: header field is missing !"); } if (From == null) { throw new SIP_ParseException("From: header field is missing !"); } if (CallID == null) { throw new SIP_ParseException("CallID: header field is missing !"); } if (CSeq == null) { throw new SIP_ParseException("CSeq: header field is missing !"); } if (MaxForwards == -1) { // We can fix it by setting it to default value 70. MaxForwards = 70; } /* RFC 3261 12.1.2 When a UAC sends a request that can establish a dialog (such as an INVITE) it MUST provide a SIP or SIPS URI with global scope (i.e., the same SIP URI can be used in messages outside this dialog) in the Contact header field of the request. If the request has a Request-URI or a topmost Route header field value with a SIPS URI, the Contact header field MUST contain a SIPS URI. */ if (SIP_Utils.MethodCanEstablishDialog(RequestLine.Method)) { if (Contact.GetAllValues().Length == 0) { throw new SIP_ParseException( "Contact: header field is missing, method that can establish a dialog MUST provide a SIP or SIPS URI !"); } if (Contact.GetAllValues().Length > 1) { throw new SIP_ParseException( "There may be only 1 Contact: header for the method that can establish a dialog !"); } if (!Contact.GetTopMostValue().Address.IsSipOrSipsUri) { throw new SIP_ParseException( "Method that can establish a dialog MUST have SIP or SIPS uri in Contact: header !"); } } // TODO: Invite must have From:/To: tag // TODO: Check that request-Method equals CSeq method // TODO: PRACK must have RAck and RSeq header fields. // TODO: get in transport made request, so check if sips and sip set as needed. } /// <summary> /// Stores SIP_Request to specified stream. /// </summary> /// <param name="stream">Stream where to store.</param> public void ToStream(Stream stream) { // Add request-line byte[] responseLine = Encoding.UTF8.GetBytes(m_pRequestLine.ToString()); stream.Write(responseLine, 0, responseLine.Length); // Add SIP-message InternalToStream(stream); } /// <summary> /// Converts this request to raw srver request data. /// </summary> /// <returns></returns> public byte[] ToByteData() { MemoryStream retVal = new MemoryStream(); ToStream(retVal); return retVal.ToArray(); } /// <summary> /// Returns request as string. /// </summary> /// <returns>Returns request as string.</returns> public override string ToString() { return Encoding.UTF8.GetString(ToByteData()); } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/vCard/EmailAddress.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.Mime.vCard { /// <summary> /// vCard email address implementation. /// </summary> public class EmailAddress { #region Members private readonly Item m_pItem; private string m_EmailAddress = ""; private EmailAddressType_enum m_Type = EmailAddressType_enum.Internet; #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="item">Owner vCard item.</param> /// <param name="type">Email type. Note: This value can be flagged value !</param> /// <param name="emailAddress">Email address.</param> internal EmailAddress(Item item, EmailAddressType_enum type, string emailAddress) { m_pItem = item; m_Type = type; m_EmailAddress = emailAddress; } #endregion #region Properties /// <summary> /// Gets or sets email address. /// </summary> public string Email { get { return m_EmailAddress; } set { m_EmailAddress = value; Changed(); } } /// <summary> /// Gets or sets email type. Note: This property can be flagged value ! /// </summary> public EmailAddressType_enum EmailType { get { return m_Type; } set { m_Type = value; Changed(); } } /// <summary> /// Gets underlaying vCrad item. /// </summary> public Item Item { get { return m_pItem; } } #endregion #region Internal methods /// <summary> /// Parses email address from vCard EMAIL structure string. /// </summary> /// <param name="item">vCard EMAIL item.</param> internal static EmailAddress Parse(Item item) { EmailAddressType_enum type = EmailAddressType_enum.NotSpecified; if (item.ParametersString.ToUpper().IndexOf("PREF") != -1) { type |= EmailAddressType_enum.Preferred; } if (item.ParametersString.ToUpper().IndexOf("INTERNET") != -1) { type |= EmailAddressType_enum.Internet; } if (item.ParametersString.ToUpper().IndexOf("X400") != -1) { type |= EmailAddressType_enum.X400; } return new EmailAddress(item, type, item.DecodedValue); } /// <summary> /// Converts EmailAddressType_enum to vCard item parameters string. /// </summary> /// <param name="type">Value to convert.</param> /// <returns></returns> internal static string EmailTypeToString(EmailAddressType_enum type) { string retVal = ""; if ((type & EmailAddressType_enum.Internet) != 0) { retVal += "INTERNET,"; } if ((type & EmailAddressType_enum.Preferred) != 0) { retVal += "PREF,"; } if ((type & EmailAddressType_enum.X400) != 0) { retVal += "X400,"; } if (retVal.EndsWith(",")) { retVal = retVal.Substring(0, retVal.Length - 1); } return retVal; } #endregion #region Utility methods /// <summary> /// This method is called when some property has changed, wee need to update underlaying vCard item. /// </summary> private void Changed() { m_pItem.ParametersString = EmailTypeToString(m_Type); m_pItem.SetDecodedValue(m_EmailAddress); } #endregion } }<file_sep>/web/studio/ASC.Web.Studio/Products/Community/Modules/Wiki/WikiUC/fckeditor/editor/plugins/ascuser/lang/it.js  FCKLang.AscUserDlgTitle = "Lista degli utenti"; FCKLang.AscUserBtn = "Inserisci/Modifica collegamento all'utente"; FCKLang.AscUserOwnerAlert = "Seleziona un utente."; FCKLang.AscUserSearchLnkName ="Ricerca:"; FCKLang.AscUserList = "Lista degli utenti:";<file_sep>/module/ASC.Api/ASC.Api.Mail/MailApi.Signature.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Linq; using ASC.Api.Attributes; using ASC.Mail.Data.Contracts; // ReSharper disable InconsistentNaming namespace ASC.Api.Mail { public partial class MailApi { /// <summary> /// This method needed for getting mailbox signature. /// </summary> /// <param name="mailbox_id"></param> /// <returns>Signature object</returns> [Read(@"signature/{mailbox_id:[0-9]+}")] public MailSignatureData GetSignature(int mailbox_id) { var accounts = GetAccounts(Username); var account = accounts.FirstOrDefault(a => a.MailboxId == mailbox_id); if (account == null) throw new ArgumentException("Mailbox not found"); return account.Signature; } /// <summary> /// This method needed for update or create signature. /// </summary> /// <param name="mailbox_id">Id of updated mailbox.</param> /// <param name="html">New signature value.</param> /// <param name="is_active">New signature status.</param> [Create(@"signature/update/{mailbox_id:[0-9]+}")] public MailSignatureData UpdateSignature(int mailbox_id, string html, bool is_active) { var accounts = GetAccounts(Username); var account = accounts.FirstOrDefault(a => a.MailboxId == mailbox_id); if (account == null) throw new ArgumentException("Mailbox not found"); return MailEngineFactory.SignatureEngine.SaveSignature(mailbox_id, html, is_active); } } } <file_sep>/module/ASC.Mail/ASC.Mail/Authorization/AuthorizationTracker.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections.Generic; using DotNetOpenAuth.OAuth2; namespace ASC.Mail.Authorization { public class AuthorizationTracker : IClientAuthorizationTracker { private List<string> _scope; public AuthorizationTracker(List<string> scope) { _scope = scope; } public IAuthorizationState GetAuthorizationState( Uri callbackUrl, string clientState) { return new AuthorizationState(_scope) { Callback = callbackUrl }; } } } <file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/SMTP/Server/old/ValidateRecipient_EventArgs.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; namespace LumiSoft.Net.SMTP.Server { /// <summary> /// Provides data for the ValidateMailTo event. /// </summary> public class ValidateRecipient_EventArgs { private SMTP_Session m_pSession = null; private string m_MailTo = ""; private bool m_Validated = true; private bool m_Authenticated = false; private bool m_LocalRecipient = true; /// <summary> /// Default constructor. /// </summary> /// <param name="session">Reference to smtp session.</param> /// <param name="mailTo">Recipient email address.</param> /// <param name="authenticated">Specifies if connected user is authenticated.</param> public ValidateRecipient_EventArgs(SMTP_Session session,string mailTo,bool authenticated) { m_pSession = session; m_MailTo = mailTo; m_Authenticated = authenticated; } #region Properties Implementation /// <summary> /// Gets reference to smtp session. /// </summary> public SMTP_Session Session { get{ return m_pSession; } } /// <summary> /// Recipient's email address. /// </summary> public string MailTo { get{ return m_MailTo; } } /// <summary> /// Gets if connected user is authenticated. /// </summary> public bool Authenticated { get{ return m_Authenticated; } } /// <summary> /// IP address of computer, which is sending mail to here. /// </summary> public string ConnectedIP { get{ return m_pSession.RemoteEndPoint.Address.ToString(); } } /// <summary> /// Gets or sets if reciptient is allowed to send mail here. /// </summary> public bool Validated { get{ return m_Validated; } set{ m_Validated = value; } } /// <summary> /// Gets or sets if recipient is local or needs relay. /// </summary> public bool LocalRecipient { get{ return m_LocalRecipient; } set{ m_LocalRecipient = value; } } #endregion } } <file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/SMTP/Relay/Relay_QueueItem.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.SMTP.Relay { #region usings using System.IO; #endregion /// <summary> /// Thsi class holds Relay_Queue queued item. /// </summary> public class Relay_QueueItem { #region Members private readonly string m_From = ""; private readonly string m_MessageID = ""; private readonly Stream m_pMessageStream; private readonly Relay_Queue m_pQueue; private readonly string m_To = ""; #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="queue">Item owner queue.</param> /// <param name="from">Sender address.</param> /// <param name="to">Target recipient address.</param> /// <param name="messageID">Message ID.</param> /// <param name="message">Raw mime message. Message reading starts from current position.</param> /// <param name="tag">User data.</param> internal Relay_QueueItem(Relay_Queue queue, string from, string to, string messageID, Stream message, object tag) { m_pQueue = queue; m_From = from; m_To = to; m_MessageID = messageID; m_pMessageStream = message; Tag = tag; } #endregion #region Properties /// <summary> /// Gets from address. /// </summary> public string From { get { return m_From; } } /// <summary> /// Gets message ID which is being relayed now. /// </summary> public string MessageID { get { return m_MessageID; } } /// <summary> /// Gets raw mime message which must be relayed. /// </summary> public Stream MessageStream { get { return m_pMessageStream; } } /// <summary> /// Gets this relay item owner queue. /// </summary> public Relay_Queue Queue { get { return m_pQueue; } } /// <summary> /// Gets or sets user data. /// </summary> public object Tag { get; set; } /// <summary> /// Gets target recipient. /// </summary> public string To { get { return m_To; } } #endregion } }<file_sep>/web/studio/ASC.Web.Studio/Products/Projects/Warmup.aspx.cs using System.Collections.Generic; using ASC.Web.Core; namespace ASC.Web.Projects { public partial class Warmup : WarmupPage { protected override List<string> Pages { get { return new List<string>(1) { "Reports.aspx?reportType=0", }; } } protected override List<string> Exclude { get { return new List<string>(1) { "Timer.aspx" }; } } } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/IMAP/Server/IMAP_Folder.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.IMAP.Server { /// <summary> /// IMAP folder. /// </summary> public class IMAP_Folder { #region Members private readonly string m_Folder = ""; private bool m_Selectable = true; #endregion #region Properties /// <summary> /// Gets IMAP folder name. Eg. Inbox, Inbox/myFolder, ... . /// </summary> public string Folder { get { return m_Folder; } } /// <summary> /// Gets or sets if folder is selectable (SELECT command can select this folder). /// </summary> public bool Selectable { get { return m_Selectable; } set { m_Selectable = value; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="folder">Full path to folder, path separator = '/'. Eg. Inbox/myFolder .</param> /// <param name="selectable">Gets or sets if folder is selectable(SELECT command can select this folder).</param> public IMAP_Folder(string folder, bool selectable) { m_Folder = folder; m_Selectable = selectable; } #endregion } }<file_sep>/module/ASC.Thrdparty/ASC.Thrdparty/Twitter/TwitterDataProvider.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text.RegularExpressions; using ASC.Common.Logging; using DotNetOpenAuth.OAuth; namespace ASC.Thrdparty.Twitter { /// <summary> /// Contains methods for getting data from Twitter /// </summary> public class TwitterDataProvider { private static WebConsumer _signInConsumer; private static readonly object SignInConsumerInitLock = new object(); private WebConsumer TwitterSignIn { get { if (_signInConsumer != null) return _signInConsumer; lock (SignInConsumerInitLock) { if (_signInConsumer == null) { var tokenManagerHolder = new InMemoryTokenManager(_apiInfo.ConsumerKey, _apiInfo.ConsumerSecret); return _signInConsumer = new WebConsumer(TwitterConsumer.SignInWithTwitterServiceDescription, tokenManagerHolder); } } return _signInConsumer; } } private readonly TwitterApiInfo _apiInfo; public enum ImageSize { Small, Original } /// <summary> /// Costructor /// </summary> /// <param name="apiInfo">TwitterApiInfo object</param> public TwitterDataProvider(TwitterApiInfo apiInfo) { if (apiInfo == null) throw new ArgumentNullException("apiInfo"); _apiInfo = apiInfo; try { TwitterSignIn.TokenManager.ExpireRequestTokenAndStoreNewAccessToken( apiInfo.ConsumerKey, String.Empty, apiInfo.AccessToken, apiInfo.AccessTokenSecret); } catch (Exception ex) { LogManager.GetLogger(typeof(TwitterDataProvider).ToString()).Error("TwitterSignIn in TwitterDataProvider", ex); } } private static String ParseTweetTextIntoHtml(String text) { text = Regex.Replace(text, "(https?://([-\\w\\.]+)+(/([\\w/_\\.]*(\\?\\S+)?(#\\S+)?)?)?)", "<a href='$1'>$1</a>"); text = Regex.Replace(text, "@(\\w+)", "<a href='https://twitter.com/$1'>@$1</a>"); text = Regex.Replace(text, "\\s#(\\w+)", "<a href='https://twitter.com/search?q=%23$1&src=hash'>#$1</a>"); return text; } private static DateTime ParseTweetDateTime(String dateTimeAsText) { var month = dateTimeAsText.Substring(4, 3).Trim(); var dayInMonth = dateTimeAsText.Substring(8, 2).Trim(); var time = dateTimeAsText.Substring(11, 9).Trim(); var year = dateTimeAsText.Substring(25, 5).Trim(); var dateTime = string.Format("{0}-{1}-{2} {3}", dayInMonth, month, year, time); return DateTime.Parse(dateTime, CultureInfo.InvariantCulture); } /// <summary> /// Gets tweets posted by specified user /// </summary> /// <returns>Message list</returns> public List<Message> GetUserTweets(decimal? userID, string screenName, int messageCount) { var localUserId = 0; if (userID.HasValue) localUserId = (int)userID.Value; var userTimeLine = TwitterConsumer.GetUserTimeLine(TwitterSignIn, _apiInfo.AccessToken, localUserId, screenName, true, messageCount); if (userTimeLine == null) return new List<Message>(); return userTimeLine.Select(x => (Message)(new TwitterMessage { UserName = x["user"].Value<String>("name"), PostedOn = ParseTweetDateTime(x.Value<String>("created_at")), Source = SocialNetworks.Twitter, Text = ParseTweetTextIntoHtml(x.Value<String>("text")), UserImageUrl = x["user"].Value<String>("profile_image_url"), UserId = screenName })).Take(20).ToList(); } /// <summary> /// Gets last 20 users /// </summary> /// <param name="search">Search string</param> /// <returns>TwitterUserInfo list</returns> public List<TwitterUserInfo> FindUsers(string search) { var findedUsers = TwitterConsumer.SearchUsers(TwitterSignIn, search, _apiInfo.AccessToken); if (findedUsers == null) return new List<TwitterUserInfo>(); return findedUsers.Select(x => new TwitterUserInfo { UserID = x.Value<Decimal>("id"), Description = x.Value<String>("description"), ScreenName = x.Value<String>("screen_name"), SmallImageUrl = x.Value<String>("profile_image_url"), UserName = x.Value<String>("name") }).Take(20).ToList(); } /// <summary> /// Gets url of User image /// </summary> /// <returns>Url of image or null if resource does not exist</returns> public string GetUrlOfUserImage(string userScreenName, ImageSize imageSize) { var userInfo = TwitterConsumer.GetUserInfo(TwitterSignIn, 0, userScreenName, _apiInfo.AccessToken); if (userInfo == null) return null; var profileImageUrl = userInfo.Value<String>("profile_image_url"); var size = GetTwitterImageSizeText(imageSize); if (size == "original") profileImageUrl = profileImageUrl.Replace("_normal", String.Empty); return profileImageUrl; } private static string GetTwitterImageSizeText(ImageSize imageSize) { var result = "original"; if (imageSize == ImageSize.Small) result = "normal"; return result; } } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/DNS/Client/DnsCache.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.Dns.Client { #region usings using System; using System.Collections; using System.IO; using System.Runtime.Serialization.Formatters.Binary; #endregion #region struct CacheEntry /// <summary> /// Dns cache entry. /// </summary> [Serializable] internal struct DnsCacheEntry { #region Members private readonly DnsServerResponse m_pResponse; private readonly DateTime m_Time; #endregion #region Properties /// <summary> /// Gets dns answers. /// </summary> public DnsServerResponse Answers { get { return m_pResponse; } } /// <summary> /// Gets entry add time. /// </summary> public DateTime Time { get { return m_Time; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="answers">Dns answers.</param> /// <param name="addTime">Entry add time.</param> public DnsCacheEntry(DnsServerResponse answers, DateTime addTime) { m_pResponse = answers; m_Time = addTime; } #endregion } #endregion /// <summary> /// This class implements dns query cache. /// </summary> public class DnsCache { #region Members private static long m_CacheTime = 10000; private static Hashtable m_pCache; #endregion #region Properties /// <summary> /// Gets or sets how long(seconds) to cache dns query. /// </summary> public static long CacheTime { get { return m_CacheTime; } set { m_CacheTime = value; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> static DnsCache() { m_pCache = new Hashtable(); } #endregion #region Methods /// <summary> /// Tries to get dns records from cache, if any. /// </summary> /// <param name="qname"></param> /// <param name="qtype"></param> /// <returns>Returns null if not in cache.</returns> public static DnsServerResponse GetFromCache(string qname, int qtype) { try { if (m_pCache.Contains(qname + qtype)) { DnsCacheEntry entry = (DnsCacheEntry) m_pCache[qname + qtype]; // If cache object isn't expired if (entry.Time.AddSeconds(m_CacheTime) > DateTime.Now) { return entry.Answers; } } } catch {} return null; } /// <summary> /// Adds dns records to cache. If old entry exists, it is replaced. /// </summary> /// <param name="qname"></param> /// <param name="qtype"></param> /// <param name="answers"></param> public static void AddToCache(string qname, int qtype, DnsServerResponse answers) { if (answers == null) { return; } try { lock (m_pCache) { // Remove old cache entry, if any. if (m_pCache.Contains(qname + qtype)) { m_pCache.Remove(qname + qtype); } m_pCache.Add(qname + qtype, new DnsCacheEntry(answers, DateTime.Now)); } } catch {} } /// <summary> /// Clears DNS cache. /// </summary> public static void ClearCache() { lock (m_pCache) { m_pCache.Clear(); } } /// <summary> /// Serializes current cache. /// </summary> /// <returns>Return serialized cache.</returns> public static byte[] SerializeCache() { lock (m_pCache) { MemoryStream retVal = new MemoryStream(); BinaryFormatter b = new BinaryFormatter(); b.Serialize(retVal, m_pCache); return retVal.ToArray(); } } /// <summary> /// DeSerializes stored cache. /// </summary> /// <param name="cacheData">This value must be DnsCache.SerializeCache() method value.</param> public static void DeSerializeCache(byte[] cacheData) { lock (m_pCache) { MemoryStream retVal = new MemoryStream(cacheData); BinaryFormatter b = new BinaryFormatter(); m_pCache = (Hashtable) b.Deserialize(retVal); } } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/SIP/Stack/SIP_Dialog.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.SIP.Stack { #region usings using System; using Message; #endregion /// <summary> /// This class is base class for SIP dialogs. Defined in RFC 3261 12. /// </summary> public class SIP_Dialog { #region Events /// <summary> /// This event is raised when Dialog state has changed. /// </summary> public event EventHandler StateChanged = null; /// <summary> /// This event is raised when remote-party terminates dialog with BYE request. /// </summary> /// <remarks>This event is useful only if the application is interested in processing the headers in the BYE message.</remarks> public event EventHandler<SIP_RequestReceivedEventArgs> TerminatedByRemoteParty = null; #endregion #region Members private readonly DateTime m_CreateTime; private string m_CallID = ""; private bool m_IsSecure; private bool m_IsTerminatedByRemoteParty; private int m_LocalSeqNo; private string m_LocalTag = ""; private SIP_Flow m_pFlow; private SIP_Uri m_pLocalContact; private AbsoluteUri m_pLocalUri; private object m_pLock = new object(); private SIP_Uri m_pRemoteTarget; private AbsoluteUri m_pRemoteUri; private SIP_t_AddressParam[] m_pRouteSet; private SIP_Stack m_pStack; private int m_RemoteSeqNo; private string m_RemoteTag = ""; private SIP_DialogState m_State = SIP_DialogState.Early; #endregion #region Properties /// <summary> /// Gets an object that can be used to synchronize access to the dialog. /// </summary> public object SyncRoot { get { return m_pLock; } } /// <summary> /// Gets dialog state. /// </summary> public SIP_DialogState State { get { return m_State; } } /// <summary> /// Gets owner stack. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public SIP_Stack Stack { get { if (State == SIP_DialogState.Disposed) { throw new ObjectDisposedException(GetType().Name); } return m_pStack; } } /// <summary> /// Gets dialog creation time. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public DateTime CreateTime { get { if (State == SIP_DialogState.Disposed) { throw new ObjectDisposedException(GetType().Name); } return m_CreateTime; } } /// <summary> /// Gets dialog ID. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public string ID { get { if (State == SIP_DialogState.Disposed) { throw new ObjectDisposedException(GetType().Name); } return CallID + "-" + LocalTag + "-" + RemoteTag; } } /// <summary> /// Get call ID. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public string CallID { get { if (State == SIP_DialogState.Disposed) { throw new ObjectDisposedException(GetType().Name); } return m_CallID; } } /// <summary> /// Gets local-tag. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public string LocalTag { get { if (State == SIP_DialogState.Disposed) { throw new ObjectDisposedException(GetType().Name); } return m_LocalTag; } } /// <summary> /// Gets remote-tag. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public string RemoteTag { get { if (State == SIP_DialogState.Disposed) { throw new ObjectDisposedException(GetType().Name); } return m_RemoteTag; } } /// <summary> /// Gets local sequence number. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public int LocalSeqNo { get { if (State == SIP_DialogState.Disposed) { throw new ObjectDisposedException(GetType().Name); } return m_LocalSeqNo; } } /// <summary> /// Gets remote sequence number. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public int RemoteSeqNo { get { if (State == SIP_DialogState.Disposed) { throw new ObjectDisposedException(GetType().Name); } return m_RemoteSeqNo; } } /// <summary> /// Gets local URI. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public AbsoluteUri LocalUri { get { if (State == SIP_DialogState.Disposed) { throw new ObjectDisposedException(GetType().Name); } return m_pLocalUri; } } /// <summary> /// Gets remote URI. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public AbsoluteUri RemoteUri { get { if (State == SIP_DialogState.Disposed) { throw new ObjectDisposedException(GetType().Name); } return m_pRemoteUri; } } /// <summary> /// Gets local contact URI. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public SIP_Uri LocalContact { get { if (State == SIP_DialogState.Disposed) { throw new ObjectDisposedException(GetType().Name); } return m_pLocalContact; } } /// <summary> /// Gets remote target URI. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public SIP_Uri RemoteTarget { get { if (State == SIP_DialogState.Disposed) { throw new ObjectDisposedException(GetType().Name); } return m_pRemoteTarget; } } /// <summary> /// Gets if dialog uses secure transport. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public bool IsSecure { get { if (State == SIP_DialogState.Disposed) { throw new ObjectDisposedException(GetType().Name); } return m_IsSecure; } } /// <summary> /// Gets route set. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public SIP_t_AddressParam[] RouteSet { get { if (State == SIP_DialogState.Disposed) { throw new ObjectDisposedException(GetType().Name); } return m_pRouteSet; } } /// <summary> /// Gets if dialog was terminated by remote-party. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public bool IsTerminatedByRemoteParty { get { if (State == SIP_DialogState.Disposed) { throw new ObjectDisposedException(GetType().Name); } return m_IsTerminatedByRemoteParty; } } /// <summary> /// Gets data flow used to send or receive last SIP message. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public SIP_Flow Flow { get { if (State == SIP_DialogState.Disposed) { throw new ObjectDisposedException(GetType().Name); } return m_pFlow; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> public SIP_Dialog() { m_CreateTime = DateTime.Now; m_pRouteSet = new SIP_t_AddressParam[0]; } #endregion #region Methods /// <summary> /// Cleans up any resources being used. /// </summary> public virtual void Dispose() { lock (m_pLock) { if (State == SIP_DialogState.Disposed) { return; } SetState(SIP_DialogState.Disposed, true); m_pStack = null; m_CallID = null; m_LocalTag = null; m_RemoteTag = null; m_pLocalUri = null; m_pRemoteUri = null; m_pLocalContact = null; m_pRemoteTarget = null; m_pRouteSet = null; m_pFlow = null; m_pLock = null; } } /// <summary> /// Terminates dialog. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this method is accessed.</exception> public void Terminate() { Terminate(null, true); } /// <summary> /// Terminates dialog. /// </summary> /// <param name="reason">Termination reason. This value may be null.</param> /// <param name="sendBye">If true BYE is sent to remote party.</param> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this method is accessed.</exception> public virtual void Terminate(string reason, bool sendBye) { lock (m_pLock) { if (State == SIP_DialogState.Disposed) { throw new ObjectDisposedException(GetType().Name); } if (State == SIP_DialogState.Terminating || State == SIP_DialogState.Terminated) { return; } /* RFC 3261 15. The caller's UA MAY send a BYE for either confirmed or early dialogs, and the callee's UA MAY send a BYE on confirmed dialogs, but MUST NOT send a BYE on early dialogs. RFC 3261 15.1. Once the BYE is constructed, the UAC core creates a new non-INVITE client transaction, and passes it the BYE request. The UAC MUST consider the session terminated (and therefore stop sending or listening for media) as soon as the BYE request is passed to the client transaction. If the response for the BYE is a 481 (Call/Transaction Does Not Exist) or a 408 (Request Timeout) or no response at all is received for the BYE (that is, a timeout is returned by the client transaction), the UAC MUST consider the session and the dialog terminated. */ SetState(SIP_DialogState.Terminating, true); if (sendBye) { // TODO: UAS early if (State == SIP_DialogState.Confirmed) { SIP_Request bye = CreateRequest(SIP_Methods.BYE); if (!string.IsNullOrEmpty(reason)) { SIP_t_ReasonValue r = new SIP_t_ReasonValue(); r.Protocol = "SIP"; r.Text = reason; bye.Reason.Add(r.ToStringValue()); } // Send BYE, just wait BYE to complete, we don't care about response code. SIP_RequestSender sender = CreateRequestSender(bye); sender.Completed += delegate { SetState(SIP_DialogState.Terminated, true); }; sender.Start(); } } else { SetState(SIP_DialogState.Terminated, true); } } } /// <summary> /// Creates new SIP request using this dialog info. /// </summary> /// <param name="method">SIP method.</param> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this method is accessed.</exception> /// <exception cref="ArgumentNullException">Is raised when <b>method</b> is null reference.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> /// <returns>Returns created request.</returns> public SIP_Request CreateRequest(string method) { if (State == SIP_DialogState.Disposed) { throw new ObjectDisposedException(GetType().Name); } if (method == null) { throw new ArgumentNullException("method"); } if (method == string.Empty) { throw new ArgumentException("Argument 'method' value must be specified."); } /* RFC 3261 172.16.17.32. A request within a dialog is constructed by using many of the components of the state stored as part of the dialog. The URI in the To field of the request MUST be set to the remote URI from the dialog state. The tag in the To header field of the request MUST be set to the remote tag of the dialog ID. The From URI of the request MUST be set to the local URI from the dialog state. The tag in the From header field of the request MUST be set to the local tag of the dialog ID. If the value of the remote or local tags is null, the tag parameter MUST be omitted from the To or From header fields, respectively. The Call-ID of the request MUST be set to the Call-ID of the dialog. Requests within a dialog MUST contain strictly monotonically increasing and contiguous CSeq sequence numbers (increasing-by-one) in each direction (excepting ACK and CANCEL of course, whose numbers equal the requests being acknowledged or cancelled). Therefore, if the local sequence number is not empty, the value of the local sequence number MUST be incremented by one, and this value MUST be placed into the CSeq header field. If the local sequence number is empty, an initial value MUST be chosen using the guidelines of Section 8.1.1.5. The method field in the CSeq header field value MUST match the method of the request. With a length of 32 bits, a client could generate, within a single call, one request a second for about 136 years before needing to wrap around. The initial value of the sequence number is chosen so that subsequent requests within the same call will not wrap around. A non-zero initial value allows clients to use a time- based initial sequence number. A client could, for example, choose the 31 most significant bits of a 32-bit second clock as an initial sequence number. The UAC uses the remote target and route set to build the Request-URI and Route header field of the request. If the route set is empty, the UAC MUST place the remote target URI into the Request-URI. The UAC MUST NOT add a Route header field to the request. If the route set is not empty, and the first URI in the route set contains the lr parameter (see Section 19.1.1), the UAC MUST place the remote target URI into the Request-URI and MUST include a Route header field containing the route set values in order, including all parameters. If the route set is not empty, and its first URI does not contain the lr parameter, the UAC MUST place the first URI from the route set into the Request-URI, stripping any parameters that are not allowed in a Request-URI. The UAC MUST add a Route header field containing the remainder of the route set values in order, including all parameters. The UAC MUST then place the remote target URI into the Route header field as the last value. For example, if the remote target is sip:user@remoteua and the route set contains: <sip:proxy1>,<sip:proxy2>,<sip:proxy3;lr>,<sip:proxy4> The request will be formed with the following Request-URI and Route header field: METHOD sip:proxy1 Route: <sip:proxy2>,<sip:proxy3;lr>,<sip:proxy4>,<sip:user@remoteua> If the first URI of the route set does not contain the lr parameter, the proxy indicated does not understand the routing mechanisms described in this document and will act as specified in RFC 2543, replacing the Request-URI with the first Route header field value it receives while forwarding the message. Placing the Request-URI at the end of the Route header field preserves the information in that Request-URI across the strict router (it will be returned to the Request-URI when the request reaches a loose- router). A UAC SHOULD include a Contact header field in any target refresh requests within a dialog, and unless there is a need to change it, the URI SHOULD be the same as used in previous requests within the dialog. If the "secure" flag is true, that URI MUST be a SIPS URI. As discussed in Section 12.2.2, a Contact header field in a target refresh request updates the remote target URI. This allows a UA to provide a new contact address, should its address change during the duration of the dialog. However, requests that are not target refresh requests do not affect the remote target URI for the dialog. The rest of the request is formed as described in Section 8.1.1. */ lock (m_pLock) { SIP_Request request = m_pStack.CreateRequest(method, new SIP_t_NameAddress("", m_pRemoteUri), new SIP_t_NameAddress("", m_pLocalUri)); if (m_pRouteSet.Length == 0) { request.RequestLine.Uri = m_pRemoteTarget; } else { SIP_Uri topmostRoute = ((SIP_Uri) m_pRouteSet[0].Address.Uri); if (topmostRoute.Param_Lr) { request.RequestLine.Uri = m_pRemoteTarget; for (int i = 0; i < m_pRouteSet.Length; i++) { request.Route.Add(m_pRouteSet[i].ToStringValue()); } } else { request.RequestLine.Uri = SIP_Utils.UriToRequestUri(topmostRoute); for (int i = 1; i < m_pRouteSet.Length; i++) { request.Route.Add(m_pRouteSet[i].ToStringValue()); } } } request.To.Tag = m_RemoteTag; request.From.Tag = m_LocalTag; request.CallID = m_CallID; request.CSeq.SequenceNumber = ++m_LocalSeqNo; request.Contact.Add(m_pLocalContact.ToString()); return request; } } /// <summary> /// Creates SIP request sender for the specified request. /// </summary> /// <remarks>All requests sent through this dialog SHOULD use this request sender to send out requests.</remarks> /// <param name="request">SIP request.</param> /// <returns>Returns created sender.</returns> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this method is accessed.</exception> /// <exception cref="ArgumentNullException">Is raised when <b>request</b> is null.</exception> public SIP_RequestSender CreateRequestSender(SIP_Request request) { lock (m_pLock) { if (State == SIP_DialogState.Terminated) { throw new ObjectDisposedException(GetType().Name); } if (request == null) { throw new ArgumentNullException("request"); } SIP_RequestSender sender = m_pStack.CreateRequestSender(request, Flow); return sender; } } #endregion #region Virtual methods /// <summary> /// Initializes dialog. /// </summary> /// <param name="stack">Owner stack.</param> /// <param name="transaction">Owner transaction.</param> /// <param name="response">SIP response what caused dialog creation.</param> /// <exception cref="ArgumentNullException">Is raised when <b>stack</b>,<b>transaction</b> or <b>response</b>.</exception> protected internal virtual void Init(SIP_Stack stack, SIP_Transaction transaction, SIP_Response response) { if (stack == null) { throw new ArgumentNullException("stack"); } if (transaction == null) { throw new ArgumentNullException("transaction"); } if (response == null) { throw new ArgumentNullException("response"); } m_pStack = stack; #region UAS /* RFC 3261 12.1.1. The UAS then constructs the state of the dialog. This state MUST be maintained for the duration of the dialog. If the request arrived over TLS, and the Request-URI contained a SIPS URI, the "secure" flag is set to TRUE. The route set MUST be set to the list of URIs in the Record-Route header field from the request, taken in order and preserving all URI parameters. If no Record-Route header field is present in the request, the route set MUST be set to the empty set. This route set, even if empty, overrides any pre-existing route set for future requests in this dialog. The remote target MUST be set to the URI from the Contact header field of the request. The remote sequence number MUST be set to the value of the sequence number in the CSeq header field of the request. The local sequence number MUST be empty. The call identifier component of the dialog ID MUST be set to the value of the Call-ID in the request. The local tag component of the dialog ID MUST be set to the tag in the To field in the response to the request (which always includes a tag), and the remote tag component of the dialog ID MUST be set to the tag from the From field in the request. A UAS MUST be prepared to receive a request without a tag in the From field, in which case the tag is considered to have a value of null. This is to maintain backwards compatibility with RFC 2543, which did not mandate From tags. The remote URI MUST be set to the URI in the From field, and the local URI MUST be set to the URI in the To field. */ if (transaction is SIP_ServerTransaction) { // TODO: Validate request or client transaction must do it ? m_IsSecure = ((SIP_Uri) transaction.Request.RequestLine.Uri).IsSecure; m_pRouteSet = (SIP_t_AddressParam[]) Core.ReverseArray(transaction.Request.RecordRoute.GetAllValues()); m_pRemoteTarget = (SIP_Uri) transaction.Request.Contact.GetTopMostValue().Address.Uri; m_RemoteSeqNo = transaction.Request.CSeq.SequenceNumber; m_LocalSeqNo = 0; m_CallID = transaction.Request.CallID; m_LocalTag = response.To.Tag; m_RemoteTag = transaction.Request.From.Tag; m_pRemoteUri = transaction.Request.From.Address.Uri; m_pLocalUri = transaction.Request.To.Address.Uri; m_pLocalContact = (SIP_Uri) response.Contact.GetTopMostValue().Address.Uri; } #endregion #region UAC /* RFC 3261 12.1.2. When a UAC receives a response that establishes a dialog, it constructs the state of the dialog. This state MUST be maintained for the duration of the dialog. If the request was sent over TLS, and the Request-URI contained a SIPS URI, the "secure" flag is set to TRUE. The route set MUST be set to the list of URIs in the Record-Route header field from the response, taken in reverse order and preserving all URI parameters. If no Record-Route header field is present in the response, the route set MUST be set to the empty set. This route set, even if empty, overrides any pre-existing route set for future requests in this dialog. The remote target MUST be set to the URI from the Contact header field of the response. The local sequence number MUST be set to the value of the sequence number in the CSeq header field of the request. The remote sequence number MUST be empty (it is established when the remote UA sends a request within the dialog). The call identifier component of the dialog ID MUST be set to the value of the Call-ID in the request. The local tag component of the dialog ID MUST be set to the tag in the From field in the request, and the remote tag component of the dialog ID MUST be set to the tag in the To field of the response. A UAC MUST be prepared to receive a response without a tag in the To field, in which case the tag is considered to have a value of null. This is to maintain backwards compatibility with RFC 2543, which did not mandate To tags. The remote URI MUST be set to the URI in the To field, and the local URI MUST be set to the URI in the From field. */ else { // TODO: Validate request or client transaction must do it ? m_IsSecure = ((SIP_Uri) transaction.Request.RequestLine.Uri).IsSecure; m_pRouteSet = (SIP_t_AddressParam[]) Core.ReverseArray(response.RecordRoute.GetAllValues()); m_pRemoteTarget = (SIP_Uri) response.Contact.GetTopMostValue().Address.Uri; m_LocalSeqNo = transaction.Request.CSeq.SequenceNumber; m_RemoteSeqNo = 0; m_CallID = transaction.Request.CallID; m_LocalTag = transaction.Request.From.Tag; m_RemoteTag = response.To.Tag; m_pRemoteUri = transaction.Request.To.Address.Uri; m_pLocalUri = transaction.Request.From.Address.Uri; m_pLocalContact = (SIP_Uri) transaction.Request.Contact.GetTopMostValue().Address.Uri; } #endregion m_pFlow = transaction.Flow; } /// <summary> /// Processes specified request through this dialog. /// </summary> /// <param name="e">Method arguments.</param> /// <returns>Returns true if this dialog processed specified response, otherwise false.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>e</b> is null reference.</exception> protected internal virtual bool ProcessRequest(SIP_RequestReceivedEventArgs e) { if (e == null) { throw new ArgumentNullException("e"); } if (e.Request.RequestLine.Method == SIP_Methods.BYE) { e.ServerTransaction.SendResponse(m_pStack.CreateResponse(SIP_ResponseCodes.x200_Ok, e.Request)); m_IsTerminatedByRemoteParty = true; OnTerminatedByRemoteParty(e); SetState(SIP_DialogState.Terminated, true); return true; } return false; } /// <summary> /// Processes specified response through this dialog. /// </summary> /// <param name="response">SIP response to process.</param> /// <returns>Returns true if this dialog processed specified response, otherwise false.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>response</b> is null.</exception> protected internal virtual bool ProcessResponse(SIP_Response response) { if (response == null) { throw new ArgumentNullException("response"); } return false; } #endregion #region Utility methods /// <summary> /// Raises <b>StateChanged</b> event. /// </summary> private void OnStateChanged() { if (StateChanged != null) { StateChanged(this, new EventArgs()); } } /// <summary> /// Raises <b>TerminatedByRemoteParty</b> event. /// </summary> /// <param name="bye">BYE request.</param> private void OnTerminatedByRemoteParty(SIP_RequestReceivedEventArgs bye) { if (TerminatedByRemoteParty != null) { TerminatedByRemoteParty(this, bye); } } #endregion /// <summary> /// Gets if sepcified request method is target-refresh method. /// </summary> /// <param name="method">SIP request method.</param> /// <returns>Returns true if specified method is target-refresh method.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>method</b> is null reference.</exception> protected bool IsTargetRefresh(string method) { if (method == null) { throw new ArgumentNullException("method"); } method = method.ToUpper(); // RFC 5057 5.4. Target Refresh Requests. if (method == SIP_Methods.INVITE) { return true; } else if (method == SIP_Methods.UPDATE) { return true; } else if (method == SIP_Methods.SUBSCRIBE) { return true; } else if (method == SIP_Methods.NOTIFY) { return true; } else if (method == SIP_Methods.REFER) { return true; } return false; } /// <summary> /// Sets dialog state. /// </summary> /// <param name="state">New dialog state,</param> /// <param name="raiseEvent">If true, StateChanged event is raised after state change.</param> protected void SetState(SIP_DialogState state, bool raiseEvent) { m_State = state; if (raiseEvent) { OnStateChanged(); } if (m_State == SIP_DialogState.Terminated) { Dispose(); } } } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/Mail/Mail_t_Address.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.Mail { #region usings using MIME; #endregion /// <summary> /// This class represents RFC 5322 3.4 Address class. /// This class is base class for <see cref="Mail_t_Mailbox">mailbox address</see> and <see cref="Mail_t_Group">group address</see>. /// </summary> public abstract class Mail_t_Address { #region Methods /// <summary> /// Returns address as string value. /// </summary> /// <param name="wordEncoder">8-bit words ecnoder. Value null means that words are not encoded.</param> /// <returns>Returns address as string value.</returns> public abstract string ToString(MIME_Encoding_EncodedWord wordEncoder); #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/HostEndPoint.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net { #region usings using System; using System.Net; #endregion /// <summary> /// Represents a network endpoint as an host(name or IP address) and a port number. /// </summary> public class HostEndPoint { #region Members private readonly string m_Host = ""; private readonly int m_Port; #endregion #region Properties /// <summary> /// Gets if <b>Host</b> is IP address. /// </summary> public bool IsIPAddress { get { return Net_Utils.IsIPAddress(m_Host); } } /// <summary> /// Gets host name or IP address. /// </summary> public string Host { get { return m_Host; } } /// <summary> /// Gets the port number of the endpoint. Value -1 means port not specified. /// </summary> public int Port { get { return m_Port; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="host">Host name or IP address.</param> /// <param name="port">The port number associated with the host. Value -1 means port not specified.</param> /// <exception cref="ArgumentNullException">Is raised when <b>host</b> is null.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> public HostEndPoint(string host, int port) { if (host == null) { throw new ArgumentNullException("host"); } if (host == "") { throw new ArgumentException("Argument 'host' value must be specified."); } m_Host = host; m_Port = port; } /// <summary> /// Default constructor. /// </summary> /// <param name="endPoint">Host IP end point.</param> /// <exception cref="ArgumentNullException">Is raised when <b>endPoint</b> is null reference.</exception> public HostEndPoint(IPEndPoint endPoint) { if (endPoint == null) { throw new ArgumentNullException("endPoint"); } m_Host = endPoint.Address.ToString(); m_Port = endPoint.Port; } #endregion #region Methods /// <summary> /// Parses HostEndPoint from the specified string. /// </summary> /// <param name="value">HostEndPoint value.</param> /// <returns>Returns parsed HostEndPoint value.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>value</b> is null.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> public static HostEndPoint Parse(string value) { return Parse(value, -1); } /// <summary> /// Parses HostEndPoint from the specified string. /// </summary> /// <param name="value">HostEndPoint value.</param> /// <param name="defaultPort">If port isn't specified in value, specified port will be used.</param> /// <returns>Returns parsed HostEndPoint value.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>value</b> is null.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> public static HostEndPoint Parse(string value, int defaultPort) { if (value == null) { throw new ArgumentNullException("value"); } if (value == "") { throw new ArgumentException("Argument 'value' value must be specified."); } // We have IP address without a port. try { IPAddress.Parse(value); return new HostEndPoint(value, defaultPort); } catch { // We have host name with port. if (value.IndexOf(':') > -1) { string[] host_port = value.Split(new[] {':'}, 2); try { return new HostEndPoint(host_port[0], Convert.ToInt32(host_port[1])); } catch { throw new ArgumentException("Argument 'value' has invalid value."); } } // We have host name without port. else { return new HostEndPoint(value, defaultPort); } } } /// <summary> /// Returns HostEndPoint as string. /// </summary> /// <returns>Returns HostEndPoint as string.</returns> public override string ToString() { if (m_Port == -1) { return m_Host; } else { return m_Host + ":" + m_Port; } } #endregion } }<file_sep>/module/ASC.AuditTrail/Mappers/OthersActionMapper.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System.Collections.Generic; using ASC.MessagingSystem; namespace ASC.AuditTrail.Mappers { internal class OthersActionsMapper { public static Dictionary<MessageAction, MessageMaps> GetMaps() { return new Dictionary<MessageAction, MessageMaps> { { MessageAction.ContactAdminMailSent, new MessageMaps { ActionTypeTextResourceName = "SendActionType", ActionTextResourceName = "ContactAdminMailSent", ProductResourceName = "OthersProduct" } } }; } } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/NNTP/Client/NNTP_Client.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.NNTP.Client { #region usings using System; using System.Collections.Generic; using System.IO; using TCP; #endregion /// <summary> /// NNTP client. Defined in RFC 977. /// </summary> public class NNTP_Client : TCP_Client { #region Methods /// <summary> /// Closes connection to NNTP server. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when NNTP client is not connected.</exception> public override void Disconnect() { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (!IsConnected) { throw new InvalidOperationException("NNTP client is not connected."); } try { // Send QUIT command to server. WriteLine("QUIT"); } catch {} try { base.Disconnect(); } catch {} } /// <summary> /// Gets NNTP newsgoups. /// </summary> /// <returns></returns> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when NNTP client is not connected.</exception> public string[] GetNewsGroups() { /* RFC 977 3.6.1. LIST Returns a list of valid newsgroups and associated information. Each newsgroup is sent as a line of text in the following format: group last first p where <group> is the name of the newsgroup, <last> is the number of the last known article currently in that newsgroup, <first> is the number of the first article currently in the newsgroup, and <p> is either 'y' or 'n' indicating whether posting to this newsgroup is allowed ('y') or prohibited ('n'). The <first> and <last> fields will always be numeric. They may have leading zeros. If the <last> field evaluates to less than the <first> field, there are no articles currently on file in the newsgroup. Example: C: LIST S: 215 list of newsgroups follows S: net.wombats 00543 00501 y S: net.unix-wizards 10125 10011 y S: . */ if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (!IsConnected) { throw new InvalidOperationException("NNTP client is not connected."); } // Send LIST command WriteLine("LIST"); // Read server response string responseLine = ReadLine(); if (!responseLine.StartsWith("215")) { throw new Exception(responseLine); } List<string> newsGroups = new List<string>(); responseLine = ReadLine(); while (responseLine != ".") { newsGroups.Add(responseLine.Split(' ')[0]); responseLine = ReadLine(); } return newsGroups.ToArray(); } /// <summary> /// Posts specified message to the specified newsgroup. /// </summary> /// <param name="newsgroup">Newsgroup where to post message.</param> /// <param name="message">Message to post. Message is taken from stream current position.</param> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when NNTP client is not connected.</exception> public void PostMessage(string newsgroup, Stream message) { /* RFC 977 3.10.1. POST If posting is allowed, response code 340 is returned to indicate that the article to be posted should be sent. Response code 440 indicates that posting is prohibited for some installation-dependent reason. If posting is permitted, the article should be presented in the format specified by RFC850, and should include all required header lines. After the article's header and body have been completely sent by the client to the server, a further response code will be returned to indicate success or failure of the posting attempt. The text forming the header and body of the message to be posted should be sent by the client using the conventions for text received from the news server: A single period (".") on a line indicates the end of the text, with lines starting with a period in the original text having that period doubled during transmission. No attempt shall be made by the server to filter characters, fold or limit lines, or otherwise process incoming text. It is our intent that the server just pass the incoming message to be posted to the server installation's news posting software, which is separate from this specification. See RFC850 for more details. Example: C: POST S: 340 Continue posting; Period on a line by itself to end C: (transmits news article in RFC850 format) C: . S: 240 Article posted successfully. */ if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (!IsConnected) { throw new InvalidOperationException("NNTP client is not connected."); } // Send POST command WriteLine("POST"); // Read server response string responseLine = ReadLine(); if (!responseLine.StartsWith("340")) { throw new Exception(responseLine); } // POST message TcpStream.WritePeriodTerminated(message); // Read server response responseLine = ReadLine(); if (!responseLine.StartsWith("240")) { throw new Exception(responseLine); } } #endregion #region Overrides /// <summary> /// This method is called after TCP client has sucessfully connected. /// </summary> protected override void OnConnected() { // Read first line of reply, check if it's ok. string responseLine = ReadLine(); if (!responseLine.StartsWith("200")) { throw new Exception(responseLine); } } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/Mail/Mail_Utils.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.Mail { #region usings using System; using System.Text; using MIME; #endregion /// <summary> /// This class provides mail message related utility methods. /// </summary> public class Mail_Utils { #region Internal methods /// <summary> /// Reads SMTP "Mailbox" from the specified MIME reader. /// </summary> /// <param name="reader">MIME reader.</param> /// <returns>Returns SMTP "Mailbox" or null if no SMTP mailbox available.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>reader</b> is null reference.</exception> internal static string SMTP_Mailbox(MIME_Reader reader) { if (reader == null) { throw new ArgumentNullException("reader"); } // TODO: /* RFC 5321. Mailbox = Local-part "@" ( Domain / address-literal ) Local-part = Dot-string / Quoted-string ; MAY be case-sensitive Dot-string = Atom *("." Atom) */ StringBuilder retVal = new StringBuilder(); if (reader.Peek(true) == '\"') { retVal.Append("\"" + reader.QuotedString() + "\""); } else { retVal.Append(reader.DotAtom()); } if (reader.Peek(true) != '@') { return null; ; } else { // Eat "@". reader.Char(true); retVal.Append('@'); retVal.Append(reader.DotAtom()); } return retVal.ToString(); } #endregion } }<file_sep>/common/ASC.Core.Common/Billing/TariffSyncService.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Threading; using ASC.Common.Logging; using ASC.Common.Module; using ASC.Core.Data; using ASC.Core.Tenants; namespace ASC.Core.Billing { public class TariffSyncService : ITariffSyncService, IServiceController { private readonly static ILog log = LogManager.GetLogger("ASC"); private readonly TariffSyncServiceSection config; private readonly IDictionary<int, IEnumerable<TenantQuota>> quotaServices = new Dictionary<int, IEnumerable<TenantQuota>>(); private Timer timer; public TariffSyncService() { config = TariffSyncServiceSection.GetSection(); } // server part of service public IEnumerable<TenantQuota> GetTariffs(int version, string key) { lock (quotaServices) { if (!quotaServices.ContainsKey(version)) { var cs = ConfigurationManager.ConnectionStrings[config.ConnectionStringName + version] ?? ConfigurationManager.ConnectionStrings[config.ConnectionStringName]; quotaServices[version] = new DbQuotaService(cs).GetTenantQuotas(); } return quotaServices[version]; } } // client part of service public string ServiceName { get { return "Tariffs synchronizer"; } } public void Start() { if (timer == null) { timer = new Timer(Sync, null, TimeSpan.Zero, config.Period); } } public void Stop() { if (timer != null) { timer.Change(Timeout.Infinite, Timeout.Infinite); timer.Dispose(); timer = null; } } private void Sync(object _) { try { var tenant = CoreContext.TenantManager.GetTenants(false).OrderByDescending(t => t.Version).FirstOrDefault(); if (tenant != null) { using (var wcfClient = new TariffSyncClient()) { var quotaService = new DbQuotaService(ConfigurationManager.ConnectionStrings[config.ConnectionStringName]); var oldtariffs = quotaService.GetTenantQuotas().ToDictionary(t => t.Id); // save new foreach (var tariff in wcfClient.GetTariffs(tenant.Version, CoreContext.Configuration.GetKey(tenant.TenantId))) { quotaService.SaveTenantQuota(tariff); oldtariffs.Remove(tariff.Id); } // remove old foreach (var tariff in oldtariffs.Values) { tariff.Visible = false; quotaService.SaveTenantQuota(tariff); } } } } catch (Exception error) { log.Error(error); } } } } <file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/_Obsolete/SocketServer.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net { #region usings using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Net; using System.Net.Sockets; using System.Threading; using System.Timers; using Timer=System.Timers.Timer; #endregion /// <summary> /// This is base class for Socket and Session based servers. /// </summary> public abstract class SocketServer : Component { #region Nested type: QueuedConnection /// <summary> /// This struct holds queued connection info. /// </summary> private struct QueuedConnection { #region Members private readonly IPBindInfo m_pBindInfo; private readonly Socket m_pSocket; #endregion #region Properties /// <summary> /// Gets socket. /// </summary> public Socket Socket { get { return m_pSocket; } } /// <summary> /// Gets bind info. /// </summary> public IPBindInfo BindInfo { get { return m_pBindInfo; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="socket">Socket.</param> /// <param name="bindInfo">Bind info.</param> public QueuedConnection(Socket socket, IPBindInfo bindInfo) { m_pSocket = socket; m_pBindInfo = bindInfo; } #endregion } #endregion #region Events /// <summary> /// Occurs when server or session has system error(unhandled error). /// </summary> public event ErrorEventHandler SysError = null; #endregion #region Members private readonly Queue<QueuedConnection> m_pQueuedConnections; private readonly List<SocketServerSession> m_pSessions; private readonly Timer m_pTimer; private int m_MaxBadCommands = 8; private int m_MaxConnections = 1000; private IPBindInfo[] m_pBindInfo; private bool m_Running; private int m_SessionIdleTimeOut = 30000; #endregion #region Properties /// <summary> /// Gets or set socket binding info. Use this property to specify on which IP,port server /// listnes and also if is SSL or STARTTLS support. /// </summary> public IPBindInfo[] BindInfo { get { return m_pBindInfo; } set { if (value == null) { throw new NullReferenceException("BindInfo can't be null !"); } //--- See if bindinfo has changed ----------- bool changed = false; if (m_pBindInfo.Length != value.Length) { changed = true; } else { for (int i = 0; i < m_pBindInfo.Length; i++) { if (!m_pBindInfo[i].Equals(value[i])) { changed = true; break; } } } //------------------------------------------- if (changed) { // If server is currently running, stop it before applying bind info. bool running = m_Running; if (running) { StopServer(); } m_pBindInfo = value; // We need to restart server to take effect IP or Port change if (running) { StartServer(); } } } } /// <summary> /// Gets or sets maximum allowed connections. /// </summary> public int MaxConnections { get { return m_MaxConnections; } set { m_MaxConnections = value; } } /// <summary> /// Runs and stops server. /// </summary> public bool Enabled { get { return m_Running; } set { if (value != m_Running & !DesignMode) { if (value) { StartServer(); } else { StopServer(); } } } } /// <summary> /// Gets or sets if to log commands. /// </summary> public bool LogCommands { get; set; } /// <summary> /// Session idle timeout in milliseconds. /// </summary> public int SessionIdleTimeOut { get { return m_SessionIdleTimeOut; } set { m_SessionIdleTimeOut = value; } } /// <summary> /// Gets or sets maximum bad commands allowed to session. /// </summary> public int MaxBadCommands { get { return m_MaxBadCommands; } set { m_MaxBadCommands = value; } } /// <summary> /// Gets active sessions. /// </summary> public SocketServerSession[] Sessions { get { return m_pSessions.ToArray(); } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> public SocketServer() { m_pSessions = new List<SocketServerSession>(); m_pQueuedConnections = new Queue<QueuedConnection>(); m_pTimer = new Timer(15000); m_pBindInfo = new[] { new IPBindInfo(System.Net.Dns.GetHostName(), IPAddress.Any, 10000, SslMode.None, null) }; m_pTimer.AutoReset = true; m_pTimer.Elapsed += m_pTimer_Elapsed; } #endregion #region Methods /// <summary> /// Clean up any resources being used and stops server. /// </summary> public new void Dispose() { base.Dispose(); StopServer(); } /// <summary> /// Starts server. /// </summary> public void StartServer() { if (!m_Running) { m_Running = true; // Start accepting ang queueing connections Thread tr = new Thread(StartProcCons); tr.Start(); // Start proccessing queued connections Thread trSessionCreator = new Thread(StartProcQueuedCons); trSessionCreator.Start(); m_pTimer.Enabled = true; } } /// <summary> /// Stops server. NOTE: Active sessions aren't cancled. /// </summary> public void StopServer() { if (m_Running) { m_Running = false; // Stop accepting new connections foreach (IPBindInfo bindInfo in m_pBindInfo) { if (bindInfo.Tag != null) { ((Socket) bindInfo.Tag).Close(); bindInfo.Tag = null; } } // Wait method StartProcCons to exit Thread.Sleep(100); } } #endregion #region Virtual methods /// <summary> /// Initialize and start new session here. Session isn't added to session list automatically, /// session must add itself to server session list by calling AddSession(). /// </summary> /// <param name="socket">Connected client socket.</param> /// <param name="bindInfo">BindInfo what accepted socket.</param> protected virtual void InitNewSession(Socket socket, IPBindInfo bindInfo) {} #endregion #region Event handlers private void m_pTimer_Elapsed(object sender, ElapsedEventArgs e) { OnSessionTimeoutTimer(); } #endregion #region Utility methods /// <summary> /// Starts proccessiong incoming connections (Accepts and queues connections). /// </summary> private void StartProcCons() { try { CircleCollection<IPBindInfo> binds = new CircleCollection<IPBindInfo>(); foreach (IPBindInfo bindInfo in m_pBindInfo) { Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); s.Bind(new IPEndPoint(bindInfo.IP, bindInfo.Port)); s.Listen(500); bindInfo.Tag = s; binds.Add(bindInfo); } // Accept connections and queue them while (m_Running) { // We have reached maximum connection limit if (m_pSessions.Count > m_MaxConnections) { // Wait while some active connectins are closed while (m_pSessions.Count > m_MaxConnections) { Thread.Sleep(100); } } // Get incomong connection IPBindInfo bindInfo = binds.Next(); // There is waiting connection if (m_Running && ((Socket) bindInfo.Tag).Poll(0, SelectMode.SelectRead)) { // Accept incoming connection Socket s = ((Socket) bindInfo.Tag).Accept(); // Add session to queue lock (m_pQueuedConnections) { m_pQueuedConnections.Enqueue(new QueuedConnection(s, bindInfo)); } } Thread.Sleep(2); } } catch (SocketException x) { // Socket listening stopped, happens when StopServer is called. // We need just skip this error. if (x.ErrorCode == 10004) {} else { OnSysError("WE MUST NEVER REACH HERE !!! StartProcCons:", x); } } catch (Exception x) { OnSysError("WE MUST NEVER REACH HERE !!! StartProcCons:", x); } } /// <summary> /// Starts queueed connections proccessing (Creates and starts session foreach queued connection). /// </summary> private void StartProcQueuedCons() { try { while (m_Running) { // There are queued connections, start sessions. if (m_pQueuedConnections.Count > 0) { QueuedConnection connection; lock (m_pQueuedConnections) { connection = m_pQueuedConnections.Dequeue(); } try { InitNewSession(connection.Socket, connection.BindInfo); } catch (Exception x) { OnSysError("StartProcQueuedCons InitNewSession():", x); } } // There are no connections to proccess, delay proccessing. We need to it // because if there are no connections to proccess, while loop takes too much CPU. else { Thread.Sleep(10); } } } catch (Exception x) { OnSysError("WE MUST NEVER REACH HERE !!! StartProcQueuedCons:", x); } } /// <summary> /// This method must get timedout sessions and end them. /// </summary> private void OnSessionTimeoutTimer() { try { // Close/Remove timed out sessions lock (m_pSessions) { SocketServerSession[] sessions = Sessions; // Loop sessions and and call OnSessionTimeout() for timed out sessions. for (int i = 0; i < sessions.Length; i++) { // If session throws exception, handle it here or next sessions timouts are not handled. try { // Session timed out if (DateTime.Now > sessions[i].SessionLastDataTime.AddMilliseconds(SessionIdleTimeOut)) { sessions[i].OnSessionTimeout(); } } catch (Exception x) { OnSysError("OnTimer:", x); } } } } catch (Exception x) { OnSysError("WE MUST NEVER REACH HERE !!! OnTimer:", x); } } #endregion /// <summary> /// Adds specified session to sessions collection. /// </summary> /// <param name="session">Session to add.</param> protected internal void AddSession(SocketServerSession session) { lock (m_pSessions) { m_pSessions.Add(session); } } /// <summary> /// Removes specified session from sessions collection. /// </summary> /// <param name="session">Session to remove.</param> protected internal void RemoveSession(SocketServerSession session) { lock (m_pSessions) { m_pSessions.Remove(session); } } /// <summary> /// /// </summary> /// <param name="text"></param> /// <param name="x"></param> protected internal void OnSysError(string text, Exception x) { if (SysError != null) { SysError(this, new Error_EventArgs(x, new StackTrace())); } } } }<file_sep>/module/ASC.Api/ASC.Api.MailServer/MailServerApi.Notification.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using ASC.Api.Attributes; using ASC.Mail.Data.Contracts; // ReSharper disable InconsistentNaming namespace ASC.Api.MailServer { public partial class MailServerApi { /// <summary> /// Create address for tenant notifications /// </summary> /// <param name="name"></param> /// <param name="password"></param> /// <param name="domain_id"></param> /// <returns>NotificationAddressData associated with tenant</returns> /// <short>Create notification address</short> /// <category>Notifications</category> [Create(@"notification/address/add")] public ServerNotificationAddressData CreateNotificationAddress(string name, string password, int domain_id) { var notifyAddress = MailEngineFactory.ServerEngine.CreateNotificationAddress(name, password, domain_id); return notifyAddress; } /// <summary> /// Deletes address for notification /// </summary> /// <short>Remove mailbox from mail server</short> /// <category>Notifications</category> [Delete(@"notification/address/remove")] public void RemoveNotificationAddress(string address) { MailEngineFactory.ServerEngine.RemoveNotificationAddress(address); } } } <file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/RTP/RTP_Source_Remote.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.RTP { #region usings using System; #endregion /// <summary> /// This class represents RTP remote source what we receive. /// </summary> /// <remarks>Source indicates an entity sending packets, either RTP and/or RTCP. /// Sources what send RTP packets are called "active", only RTCP sending ones are "passive". /// </remarks> public class RTP_Source_Remote : RTP_Source { #region Events /// <summary> /// Is raised when source sends RTCP APP packet. /// </summary> public event EventHandler<EventArgs<RTCP_Packet_APP>> ApplicationPacket = null; #endregion #region Members private RTP_Participant_Remote m_pParticipant; private RTP_ReceiveStream m_pStream; #endregion #region Properties /// <summary> /// Returns false. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public override bool IsLocal { get { if (State == RTP_SourceState.Disposed) { throw new ObjectDisposedException(GetType().Name); } return false; } } /// <summary> /// Gets remote participant. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public RTP_Participant_Remote Participant { get { if (State == RTP_SourceState.Disposed) { throw new ObjectDisposedException(GetType().Name); } return m_pParticipant; } } /// <summary> /// Gets the stream we receive. Value null means that source is passive and doesn't send any RTP data. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public RTP_ReceiveStream Stream { get { if (State == RTP_SourceState.Disposed) { throw new ObjectDisposedException(GetType().Name); } return m_pStream; } } /// <summary> /// Gets source CNAME. Value null means that source not binded to participant. /// </summary> internal override string CName { get { if (Participant != null) { return null; } else { return Participant.CNAME; } } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="session">Owner RTP session.</param> /// <param name="ssrc">Synchronization source ID.</param> /// <exception cref="ArgumentNullException">Is raised when <b>session</b> is null reference.</exception> internal RTP_Source_Remote(RTP_Session session, uint ssrc) : base(session, ssrc) {} #endregion #region Overrides /// <summary> /// Cleans up any resources being used. /// </summary> internal override void Dispose() { m_pParticipant = null; if (m_pStream != null) { m_pStream.Dispose(); } ApplicationPacket = null; base.Dispose(); } #endregion #region Utility methods /// <summary> /// Raises <b>ApplicationPacket</b> event. /// </summary> /// <exception cref="ArgumentNullException">Is raised when <b>packet</b> is null reference.</exception> private void OnApplicationPacket(RTCP_Packet_APP packet) { if (packet == null) { throw new ArgumentNullException("packet"); } if (ApplicationPacket != null) { ApplicationPacket(this, new EventArgs<RTCP_Packet_APP>(packet)); } } #endregion #region Internal methods /// <summary> /// Sets source owner participant. /// </summary> /// <param name="participant">RTP participant.</param> /// <exception cref="ArgumentNullException">Is raised when <b>participant</b> is null reference.</exception> internal void SetParticipant(RTP_Participant_Remote participant) { if (participant == null) { throw new ArgumentNullException("participant"); } m_pParticipant = participant; } /// <summary> /// Is called when RTP session receives new RTP packet. /// </summary> /// <param name="packet">RTP packet.</param> /// <param name="size">Packet size in bytes.</param> /// <exception cref="ArgumentNullException">Is raised when <b>packet</b> is null reference.</exception> internal void OnRtpPacketReceived(RTP_Packet packet, int size) { if (packet == null) { throw new ArgumentNullException("packet"); } SetLastRtpPacket(DateTime.Now); // Passive source and first RTP packet. if (m_pStream == null) { m_pStream = new RTP_ReceiveStream(Session, this, packet.SeqNo); SetState(RTP_SourceState.Active); } m_pStream.Process(packet, size); } /// <summary> /// This method is called when this source got sender report. /// </summary> /// <param name="report">Sender report.</param> /// <exception cref="ArgumentNullException">Is raised when <b>report</b> is null reference.</exception> internal void OnSenderReport(RTCP_Report_Sender report) { if (report == null) { throw new ArgumentNullException("report"); } if (m_pStream != null) { m_pStream.SetSR(report); } } /// <summary> /// This method is called when this source got RTCP APP apcket. /// </summary> /// <param name="packet">RTCP APP packet.</param> /// <exception cref="ArgumentNullException">Is raised when <b>packet</b> is null reference.</exception> internal void OnAppPacket(RTCP_Packet_APP packet) { if (packet == null) { throw new ArgumentNullException("packet"); } OnApplicationPacket(packet); } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/SIP/Stack/SIP_ResponseCodes.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.SIP.Stack { /// <summary> /// This class holds SIP respnse codes. /// </summary> public class SIP_ResponseCodes { #region Members /// <summary> /// This response indicates that the request has been received by the /// next-hop server and that some unspecified action is being taken on /// behalf of this call (for example, a database is being consulted). /// </summary> public static readonly string x100_Trying = "100 Trying"; /// <summary> /// The UA receiving the INVITE is trying to alert the user. /// </summary> public static readonly string x180_Ringing = "180 Ringing"; /// <summary> /// A server MAY use this status code to indicate that the call is being /// forwarded to a different set of destinations. /// </summary> public static readonly string x181_Call_Forwarded = "181 Call Is Being Forwarded"; /// <summary> /// The called party is temporarily unavailable, but the server has /// decided to queue the call rather than reject it. When the callee /// becomes available, it will return the appropriate final status response. /// </summary> public static readonly string x182_Queued = "182 Queued"; /// <summary> /// The 183 (Session Progress) response is used to convey information /// about the progress of the call that is not otherwise classified. /// </summary> public static readonly string x183_Session_Progress = "183 Session Progress"; /// <summary> /// The request has succeeded. /// </summary> public static readonly string x200_Ok = "200 OK"; /// <summary> /// The request has accepted. Defined in rfc 3265. /// </summary> public static readonly string x202_Ok = "202 Accepted"; /// <summary> /// The request could not be understood due to malformed syntax. The /// Reason-Phrase SHOULD identify the syntax problem in more detail, for /// example, "Missing Call-ID header field". /// </summary> public static readonly string x400_Bad_Request = "400 Bad Request"; /// <summary> /// The request requires user authentication. /// </summary> public static readonly string x401_Unauthorized = "401 Unauthorized"; /// <summary> /// The server understood the request, but is refusing to fulfill it. /// Authorization will not help, and the request SHOULD NOT be repeated. /// </summary> public static readonly string x403_Forbidden = "403 Forbidden"; /// <summary> /// The server has definitive information that the user does not exist at /// the domain specified in the Request-URI. /// </summary> public static readonly string x404_Not_Found = "404 Not Found"; /// <summary> /// The method specified in the Request-Line is understood, but not /// allowed for the address identified by the Request-URI. /// </summary> public static readonly string x405_Method_Not_Allowed = "405 Method Not Allowed"; /// <summary> /// The resource identified by the request is only capable of generating /// response entities that have content characteristics not acceptable /// according to the Accept header field sent in the request. /// </summary> public static readonly string x406_Not_Acceptable = "406 Not Acceptable"; /// <summary> /// This code is similar to 401 (Unauthorized), but indicates that the /// client MUST first authenticate itself with the proxy. /// </summary> public static readonly string x407_Proxy_Authentication_Required = "407 Proxy Authentication Required"; /// <summary> /// The server could not produce a response within a suitable amount of /// time, for example, if it could not determine the location of the user in time. /// </summary> public static readonly string x408_Request_Timeout = "408 Request Timeout"; /// <summary> /// The requested resource is no longer available at the server and no /// forwarding address is known. This condition is expected to be /// considered permanent. /// </summary> public static readonly string x410_Gone = "410 Gone"; /// <summary> /// Is used to indicate that the precondition given for the request has failed. Defined in rfc 3903. /// </summary> public static readonly string x412_Conditional_Request_Failed = "412 Conditional Request Failed"; /// <summary> /// The server is refusing to process a request because the request /// entity-body is larger than the server is willing or able to process. /// The server MAY close the connection to prevent the client from /// continuing the request. /// </summary> public static readonly string x413_Request_Entity_Too_Large = "413 Request Entity Too Large"; /// <summary> /// The server is refusing to service the request because the Request-URI /// is longer than the server is willing to interpret. /// </summary> public static readonly string x414_RequestURI_Too_Long = "414 Request-URI Too Long"; /// <summary> /// The server is refusing to service the request because the message /// body of the request is in a format not supported by the server for /// the requested method. The server MUST return a list of acceptable /// formats using the Accept, Accept-Encoding, or Accept-Language header /// field, depending on the specific problem with the content. /// </summary> public static readonly string x415_Unsupported_Media_Type = "415 Unsupported Media Type"; /// <summary> /// The server cannot process the request because the scheme of the URI /// in the Request-URI is unknown to the server. /// </summary> public static readonly string x416_Unsupported_URI_Scheme = "416 Unsupported URI Scheme"; /// <summary> /// TODO: add description. Defined in rfc 4412. /// </summary> public static readonly string x417_Unknown_Resource_Priority = "417 Unknown Resource-Priority"; /// <summary> /// The server did not understand the protocol extension specified in a /// Proxy-Require or Require header field. /// </summary> public static readonly string x420_Bad_Extension = "420 Bad Extension"; /// <summary> /// The UAS needs a particular extension to process the request, but this /// extension is not listed in a Supported header field in the request. /// Responses with this status code MUST contain a Require header field /// listing the required extensions. /// </summary> public static readonly string x421_Extension_Required = "421 Extension Required"; /// <summary> /// It is generated by a UAS or proxy when a request contains a Session-Expires header field /// with a duration below the minimum timer for the server. The 422 response MUST contain a Min-SE /// header field with the minimum timer for that server. /// </summary> public static readonly string x422_Session_Interval_Too_Small = "422 Session Interval Too Small"; /// <summary> /// The server is rejecting the request because the expiration time of /// the resource refreshed by the request is too short. This response /// can be used by a registrar to reject a registration whose Contact /// header field expiration time was too small. /// </summary> public static readonly string x423_Interval_Too_Brief = "423 Interval Too Brief"; /// <summary> /// It is used when the verifier receives a message with an Identity signature that does not /// correspond to the digest-string calculated by the verifier. Defined in rfc 4474. /// </summary> public static readonly string x428_Use_Identity_Header = "428 Use Identity Header"; /// <summary> /// TODO: add description. Defined in rfc 3892. /// </summary> public static readonly string x429_Provide_Referrer_Identity = "429 Provide Referrer Identity"; /// <summary> /// It is used when the Identity-Info header contains a URI that cannot be dereferenced by the /// verifier (either the URI scheme is unsupported by the verifier, or the resource designated by /// the URI is otherwise unavailable). Defined in rfc 4474. /// </summary> public static readonly string x436_Bad_Identity_Info = "436 Bad Identity-Info"; /// <summary> /// It is used when the verifier cannot validate the certificate referenced by the URI of the /// Identity-Info header, because, for example, the certificate is self-signed, or signed by a /// root certificate authority for whom the verifier does not possess a root certificate. /// Defined in rfc 4474. /// </summary> public static readonly string x437_Unsupported_Certificate = "437 Unsupported Certificate"; /// <summary> /// It is used when the verifier receives a message with an Identity signature that does not /// correspond to the digest-string calculated by the verifier. Defined in rfc 4474. /// </summary> public static readonly string x438_Invalid_Identity_Header = "438 Invalid Identity Header"; /// <summary> /// The callee's end system was contacted successfully but the callee is /// currently unavailable (for example, is not logged in, logged in but /// in a state that precludes communication with the callee, or has /// activated the "do not disturb" feature). /// </summary> public static readonly string x480_Temporarily_Unavailable = "480 Temporarily Unavailable"; /// <summary> /// This status indicates that the UAS received a request that does not /// match any existing dialog or transaction. /// </summary> public static readonly string x481_Call_Transaction_Does_Not_Exist = "481 Call/Transaction Does Not Exist"; /// <summary> /// The server has detected a loop. /// </summary> public static readonly string x482_Loop_Detected = "482 Loop Detected"; /// <summary> /// The server received a request that contains a Max-Forwards. /// </summary> public static readonly string x483_Too_Many_Hops = "483 Too Many Hops"; /// <summary> /// The server received a request with a Request-URI that was incomplete. /// Additional information SHOULD be provided in the reason phrase. /// </summary> public static readonly string x484_Address_Incomplete = "484 Address Incomplete"; /// <summary> /// The Request-URI was ambiguous. /// </summary> public static readonly string x485_Ambiguous = "485 Ambiguous"; /// <summary> /// The callee's end system was contacted successfully, but the callee is /// currently not willing or able to take additional calls at this end /// system. The response MAY indicate a better time to call in the /// Retry-After header field. /// </summary> public static readonly string x486_Busy_Here = "486 Busy Here"; /// <summary> /// The request was terminated by a BYE or CANCEL request. This response /// is never returned for a CANCEL request itself. /// </summary> public static readonly string x487_Request_Terminated = "487 Request Terminated"; /// <summary> /// The response has the same meaning as 606 (Not Acceptable), but only /// applies to the specific resource addressed by the Request-URI and the /// request may succeed elsewhere. /// </summary> public static readonly string x488_Not_Acceptable_Here = "488 Not Acceptable Here"; /// <summary> /// Is used to indicate that the server did not understand the event package specified /// in a "Event" header field. Defined in rfc 3265. /// </summary> public static readonly string x489_Bad_Event = "489 Bad Event"; /// <summary> /// The request was received by a UAS that had a pending request within /// the same dialog. /// </summary> public static readonly string x491_Request_Pending = "491 Request Pending"; /// <summary> /// The request was received by a UAS that contained an encrypted MIME /// body for which the recipient does not possess or will not provide an /// appropriate decryption key. /// </summary> public static readonly string x493_Undecipherable = "493 Undecipherable"; /// <summary> /// TODO: add description. Defined in rfc 3329. /// </summary> public static readonly string x494_Security_Agreement_Required = "494 Security Agreement Required"; /// <summary> /// The server encountered an unexpected condition that prevented it from /// fulfilling the request. /// </summary> public static readonly string x500_Server_Internal_Error = "500 Server Internal Error"; /// <summary> /// The server does not support the functionality required to fulfill the request. /// </summary> public static readonly string x501_Not_Implemented = "501 Not Implemented"; /// <summary> /// The server, while acting as a gateway or proxy, received an invalid /// response from the downstream server it accessed in attempting to /// fulfill the request. /// </summary> public static readonly string x502_Bad_Gateway = "502 Bad Gateway"; /// <summary> /// The server is temporarily unable to process the request due to a /// temporary overloading or maintenance of the server. /// </summary> public static readonly string x503_Service_Unavailable = "503 Service Unavailable"; /// <summary> /// The server did not receive a timely response from an external server /// it accessed in attempting to process the request. /// </summary> public static readonly string x504_Timeout = "504 Server Time-out"; /// <summary> /// The server does not support, or refuses to support, the SIP protocol /// version that was used in the request. /// </summary> public static readonly string x504_Version_Not_Supported = "505 Version Not Supported"; /// <summary> /// The server was unable to process the request since the message length /// exceeded its capabilities. /// </summary> public static readonly string x513_Message_Too_Large = "513 Message Too Large"; /// <summary> /// When a UAS, acting as an answerer, cannot or is not willing to meet the preconditions /// in the offer. Defined in rfc 3312. /// </summary> public static readonly string x580_Precondition_Failure = "580 Precondition Failure"; /// <summary> /// The callee's end system was contacted successfully but the callee is /// busy and does not wish to take the call at this time. /// </summary> public static readonly string x600_Busy_Everywhere = "600 Busy Everywhere"; /// <summary> /// The callee's machine was successfully contacted but the user /// explicitly does not wish to or cannot participate. /// </summary> public static readonly string x603_Decline = "603 Decline"; /// <summary> /// The server has authoritative information that the user indicated in /// the Request-URI does not exist anywhere /// </summary> public static readonly string x604_Does_Not_Exist_Anywhere = "604 Does Not Exist Anywhere"; /// <summary> /// The user's agent was contacted successfully but some aspects of the /// session description such as the requested media, bandwidth, or /// addressing style were not acceptable. /// </summary> public static readonly string x606_Not_Acceptable = "606 Not Acceptable"; #endregion } }<file_sep>/web/studio/ASC.Web.Studio/UserControls/Common/ThirdPartyBanner/ThirdPartyBanner.ascx.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using ASC.Core; using ASC.FederatedLogin.LoginProviders; using ASC.VoipService.Dao; using ASC.Web.Core; using ASC.Web.Studio.Core; using ASC.Web.Studio.Utility; using AjaxPro; using Resources; namespace ASC.Web.Studio.UserControls.Common.ThirdPartyBanner { [AjaxNamespace("ThirdPartyBanner")] public partial class ThirdPartyBanner : UserControl { public static string Location { get { return "~/UserControls/Common/ThirdPartyBanner/ThirdPartyBanner.ascx"; } } public static bool Display { get { return SetupInfo.ThirdPartyBannerEnabled && SecurityContext.CheckPermissions(SecutiryConstants.EditPortalSettings) && GetBanner.Any(); } } protected Tuple<string, string> CurrentBanner; protected void Page_Load(object sender, EventArgs e) { AjaxPro.Utility.RegisterTypeForAjax(GetType()); Page.RegisterStyle("~/UserControls/Common/ThirdPartyBanner/css/thirdpartybanner.css"); var tmp = GetBanner; var i = new Random().Next(0, tmp.Count()); CurrentBanner = GetBanner.ToArray()[i]; } private static IEnumerable<Tuple<string, string>> GetBanner { get { if (CoreContext.Configuration.Personal || CoreContext.Configuration.CustomMode || HttpContext.Current.Request.DesktopApp()) { yield break; } var currentProductId = CommonLinkUtility.GetProductID(); if ((currentProductId == WebItemManager.DocumentsProductID || currentProductId == WebItemManager.PeopleProductID) && !ThirdPartyBannerSettings.CheckClosed("bitly") && !BitlyLoginProvider.Enabled) { yield return new Tuple<string, string>("bitly", UserControlsCommonResource.BannerBitly); } if ((currentProductId == WebItemManager.CRMProductID || currentProductId == WebItemManager.PeopleProductID) && !ThirdPartyBannerSettings.CheckClosed("social") && (!TwitterLoginProvider.Instance.IsEnabled || !FacebookLoginProvider.Instance.IsEnabled || !LinkedInLoginProvider.Instance.IsEnabled || !GoogleLoginProvider.Instance.IsEnabled)) { yield return new Tuple<string, string>("social", UserControlsCommonResource.BannerSocial); } if (currentProductId == WebItemManager.DocumentsProductID && !ThirdPartyBannerSettings.CheckClosed("storage") && (!BoxLoginProvider.Instance.IsEnabled || !DropboxLoginProvider.Instance.IsEnabled || !OneDriveLoginProvider.Instance.IsEnabled)) { yield return new Tuple<string, string>("storage", UserControlsCommonResource.BannerStorage); } if (currentProductId == WebItemManager.CRMProductID && !VoipDao.ConfigSettingsExist && VoipDao.Consumer.CanSet) { if(!ThirdPartyBannerSettings.CheckClosed("twilio2")) yield return new Tuple<string, string>("twilio2", UserControlsCommonResource.BannerTwilio2); } } } [AjaxMethod] public void CloseBanner(string banner) { ThirdPartyBannerSettings.Close(banner); } } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/ICMP/Icmp.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.ICMP { #region usings using System; using System.Collections.Generic; using System.Net; using System.Net.Sockets; #endregion /// <summary> /// ICMP type. /// </summary> public enum ICMP_Type { /// <summary> /// Echo rely. /// </summary> EchoReply = 0, /// <summary> /// Time to live exceeded reply. /// </summary> TimeExceeded = 11, /// <summary> /// Echo. /// </summary> Echo = 8, } #region class EchoMessage /// <summary> /// Echo reply message. /// </summary> public class EchoMessage { #region Members private readonly IPAddress m_pIP; private readonly int m_Time; private readonly int m_TTL; #endregion #region Properties /// <summary> /// Gets IP address what sent echo message. /// </summary> public IPAddress IPAddress { get { return m_pIP; } } /* /// <summary> /// Gets time to live in milli seconds. /// </summary> public int TTL { get{ return m_TTL; } }*/ /// <summary> /// Gets time in milliseconds what toke to get reply. /// </summary> public int ReplyTime { get { return m_Time; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="ip">IP address what sent echo message.</param> /// <param name="ttl">Time to live in milli seconds.</param> /// <param name="time">Time what elapsed before getting echo response.</param> internal EchoMessage(IPAddress ip, int ttl, int time) { m_pIP = ip; m_TTL = ttl; m_Time = time; } #endregion #region Methods /// <summary> /// /// </summary> /// <param name="messages"></param> /// <returns></returns> [Obsolete("Will be removed !")] public static string ToStringEx(EchoMessage[] messages) { string retVal = ""; foreach (EchoMessage m in messages) { retVal += m.ToStringEx() + "\r\n"; } return retVal; } /// <summary> /// /// </summary> /// <returns></returns> [Obsolete("Will be removed !")] public string ToStringEx() { return "TTL=" + m_TTL + "\tTime=" + m_Time + "ms" + "\tIP=" + m_pIP; } #endregion } #endregion /// <summary> /// Icmp utils. /// </summary> public class Icmp { #region Methods /// <summary> /// Traces specified ip. /// </summary> /// <param name="destIP">Destination IP address.</param> /// <returns></returns> public static EchoMessage[] Trace(string destIP) { return Trace(IPAddress.Parse(destIP), 2000); } /// <summary> /// Traces specified ip. /// </summary> /// <param name="ip">IP address to tracce.</param> /// <param name="timeout">Send recieve timeout in milli seconds.</param> /// <returns></returns> public static EchoMessage[] Trace(IPAddress ip, int timeout) { List<EchoMessage> retVal = new List<EchoMessage>(); //Create Raw ICMP Socket Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.Icmp); IPEndPoint ipdest = new IPEndPoint(ip, 80); EndPoint endpoint = (new IPEndPoint(Dns.GetHostEntry(Dns.GetHostName()).AddressList[0], 80)); ushort id = (ushort) DateTime.Now.Millisecond; byte[] sendPacket = CreatePacket(id); int continuesNoReply = 0; //send requests with increasing number of TTL for (int ittl = 1; ittl <= 30; ittl++) { byte[] buffer = new byte[1024]; try { //Socket options to set TTL and Timeouts s.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.IpTimeToLive, ittl); s.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, timeout); s.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, timeout); //Get current time DateTime startTime = DateTime.Now; //Send Request s.SendTo(sendPacket, sendPacket.Length, SocketFlags.None, ipdest); //Receive s.ReceiveFrom(buffer, buffer.Length, SocketFlags.None, ref endpoint); //Calculate time required TimeSpan ts = DateTime.Now - startTime; retVal.Add(new EchoMessage(((IPEndPoint) endpoint).Address, ittl, ts.Milliseconds)); // Endpoint reached if (buffer[20] == (byte) ICMP_Type.EchoReply) { break; } // Un wanted reply if (buffer[20] != (byte) ICMP_Type.TimeExceeded) { throw new Exception("UnKnown error !"); } continuesNoReply = 0; } catch { //ToDo: Handle recive/send timeouts continuesNoReply++; } // If there is 3 continues no reply, consider that destination host won't accept ping. if (continuesNoReply >= 3) { break; } } return retVal.ToArray(); } /// <summary> /// Pings specified destination host. /// </summary> /// <param name="ip">IP address to ping.</param> /// <param name="timeout">Send recieve timeout in milli seconds.</param> /// <returns></returns> public static EchoMessage Ping(IPAddress ip, int timeout) { //Create Raw ICMP Socket Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.Icmp); IPEndPoint ipdest = new IPEndPoint(ip, 80); EndPoint endpoint = (new IPEndPoint(Dns.GetHostEntry(Dns.GetHostName()).AddressList[0], 80)); ushort id = (ushort) DateTime.Now.Millisecond; byte[] sendPacket = CreatePacket(id); //Socket options to set TTL and Timeouts s.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.IpTimeToLive, 30); s.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, timeout); s.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, timeout); //Get current time DateTime startTime = DateTime.Now; //Send Request s.SendTo(sendPacket, sendPacket.Length, SocketFlags.None, ipdest); //Receive byte[] buffer = new byte[1024]; s.ReceiveFrom(buffer, buffer.Length, SocketFlags.None, ref endpoint); // Endpoint reached if (buffer[20] == (byte) ICMP_Type.EchoReply) {} // Un wanted reply else if (buffer[20] != (byte) ICMP_Type.TimeExceeded) { throw new Exception("UnKnown error !"); } //Calculate time elapsed TimeSpan ts = DateTime.Now - startTime; return new EchoMessage(((IPEndPoint) endpoint).Address, 0, ts.Milliseconds); } #endregion #region Utility methods private static byte[] CreatePacket(ushort id) { /*Rfc 792 Echo or Echo Reply Message 0 8 16 24 +---------------+---------------+---------------+---------------+ | Type | Code | Checksum | +---------------+---------------+---------------+---------------+ | ID Number | Sequence Number | +---------------+---------------+---------------+---------------+ | Data... +---------------+---------------+---------------+---------------+ */ byte[] packet = new byte[8 + 2]; packet[0] = (byte) ICMP_Type.Echo; // Type packet[1] = 0; // Code packet[2] = 0; // Checksum packet[3] = 0; // Checksum packet[4] = 0; // ID packet[5] = 0; // ID packet[6] = 0; // Sequence packet[7] = 0; // Sequence // Set id Array.Copy(BitConverter.GetBytes(id), 0, packet, 4, 2); // Fill data 2 byte data for (int i = 0; i < 2; i++) { packet[i + 8] = (byte) 'x'; // Data } // calculate checksum int checkSum = 0; for (int i = 0; i < packet.Length; i += 2) { checkSum += Convert.ToInt32(BitConverter.ToUInt16(packet, i)); } // The checksum is the 16-bit ones's complement of the one's // complement sum of the ICMP message starting with the ICMP Type. checkSum = (checkSum & 0xffff); Array.Copy(BitConverter.GetBytes((ushort) ~checkSum), 0, packet, 2, 2); return packet; } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/IMAP/IMAP_BODY.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.IMAP { #region usings using System.Collections.Generic; using System.IO; using System.Text; using Mime; #endregion /// <summary> /// IMAP BODYSTRUCTURE. Defined in RFC 3501 7.4.2. /// </summary> public class IMAP_BODY { #region Members private IMAP_BODY_Entity m_pMainEntity; #endregion #region Properties /// <summary> /// Gets main entity. /// </summary> public IMAP_BODY_Entity MainEntity { get { return m_pMainEntity; } } /// <summary> /// Gets all entities contained in BODYSTRUCTURE, including child entities. /// </summary> public IMAP_BODY_Entity[] Entities { get { List<IMAP_BODY_Entity> allEntities = new List<IMAP_BODY_Entity>(); allEntities.Add(m_pMainEntity); GetEntities(m_pMainEntity.ChildEntities, allEntities); return allEntities.ToArray(); } } /// <summary> /// Gets attachment entities. Entity is considered as attachmnet if:<p/> /// *) Content-Type: name = "" is specified (old RFC 822 message)<p/> /// </summary> public IMAP_BODY_Entity[] Attachmnets { // Cant use these at moment, we need to use extended BODYSTRUCTURE fo that // *) Content-Disposition: attachment (RFC 2822 message)<p/> // *) Content-Disposition: filename = "" is specified (RFC 2822 message)<p/> get { List<IMAP_BODY_Entity> attachments = new List<IMAP_BODY_Entity>(); IMAP_BODY_Entity[] entities = Entities; foreach (IMAP_BODY_Entity entity in entities) { if (entity.ContentType_Paramters != null) { foreach (HeaderFieldParameter parameter in entity.ContentType_Paramters) { if (parameter.Name.ToLower() == "name") { attachments.Add(entity); break; } } } } return attachments.ToArray(); } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> public IMAP_BODY() { m_pMainEntity = new IMAP_BODY_Entity(); } #endregion #region Methods /// <summary> /// Constructs FETCH BODY and BODYSTRUCTURE response. /// </summary> /// <param name="mime">Mime message.</param> /// <param name="bodystructure">Specifies if to construct BODY or BODYSTRUCTURE.</param> /// <returns></returns> public static string ConstructBodyStructure(Mime mime, bool bodystructure) { if (bodystructure) { return "BODYSTRUCTURE " + ConstructParts(mime.MainEntity, bodystructure); } else { return "BODY " + ConstructParts(mime.MainEntity, bodystructure); } } /// <summary> /// Parses IMAP BODYSTRUCTURE from body structure string. /// </summary> /// <param name="bodyStructureString">Body structure string</param> public void Parse(string bodyStructureString) { m_pMainEntity = new IMAP_BODY_Entity(); m_pMainEntity.Parse(bodyStructureString); } #endregion #region Utility methods /// <summary> /// Constructs specified entity and it's childentities bodystructure string. /// </summary> /// <param name="entity">Mime entity.</param> /// <param name="bodystructure">Specifies if to construct BODY or BODYSTRUCTURE.</param> /// <returns></returns> private static string ConstructParts(MimeEntity entity, bool bodystructure) { /* RFC 3501 7.4.2 BODYSTRUCTURE BODY A form of BODYSTRUCTURE without extension data. A parenthesized list that describes the [MIME-IMB] body structure of a message. This is computed by the server by parsing the [MIME-IMB] header fields, defaulting various fields as necessary. For example, a simple text message of 48 lines and 2279 octets can have a body structure of: ("TEXT" "PLAIN" ("CHARSET" "US-ASCII") NIL NIL "7BIT" 2279 48) Multiple parts are indicated by parenthesis nesting. Instead of a body type as the first element of the parenthesized list, there is a sequence of one or more nested body structures. The second element of the parenthesized list is the multipart subtype (mixed, digest, parallel, alternative, etc.). For example, a two part message consisting of a text and a BASE64-encoded text attachment can have a body structure of: (("TEXT" "PLAIN" ("CHARSET" "US-ASCII") NIL NIL "7BIT" 1152 23)("TEXT" "PLAIN" ("CHARSET" "US-ASCII" "NAME" "cc.diff") "<960723163407.<EMAIL>>" "Compiler diff" "BASE64" 4554 73) "MIXED") Extension data follows the multipart subtype. Extension data is never returned with the BODY fetch, but can be returned with a BODYSTRUCTURE fetch. Extension data, if present, MUST be in the defined order. The extension data of a multipart body part are in the following order: body parameter parenthesized list A parenthesized list of attribute/value pairs [e.g., ("foo" "bar" "baz" "rag") where "bar" is the value of "foo", and "rag" is the value of "baz"] as defined in [MIME-IMB]. body disposition A parenthesized list, consisting of a disposition type string, followed by a parenthesized list of disposition attribute/value pairs as defined in [DISPOSITION]. body language A string or parenthesized list giving the body language value as defined in [LANGUAGE-TAGS]. body location A string list giving the body content URI as defined in [LOCATION]. Any following extension data are not yet defined in this version of the protocol. Such extension data can consist of zero or more NILs, strings, numbers, or potentially nested parenthesized lists of such data. Client implementations that do a BODYSTRUCTURE fetch MUST be prepared to accept such extension data. Server implementations MUST NOT send such extension data until it has been defined by a revision of this protocol. The basic fields of a non-multipart body part are in the following order: body type A string giving the content media type name as defined in [MIME-IMB]. body subtype A string giving the content subtype name as defined in [MIME-IMB]. body parameter parenthesized list A parenthesized list of attribute/value pairs [e.g., ("foo" "bar" "baz" "rag") where "bar" is the value of "foo" and "rag" is the value of "baz"] as defined in [MIME-IMB]. body id A string giving the content id as defined in [MIME-IMB]. body description A string giving the content description as defined in [MIME-IMB]. body encoding A string giving the content transfer encoding as defined in [MIME-IMB]. body size A number giving the size of the body in octets. Note that this size is the size in its transfer encoding and not the resulting size after any decoding. A body type of type MESSAGE and subtype RFC822 contains, immediately after the basic fields, the envelope structure, body structure, and size in text lines of the encapsulated message. A body type of type TEXT contains, immediately after the basic fields, the size of the body in text lines. Note that this size is the size in its content transfer encoding and not the resulting size after any decoding. Extension data follows the basic fields and the type-specific fields listed above. Extension data is never returned with the BODY fetch, but can be returned with a BODYSTRUCTURE fetch. Extension data, if present, MUST be in the defined order. The extension data of a non-multipart body part are in the following order: body MD5 A string giving the body MD5 value as defined in [MD5]. body disposition A parenthesized list with the same content and function as the body disposition for a multipart body part. body language A string or parenthesized list giving the body language value as defined in [LANGUAGE-TAGS]. body location A string list giving the body content URI as defined in [LOCATION]. Any following extension data are not yet defined in this version of the protocol, and would be as described above under multipart extension data. // We don't construct extention fields like rfc says: Server implementations MUST NOT send such extension data until it has been defined by a revision of this protocol. contentTypeMainMediaType - Example: 'TEXT' contentTypeSubMediaType - Example: 'PLAIN' conentTypeParameters - Example: '("CHARSET" "iso-8859-1" ...)' contentID - Content-ID: header field value. contentDescription - Content-Description: header field value. contentEncoding - Content-Transfer-Encoding: header field value. contentSize - mimeEntity ENCODED data size [envelope] - NOTE: included only if contentType = "message" !!! [contentLines] - number of ENCODED data lines. NOTE: included only if contentType = "text" !!! // Basic fields for multipart (nestedMimeEntries) contentTypeSubMediaType // Basic fields for non-multipart contentTypeMainMediaType contentTypeSubMediaType (conentTypeParameters) contentID contentDescription contentEncoding contentSize [envelope] [contentLine] */ StringBuilder retVal = new StringBuilder(); // Multipart message if ((entity.ContentType & MediaType_enum.Multipart) != 0) { retVal.Append("("); // Construct child entities. foreach (MimeEntity childEntity in entity.ChildEntities) { // Construct child entity. This can be multipart or non multipart. retVal.Append(ConstructParts(childEntity, bodystructure)); } // Add contentTypeSubMediaType string contentType = entity.ContentTypeString.Split(';')[0]; if (contentType.Split('/').Length == 2) { retVal.Append(" \"" + contentType.Split('/')[1].Replace(";", "") + "\""); } else { retVal.Append(" NIL"); } retVal.Append(")"); } // Single part message else { retVal.Append("("); // NOTE: all header fields and parameters must in ENCODED form !!! // Add contentTypeMainMediaType if (entity.ContentTypeString != null) { string contentType = entity.ContentTypeString.Split(';')[0]; if (contentType.Split('/').Length == 2) { retVal.Append("\"" + entity.ContentTypeString.Split('/')[0] + "\""); } else { retVal.Append("NIL"); } } else { retVal.Append("NIL"); } // contentTypeSubMediaType if (entity.ContentTypeString != null) { string contentType = entity.ContentTypeString.Split(';')[0]; if (contentType.Split('/').Length == 2) { retVal.Append(" \"" + contentType.Split('/')[1].Replace(";", "") + "\""); } else { retVal.Append(" NIL"); } } else { retVal.Append(" NIL"); } // conentTypeParameters - Syntax: {("name" SP "value" *(SP "name" SP "value"))} if (entity.ContentTypeString != null) { ParametizedHeaderField contentTypeParameters = new ParametizedHeaderField(entity.Header.GetFirst("Content-Type:")); if (contentTypeParameters.Parameters.Count > 0) { retVal.Append(" ("); bool first = true; foreach (HeaderFieldParameter param in contentTypeParameters.Parameters) { // For first item, don't add SP if (!first) { retVal.Append(" "); } else { // Clear first flag first = false; } retVal.Append("\"" + param.Name + "\" \"" + MimeUtils.EncodeHeaderField(param.Value) + "\""); } retVal.Append(")"); } else { retVal.Append(" NIL"); } } else { retVal.Append(" NIL"); } // contentID string contentID = entity.ContentID; if (contentID != null) { retVal.Append(" \"" + MimeUtils.EncodeHeaderField(contentID) + "\""); } else { retVal.Append(" NIL"); } // contentDescription string contentDescription = entity.ContentDescription; if (contentDescription != null) { retVal.Append(" \"" + MimeUtils.EncodeHeaderField(contentDescription) + "\""); } else { retVal.Append(" NIL"); } // contentEncoding HeaderField contentEncoding = entity.Header.GetFirst("Content-Transfer-Encoding:"); if (contentEncoding != null) { retVal.Append(" \"" + MimeUtils.EncodeHeaderField(contentEncoding.Value) + "\""); } else { // If not specified, then must be 7bit. retVal.Append(" \"7bit\""); } // contentSize if (entity.DataEncoded != null) { retVal.Append(" " + entity.DataEncoded.Length); } else { retVal.Append(" 0"); } // envelope ---> FOR ContentType: message/rfc822 ONLY ### if ((entity.ContentType & MediaType_enum.Message_rfc822) != 0) { retVal.Append(" " + IMAP_Envelope.ConstructEnvelope(entity)); // TODO: BODYSTRUCTURE,LINES } // contentLines ---> FOR ContentType: text/xxx ONLY ### if ((entity.ContentType & MediaType_enum.Text) != 0) { if (entity.DataEncoded != null) { long lineCount = 0; StreamLineReader r = new StreamLineReader(new MemoryStream(entity.DataEncoded)); byte[] line = r.ReadLine(); while (line != null) { lineCount++; line = r.ReadLine(); } retVal.Append(" " + lineCount); } else { retVal.Append(" 0"); } } retVal.Append(")"); } return retVal.ToString(); } /// <summary> /// Gets mime entities, including nested entries. /// </summary> /// <param name="entities"></param> /// <param name="allEntries"></param> private void GetEntities(IMAP_BODY_Entity[] entities, List<IMAP_BODY_Entity> allEntries) { if (entities != null) { foreach (IMAP_BODY_Entity ent in entities) { allEntries.Add(ent); // Add child entities, if any if (ent.ChildEntities.Length > 0) { GetEntities(ent.ChildEntities, allEntries); } } } } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/_Obsolete/WriteStream_EventArgs.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.IO { #region usings using System; using System.IO; #endregion /// <summary> /// This class provides data to asynchronous write from stream methods callback. /// </summary> public class WriteStream_EventArgs { #region Members private readonly int m_CountReaded; private readonly int m_CountWritten; private readonly Exception m_pException; private readonly Stream m_pStream; #endregion #region Properties /// <summary> /// Gets exception happened during write or null if operation was successfull. /// </summary> public Exception Exception { get { return m_pException; } } /// <summary> /// Gets stream what data was written. /// </summary> public Stream Stream { get { return m_pStream; } } /// <summary> /// Gets number of bytes readed from <b>Stream</b>. /// </summary> public int CountReaded { get { return m_CountReaded; } } /// <summary> /// Gets number of bytes written to source stream. /// </summary> public int CountWritten { get { return m_CountWritten; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="exception">Exception happened during write or null if operation was successfull.</param> /// <param name="stream">Stream which data was written.</param> /// <param name="countReaded">Number of bytes readed from <b>stream</b>.</param> /// <param name="countWritten">Number of bytes written to source stream.</param> internal WriteStream_EventArgs(Exception exception, Stream stream, int countReaded, int countWritten) { m_pException = exception; m_pStream = stream; m_CountReaded = countReaded; m_CountWritten = countWritten; } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/IMAP/Server/IMAP_eArgs_MessageItems.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.IMAP.Server { #region usings using System; using System.IO; #endregion /// <summary> /// Provides data to event GetMessageItems. /// </summary> public class IMAP_eArgs_MessageItems { #region Members private readonly IMAP_MessageItems_enum m_MessageItems = IMAP_MessageItems_enum.Message; private readonly IMAP_Message m_pMessageInfo; private readonly IMAP_Session m_pSession; private string m_BodyStructure; private bool m_CloseMessageStream = true; private string m_Envelope; private byte[] m_Header; private bool m_MessageExists = true; private long m_MessageStartOffset; private Stream m_MessageStream; #endregion #region Properties /// <summary> /// Gets reference to current IMAP session. /// </summary> public IMAP_Session Session { get { return m_pSession; } } /// <summary> /// Gets message info what message items to get. /// </summary> public IMAP_Message MessageInfo { get { return m_pMessageInfo; } } /// <summary> /// Gets what message items must be filled. /// </summary> public IMAP_MessageItems_enum MessageItems { get { return m_MessageItems; } } /// <summary> /// Gets or sets if message stream is closed automatically if all actions on it are completed. /// Default value is true. /// </summary> public bool CloseMessageStream { get { return m_CloseMessageStream; } set { m_CloseMessageStream = value; } } /// <summary> /// Gets or sets message stream. When setting this property Stream position must be where message begins. /// Fill this property only if IMAP_MessageItems_enum.Message flag is specified. /// </summary> public Stream MessageStream { get { if (m_MessageStream != null) { m_MessageStream.Position = m_MessageStartOffset; } return m_MessageStream; } set { if (value == null) { throw new ArgumentNullException("Property MessageStream value can't be null !"); } if (!value.CanSeek) { throw new Exception("Stream must support seeking !"); } m_MessageStream = value; m_MessageStartOffset = m_MessageStream.Position; } } /// <summary> /// Gets message size in bytes. /// </summary> public long MessageSize { get { if (m_MessageStream == null) { throw new Exception("You must set MessageStream property first to use this property !"); } else { return m_MessageStream.Length - m_MessageStream.Position; } } } /// <summary> /// Gets or sets message main header. /// Fill this property only if IMAP_MessageItems_enum.Header flag is specified. /// </summary> public byte[] Header { get { return m_Header; } set { if (value == null) { throw new ArgumentNullException("Property Header value can't be null !"); } m_Header = value; } } /// <summary> /// Gets or sets IMAP ENVELOPE string. /// Fill this property only if IMAP_MessageItems_enum.Envelope flag is specified. /// </summary> public string Envelope { get { return m_Envelope; } set { if (value == null) { throw new ArgumentNullException("Property Envelope value can't be null !"); } m_Envelope = value; } } /// <summary> /// Gets or sets IMAP BODYSTRUCTURE string. /// Fill this property only if IMAP_MessageItems_enum.BodyStructure flag is specified. /// </summary> public string BodyStructure { get { return m_BodyStructure; } set { if (value == null) { throw new ArgumentNullException("Property BodyStructure value can't be null !"); } m_BodyStructure = value; } } /// <summary> /// Gets or sets if message exists. Set this false, if message actually doesn't exist any more. /// </summary> public bool MessageExists { get { return m_MessageExists; } set { m_MessageExists = value; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="session">Reference to current IMAP session.</param> /// <param name="messageInfo">Message info what message items to get.</param> /// <param name="messageItems">Specifies message items what must be filled.</param> public IMAP_eArgs_MessageItems(IMAP_Session session, IMAP_Message messageInfo, IMAP_MessageItems_enum messageItems) { m_pSession = session; m_pMessageInfo = messageInfo; m_MessageItems = messageItems; } #endregion #region Methods /// <summary> /// Clean up any resources being used. /// </summary> public void Dispose() { if (m_CloseMessageStream && m_MessageStream != null) { m_MessageStream.Dispose(); m_MessageStream = null; } } #endregion #region Overrides /// <summary> /// Default deconstructor. /// </summary> ~IMAP_eArgs_MessageItems() { Dispose(); } #endregion #region Internal methods /// <summary> /// Checks that all required data items are provided, if not throws exception. /// </summary> internal void Validate() { if ((m_MessageItems & IMAP_MessageItems_enum.BodyStructure) != 0 && m_BodyStructure == null) { throw new Exception( "IMAP BODYSTRUCTURE is required, but not provided to IMAP server component !"); } if ((m_MessageItems & IMAP_MessageItems_enum.Envelope) != 0 && m_Envelope == null) { throw new Exception("IMAP ENVELOPE is required, but not provided to IMAP server component !"); } if ((m_MessageItems & IMAP_MessageItems_enum.Header) != 0 && m_Header == null) { throw new Exception("Message header is required, but not provided to IMAP server component !"); } if ((m_MessageItems & IMAP_MessageItems_enum.Message) != 0 && m_MessageStream == null) { throw new Exception("Full message is required, but not provided to IMAP server component !"); } } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/vCard/vCard.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.Mime.vCard { #region usings using System; using System.Drawing; using System.Drawing.Imaging; using System.Globalization; using System.IO; using System.Text; #endregion /// <summary> /// Rfc 2426 vCard implementation. /// </summary> public class vCard { #region Members private readonly ItemCollection m_pItems; private DeliveryAddressCollection m_pAddresses; private EmailAddressCollection m_pEmailAddresses; private PhoneNumberCollection m_pPhoneNumbers; #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> public vCard() { m_pItems = new ItemCollection(); Version = "3.0"; UID = Guid.NewGuid().ToString(); } #endregion #region Properties /// <summary> /// Gets addresses collection. /// </summary> public DeliveryAddressCollection Addresses { get { // Delay collection creation, create it when needed. if (m_pAddresses == null) { m_pAddresses = new DeliveryAddressCollection(this); } return m_pAddresses; } } /// <summary> /// Gets or sets birth date. Returns DateTime.MinValue if not set. /// </summary> public DateTime BirthDate { get { Item item = m_pItems.GetFirst("BDAY"); if (item != null) { string date = item.DecodedValue.Replace("-", ""); string[] dateFormats = new[] {"yyyyMMdd", "yyyyMMddz"}; return DateTime.ParseExact(date, dateFormats, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.None); } else { return DateTime.MinValue; } } set { if (value != DateTime.MinValue) { m_pItems.SetValue("BDAY", value.ToString("yyyyMMdd")); } else { m_pItems.SetValue("BDAY", null); } } } /// <summary> /// Gets email addresses collection. /// </summary> public EmailAddressCollection EmailAddresses { get { // Delay collection creation, create it when needed. if (m_pEmailAddresses == null) { m_pEmailAddresses = new EmailAddressCollection(this); } return m_pEmailAddresses; } } /// <summary> /// Gets or sets formatted(Display name) name. Returns null if FN: item doesn't exist. /// </summary> public string FormattedName { get { Item item = m_pItems.GetFirst("FN"); if (item != null) { return item.DecodedValue; } else { return null; } } set { m_pItems.SetDecodedValue("FN", value); } } /// <summary> /// Gets or sets vCard home URL. /// </summary> public string HomeURL { get { Item[] items = m_pItems.Get("URL"); foreach (Item item in items) { if (item.ParametersString == "" || item.ParametersString.ToUpper().IndexOf("HOME") > -1) { return item.DecodedValue; } } return null; } set { Item[] items = m_pItems.Get("URL"); foreach (Item item in items) { if (item.ParametersString.ToUpper().IndexOf("HOME") > -1) { if (value != null) { item.Value = value; } else { m_pItems.Remove(item); } return; } } if (value != null) { // If we reach here, URL;Work doesn't exist, add it. m_pItems.Add("URL", "HOME", value); } } } /// <summary> /// Gets reference to vCard items. /// </summary> public ItemCollection Items { get { return m_pItems; } } /// <summary> /// Gets or sets name info. Returns null if N: item doesn't exist. /// </summary> public Name Name { get { Item item = m_pItems.GetFirst("N"); if (item != null) { return Name.Parse(item); } else { return null; } } set { if (value != null) { m_pItems.SetDecodedValue("N", value.ToValueString()); } else { m_pItems.SetDecodedValue("N", null); } } } /// <summary> /// Gets or sets nick name. Returns null if NICKNAME: item doesn't exist. /// </summary> public string NickName { get { Item item = m_pItems.GetFirst("NICKNAME"); if (item != null) { return item.DecodedValue; } else { return null; } } set { m_pItems.SetDecodedValue("NICKNAME", value); } } /// <summary> /// Gets or sets note text. Returns null if NOTE: item doesn't exist. /// </summary> public string NoteText { get { Item item = m_pItems.GetFirst("NOTE"); if (item != null) { return item.DecodedValue; } else { return null; } } set { m_pItems.SetDecodedValue("NOTE", value); } } /// <summary> /// Gets or sets organization name. Usually this value is: comapny;department;office. Returns null if ORG: item doesn't exist. /// </summary> public string Organization { get { Item item = m_pItems.GetFirst("ORG"); if (item != null) { return item.DecodedValue; } else { return null; } } set { m_pItems.SetDecodedValue("ORG", value); } } /// <summary> /// Gets phone number collection. /// </summary> public PhoneNumberCollection PhoneNumbers { get { // Delay collection creation, create it when needed. if (m_pPhoneNumbers == null) { m_pPhoneNumbers = new PhoneNumberCollection(this); } return m_pPhoneNumbers; } } /// <summary> /// Gets or sets person photo. Returns null if PHOTO: item doesn't exist. /// </summary> public Image Photo { get { Item item = m_pItems.GetFirst("PHOTO"); if (item != null) { return Image.FromStream(new MemoryStream(Encoding.Default.GetBytes(item.DecodedValue))); } else { return null; } } set { if (value != null) { MemoryStream ms = new MemoryStream(); value.Save(ms, ImageFormat.Jpeg); m_pItems.SetValue("PHOTO", "ENCODING=b;TYPE=JPEG", Convert.ToBase64String(ms.ToArray())); } else { m_pItems.SetValue("PHOTO", null); } } } /// <summary> /// Gets or sets role. Returns null if ROLE: item doesn't exist. /// </summary> public string Role { get { Item item = m_pItems.GetFirst("ROLE"); if (item != null) { return item.DecodedValue; } else { return null; } } set { m_pItems.SetDecodedValue("ROLE", value); } } /// <summary> /// Gets or sets job title. Returns null if TITLE: item doesn't exist. /// </summary> public string Title { get { Item item = m_pItems.GetFirst("TITLE"); if (item != null) { return item.DecodedValue; } else { return null; } } set { m_pItems.SetDecodedValue("TITLE", value); } } /// <summary> /// Gets or sets vCard unique ID. Returns null if UID: item doesn't exist. /// </summary> public string UID { get { Item item = m_pItems.GetFirst("UID"); if (item != null) { return item.DecodedValue; } else { return null; } } set { m_pItems.SetDecodedValue("UID", value); } } /// <summary> /// Gets or sets vCard version. Returns null if VERSION: item doesn't exist. /// </summary> public string Version { get { Item item = m_pItems.GetFirst("VERSION"); if (item != null) { return item.DecodedValue; } else { return null; } } set { m_pItems.SetDecodedValue("VERSION", value); } } /// <summary> /// Gets or sets vCard Work URL. /// </summary> public string WorkURL { get { Item[] items = m_pItems.Get("URL"); foreach (Item item in items) { if (item.ParametersString.ToUpper().IndexOf("WORK") > -1) { return item.DecodedValue; } } return null; } set { Item[] items = m_pItems.Get("URL"); foreach (Item item in items) { if (item.ParametersString.ToUpper().IndexOf("WORK") > -1) { if (value != null) { item.Value = value; } else { m_pItems.Remove(item); } return; } } if (value != null) { // If we reach here, URL;Work doesn't exist, add it. m_pItems.Add("URL", "WORK", value); } } } #endregion #region Methods /// <summary> /// Stores vCard structure to byte[]. /// </summary> /// <returns></returns> public byte[] ToByte() { MemoryStream ms = new MemoryStream(); ToStream(ms); return ms.ToArray(); } /// <summary> /// Stores vCard to the specified file. /// </summary> /// <param name="file">File name with path where to store vCard.</param> public void ToFile(string file) { using (FileStream fs = File.Create(file)) { ToStream(fs); } } /// <summary> /// Stores vCard structure to the specified stream. /// </summary> /// <param name="stream">Stream where to store vCard structure.</param> public void ToStream(Stream stream) { /* BEGIN:VCARD<CRLF> .... END:VCARD<CRLF> */ StringBuilder retVal = new StringBuilder(); retVal.Append("BEGIN:VCARD\r\n"); foreach (Item item in m_pItems) { retVal.Append(item.ToItemString() + "\r\n"); } retVal.Append("END:VCARD\r\n"); byte[] data = Encoding.UTF8.GetBytes(retVal.ToString()); stream.Write(data, 0, data.Length); } /// <summary> /// Parses vCard from the specified file. /// </summary> /// <param name="file">vCard file with path.</param> public void Parse(string file) { using (FileStream fs = File.OpenRead(file)) { Parse(fs); } } /// <summary> /// Parses vCard from the specified stream. /// </summary> /// <param name="stream">Stream what contains vCard.</param> public void Parse(Stream stream) { m_pItems.Clear(); m_pPhoneNumbers = null; m_pEmailAddresses = null; TextReader r = new StreamReader(stream, Encoding.Default); string line = r.ReadLine(); // Find row BEGIN:VCARD while (line != null && line.ToUpper() != "BEGIN:VCARD") { line = r.ReadLine(); } // Read frist vCard line after BEGIN:VCARD line = r.ReadLine(); while (line != null && line.ToUpper() != "END:VCARD") { StringBuilder item = new StringBuilder(); item.Append(line); // Get next line, see if item continues (folded line). line = r.ReadLine(); while (line != null && (line.StartsWith("\t") || line.StartsWith(" "))) { item.Append(line.Substring(1)); line = r.ReadLine(); } string[] name_value = item.ToString().Split(new[] {':'}, 2); // Item syntax: name[*(;parameter)]:value string[] name_params = name_value[0].Split(new[] {';'}, 2); string name = name_params[0]; string parameters = ""; if (name_params.Length == 2) { parameters = name_params[1]; } string value = ""; if (name_value.Length == 2) { value = name_value[1]; } m_pItems.Add(name, parameters, value); } } #endregion } }<file_sep>/web/studio/ASC.Web.Studio/ThirdParty/ImportContacts/Google.aspx.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Web; using System.Xml.Linq; using ASC.FederatedLogin; using ASC.FederatedLogin.Helpers; using ASC.FederatedLogin.LoginProviders; using ASC.Web.Core; using ASC.Web.Studio.Utility; namespace ASC.Web.Studio.ThirdParty.ImportContacts { public partial class Google : BasePage { public static string Location { get { return CommonLinkUtility.ToAbsolute("~/ThirdParty/ImportContacts/Google.aspx"); } } public static bool Enable { get { return GoogleLoginProvider.Instance.IsEnabled; } } protected void Page_Load(object sender, EventArgs e) { try { var token = GoogleLoginProvider.Instance.Auth(HttpContext.Current); ImportContacts(token); Master.SubmitContacts(); } catch (ThreadAbortException) { } catch (Exception ex) { Master.SubmitError(ex.Message); } } private void ImportContacts(OAuth20Token token) { var doc = RequestContacts(token); //selecting from xdocument var contacts = doc.Root.Elements("{http://www.w3.org/2005/Atom}entry") .Select(e => new { Name = e.Element("{http://www.w3.org/2005/Atom}title").Value, Email = e.Elements("{http://schemas.google.com/g/2005}email") .Where(a => a.Attribute("address") != null) .Select(a => a.Attribute("address").Value) .FirstOrDefault() }).ToList(); foreach (var contact in contacts) { Master.AddContactInfo(contact.Name, contact.Email); } } public XDocument RequestContacts(OAuth20Token token) { var response = RequestHelper.PerformRequest(GoogleLoginProvider.GoogleUrlContacts, headers: new Dictionary<string, string> { { "Authorization", "Bearer " + token.AccessToken } }); return XDocument.Parse(response); } } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/IMAP/Client/IMAP_FetchItem_Flags.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.IMAP.Client { /// <summary> /// Specifies what data is requested from IMAP server FETCH command. /// Fetch items are flags and can be combined. For example: IMAP_FetchItem_Flags.MessageFlags | IMAP_FetchItem_Flags.Header. /// </summary> public enum IMAP_FetchItem_Flags { /// <summary> /// Message UID value. /// </summary> UID = 1, /// <summary> /// Message size in bytes. /// </summary> Size = 2, /// <summary> /// Message IMAP server INTERNALDATE. /// </summary> InternalDate = 4, /// <summary> /// Fetches message flags. (\SEEN \ANSWERED ...) /// </summary> MessageFlags = 8, /// <summary> /// Fetches message header. /// </summary> Header = 16, /// <summary> /// Fetches full message. /// </summary> Message = 32, /// <summary> /// Fetches message ENVELOPE structure. /// </summary> Envelope = 64, /// <summary> /// Fetches message BODYSTRUCTURE structure. /// </summary> BodyStructure = 128, /// <summary> /// Fetches all info. /// </summary> All = 0xFFFF } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/Data/LDB_DataColumn.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Data.lsDB { #region usings using System; using System.Text; #endregion /// <summary> /// /// </summary> public class LDB_DataColumn { #region Members private string m_ColumnName = ""; private int m_ColumSize = -1; private LDB_DataType m_DataType = LDB_DataType.String; #endregion #region Properties /// <summary> /// Gets LDB data type. /// </summary> public LDB_DataType DataType { get { return m_DataType; } } /// <summary> /// Gets column name. /// </summary> public string ColumnName { get { return m_ColumnName; } } /// <summary> /// Gets column size. Returns -1 if column is with variable length. /// </summary> public int ColumnSize { get { return m_ColumSize; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="columnName">Column name.</param> /// <param name="dataType">Column data type.</param> public LDB_DataColumn(string columnName, LDB_DataType dataType) : this(columnName, dataType, -1) {} /// <summary> /// Default constructor. /// </summary> /// <param name="columnName">Column name.</param> /// <param name="dataType">Column data type.</param> /// <param name="columnSize">Specifies column data size. This is available for String datatype only.</param> public LDB_DataColumn(string columnName, LDB_DataType dataType, int columnSize) { m_ColumnName = columnName; m_DataType = dataType; // TODO: check that column name won't exceed 50 bytes if (dataType == LDB_DataType.Bool) { m_ColumSize = 1; } else if (dataType == LDB_DataType.DateTime) { m_ColumSize = 13; } else if (dataType == LDB_DataType.Int) { m_ColumSize = 4; } else if (dataType == LDB_DataType.Long) { m_ColumSize = 8; } else { m_ColumSize = columnSize; } } /// <summary> /// Internal constructor. /// </summary> internal LDB_DataColumn() {} #endregion #region Internal methods /// <summary> /// Gets string from char(0) terminated text. /// </summary> /// <param name="text">Text.</param> /// <returns></returns> internal static string GetChar0TerminatedString(string text) { if (text.IndexOf('\0') > -1) { return text.Substring(0, text.IndexOf('\0')); } else { return text; } } /// <summary> /// Parses column from byte[] data. /// </summary> /// <param name="columnData">Column data.</param> internal void Parse(byte[] columnData) { if (columnData.Length != 102) { throw new Exception("Invalid column data length '" + columnData.Length + "' !"); } //-- total 102 bytes // 1 byte - column type // 4 bytes - column size // 45 bytes - reserved // 50 bytes - column name // 2 bytes - CRLF // column type m_DataType = (LDB_DataType) columnData[0]; // column size m_ColumSize = (columnData[1] << 24) | (columnData[2] << 16) | (columnData[3] << 8) | (columnData[4] << 0); // reserved // 45 bytes // column name byte[] columnName = new byte[50]; Array.Copy(columnData, 50, columnName, 0, columnName.Length); m_ColumnName = GetChar0TerminatedString(Encoding.UTF8.GetString(columnName)); if (m_DataType == LDB_DataType.Bool) { m_ColumSize = 1; } else if (m_DataType == LDB_DataType.DateTime) { m_ColumSize = 13; } else if (m_DataType == LDB_DataType.Int) { m_ColumSize = 4; } else if (m_DataType == LDB_DataType.Long) { m_ColumSize = 8; } } /// <summary> /// Convert column to byte[] data. /// </summary> /// <returns></returns> internal byte[] ToColumnInfo() { //-- total 100 + CRLF bytes // 1 byte - column type // 4 bytes - column size // 45 bytes - reserved // 50 bytes - column name // CRLF byte[] columnData = new byte[102]; // column type columnData[0] = (byte) m_DataType; // column size columnData[1] = (byte) ((m_ColumSize & (1 << 24)) >> 24); columnData[2] = (byte) ((m_ColumSize & (1 << 16)) >> 16); columnData[3] = (byte) ((m_ColumSize & (1 << 8)) >> 8); columnData[4] = (byte) ((m_ColumSize & (1 << 0)) >> 0); // reserved // 45 bytes // column name byte[] columnName = Encoding.UTF8.GetBytes(m_ColumnName); Array.Copy(columnName, 0, columnData, 50, columnName.Length); // CRLF columnData[100] = (byte) '\r'; columnData[101] = (byte) '\n'; return columnData; } #endregion } }<file_sep>/module/ASC.Api/ASC.Api.Security/SecurityApi.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using ASC.Api.Attributes; using ASC.Api.Interfaces; using ASC.AuditTrail; using ASC.AuditTrail.Data; using ASC.Core; using ASC.Core.Billing; using ASC.Core.Tenants; using ASC.MessagingSystem; using ASC.Web.Studio.Core; using ASC.Web.Studio.Utility; using Resources; using System; using System.Collections.Generic; using System.Linq; using System.Web; using SecurityContext = ASC.Core.SecurityContext; namespace ASC.Api.Security { public class SecurityApi : IApiEntryPoint { private static HttpRequest Request { get { return HttpContext.Current.Request; } } public string Name { get { return "security"; } } [Read("/audit/login/last")] public IEnumerable<LoginEventWrapper> GetLastLoginEvents() { SecurityContext.DemandPermissions(SecutiryConstants.EditPortalSettings); if (!SetupInfo.IsVisibleSettings(ManagementType.LoginHistory.ToString()) || CoreContext.Configuration.Standalone && !CoreContext.TenantManager.GetTenantQuota(TenantProvider.CurrentTenantID).Audit) throw new BillingException(Resource.ErrorNotAllowedOption, "Audit"); return LoginEventsRepository.GetLast(TenantProvider.CurrentTenantID, 20).Select(x => new LoginEventWrapper(x)); } [Read("/audit/events/last")] public IEnumerable<AuditEventWrapper> GetLastAuditEvents() { SecurityContext.DemandPermissions(SecutiryConstants.EditPortalSettings); if (!SetupInfo.IsVisibleSettings(ManagementType.AuditTrail.ToString()) || CoreContext.Configuration.Standalone && !CoreContext.TenantManager.GetTenantQuota(TenantProvider.CurrentTenantID).Audit) throw new BillingException(Resource.ErrorNotAllowedOption, "Audit"); return AuditEventsRepository.GetLast(TenantProvider.CurrentTenantID, 20).Select(x => new AuditEventWrapper(x)); } [Create("/audit/login/report")] public string CreateLoginHistoryReport() { SecurityContext.DemandPermissions(SecutiryConstants.EditPortalSettings); var tenantId = TenantProvider.CurrentTenantID; if (!SetupInfo.IsVisibleSettings(ManagementType.LoginHistory.ToString()) || CoreContext.Configuration.Standalone && !CoreContext.TenantManager.GetTenantQuota(tenantId).Audit) throw new BillingException(Resource.ErrorNotAllowedOption, "Audit"); var settings = TenantAuditSettings.LoadForTenant(tenantId); var to = DateTime.UtcNow; var from = to.Subtract(TimeSpan.FromDays(settings.LoginHistoryLifeTime)); var reportName = string.Format(AuditReportResource.LoginHistoryReportName + ".csv", from.ToString("MM.dd.yyyy"), to.ToString("MM.dd.yyyy")); var events = LoginEventsRepository.Get(tenantId, from, to); var result = AuditReportCreator.CreateCsvReport(events, reportName); MessageService.Send(Request, MessageAction.LoginHistoryReportDownloaded); return result; } [Create("/audit/events/report")] public string CreateAuditTrailReport() { SecurityContext.DemandPermissions(SecutiryConstants.EditPortalSettings); var tenantId = TenantProvider.CurrentTenantID; if (!SetupInfo.IsVisibleSettings(ManagementType.AuditTrail.ToString()) || CoreContext.Configuration.Standalone && !CoreContext.TenantManager.GetTenantQuota(tenantId).Audit) throw new BillingException(Resource.ErrorNotAllowedOption, "Audit"); var settings = TenantAuditSettings.LoadForTenant(tenantId); var to = DateTime.UtcNow; var from = to.Subtract(TimeSpan.FromDays(settings.AuditTrailLifeTime)); var reportName = string.Format(AuditReportResource.AuditTrailReportName + ".csv", from.ToString("MM.dd.yyyy"), to.ToString("MM.dd.yyyy")); var events = AuditEventsRepository.Get(tenantId, from, to); var result = AuditReportCreator.CreateCsvReport(events, reportName); MessageService.Send(Request, MessageAction.AuditTrailReportDownloaded); return result; } [Read("/audit/settings/lifetime")] public TenantAuditSettings GetAuditSettings() { SecurityContext.DemandPermissions(SecutiryConstants.EditPortalSettings); return TenantAuditSettings.LoadForTenant(TenantProvider.CurrentTenantID); } [Create("/audit/settings/lifetime")] public TenantAuditSettings SetAuditSettings(TenantAuditSettings settings) { SecurityContext.DemandPermissions(SecutiryConstants.EditPortalSettings); if (settings.LoginHistoryLifeTime <= 0 || settings.LoginHistoryLifeTime > TenantAuditSettings.MaxLifeTime) throw new ArgumentException("LoginHistoryLifeTime"); if (settings.AuditTrailLifeTime <= 0 || settings.AuditTrailLifeTime > TenantAuditSettings.MaxLifeTime) throw new ArgumentException("AuditTrailLifeTime"); settings.SaveForTenant(TenantProvider.CurrentTenantID); MessageService.Send(Request, MessageAction.AuditSettingsUpdated); return settings; } } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/_Obsolete/MIME/Address.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.Mime { #region usings using System; #endregion /// <summary> /// Rfc 2822 3.4 Address class. This class is base class for MailboxAddress and GroupAddress. /// </summary> [Obsolete("See LumiSoft.Net.MIME or LumiSoft.Net.Mail namepaces for replacement.")] public abstract class Address { #region Members private readonly bool m_GroupAddress; #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="groupAddress">Spcified is address is group or mailbox address.</param> public Address(bool groupAddress) { m_GroupAddress = groupAddress; } #endregion #region Properties /// <summary> /// Gets if address is group address or mailbox address. /// </summary> public bool IsGroupAddress { get { return m_GroupAddress; } } /// <summary> /// Gets or sets owner of this address. /// </summary> internal object Owner { get; set; } #endregion } }<file_sep>/module/ASC.Mail/ASC.Mail/Core/Engine/Operations/MailDownloadAllAttachmentsOperation.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.IO; using System.Linq; using System.Text; using System.Threading; using ASC.Common.Logging; using ASC.Common.Security.Authentication; using ASC.Core; using ASC.Core.Tenants; using ASC.Mail.Resources; using ASC.Mail.Core.Engine.Operations.Base; using ASC.Mail.Core.Dao.Expressions.Attachment; using ASC.Mail.Data.Storage; using ASC.Web.Core.Files; using ASC.Web.Files.Classes; using ASC.Files.Core; using ASC.Data.Storage; using Ionic.Zip; using Ionic.Zlib; using Resources; namespace ASC.Mail.Core.Engine.Operations { public class MailDownloadAllAttachmentsOperation : MailOperation { public int MessageId { get; set; } public ILog Log { get; set; } public override MailOperationType OperationType { get { return MailOperationType.DownloadAllAttachments; } } public MailDownloadAllAttachmentsOperation(Tenant tenant, IAccount user, int messageId) : base(tenant, user) { MessageId = messageId; Log = LogManager.GetLogger("ASC.Mail.MailDownloadAllAttachmentsOperation"); } protected override void Do() { try { SetProgress((int?) MailOperationDownloadAllAttachmentsProgress.Init); CoreContext.TenantManager.SetCurrentTenant(CurrentTenant); try { SecurityContext.AuthenticateMe(CurrentUser); } catch { Error = Resource.SsoSettingsNotValidToken; Logger.Error(Error); } var engine = new EngineFactory(CurrentTenant.TenantId, CurrentUser.ID.ToString()); SetProgress((int?) MailOperationDownloadAllAttachmentsProgress.GetAttachments); var attachments = engine.AttachmentEngine.GetAttachments(new ConcreteMessageAttachmentsExp(MessageId, CurrentTenant.TenantId, CurrentUser.ID.ToString())); if (!attachments.Any()) { Error = MailCoreResource.NoAttachmentsInMessage; throw new Exception(Error); } SetProgress((int?) MailOperationDownloadAllAttachmentsProgress.Zipping); var damagedAttachments = 0; using (var stream = TempStream.Create()) { using (var zip = new ZipOutputStream(stream, true)) { zip.CompressionLevel = CompressionLevel.Level3; zip.AlternateEncodingUsage = ZipOption.AsNecessary; zip.AlternateEncoding = Encoding.GetEncoding(Thread.CurrentThread.CurrentCulture.TextInfo.OEMCodePage); var attachmentsCount = attachments.Count; var progressMaxValue = (int) MailOperationDownloadAllAttachmentsProgress.ArchivePreparation; var progressMinValue = (int) MailOperationDownloadAllAttachmentsProgress.Zipping; var progresslength = progressMaxValue - progressMinValue; var progressStep = (double) progresslength/attachmentsCount; var zippingProgress = 0.0; foreach (var attachment in attachments) { try { using (var file = attachment.ToAttachmentStream()) { ZipFile(zip, file.FileName, file.FileStream); } } catch (Exception ex) { Logger.Error(ex); Error = string.Format(MailCoreResource.FileNotFoundOrDamaged, attachment.fileName); damagedAttachments++; ZipFile(zip, attachment.fileName); // Zip empty file } zippingProgress += progressStep; SetProgress(progressMinValue + (int?) zippingProgress); } } SetProgress((int?) MailOperationDownloadAllAttachmentsProgress.ArchivePreparation); if (stream.Length == 0) { Error = "File stream is empty"; throw new Exception(Error); } stream.Position = 0; var store = Global.GetStore(); var path = store.Save( FileConstant.StorageDomainTmp, string.Format(@"{0}\{1}", ((IAccount) Thread.CurrentPrincipal.Identity).ID, Defines.ARCHIVE_NAME), stream, "application/zip", "attachment; filename=\"" + Defines.ARCHIVE_NAME + "\""); Log.DebugFormat("Zipped archive has been stored to {0}", path.ToString()); } SetProgress((int?) MailOperationDownloadAllAttachmentsProgress.CreateLink); var baseDomain = CoreContext.Configuration.BaseDomain; var source = string.Format("{0}?{1}=bulk", "/Products/Files/HttpHandlers/filehandler.ashx", FilesLinkUtility.Action); if (damagedAttachments > 1) Error = string.Format(MailCoreResource.FilesNotFound, damagedAttachments); SetProgress((int?)MailOperationDownloadAllAttachmentsProgress.Finished, null, source); } catch (Exception ex) { Logger.ErrorFormat("Mail operation error -> Download all attachments: {0}", ex.ToString()); Error = string.IsNullOrEmpty(Error) ? "InternalServerError" : Error; } } private static void ZipFile(ZipOutputStream zip, string filename, Stream fileStream = null) { filename = filename ?? "file"; if (zip.ContainsEntry(filename)) { var counter = 1; var tempName = filename; while (zip.ContainsEntry(tempName)) { tempName = filename; var suffix = " (" + counter + ")"; tempName = 0 < tempName.IndexOf('.') ? tempName.Insert(tempName.LastIndexOf('.'), suffix) : tempName + suffix; counter++; } filename = tempName; } zip.PutNextEntry(filename); if (fileStream != null) { fileStream.CopyTo(zip); } } } } <file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/SIP/Proxy/SIP_Route.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.SIP.Proxy { #region usings using System.Net; #endregion /// <summary> /// /// </summary> public class SIP_Route { #region Properties /// <summary> /// Gets regex match pattern. /// </summary> public string MatchPattern { get { return ""; } } /// <summary> /// Gets matched URI. /// </summary> public string Uri { get { return ""; } } /// <summary> /// Gets SIP targets for <b>Uri</b>. /// </summary> public string[] Targets { get { return null; } } /// <summary> /// Gets targets processing mode. /// </summary> public SIP_ForkingMode ProcessMode { get { return SIP_ForkingMode.Parallel; } } /// <summary> /// Gets if user needs to authenticate to use this route. /// </summary> public bool RequireAuthentication { get { return true; } } /// <summary> /// Gets targets credentials. /// </summary> public NetworkCredential[] Credentials { get { return null; } } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/IMAP/Server/IMAP_eArgs_GETACL.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.IMAP.Server { #region usings using System.Collections; #endregion /// <summary> /// Provides data for GetFolderACL event. /// </summary> public class IMAP_GETACL_eArgs { #region Members private readonly Hashtable m_ACLs; private readonly string m_pFolderName = ""; private readonly IMAP_Session m_pSession; private string m_ErrorText = ""; #endregion #region Properties /// <summary> /// Gets current IMAP session. /// </summary> public IMAP_Session Session { get { return m_pSession; } } /// <summary> /// Gets folder name which ACL to get. /// </summary> public string Folder { get { return m_pFolderName; } } /// <summary> /// Gets ACL collection. Key = userName, Value = IMAP_ACL_Flags. /// </summary> public Hashtable ACL { get { return m_ACLs; } } /// <summary> /// Gets or sets error text returned to connected client. /// </summary> public string ErrorText { get { return m_ErrorText; } set { m_ErrorText = value; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="session">Owner IMAP session.</param> /// <param name="folderName">Folder name which ACL to get.</param> public IMAP_GETACL_eArgs(IMAP_Session session, string folderName) { m_pSession = session; m_pFolderName = folderName; m_ACLs = new Hashtable(); } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/Data/_DataPage.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Data.lsDB { #region usings using System; #endregion /// <summary> /// Data page. /// </summary> internal class DataPage { #region Members private readonly byte[] m_Data; private readonly int m_DataAreaSize = 1000; private readonly long m_OwnerID; private readonly DbFile m_pOwnerDB; private readonly long m_StartPointer; private readonly bool m_Used; private long m_NextDataPagePointer; private long m_OwnerDataPagePointer; private int m_StoredDataLength; #endregion #region Properties /// <summary> /// Gets data page size on disk in bytes. /// </summary> public int DataPageSize { get { return 33 + DataAreaSize; } } /// <summary> /// Gets this data page address (offset in database file). /// </summary> public long Pointer { get { return m_StartPointer; } } /// <summary> /// Gets or sets if data page used or free space. /// </summary> public bool Used { get { return m_Used; } set { m_pOwnerDB.SetFilePosition(m_StartPointer + 2); m_pOwnerDB.WriteToFile(new[] {Convert.ToByte(value)}, 0, 1); } } /// <summary> /// Gets owner object id what owns this data page. /// </summary> public long OwnerID { get { return m_OwnerID; } } /// <summary> /// Gets or sets owner data page pointer. /// Returns 0 if this is first data page of multiple data pages or only data page. /// </summary> public long OwnerDataPagePointer { get { return m_OwnerDataPagePointer; } set { // owner data page pointer m_pOwnerDB.SetFilePosition(m_StartPointer + 11); m_pOwnerDB.WriteToFile(ldb_Utils.LongToByte(value), 0, 8); m_OwnerDataPagePointer = value; } } /// <summary> /// Gets or sets pointer to data page what continues this data page. /// Returns 0 if data page has enough room for data and there isn't continuing data page. /// </summary> public long NextDataPagePointer { get { return m_NextDataPagePointer; } set { // continuing data page pointer m_pOwnerDB.SetFilePosition(m_StartPointer + 19); m_pOwnerDB.WriteToFile(ldb_Utils.LongToByte(value), 0, 8); m_NextDataPagePointer = value; } } /* /// <summary> /// Gets or sets data that data page holds. Maximum size is this.DataAreaSize. Returns null if no data stored. /// </summary> public byte[] Data { get{ byte[] data = new byte[m_StoredDataLength]; m_pDbFileStream.Position = m_StartPointer + 33; m_pDbFileStream.Read(data,0,data.Length); return data; } set{ if(value.Length > this.DataAreaSize){ throw new Exception("Data page can't store more than " + this.DataAreaSize + " bytes, use mutliple data pages !"); } // Set stored data length m_pDbFileStream.Position = m_StartPointer + 27; byte[] dataLength = ldb_Utils.IntToByte(value.Length); m_pDbFileStream.Write(dataLength,0,dataLength.Length); // Store data m_pDbFileStream.Position = m_StartPointer + 33; m_pDbFileStream.Write(value,0,value.Length); m_StoredDataLength = value.Length; } } */ /// <summary> /// Gets how many data data page can store. /// </summary> public int DataAreaSize { get { return m_DataAreaSize; } } /// <summary> /// Gets stored data length. /// </summary> public int StoredDataLength { get { return m_StoredDataLength; } } /// <summary> /// Gets how much free data space is availabe in data page. /// </summary> public long SpaceAvailable { get { return DataAreaSize - m_StoredDataLength; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="dataPageDataAreaSize">Specifies how much data data page can store.</param> /// <param name="ownerDB">Owner DB file..</param> /// <param name="startOffset">Data page start offset pointer.</param> public DataPage(int dataPageDataAreaSize, DbFile ownerDB, long startOffset) { /* DataPage structure 2 bytes - CRLF 1 byte - used (f - unused,u - used) 8 byte - owner object id 8 bytes - owner data page pointer 8 bytes - continuing data page pointer 4 bytes - stored data length in data area 2 bytes - CRLF 1000 bytes - data area */ m_DataAreaSize = dataPageDataAreaSize; m_pOwnerDB = ownerDB; m_StartPointer = startOffset; byte[] dataPageInfo = new byte[33]; ownerDB.SetFilePosition(startOffset); ownerDB.ReadFromFile(dataPageInfo, 0, dataPageInfo.Length); m_Data = new byte[dataPageDataAreaSize]; ownerDB.ReadFromFile(m_Data, 0, dataPageDataAreaSize); // CRLF if (dataPageInfo[0] != (byte) '\r') { throw new Exception( "Not right data page startOffset, or invalid data page <CR> is expected but is '" + (int) dataPageInfo[0] + "' !"); } if (dataPageInfo[1] != (byte) '\n') { throw new Exception( "Not right data page startOffset, or invalid data page <LF> is expected but is '" + (int) dataPageInfo[1] + "' !"); } // used if (dataPageInfo[2] == (byte) 'u') { m_Used = true; } else { m_Used = false; } // owner object id m_OwnerID = ldb_Utils.ByteToLong(dataPageInfo, 3); // owner data page pointer m_OwnerDataPagePointer = ldb_Utils.ByteToLong(dataPageInfo, 11); // continuing data page pointer m_NextDataPagePointer = ldb_Utils.ByteToLong(dataPageInfo, 19); // stored data length in data area m_StoredDataLength = ldb_Utils.ByteToInt(dataPageInfo, 27); // CRLF if (dataPageInfo[31] != (byte) '\r') { throw new Exception( "Not right data page startOffset, or invalid data page <CR> is expected but is '" + (int) dataPageInfo[31] + "' !"); } if (dataPageInfo[32] != (byte) '\n') { throw new Exception( "Not right data page startOffset, or invalid data page <LF> is expected but is '" + (int) dataPageInfo[32] + "' !"); } } #endregion #region Methods /// <summary> /// Creates new data page structure. /// </summary> /// <param name="dataPageDataAreaSize">Specifies how much data can data page store.</param> /// <param name="used">Specifies if data page is used or free space. If this value is false, all toher parameters aren't stored.</param> /// <param name="ownerID">Owner data object ID.</param> /// <param name="ownerDataPagePointer">This data page owner data page pointer. This value can be 0, if no owner.</param> /// <param name="nextDataPagePointer">Data page pointer, what continues this data page. This value can be 0 if, data page won't spread to multiple data pages.</param> /// <param name="data">Data what data page stores. Maximum length is dataPageDataAreaSize.</param> /// <returns></returns> public static byte[] CreateDataPage(int dataPageDataAreaSize, bool used, long ownerID, long ownerDataPagePointer, long nextDataPagePointer, byte[] data) { /* DataPage structure 2 bytes - CRLF 1 byte - used (f - unused,u - used) 8 byte - owner object id 8 bytes - owner data page pointer 8 bytes - continuing data page pointer 4 bytes - stored data length in data area 2 bytes - CRLF dataPageDataAreaSize bytes - data area */ if (data.Length > dataPageDataAreaSize) { throw new Exception("Data page can store only " + dataPageDataAreaSize + " bytes, data conatins '" + data.Length + "' bytes !"); } byte[] dataPage = new byte[dataPageDataAreaSize + 33]; // CRLF dataPage[0] = (byte) '\r'; dataPage[1] = (byte) '\n'; if (used) { // used dataPage[2] = (byte) 'u'; // owner object id Array.Copy(ldb_Utils.LongToByte(ownerID), 0, dataPage, 3, 8); // owner data page pointer Array.Copy(ldb_Utils.LongToByte(ownerDataPagePointer), 0, dataPage, 11, 8); // continuing data page pointer Array.Copy(ldb_Utils.LongToByte(nextDataPagePointer), 0, dataPage, 19, 8); // stored data length in data area Array.Copy(ldb_Utils.IntToByte(data.Length), 0, dataPage, 27, 4); // CRLF dataPage[31] = (byte) '\r'; dataPage[32] = (byte) '\n'; // data area Array.Copy(data, 0, dataPage, 33, data.Length); } else { // used dataPage[2] = (byte) 'f'; // CRLF dataPage[31] = (byte) '\r'; dataPage[32] = (byte) '\n'; } return dataPage; } /// <summary> /// Reads specified amount data to buffer. /// </summary> /// <param name="buffer">Buffer where to store data.</param> /// <param name="startIndexInBuffer">Start index in buffer where data storing begins. Start index is included.</param> /// <param name="length">Number of bytes to read.</param> /// <param name="startOffset">Zero based offset of data area.</param> /// <returns></returns> public void ReadData(byte[] buffer, int startIndexInBuffer, int length, int startOffset) { if (startOffset < 0) { throw new Exception("startOffset can't negative value !"); } if ((length + startOffset) > DataAreaSize) { throw new Exception("startOffset and length are out of range data page data area !"); } if ((length + startOffset) > m_StoredDataLength) { throw new Exception( "There isn't so much data stored in data page as requested ! Stored data length = " + m_StoredDataLength + "; start offset = " + startOffset + "; length wanted = " + length); } Array.Copy(m_Data, startOffset, buffer, startIndexInBuffer, length); } /// <summary> /// Reads data page data. Offset byte is included. /// </summary> /// <param name="startOffset">Zero based offset of data area.</param> /// <param name="length">Specifies how much data to read.</param> /// <returns></returns> public byte[] ReadData(int startOffset, int length) { if (startOffset < 0) { throw new Exception("startOffset can't negative value !"); } if ((length + startOffset) > DataAreaSize) { throw new Exception("startOffset and length are out of range data page data area !"); } if ((length + startOffset) > m_StoredDataLength) { throw new Exception( "There isn't so much data stored in data page as requested ! Stored data length = " + m_StoredDataLength + "; start offset = " + startOffset + "; length wanted = " + length); } byte[] data = new byte[length]; Array.Copy(m_Data, startOffset, data, 0, length); return data; } /// <summary> /// Writed data to data page. /// </summary> /// <param name="data">Data to write.</param> public void WriteData(byte[] data) { if (data.Length > DataAreaSize) { throw new Exception("Data page can't store more than " + DataAreaSize + " bytes, use mutliple data pages !"); } // Set stored data length m_pOwnerDB.SetFilePosition(m_StartPointer + 27); m_pOwnerDB.WriteToFile(ldb_Utils.IntToByte(data.Length), 0, 4); // Store data m_pOwnerDB.SetFilePosition(m_StartPointer + 33); m_pOwnerDB.WriteToFile(data, 0, data.Length); m_StoredDataLength = data.Length; } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/ABNF/ABFN.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.ABNF { #region usings using System; using System.Collections.Generic; #endregion /// <summary> /// This class implements ABNF parser. Defined in RFC 5234. /// </summary> public class ABFN { #region Members private readonly List<ABNF_Rule> m_pRules; #endregion #region Properties /// <summary> /// Gets ABNF rules collection. /// </summary> public List<ABNF_Rule> Rules { get { return m_pRules; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> public ABFN() { m_pRules = new List<ABNF_Rule>(); Init(); } #endregion #region Methods /// <summary> /// Parses and adds ABNF rules from the specified ABFN string. /// </summary> /// <param name="value">ABNF string.</param> /// <exception cref="ArgumentNullException">Is raised when <b>value</b> is null reference.</exception> public void AddRules(string value) { if (value == null) { throw new ArgumentNullException("value"); } // TODO: } #endregion #region Utility methods private void Init() { #region Add basic rules /* ALPHA = %x41-5A / %x61-7A ; A-Z / a-z BIT = "0" / "1" CHAR = %x01-7F ; any 7-bit US-ASCII character, ; excluding NUL CR = %x0D ; carriage return CRLF = CR LF ; Internet standard newline CTL = %x00-1F / %x7F ; controls DIGIT = %x30-39 ; 0-9 DQUOTE = %x22 ; " (Double Quote) HEXDIG = DIGIT / "A" / "B" / "C" / "D" / "E" / "F" HTAB = %x09 ; horizontal tab LF = %x0A ; linefeed LWSP = *(WSP / CRLF WSP) ; Use of this linear-white-space rule ; permits lines containing only white ; space that are no longer legal in ; mail headers and have caused ; interoperability problems in other ; contexts. ; Do not use when defining mail ; headers and use with caution in ; other contexts. OCTET = %x00-FF ; 8 bits of data SP = %x20 VCHAR = %x21-7E ; visible (printing) characters WSP = SP / HTAB ; white space */ #endregion } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/SIP/Message/SIP_t_MinSE.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.SIP.Message { #region usings using System; using System.Text; #endregion /// <summary> /// Implements SIP "Min-SE" value. Defined in RFC 4028. /// </summary> /// <remarks> /// <code> /// RFC 4028 Syntax: /// Min-SE = delta-seconds *(SEMI generic-param) /// </code> /// </remarks> public class SIP_t_MinSE : SIP_t_ValueWithParams { #region Members private int m_Time = 90; #endregion #region Properties /// <summary> /// Gets or sets time in seconds when session expires. /// </summary> /// <exception cref="ArgumentException">Is raised when value is less than 1.</exception> public int Time { get { return m_Time; } set { if (m_Time < 1) { throw new ArgumentException("Time value must be > 0 !"); } m_Time = value; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="value">Min-SE value.</param> public SIP_t_MinSE(string value) { Parse(value); } /// <summary> /// Default constructor. /// </summary> /// <param name="minExpires">Minimum session expries value in seconds.</param> public SIP_t_MinSE(int minExpires) { m_Time = minExpires; } #endregion #region Methods /// <summary> /// Parses "Min-SE" from specified value. /// </summary> /// <param name="value">SIP "Min-SE" value.</param> /// <exception cref="ArgumentNullException">Raised when <b>value</b> is null.</exception> /// <exception cref="SIP_ParseException">Raised when invalid SIP message.</exception> public void Parse(string value) { if (value == null) { throw new ArgumentNullException("value"); } Parse(new StringReader(value)); } /// <summary> /// Parses "Min-SE" from specified reader. /// </summary> /// <param name="reader">Reader from where to parse.</param> /// <exception cref="ArgumentNullException">Raised when <b>reader</b> is null.</exception> /// <exception cref="SIP_ParseException">Raised when invalid SIP message.</exception> public override void Parse(StringReader reader) { /* Min-SE = delta-seconds *(SEMI generic-param) */ if (reader == null) { throw new ArgumentNullException("reader"); } // Parse address string word = reader.ReadWord(); if (word == null) { throw new SIP_ParseException("Min-SE delta-seconds value is missing !"); } try { m_Time = Convert.ToInt32(word); } catch { throw new SIP_ParseException("Invalid Min-SE delta-seconds value !"); } // Parse parameters ParseParameters(reader); } /// <summary> /// Converts this to valid "Min-SE" value. /// </summary> /// <returns>Returns "Min-SE" value.</returns> public override string ToStringValue() { /* Min-SE = delta-seconds *(SEMI generic-param) */ StringBuilder retVal = new StringBuilder(); // Add address retVal.Append(m_Time.ToString()); // Add parameters retVal.Append(ParametersToString()); return retVal.ToString(); } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/STUN/Message/STUN_t_ChangeRequest.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.STUN.Message { /// <summary> /// This class implements STUN CHANGE-REQUEST attribute. Defined in RFC 3489 11.2.4. /// </summary> public class STUN_t_ChangeRequest { #region Members private bool m_ChangeIP = true; private bool m_ChangePort = true; #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> public STUN_t_ChangeRequest() {} /// <summary> /// Default constructor. /// </summary> /// <param name="changeIP">Specifies if STUN server must send response to different IP than request was received.</param> /// <param name="changePort">Specifies if STUN server must send response to different port than request was received.</param> public STUN_t_ChangeRequest(bool changeIP, bool changePort) { m_ChangeIP = changeIP; m_ChangePort = changePort; } #endregion #region Properties /// <summary> /// Gets or sets if STUN server must send response to different IP than request was received. /// </summary> public bool ChangeIP { get { return m_ChangeIP; } set { m_ChangeIP = value; } } /// <summary> /// Gets or sets if STUN server must send response to different port than request was received. /// </summary> public bool ChangePort { get { return m_ChangePort; } set { m_ChangePort = value; } } #endregion } }<file_sep>/web/studio/ASC.Web.Studio/UserControls/Statistics/PortalAnalytics/js/portalanalytics.js /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ jq(function () { jq("#portalAnalyticsView .button").on("click", function () { if (jq(this).hasClass("disable")) return; Teamlab.updatePortalAnalytics({}, jq("#portalAnalyticsOn").is(":checked"), { before: function () { LoadingBanner.showLoaderBtn("#portalAnalyticsView"); }, after: function () { LoadingBanner.hideLoaderBtn("#portalAnalyticsView"); }, success: function () { LoadingBanner.showMesInfoBtn("#portalAnalyticsView", ASC.Resources.Master.Resource.ChangesSuccessfullyAppliedMsg, "success"); }, error: function (params, errors) { LoadingBanner.showMesInfoBtn("#portalAnalyticsView", errors[0], "error"); } }); }); });<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/SNTP/Client/SNTP_Client.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections.Generic; using System.Text; namespace LumiSoft.Net.SNTP.Client { /// <summary> /// This class implments Simple Network Time Protocol (SNTP) protocol. Defined in RFC 2030. /// </summary> public class SNTP_Client { /// <summary> /// Gets UTC time from NTP server. /// </summary> /// <param name="server">NTP server.</param> /// <param name="port">NTP port. Default NTP port is 123.</param> /// <returns>Returns UTC time.</returns> public static DateTime GetTime(string server,int port) { /* RFC 2030 4. Below is a description of the NTP/SNTP Version 4 message format, which follows the IP and UDP headers. This format is identical to that described in RFC-1305, with the exception of the contents of the reference identifier field. The header fields are defined as follows: 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |LI | VN |Mode | Stratum | Poll | Precision | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Root Delay | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Root Dispersion | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Reference Identifier | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | | | Reference Timestamp (64) | | | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | | | Originate Timestamp (64) | | | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | | | Receive Timestamp (64) | | | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | | | Transmit Timestamp (64) | | | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Key Identifier (optional) (32) | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | | | | | Message Digest (optional) (128) | | | | | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 2030 5. For unicast request we need to fill version and mode only. */ } } } <file_sep>/web/studio/ASC.Web.Studio/UserControls/Management/SmsControls/js/smsvalidation.js /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ ; window.ASC.Controls.SmsValidationSettings = (function () { return { SaveSmsValidationSettings: function () { AjaxPro.onLoading = function (loading) { if (loading) { LoadingBanner.showLoaderBtn("#sms-validation-settings"); } else { LoadingBanner.hideLoaderBtn("#sms-validation-settings"); } }; var smsEnable = jq("#chk2FactorAuthEnable").is(":checked"); var tfaAppEnable = jq("#chk2FactorAppAuthEnable").is(":checked"); var callback = { success: function (_, data) { LoadingBanner.showMesInfoBtn("#studio_smsValidationSettings", ASC.Resources.Master.Resource.SuccessfullySaveSettingsMessage, "success"); if (data) { window.location.reload(true); } }, error: function (params, error) { LoadingBanner.showMesInfoBtn("#studio_smsValidationSettings", error[0], "error"); } }; if (smsEnable) { Teamlab.tfaAppAuthSettings("sms", callback); } else if (tfaAppEnable) { Teamlab.tfaAppAuthSettings("app", callback); } else { Teamlab.tfaAppAuthSettings("none", callback); } } }; })(); (function () { jq(function () { jq("#studio_smsValidationSettings").on("click", "#chk2FactorAuthSave:not(.disable)", ASC.Controls.SmsValidationSettings.SaveSmsValidationSettings); jq("input[name=\"chk2FactorAuth\"]").change(function () { jq("#chk2FactorAuthSave").removeClass("disable"); }); }); })();<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/Log/LogEntry.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.Log { #region usings using System; using System.Net; using System.Security.Principal; #endregion /// <summary> /// Implements log entry. /// </summary> public class LogEntry { #region Members private readonly string m_ID = ""; private readonly byte[] m_pData; private readonly Exception m_pException; private readonly IPEndPoint m_pLocalEP; private readonly IPEndPoint m_pRemoteEP; private readonly GenericIdentity m_pUserIdentity; private readonly long m_Size; private readonly string m_Text = ""; private readonly DateTime m_Time; private readonly LogEntryType m_Type = LogEntryType.Text; #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="type">Log entry type.</param> /// <param name="id">Log entry ID.</param> /// <param name="size">Specified how much data was readed or written.</param> /// <param name="text">Description text.</param> public LogEntry(LogEntryType type, string id, long size, string text) { m_Type = type; m_ID = id; m_Size = size; m_Text = text; m_Time = DateTime.Now; } /// <summary> /// Default constructor. /// </summary> /// <param name="type">Log entry type.</param> /// <param name="id">Log entry ID.</param> /// <param name="userIdentity">Log entry owner user or null if none.</param> /// <param name="size">Log entry read/write size in bytes.</param> /// <param name="text">Log text.</param> /// <param name="localEP">Local IP end point.</param> /// <param name="remoteEP">Remote IP end point.</param> /// <param name="data">Log data.</param> public LogEntry(LogEntryType type, string id, GenericIdentity userIdentity, long size, string text, IPEndPoint localEP, IPEndPoint remoteEP, byte[] data) { m_Type = type; m_ID = id; m_pUserIdentity = userIdentity; m_Size = size; m_Text = text; m_pLocalEP = localEP; m_pRemoteEP = remoteEP; m_pData = data; m_Time = DateTime.Now; } /// <summary> /// Default constructor. /// </summary> /// <param name="type">Log entry type.</param> /// <param name="id">Log entry ID.</param> /// <param name="userIdentity">Log entry owner user or null if none.</param> /// <param name="size">Log entry read/write size in bytes.</param> /// <param name="text">Log text.</param> /// <param name="localEP">Local IP end point.</param> /// <param name="remoteEP">Remote IP end point.</param> /// <param name="exception">Exception happened. Can be null.</param> public LogEntry(LogEntryType type, string id, GenericIdentity userIdentity, long size, string text, IPEndPoint localEP, IPEndPoint remoteEP, Exception exception) { m_Type = type; m_ID = id; m_pUserIdentity = userIdentity; m_Size = size; m_Text = text; m_pLocalEP = localEP; m_pRemoteEP = remoteEP; m_pException = exception; m_Time = DateTime.Now; } #endregion #region Properties /// <summary> /// Gest log data. Value null means no log data. /// </summary> public byte[] Data { get { return m_pData; } } /// <summary> /// Gets log entry type. /// </summary> public LogEntryType EntryType { get { return m_Type; } } /// <summary> /// Gets exception happened. This property is available only if LogEntryType.Exception. /// </summary> public Exception Exception { get { return m_pException; } } /// <summary> /// Gets log entry ID. /// </summary> public string ID { get { return m_ID; } } /// <summary> /// Gets local IP end point. Value null means no local end point. /// </summary> public IPEndPoint LocalEndPoint { get { return m_pLocalEP; } } /// <summary> /// Gets remote IP end point. Value null means no remote end point. /// </summary> public IPEndPoint RemoteEndPoint { get { return m_pRemoteEP; } } /// <summary> /// Gets how much data was readed or written, depends on <b>LogEntryType</b>. /// </summary> public long Size { get { return m_Size; } } /// <summary> /// Gets describing text. /// </summary> public string Text { get { return m_Text; } } /// <summary> /// Gets time when log entry was created. /// </summary> public DateTime Time { get { return m_Time; } } /// <summary> /// Gets log entry related user identity. /// </summary> public GenericIdentity UserIdentity { get { return m_pUserIdentity; } } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/Mail/Mail_h_Mailbox.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.Mail { #region usings using System; using System.Text; using MIME; #endregion /// <summary> /// This class represent generic <b>mailbox</b> header fields. For example: Sender: header. /// </summary> /// <example> /// <code> /// RFC 5322. /// header = "FiledName:" mailbox CRLF /// </code> /// </example> public class Mail_h_Mailbox : MIME_h { #region Members private readonly string m_Name; private readonly Mail_t_Mailbox m_pAddress; private string m_ParseValue; #endregion #region Properties /// <summary> /// Gets if this header field is modified since it has loaded. /// </summary> /// <remarks>All new added header fields has <b>IsModified = true</b>.</remarks> /// <exception cref="ObjectDisposedException">Is riased when this class is disposed and this property is accessed.</exception> public override bool IsModified { get { return false; } } /// <summary> /// Gets header field name. For example "Sender". /// </summary> public override string Name { get { return m_Name; } } /// <summary> /// Gets mailbox address. /// </summary> public Mail_t_Mailbox Address { get { return m_pAddress; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="fieldName">Header field name. For example: "Sender".</param> /// <param name="mailbox">Mailbox value.</param> /// <exception cref="ArgumentNullException">Is raised when <b>filedName</b> or <b>mailbox</b> is null reference.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> public Mail_h_Mailbox(string fieldName, Mail_t_Mailbox mailbox) { if (fieldName == null) { throw new ArgumentNullException("fieldName"); } if (fieldName == string.Empty) { throw new ArgumentException("Argument 'fieldName' value must be specified."); } if (mailbox == null) { throw new ArgumentNullException("mailbox"); } m_Name = fieldName; m_pAddress = mailbox; } #endregion #region Methods /// <summary> /// Parses header field from the specified value. /// </summary> /// <param name="value">Header field value. Header field name must be included. For example: 'Sender: <EMAIL>'.</param> /// <returns>Returns parsed header field.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>value</b> is null reference.</exception> /// <exception cref="ParseException">Is raised when header field parsing errors.</exception> public static Mail_h_Mailbox Parse(string value) { if (value == null) { throw new ArgumentNullException("value"); } string[] name_value = value.Split(new[] {':'}, 2); if (name_value.Length != 2) { throw new ParseException("Invalid header field value '" + value + "'."); } MIME_Reader r = new MIME_Reader(name_value[1]); string word = r.QuotedReadToDelimiter(new[] {',', '<', ':'}); // Invalid value. if (word == null) { throw new ParseException("Invalid header field value '" + value + "'."); } // name-addr else if (r.Peek(true) == '<') { Mail_h_Mailbox h = new Mail_h_Mailbox(name_value[0], new Mail_t_Mailbox( word != null ? MIME_Encoding_EncodedWord.DecodeS( TextUtils.UnQuoteString(word)) : null, r.ReadParenthesized())); h.m_ParseValue = value; return h; } // addr-spec else { Mail_h_Mailbox h = new Mail_h_Mailbox(name_value[0], new Mail_t_Mailbox(null, word)); h.m_ParseValue = value; return h; } } /// <summary> /// Returns header field as string. /// </summary> /// <param name="wordEncoder">8-bit words ecnoder. Value null means that words are not encoded.</param> /// <param name="parmetersCharset">Charset to use to encode 8-bit characters. Value null means parameters not encoded.</param> /// <returns>Returns header field as string.</returns> public override string ToString(MIME_Encoding_EncodedWord wordEncoder, Encoding parmetersCharset) { if (m_ParseValue != null) { return m_ParseValue; } else { return m_Name + ": " + m_pAddress.ToString(wordEncoder) + "\r\n"; } } #endregion } }<file_sep>/web/studio/ASC.Web.Studio/UserControls/Users/UserProfile/js/userprofilecontrol.js /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ jq(function () { initActionMenu(); initTenantQuota(); initBorderPhoto(); jq("#userProfilePhoto img").on("load", function () { initBorderPhoto(); LoadingBanner.hideLoading(); }); jq("#loadPhotoImage").on("click", function () { ASC.Controls.LoadPhotoImage.showDialog(); }); jq("#joinToAffilliate:not(.disable)").on("click", function () { JoinToAffilliate(); }); if (jq("#studio_emailChangeDialog").length == 0) { jq(".profile-status.pending div").css("cursor", "default"); } else { jq("#linkNotActivatedActivation").on("click", function() { var userEmail = jq("#studio_userProfileCardInfo").attr("data-email"); var userId = jq("#studio_userProfileCardInfo").attr("data-id"); ASC.EmailOperationManager.sendEmailActivationInstructions(userEmail, userId, onActivateEmail.bind(null, userEmail)); return false; }); jq("#imagePendingActivation, #linkPendingActivation, #linkPendingEmailChange").on("click", function () { var userEmail = jq("#studio_userProfileCardInfo").attr("data-email"); var userId = jq("#studio_userProfileCardInfo").attr("data-id"); ASC.EmailOperationManager.showResendInviteWindow(userEmail, userId, Teamlab.profile.isAdmin, onActivateEmail.bind(null, userEmail)); return false; }); } jq.switcherAction("#switcherAccountLinks", ".account-links"); jq.switcherAction("#switcherLoginSettings", "#loginSettingsContainer") jq.switcherAction("#switcherCommentButton", "#commentContainer"); jq.switcherAction("#switcherContactsPhoneButton", "#contactsPhoneContainer"); jq.switcherAction("#switcherContactsSocialButton", "#contactsSocialContainer"); jq.switcherAction("#switcherSubscriptionButton", "#subscriptionContainer"); //track event jq("#joinToAffilliate").trackEvent("affilliate-button", "affilliate-button-click", ""); }); function initActionMenu() { var _top = jq(".profile-header").offset() == null ? 0 : -jq(".profile-header").offset().top, _left = jq(".profile-header").offset() == null ? 0 : -jq(".profile-header").offset().left, menuID = "actionMenu"; jq.dropdownToggle({ dropdownID: menuID, switcherSelector: ".header-with-menu .menu-small", addTop: _top, addLeft: _left - 11, showFunction: function(switcherObj, dropdownItem) { if (dropdownItem.is(":hidden")) { switcherObj.addClass("active"); } else { switcherObj.removeClass("active"); } }, hideFunction: function() { jq(".header-with-menu .menu-small.active").removeClass("active"); } }); jq(jq("#" + menuID).find(".dropdown-item")).on("click", function() { var $menuItem = jq("#" + menuID); var userId = $menuItem.attr("data-id"), userEmail = $menuItem.attr("data-email"), userAdmin = $menuItem.attr("data-admin") == "true", displayName = $menuItem.attr("data-displayname"), userName = $menuItem.attr("data-username"), isVisitor = $menuItem.attr("data-visitor").toLowerCase(), parent = jq(this).parent(); jq("#actionMenu").hide(); jq("#userMenu").removeClass("active"); if (jq(parent).hasClass("enable-user")) { onChangeUserStatus(userId, 1, isVisitor); } if (jq(parent).hasClass("disable-user")) { onChangeUserStatus(userId, 2, isVisitor); } if (jq(parent).hasClass("psw-change")) { PasswordTool.ShowPwdReminderDialog("1", userEmail); } if (jq(parent).hasClass("email-change")) { ASC.EmailOperationManager.showEmailChangeWindow(userEmail, userId); } if (jq(parent).hasClass("email-activate")) { ASC.EmailOperationManager.sendEmailActivationInstructions(userEmail, userId, onActivateEmail.bind(null, userEmail)); } if (jq(parent).hasClass("edit-photo")) { window.ASC.Controls.LoadPhotoImage.showDialog(); } if (jq(parent).hasClass("delete-user")) { jq("#actionMenu").hide(); StudioBlockUIManager.blockUI("#studio_deleteProfileDialog", 400); PopupKeyUpActionProvider.ClearActions(); PopupKeyUpActionProvider.EnterAction = 'SendInstrunctionsToRemoveProfile();'; } if (jq(parent).hasClass("delete-self")) { ProfileManager.RemoveUser(userId, displayName, userName, function () { window.location.replace("/Products/People/"); }); } if (jq(parent).hasClass("subscribe-tips")) { onChangeTipsSubscription(jq(this)); } }); } function onActivateEmail(userEmail, response) { var newEmail = response.request.args.email; var $oldEmail = jq("#emailUserProfile .mail"); var $menuItem = jq("#email-activate"); $menuItem.attr("data-email", newEmail); $oldEmail.attr("title", newEmail); $oldEmail.attr("href", $oldEmail.attr("href").replace(userEmail, newEmail)); $oldEmail.text(newEmail); jq("#studio_userProfileCardInfo").attr("data-email", newEmail); } function onChangeUserStatus(userID, status, isVisitor) { if (status == 1 && tenantQuota.availableUsersCount == 0 && isVisitor =="false") { if (jq("#tariffLimitExceedUsersPanel").length) { TariffLimitExceed.showLimitExceedUsers(); } return; } var user = new Array(); user.push(userID); var data = { userIds: user }; Teamlab.updateUserStatus({}, status, data, { success: function (params, data) { window.location.reload(true); //switch (status) { // case 1: // jq(".profile-status").show(); // jq(".profile-status.blocked").hide(); // jq(".enable-user, .delete-self").addClass("display-none"); // jq(".edit-user, .psw-change, .email-change, .disable-user, .email-activate").removeClass("display-none"); // break; // case 2: // jq(".profile-status").hide(); // jq(".profile-status.blocked").show(); // jq(".enable-user, .delete-self").removeClass("display-none"); // jq(".edit-user, .psw-change, .email-change, .disable-user, .email-activate").addClass("display-none"); // break; //} //toastr.success(ASC.People.Resources.PeopleJSResource.SuccessChangeUserStatus); //initTenantQuota(); }, before: LoadingBanner.displayLoading, after: LoadingBanner.hideLoading, error: function (params, errors) { toastr.error(errors); } }); } function onChangeTipsSubscription(obj) { Teamlab.updateTipsSubscription({ success: function (params, data) { var text = data ? ASC.Resources.Master.Resource.TipsAndTricksUnsubscribeBtn : ASC.Resources.Master.Resource.TipsAndTricksSubscribeBtn; obj.attr("title", text).html(text); toastr.success(ASC.Resources.Master.Resource.ChangesSuccessfullyAppliedMsg); }, before: LoadingBanner.displayLoading, after: LoadingBanner.hideLoading, error: function (params, errors) { toastr.error(errors); } }); } var tenantQuota = {}; var initTenantQuota = function () { Teamlab.getQuotas({}, { success: function (params, data) { tenantQuota = data; }, error: function (params, errors) { } }); }; function initBorderPhoto() { var $block = jq("#userProfilePhoto"), $img = $block.children("img"), indent = ($img.width() < $block.width() && $img.height() < 200 ) ? ($block.width() - $img.width()) / 2 : 0; $img.css("padding", indent + "px 0"); setStatusPosition(); }; function setStatusPosition() { var $block = jq("#userProfilePhoto"), $img = $block.children("img"), status = $block.siblings(".profile-status"); for (var i = 0, n = status.length; i < n; i++) { jq(status[i]).css({ top: ($img.outerHeight() - jq(status[i]).outerHeight()) / 2, left: ($block.width() - jq(status[i]).outerWidth()) / 2 }); if (jq(status[i]).attr("data-visible") !== "hidden") { jq(status[i]).show(); } } } function JoinToAffilliate() { Teamlab.joinAffiliate({}, { before: function (params) { jq("#joinToAffilliate").addClass("disable"); LoadingBanner.displayLoading(); }, after: function (params) { jq("#joinToAffilliate").removeClass("disable"); LoadingBanner.hideLoading(); }, success: function (params, response) { location.href = response; }, error: function (params, errors) { var err = errors[0]; jq("#errorAffilliate").text(err); } }); } var SendInstrunctionsToRemoveProfile = function () { Teamlab.removeSelf({}, { success: function (params, response) { jq.unblockUI(); toastr.success(response); } }); };<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/ABNF/ABNF_Option.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.ABNF { #region usings using System; using System.IO; #endregion /// <summary> /// This class represent ABNF "option". Defined in RFC 5234 4. /// </summary> public class ABNF_Option : ABNF_Element { #region Members private ABNF_Alternation m_pAlternation; #endregion #region Properties /// <summary> /// Gets option alternation elements. /// </summary> public ABNF_Alternation Alternation { get { return m_pAlternation; } } #endregion #region Methods /// <summary> /// /// </summary> /// <param name="reader"></param> /// <returns></returns> public static ABNF_Option Parse(StringReader reader) { if (reader == null) { throw new ArgumentNullException("reader"); } // option = "[" *c-wsp alternation *c-wsp "]" if (reader.Peek() != '[') { throw new ParseException("Invalid ABNF 'option' value '" + reader.ReadToEnd() + "'."); } // Eat "[". reader.Read(); // TODO: *c-wsp ABNF_Option retVal = new ABNF_Option(); // We reached end of stream, no closing "]". if (reader.Peek() == -1) { throw new ParseException("Invalid ABNF 'option' value '" + reader.ReadToEnd() + "'."); } retVal.m_pAlternation = ABNF_Alternation.Parse(reader); // We don't have closing ")". if (reader.Peek() != ']') { throw new ParseException("Invalid ABNF 'option' value '" + reader.ReadToEnd() + "'."); } else { reader.Read(); } return retVal; } #endregion } }<file_sep>/module/ASC.Socket.IO/app/controllers/mail.js module.exports = (counters) => { const router = require('express').Router(); router .post("/updateFolders", (req, res) => { counters.updateFolders(req.body); res.end(); }) .post("/sendMailNotification", (req, res) => { counters.sendMailNotification(req.body); res.end(); }); return router; }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/SIP/Stack/SIP_StatusLine.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.SIP.Stack { #region usings using System; #endregion /// <summary> /// Implements SIP Status-Line. Defined in RFC 3261. /// </summary> public class SIP_StatusLine { #region Members private string m_Reason = ""; private int m_StatusCode; private string m_Version = ""; #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="statusCode">Status code.</param> /// <param name="reason">Reason text.</param> /// <exception cref="ArgumentException">Is raised when </exception> /// <exception cref="ArgumentNullException">Is raised when <b>reason</b> is null reference.</exception> public SIP_StatusLine(int statusCode, string reason) { if (statusCode < 100 || statusCode > 699) { throw new ArgumentException("Argument 'statusCode' value must be >= 100 and <= 699."); } if (reason == null) { throw new ArgumentNullException("reason"); } m_Version = "SIP/2.0"; m_StatusCode = statusCode; m_Reason = reason; } #endregion #region Properties /// <summary> /// Gets or sets reason phrase. /// </summary> /// <exception cref="ArgumentNullException">Is raised when <b>value</b> is null reference.</exception> public string Reason { get { return m_Reason; } set { if (Reason == null) { throw new ArgumentNullException("Reason"); } m_Reason = value; } } /// <summary> /// Gets or sets status code. /// </summary> /// <exception cref="ArgumentException">Is raised when <b>value</b> has invalid value.</exception> public int StatusCode { get { return m_StatusCode; } set { if (value < 100 || value > 699) { throw new ArgumentException("Argument 'statusCode' value must be >= 100 and <= 699."); } m_StatusCode = value; } } /// <summary> /// Gets or sets SIP version. /// </summary> /// <exception cref="ArgumentNullException">Is raised when <b>value</b> is null reference.</exception> /// <exception cref="ArgumentException">Is raised when <b>value</b> has invalid value.</exception> public string Version { get { return m_Version; } set { if (value == null) { throw new ArgumentNullException("Version"); } if (value == "") { throw new ArgumentException("Property 'Version' value must be specified."); } m_Version = value; } } #endregion #region Methods /// <summary> /// Returns Status-Line string. /// </summary> /// <returns>Returns Status-Line string.</returns> public override string ToString() { // RFC 3261 25. // Status-Line = SIP-Version SP Status-Code SP Reason-Phrase CRLF return m_Version + " " + m_StatusCode + " " + m_Reason + "\r\n"; } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/SIP/Message/SIP_t_Replaces.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.SIP.Message { #region usings using System; using System.Text; #endregion /// <summary> /// Implements SIP "Replaces" value. Defined in RFC 3891. /// </summary> /// <remarks> /// <code> /// RFC 3891 Syntax: /// Replaces = callid *(SEMI replaces-param) /// replaces-param = to-tag / from-tag / early-flag / generic-param /// to-tag = "to-tag" EQUAL token /// from-tag = "from-tag" EQUAL token /// early-flag = "early-only" /// </code> /// </remarks> public class SIP_t_Replaces : SIP_t_ValueWithParams { #region Members private string m_CallID = ""; #endregion #region Properties /// <summary> /// Gets or sets call id. /// </summary> /// <exception cref="ArgumentNullException">Is raised when null value is passed.</exception> public string CallID { get { return m_CallID; } set { if (value == null) { throw new ArgumentNullException("CallID"); } m_CallID = value; } } /// <summary> /// Gets or sets Replaces 'to-tag' parameter. Value null means not specified. /// </summary> public string ToTag { get { SIP_Parameter parameter = Parameters["to-tag"]; if (parameter != null) { return parameter.Value; } else { return null; } } set { if (value == null) { Parameters.Remove("to-tag"); } else { Parameters.Set("to-tag", value); } } } /// <summary> /// Gets or sets Replaces 'from-tag' parameter. Value null means not specified. /// </summary> public string FromTag { get { SIP_Parameter parameter = Parameters["from-tag"]; if (parameter != null) { return parameter.Value; } else { return null; } } set { if (value == null) { Parameters.Remove("from-tag"); } else { Parameters.Set("from-tag", value); } } } /// <summary> /// Gets or sets Replaces 'early-flag' parameter. /// </summary> public bool EarlyFlag { get { if (Parameters.Contains("early-only")) { return true; } else { return false; } } set { if (!value) { Parameters.Remove("early-only"); } else { Parameters.Set("early-only", null); } } } #endregion #region Methods /// <summary> /// Parses "Replaces" from specified value. /// </summary> /// <param name="value">SIP "Replaces" value.</param> /// <exception cref="ArgumentNullException">Raised when <b>value</b> is null.</exception> /// <exception cref="SIP_ParseException">Raised when invalid SIP message.</exception> public void Parse(string value) { if (value == null) { throw new ArgumentNullException("value"); } Parse(new StringReader(value)); } /// <summary> /// Parses "Replaces" from specified reader. /// </summary> /// <param name="reader">Reader from where to parse.</param> /// <exception cref="ArgumentNullException">Raised when <b>reader</b> is null.</exception> /// <exception cref="SIP_ParseException">Raised when invalid SIP message.</exception> public override void Parse(StringReader reader) { /* Replaces = callid *(SEMI replaces-param) replaces-param = to-tag / from-tag / early-flag / generic-param to-tag = "to-tag" EQUAL token from-tag = "from-tag" EQUAL token early-flag = "early-only" */ if (reader == null) { throw new ArgumentNullException("reader"); } // callid string word = reader.ReadWord(); if (word == null) { throw new SIP_ParseException("Replaces 'callid' value is missing !"); } m_CallID = word; // Parse parameters ParseParameters(reader); } /// <summary> /// Converts this to valid "Replaces" value. /// </summary> /// <returns>Returns "Replaces" value.</returns> public override string ToStringValue() { /* Replaces = callid *(SEMI replaces-param) replaces-param = to-tag / from-tag / early-flag / generic-param to-tag = "to-tag" EQUAL token from-tag = "from-tag" EQUAL token early-flag = "early-only" */ StringBuilder retVal = new StringBuilder(); // delta-seconds retVal.Append(m_CallID); // Add parameters retVal.Append(ParametersToString()); return retVal.ToString(); } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/SMTP/Server/old/SMTP_Server.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.IO; using System.ComponentModel; using System.Collections; using System.Diagnostics; using System.Net; using System.Net.Sockets; using System.Threading; using System.Security.Cryptography.X509Certificates; using LumiSoft.Net; using LumiSoft.Net.AUTH; namespace LumiSoft.Net.SMTP.Server { #region Event delegates /// <summary> /// Represents the method that will handle the AuthUser event for SMTP_Server. /// </summary> /// <param name="sender">The source of the event. </param> /// <param name="e">A AuthUser_EventArgs that contains the event data.</param> public delegate void AuthUserEventHandler(object sender,AuthUser_EventArgs e); /// <summary> /// Represents the method that will handle the ValidateMailFrom event for SMTP_Server. /// </summary> /// <param name="sender">The source of the event. </param> /// <param name="e">A ValidateSender_EventArgs that contains the event data.</param> public delegate void ValidateMailFromHandler(object sender,ValidateSender_EventArgs e); /// <summary> /// Represents the method that will handle the ValidateMailTo event for SMTP_Server. /// </summary> /// <param name="sender">The source of the event. </param> /// <param name="e">A ValidateRecipient_EventArgs that contains the event data.</param> public delegate void ValidateMailToHandler(object sender,ValidateRecipient_EventArgs e); /// <summary> /// Represents the method that will handle the ValidateMailboxSize event for SMTP_Server. /// </summary> /// <param name="sender">The source of the event. </param> /// <param name="e">A ValidateMailboxSize_EventArgs that contains the event data.</param> public delegate void ValidateMailboxSize(object sender,ValidateMailboxSize_EventArgs e); /// <summary> /// Represents the method that will handle the GetMessageStoreStream event for SMTP_Server. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">A GetMessageStoreStream_eArgs that contains the event data.</param> public delegate void GetMessageStoreStreamHandler(object sender,GetMessageStoreStream_eArgs e); /// <summary> /// Represents the method that will handle the MessageStoringCompleted event for SMTP_Server. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">A MessageStoringCompleted_eArgs that contains the event data.</param> public delegate void MessageStoringCompletedHandler(object sender,MessageStoringCompleted_eArgs e); #endregion /// <summary> /// SMTP server component. /// </summary> public class SMTP_Server : SocketServer { private int m_MaxConnectionsPerIP = 0; private int m_MaxMessageSize = 1000000; private int m_MaxRecipients = 100; private SaslAuthTypes m_SupportedAuth = SaslAuthTypes.All; private string m_GreetingText = ""; #region Event declarations /// <summary> /// Occurs when new computer connected to SMTP server. /// </summary> public event ValidateIPHandler ValidateIPAddress = null; /// <summary> /// Occurs when connected user tryes to authenticate. /// </summary> public event AuthUserEventHandler AuthUser = null; /// <summary> /// Occurs when server needs to validate sender. /// </summary> public event ValidateMailFromHandler ValidateMailFrom = null; /// <summary> /// Occurs when server needs to validate recipient. /// </summary> public event ValidateMailToHandler ValidateMailTo = null; /// <summary> /// Occurs when server needs to validate recipient mailbox size. /// </summary> public event ValidateMailboxSize ValidateMailboxSize = null; /// <summary> /// Occurs when server needs to get stream where to store incoming message. /// </summary> public event GetMessageStoreStreamHandler GetMessageStoreStream = null; /// <summary> /// Occurs when server has finished message storing. /// </summary> public event MessageStoringCompletedHandler MessageStoringCompleted = null; /// <summary> /// Occurs when SMTP session log is available. /// </summary> public event LogEventHandler SessionLog = null; #endregion /// <summary> /// Defalut constructor. /// </summary> public SMTP_Server() : base() { this.BindInfo = new IPBindInfo[]{new IPBindInfo("",IPAddress.Any,25,SslMode.None,null)}; } #region override InitNewSession /// <summary> /// Initialize and start new session here. Session isn't added to session list automatically, /// session must add itself to server session list by calling AddSession(). /// </summary> /// <param name="socket">Connected client socket.</param> /// <param name="bindInfo">BindInfo what accepted socket.</param> protected override void InitNewSession(Socket socket,IPBindInfo bindInfo) { // Check maximum conncurent connections from 1 IP. if(m_MaxConnectionsPerIP > 0){ lock(this.Sessions){ int nSessions = 0; foreach(SocketServerSession s in this.Sessions){ IPEndPoint ipEndpoint = s.RemoteEndPoint; if(ipEndpoint != null){ if(ipEndpoint.Address.Equals(((IPEndPoint)socket.RemoteEndPoint).Address)){ nSessions++; } } // Maimum allowed exceeded if(nSessions >= m_MaxConnectionsPerIP){ socket.Send(System.Text.Encoding.ASCII.GetBytes("421 Maximum connections from your IP address is exceeded, try again later !\r\n")); socket.Shutdown(SocketShutdown.Both); socket.Close(); return; } } } } string sessionID = Guid.NewGuid().ToString(); SocketEx socketEx = new SocketEx(socket); if(LogCommands){ socketEx.Logger = new SocketLogger(socket,this.SessionLog); socketEx.Logger.SessionID = sessionID; } SMTP_Session session = new SMTP_Session(sessionID,socketEx,bindInfo,this); } #endregion #region Properties Implementaion /// <summary> /// Gets or sets server greeting text. /// </summary> public string GreetingText { get{ return m_GreetingText; } set{ m_GreetingText = value; } } /// <summary> /// Gets or sets maximum allowed conncurent connections from 1 IP address. Value 0 means unlimited connections. /// </summary> public int MaxConnectionsPerIP { get{ return m_MaxConnectionsPerIP; } set{ m_MaxConnectionsPerIP = value; } } /// <summary> /// Maximum message size in bytes. /// </summary> public int MaxMessageSize { get{ return m_MaxMessageSize; } set{ m_MaxMessageSize = value; } } /// <summary> /// Maximum recipients per message. /// </summary> public int MaxRecipients { get{ return m_MaxRecipients; } set{ m_MaxRecipients = value; } } /// <summary> /// Gets or sets server supported authentication types. /// </summary> public SaslAuthTypes SupportedAuthentications { get{ return m_SupportedAuth; } set{ m_SupportedAuth = value; } } /// <summary> /// Gets active sessions. /// </summary> public new SMTP_Session[] Sessions { get{ SocketServerSession[] sessions = base.Sessions; SMTP_Session[] smtpSessions = new SMTP_Session[sessions.Length]; sessions.CopyTo(smtpSessions,0); return smtpSessions; } } #endregion #region Events Implementation #region method OnValidate_IpAddress /// <summary> /// Raises event ValidateIP event. /// </summary> /// <param name="session">Reference to current smtp session.</param> internal ValidateIP_EventArgs OnValidate_IpAddress(SMTP_Session session) { ValidateIP_EventArgs oArg = new ValidateIP_EventArgs(session.LocalEndPoint,session.RemoteEndPoint); if(this.ValidateIPAddress != null){ this.ValidateIPAddress(this, oArg); } session.Tag = oArg.SessionTag; return oArg; } #endregion #region method OnAuthUser /// <summary> /// Raises event AuthUser. /// </summary> /// <param name="session">Reference to current smtp session.</param> /// <param name="userName">User name.</param> /// <param name="passwordData">Password compare data,it depends of authentication type.</param> /// <param name="data">For md5 eg. md5 calculation hash.It depends of authentication type.</param> /// <param name="authType">Authentication type.</param> /// <returns></returns> internal AuthUser_EventArgs OnAuthUser(SMTP_Session session,string userName,string passwordData,string data,AuthType authType) { AuthUser_EventArgs oArgs = new AuthUser_EventArgs(session,userName,passwordData,data,authType); if(this.AuthUser != null){ this.AuthUser(this,oArgs); } return oArgs; } #endregion #region method OnValidate_MailFrom /// <summary> /// Raises event ValidateMailFrom. /// </summary> /// <param name="session"></param> /// <param name="reverse_path"></param> /// <param name="email"></param> /// <returns></returns> internal ValidateSender_EventArgs OnValidate_MailFrom(SMTP_Session session,string reverse_path,string email) { ValidateSender_EventArgs oArg = new ValidateSender_EventArgs(session,email); if(this.ValidateMailFrom != null){ this.ValidateMailFrom(this, oArg); } return oArg; } #endregion #region method OnValidate_MailTo /// <summary> /// Raises event ValidateMailTo. /// </summary> /// <param name="session"></param> /// <param name="forward_path"></param> /// <param name="email"></param> /// <param name="authenticated"></param> /// <returns></returns> internal ValidateRecipient_EventArgs OnValidate_MailTo(SMTP_Session session,string forward_path,string email,bool authenticated) { ValidateRecipient_EventArgs oArg = new ValidateRecipient_EventArgs(session,email,authenticated); if(this.ValidateMailTo != null){ this.ValidateMailTo(this, oArg); } return oArg; } #endregion #region method Validate_MailBoxSize /// <summary> /// Raises event ValidateMailboxSize. /// </summary> /// <param name="session"></param> /// <param name="eAddress"></param> /// <param name="messageSize"></param> /// <returns></returns> internal bool Validate_MailBoxSize(SMTP_Session session,string eAddress,long messageSize) { ValidateMailboxSize_EventArgs oArgs = new ValidateMailboxSize_EventArgs(session,eAddress,messageSize); if(this.ValidateMailboxSize != null){ this.ValidateMailboxSize(this,oArgs); } return oArgs.IsValid; } #endregion #region method OnGetMessageStoreStream /// <summary> /// Raises event GetMessageStoreStream. /// </summary> /// <param name="session">Reference to calling SMTP session.</param> /// <returns></returns> internal GetMessageStoreStream_eArgs OnGetMessageStoreStream(SMTP_Session session) { GetMessageStoreStream_eArgs eArgs = new GetMessageStoreStream_eArgs(session); if(this.GetMessageStoreStream != null){ this.GetMessageStoreStream(this,eArgs); } return eArgs; } #endregion #region method OnMessageStoringCompleted /// <summary> /// Raises event MessageStoringCompleted. /// </summary> /// <param name="session">Reference to calling SMTP session.</param> /// <param name="errorText">Null if no errors, otherwise conatians error text. If errors happened that means that messageStream is incomplete.</param> /// <param name="messageStream">Stream where message was stored.</param> internal MessageStoringCompleted_eArgs OnMessageStoringCompleted(SMTP_Session session,string errorText,Stream messageStream) { MessageStoringCompleted_eArgs eArgs = new MessageStoringCompleted_eArgs(session,errorText,messageStream); if(this.MessageStoringCompleted != null){ this.MessageStoringCompleted(this,eArgs); } return eArgs; } #endregion #endregion } } <file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/SMTP/SMTP_Utils.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.SMTP { /// <summary> /// This class provedes SMTP related utility methods. /// </summary> public class SMTP_Utils { #region Methods /// <summary> /// Gets if specified smtp address has valid syntax. /// </summary> /// <param name="address">SMTP address, eg. <EMAIL>.</param> /// <returns>Returns ture if address is valid, otherwise false.</returns> public static bool IsValidAddress(string address) { // TODO: return true; } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/SMTP/Server/SMTP_e_Message.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.SMTP.Server { #region usings using System; using System.IO; #endregion /// <summary> /// This class provided data for <b cref="SMTP_Session.GetMessageStream">SMTP_Session.GetMessageStream</b> event. /// </summary> public class SMTP_e_Message : EventArgs { #region Members private readonly SMTP_Session m_pSession; private Stream m_pStream; #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="session">Owner SMTP server session.</param> /// <exception cref="ArgumentNullException">Is raised when <b>session</b> is null reference.</exception> public SMTP_e_Message(SMTP_Session session) { if (session == null) { throw new ArgumentNullException("session"); } m_pSession = session; } #endregion #region Properties /// <summary> /// Gets owner SMTP session. /// </summary> public SMTP_Session Session { get { return m_pSession; } } /// <summary> /// Gets or stes stream where to store incoming message. /// </summary> /// <exception cref="ArgumentNullException">Is raised when null reference is passed.</exception> public Stream Stream { get { return m_pStream; } set { if (value == null) { throw new ArgumentNullException("Stream"); } m_pStream = value; } } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Autoreply/AddressParsers/ProjectAddressParser.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System.Collections.Generic; using System.Text.RegularExpressions; using ASC.Core.Tenants; using ASC.Mail.Autoreply.ParameterResolvers; namespace ASC.Mail.Autoreply.AddressParsers { internal class ProjectAddressParser : AddressParser { protected override Regex GetRouteRegex() { return new Regex(@"^(?'type'task|message)_(?'projectId'\d+)$", RegexOptions.Compiled | RegexOptions.Singleline | RegexOptions.IgnoreCase); } protected override ApiRequest ParseRequestInfo(IDictionary<string, string> groups, Tenant t) { var type = groups["type"]; if (type == "task") { return new ApiRequest(string.Format("project/{0}/task", groups["projectId"])) { Parameters = new List<RequestParameter> { new RequestParameter("description", new PlainTextContentResolver()), new RequestParameter("deadline", new TaskDeadlineResolver()), new RequestParameter("priority", new TaskPriorityResolver()), new RequestParameter("milestoneid", new TaskMilestoneResolver()), new RequestParameter("responsibles", new TaskResponsiblesResolver()), new RequestParameter("responsible", new TaskResponsibleResolver()), new RequestParameter("title", new TitleResolver(TaskDeadlineResolver.Pattern, TaskPriorityResolver.Pattern, TaskMilestoneResolver.Pattern, TaskResponsiblesResolver.Pattern)) } }; } return new ApiRequest(string.Format("project/{0}/message", groups["projectId"])) { Parameters = new List<RequestParameter> { new RequestParameter("title", new TitleResolver()), new RequestParameter("content", new HtmlContentResolver()) } }; } } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/IMAP/Server/IMAP_SelectedFolder.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; namespace ASC.Mail.Net.IMAP.Server { #region usings using System.Text; #endregion /// <summary> /// Holds IMAP selected folder info. /// </summary> public class IMAP_SelectedFolder:IDisposable { #region Members private readonly string m_Folder = ""; private readonly IMAP_MessageCollection m_pMessages; #endregion #region Properties /// <summary> /// Gets selected folder name. /// </summary> public string Folder { get { return m_Folder; } } /// <summary> /// Gets folder UID(UIDVADILITY) value. /// </summary> public long FolderUID { get; set; } /// <summary> /// Gets or sets if folder is read only. /// </summary> public bool ReadOnly { get; set; } /// <summary> /// Gets selected folder messages info. /// </summary> public IMAP_MessageCollection Messages { get { return m_pMessages; } } /// <summary> /// Gets number of messages with \UNSEEN flags in the collection. /// </summary> public int UnSeenCount { get { int count = 0; foreach (IMAP_Message message in m_pMessages) { if ((message.Flags & IMAP_MessageFlags.Seen) == 0) { count++; } } return count; } } /// <summary> /// Gets number of messages with \RECENT flags in the collection. /// </summary> public int RecentCount { get { int count = 0; foreach (IMAP_Message message in m_pMessages) { if ((message.Flags & IMAP_MessageFlags.Recent) != 0) { count++; } } return count; } } /// <summary> /// Gets number of messages with \DELETED flags in the collection. /// </summary> public int DeletedCount { get { int count = 0; foreach (IMAP_Message message in m_pMessages) { if ((message.Flags & IMAP_MessageFlags.Deleted) != 0) { count++; } } return count; } } /// <summary> /// Gets first message index in the collection which has not \SEEN flag set. /// </summary> public int FirstUnseen { get { int index = 1; foreach (IMAP_Message message in m_pMessages) { if ((message.Flags & IMAP_MessageFlags.Seen) == 0) { return index; } index++; } return 0; } } /// <summary> /// Gets next new message predicted UID. /// </summary> public long MessageUidNext { get { if (m_pMessages.Count > 0) { return m_pMessages[m_pMessages.Count - 1].UID + 1; } else { return 1; } } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="folder">Folder name.</param> internal IMAP_SelectedFolder(string folder) { m_Folder = folder; m_pMessages = new IMAP_MessageCollection(); } #endregion #region Internal methods /// <summary> /// Updates current folder messages info with new messages info. /// </summary> /// <param name="folder"></param> /// <returns></returns> internal string Update(IMAP_SelectedFolder folder) { StringBuilder retVal = new StringBuilder(); long maxUID = MessageUidNext - 1; long countExists = Messages.Count; long countRecent = RecentCount; // Add new messages for (int i = folder.Messages.Count - 1; i >= 0; i--)//FIX { IMAP_Message message = folder.Messages[i]; // New message if (message.UID > maxUID) { m_pMessages.Add(message.ID, message.UID, message.InternalDate, message.Size, message.Flags); } // New messages ended else { break; } } // Remove deleted messages for (int i = 0; i < m_pMessages.Count; i++) { IMAP_Message message = m_pMessages[i]; if (!folder.m_pMessages.ContainsUID(message.UID)) { retVal.Append("* " + message.SequenceNo + " EXPUNGE\r\n"); m_pMessages.Remove(message); i--; } } if (countExists != Messages.Count) { retVal.Append("* " + Messages.Count + " EXISTS\r\n"); } if (countRecent != RecentCount) { retVal.Append("* " + RecentCount + " RECENT\r\n"); } return retVal.ToString(); } #endregion private bool isDisposed = false; public void Dispose() { if (!isDisposed) { isDisposed = true; m_pMessages.Dispose(); } } } }<file_sep>/module/ASC.AuditTrail/Mappers/MessageMaps.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.AuditTrail.Mappers { internal class MessageMaps { public string ActionTypeTextResourceName { get; set; } public string ActionTextResourceName { get; set; } public string ProductResourceName { get; set; } public string ModuleResourceName { get; set; } public string GetActionTypeText() { try { return AuditReportResource.ResourceManager.GetString(ActionTypeTextResourceName); } catch { return null; } } public string GetActionText() { try { return AuditReportResource.ResourceManager.GetString(ActionTextResourceName); } catch { return null; } } public string GetProduct() { try { return AuditReportResource.ResourceManager.GetString(ProductResourceName); } catch { return null; } } public string GetModule() { try { return AuditReportResource.ResourceManager.GetString(ModuleResourceName); } catch { return null; } } } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/URI/SIP_Uri.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net { #region usings using System; using System.Text; using MIME; using SIP.Message; #endregion /// <summary> /// Implements SIP-URI. Defined in 3261. /// </summary> /// <remarks> /// <code> /// RFC 3261 Syntax: /// SIP-URI = "sip:" [ userinfo ] hostport uri-parameters [ headers ] /// SIPS-URI = "sips:" [ userinfo ] hostport uri-parameters [ headers ] /// userinfo = ( user / telephone-subscriber ) [ ":" password ] "@") /// hostport = host [ ":" port ] /// host = hostname / IPv4address / IPv6reference /// </code> /// </remarks> public class SIP_Uri : AbsoluteUri { #region Members private readonly SIP_ParameterCollection m_pParameters; private string m_Header; private string m_Host = ""; private int m_Port = -1; private string m_User; #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> public SIP_Uri() { m_pParameters = new SIP_ParameterCollection(); } #endregion #region Properties /// <summary> /// Gets address from SIP URI. Examples: <EMAIL>,[email protected]. /// </summary> public string Address { get { return m_User + "@" + m_Host; } } /// <summary> /// Gets or sets header. /// </summary> public string Header { get { return m_Header; } set { m_Header = value; } } /// <summary> /// Gets or sets host name or IP. /// </summary> public string Host { get { return m_Host; } set { if (string.IsNullOrEmpty(value)) { throw new ArgumentException("Property Host value can't be null or '' !"); } m_Host = value; } } /// <summary> /// Gets host with optional port. If port specified returns Host:Port, otherwise Host. /// </summary> public string HostPort { get { if (m_Port == -1) { return m_Host; } else { return m_Host + ":" + m_Port; } } } /// <summary> /// Gets or sets if secure SIP. If true then sips: uri, otherwise sip: uri. /// </summary> public bool IsSecure { get; set; } /// <summary> /// Gets or sets 'cause' parameter value. Value -1 means not specified. /// Cause is a URI parameter that is used to indicate the service that /// the User Agent Server (UAS) receiving the message should perform. /// Defined in RFC 4458. /// </summary> public int Param_Cause { get { SIP_Parameter parameter = Parameters["cause"]; if (parameter != null) { return Convert.ToInt32(parameter.Value); } else { return -1; } } set { if (value == -1) { Parameters.Remove("cause"); } else { Parameters.Set("cause", value.ToString()); } } } /// <summary> /// Gets or sets 'comp' parameter value. Value null means not specified. Defined in RFC 3486. /// </summary> public string Param_Comp { get { SIP_Parameter parameter = Parameters["comp"]; if (parameter != null) { return parameter.Value; } else { return null; } } set { if (value == null) { Parameters.Remove("comp"); } else { Parameters.Set("comp", value); } } } /// <summary> /// Gets or sets 'content-type' parameter value. Value null means not specified. Defined in RFC 4240. /// </summary> public string Param_ContentType { get { SIP_Parameter parameter = Parameters["content-type"]; if (parameter != null) { return parameter.Value; } else { return null; } } set { if (value == null) { Parameters.Remove("content-type"); } else { Parameters.Set("content-type", value); } } } /// <summary> /// Gets or sets 'delay' prameter value. Value -1 means not specified. /// Specifies a delay interval between announcement repetitions. The delay is measured in milliseconds. /// Defined in RFC 4240. /// </summary> public int Param_Delay { get { SIP_Parameter parameter = Parameters["delay"]; if (parameter != null) { return Convert.ToInt32(parameter.Value); } else { return -1; } } set { if (value == -1) { Parameters.Remove("delay"); } else { Parameters.Set("delay", value.ToString()); } } } /// <summary> /// Gets or sets 'duration' prameter value. Value -1 means not specified. /// Specifies the maximum duration of the announcement. The media server will discontinue /// the announcement and end the call if the maximum duration has been reached. The duration /// is measured in milliseconds. Defined in RFC 4240. /// </summary> public int Param_Duration { get { SIP_Parameter parameter = Parameters["duration"]; if (parameter != null) { return Convert.ToInt32(parameter.Value); } else { return -1; } } set { if (value == -1) { Parameters.Remove("duration"); } else { Parameters.Set("duration", value.ToString()); } } } /// <summary> /// Gets or sets 'locale' prameter value. Specifies the language and optionally country /// variant of the announcement sequence named in the "play=" parameter. Defined in RFC 4240. /// </summary> public string Param_Locale { get { SIP_Parameter parameter = Parameters["locale"]; if (parameter != null) { return parameter.Value; } else { return null; } } set { if (value == null) { Parameters.Remove("locale"); } else { Parameters.Set("locale", value); } } } /// <summary> /// Gets or sets 'lr' parameter. The lr parameter, when present, indicates that the element /// responsible for this resource implements the routing mechanisms /// specified in this document. Defined in RFC 3261. /// </summary> public bool Param_Lr { get { SIP_Parameter parameter = Parameters["lr"]; if (parameter != null) { return true; } else { return false; } } set { if (!value) { Parameters.Remove("lr"); } else { Parameters.Set("lr", null); } } } /// <summary> /// Gets or sets 'maddr' parameter value. Value null means not specified. /// <a style="font-weight: bold; color: red">NOTE: This value is deprecated in since SIP 2.0.</a> /// The maddr parameter indicates the server address to be contacted for this user, /// overriding any address derived from the host field. Defined in RFC 3261. /// </summary> public string Param_Maddr { get { SIP_Parameter parameter = Parameters["maddr"]; if (parameter != null) { return parameter.Value; } else { return null; } } set { if (value == null) { Parameters.Remove("maddr"); } else { Parameters.Set("maddr", value); } } } /// <summary> /// Gets or sets 'method' prameter value. Value null means not specified. Defined in RFC 3261. /// </summary> public string Param_Method { get { SIP_Parameter parameter = Parameters["method"]; if (parameter != null) { return parameter.Value; } else { return null; } } set { if (value == null) { Parameters.Remove("method"); } else { Parameters.Set("method", value); } } } // param[n] No [RFC4240] /// <summary> /// Gets or sets 'play' parameter value. Value null means not specified. /// Specifies the resource or announcement sequence to be played. Defined in RFC 4240. /// </summary> public string Param_Play { get { SIP_Parameter parameter = Parameters["play"]; if (parameter != null) { return parameter.Value; } else { return null; } } set { if (value == null) { Parameters.Remove("play"); } else { Parameters.Set("play", value); } } } /// <summary> /// Gets or sets 'repeat' parameter value. Value -1 means not specified, value int.MaxValue means 'forever'. /// Specifies how many times the media server should repeat the announcement or sequence named by /// the "play=" parameter. Defined in RFC 4240. /// </summary> public int Param_Repeat { get { SIP_Parameter parameter = Parameters["ttl"]; if (parameter != null) { if (parameter.Value.ToLower() == "forever") { return int.MaxValue; } else { return Convert.ToInt32(parameter.Value); } } else { return -1; } } set { if (value == -1) { Parameters.Remove("ttl"); } else if (value == int.MaxValue) { Parameters.Set("ttl", "forever"); } else { Parameters.Set("ttl", value.ToString()); } } } /// <summary> /// Gets or sets 'target' parameter value. Value null means not specified. Defined in RFC 4240. /// </summary> public string Param_Target { get { SIP_Parameter parameter = Parameters["target"]; if (parameter != null) { return parameter.Value; } else { return null; } } set { if (value == null) { Parameters.Remove("target"); } else { Parameters.Set("target", value); } } } /// <summary> /// Gets or sets 'transport' parameter value. Value null means not specified. /// The transport parameter determines the transport mechanism to /// be used for sending SIP messages. Defined in RFC 3261. /// </summary> public string Param_Transport { get { SIP_Parameter parameter = Parameters["transport"]; if (parameter != null) { return parameter.Value; } else { return null; } } set { if (value == null) { Parameters.Remove("transport"); } else { Parameters.Set("transport", value); } } } /// <summary> /// Gets or sets 'ttl' parameter value. Value -1 means not specified. /// <a style="font-weight: bold; color: red">NOTE: This value is deprecated in since SIP 2.0.</a> /// The ttl parameter determines the time-to-live value of the UDP /// multicast packet and MUST only be used if maddr is a multicast /// address and the transport protocol is UDP. Defined in RFC 3261. /// </summary> public int Param_Ttl { get { SIP_Parameter parameter = Parameters["ttl"]; if (parameter != null) { return Convert.ToInt32(parameter.Value); } else { return -1; } } set { if (value == -1) { Parameters.Remove("ttl"); } else { Parameters.Set("ttl", value.ToString()); } } } /// <summary> /// Gets or sets 'user' parameter value. Value null means not specified. Defined in RFC 3261. /// </summary> public string Param_User { get { SIP_Parameter parameter = Parameters["user"]; if (parameter != null) { return parameter.Value; } else { return null; } } set { if (value == null) { Parameters.Remove("user"); } else { Parameters.Set("user", value); } } } /// <summary> /// Gets or sets 'voicexml' parameter value. Value null means not specified. Defined in RFC 4240. /// </summary> public string Param_Voicexml { get { SIP_Parameter parameter = Parameters["voicexml"]; if (parameter != null) { return parameter.Value; } else { return null; } } set { if (value == null) { Parameters.Remove("voicexml"); } else { Parameters.Set("voicexml", value); } } } /// <summary> /// Gets URI parameters. /// </summary> public SIP_ParameterCollection Parameters { get { return m_pParameters; } } /// <summary> /// Gets or sets host port. Value -1 means not specified. /// </summary> public int Port { get { return m_Port; } set { m_Port = value; } } /// <summary> /// Gets URI scheme. /// </summary> public override string Scheme { get { if (IsSecure) { return "sips"; } else { return "sip"; } } } /// <summary> /// Gets or sets user name. Value null means not specified. /// </summary> public string User { get { return m_User; } set { m_User = value; } } #endregion #region Methods /// <summary> /// Parse SIP or SIPS URI from string value. /// </summary> /// <param name="value">String URI value.</param> /// <exception cref="ArgumentNullException">Is raised when <b>value</b> is null reference.</exception> /// <exception cref="ArgumentException">Is raised when <b>value</b> is not valid SIP or SIPS URI.</exception> public new static SIP_Uri Parse(string value) { AbsoluteUri uri = AbsoluteUri.Parse(value); if (uri is SIP_Uri) { return (SIP_Uri) uri; } else { throw new ArgumentException("Argument 'value' is not valid SIP or SIPS URI."); } } /// <summary> /// Compares the current instance with another object of the same type. /// </summary> /// <param name="obj">An object to compare with this instance.</param> /// <returns>Returns true if two objects are equal.</returns> public override bool Equals(object obj) { /* RFC 3261 19.1.4 URI Comparison. SIP and SIPS URIs are compared for equality according to the following rules: o A SIP and SIPS URI are never equivalent. o Comparison of the userinfo of SIP and SIPS URIs is case- sensitive. This includes userinfo containing passwords or formatted as telephone-subscribers. Comparison of all other components of the URI is case-insensitive unless explicitly defined otherwise. o The ordering of parameters and header fields is not significant in comparing SIP and SIPS URIs. o Characters other than those in the "reserved" set (see RFC 2396 [5]) are equivalent to their ""%" HEX HEX" encoding. o An IP address that is the result of a DNS lookup of a host name does not match that host name. o For two URIs to be equal, the user, password, host, and port components must match. A URI omitting the user component will not match a URI that includes one. A URI omitting the password component will not match a URI that includes one. A URI omitting any component with a default value will not match a URI explicitly containing that component with its default value. For instance, a URI omitting the optional port component will not match a URI explicitly declaring port 5060. The same is true for the transport-parameter, ttl-parameter, user-parameter, and method components. o URI uri-parameter components are compared as follows: - Any uri-parameter appearing in both URIs must match. - A user, ttl, or method uri-parameter appearing in only one URI never matches, even if it contains the default value. - A URI that includes an maddr parameter will not match a URI that contains no maddr parameter. - All other uri-parameters appearing in only one URI are ignored when comparing the URIs. o URI header components are never ignored. Any present header component MUST be present in both URIs and match for the URIs to match. */ if (obj == null) { return false; } if (!(obj is SIP_Uri)) { return false; } SIP_Uri sipUri = (SIP_Uri) obj; if (IsSecure && !sipUri.IsSecure) { return false; } if (User != sipUri.User) { return false; } /* if(this.Password != sipUri.Password){ return false; }*/ if (Host.ToLower() != sipUri.Host.ToLower()) { return false; } if (Port != sipUri.Port) { return false; } // TODO: prameters compare // TODO: header fields compare return true; } /// <summary> /// Returns the hash code. /// </summary> /// <returns>Returns the hash code.</returns> public override int GetHashCode() { return base.GetHashCode(); } /// <summary> /// Converts SIP_Uri to valid SIP-URI string. /// </summary> /// <returns>Returns SIP-URI string.</returns> public override string ToString() { // Syntax: sip:/sips: username@host *[;parameter] [?header *[&header]] StringBuilder retVal = new StringBuilder(); if (IsSecure) { retVal.Append("sips:"); } else { retVal.Append("sip:"); } if (User != null) { retVal.Append(User + "@"); } retVal.Append(Host); if (Port > -1) { retVal.Append(":" + Port); } // Add URI parameters. foreach (SIP_Parameter parameter in m_pParameters) { /* * If value is token value is not quoted(quoted-string). * If value contains `tspecials', value should be represented as quoted-string. * If value is empty string, only parameter name is added. */ if (parameter.Value != null) { if (MIME_Reader.IsToken(parameter.Value)) { retVal.Append(";" + parameter.Name + "=" + parameter.Value); } else { retVal.Append(";" + parameter.Name + "=" + TextUtils.QuoteString(parameter.Value)); } } else { retVal.Append(";" + parameter.Name); } } if (Header != null) { retVal.Append("?" + Header); } return retVal.ToString(); } #endregion #region Overrides /// <summary> /// Parses SIP_Uri from SIP-URI string. /// </summary> /// <param name="value">SIP-URI string.</param> /// <returns>Returns parsed SIP_Uri object.</returns> /// <exception cref="ArgumentNullException">Raised when <b>reader</b> is null.</exception> /// <exception cref="SIP_ParseException">Raised when invalid SIP message.</exception> protected override void ParseInternal(string value) { // Syntax: sip:/sips: username@host:port *[;parameter] [?header *[&header]] if (value == null) { throw new ArgumentNullException("value"); } value = Uri.UnescapeDataString(value); if (!(value.ToLower().StartsWith("sip:") || value.ToLower().StartsWith("sips:"))) { throw new SIP_ParseException("Specified value is invalid SIP-URI !"); } StringReader r = new StringReader(value); // IsSecure IsSecure = r.QuotedReadToDelimiter(':').ToLower() == "sips"; // Get username if (r.SourceString.IndexOf('@') > -1) { User = r.QuotedReadToDelimiter('@'); } // Gets host[:port] string[] host_port = r.QuotedReadToDelimiter(new[] {';', '?'}, false).Split(':'); Host = host_port[0]; // Optional port specified if (host_port.Length == 2) { Port = Convert.ToInt32(host_port[1]); } // We have parameters and/or header if (r.Available > 0) { // Get parameters string[] parameters = TextUtils.SplitQuotedString(r.QuotedReadToDelimiter('?'), ';'); foreach (string parameter in parameters) { if (parameter.Trim() != "") { string[] name_value = parameter.Trim().Split(new[] {'='}, 2); if (name_value.Length == 2) { Parameters.Add(name_value[0], TextUtils.UnQuoteString(name_value[1])); } else { Parameters.Add(name_value[0], null); } } } // We have header if (r.Available > 0) { m_Header = r.ReadToEnd(); } } } #endregion } }<file_sep>/module/ASC.Api/ASC.Api.Mail/MailApi.Conversations.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections.Generic; #if DEBUG using System.Diagnostics; #endif using System.Linq; using System.Web; using ASC.Api.Attributes; using ASC.Mail; using ASC.Mail.Data.Contracts; using ASC.Mail.Enums; using ASC.Specific; // ReSharper disable InconsistentNaming namespace ASC.Api.Mail { public partial class MailApi { /// <summary> /// Returns filtered conversations, if were changes since last check date /// </summary> /// <param optional="true" name="folder">Folder ID - integer. 1 - inbox, 2 - sent, 3 - drafts, 4 - trash, 5 - spam.</param> /// <param optional="true" name="unread">Message unread status. bool flag. Search in unread(true), read(false) or all(null) messages.</param> /// <param optional="true" name="attachments">Message attachments status. bool flag. Search messages with attachments(true), without attachments(false) or all(null) messages.</param> /// <param optional="true" name="period_from">Begin search period date</param> /// <param optional="true" name="period_to">End search period date</param> /// <param optional="true" name="important">Message has importance flag. bool flag.</param> /// <param optional="true" name="from_address">Address to find 'From' field</param> /// <param optional="true" name="to_address">Address to find 'To' field</param> /// <param optional="true" name="mailbox_id">Recipient mailbox id.</param> /// <param optional="true" name="tags">Messages tags. Id of tags linked with target messages.</param> /// <param optional="true" name="search">Text to search in messages body and subject.</param> /// <param optional="true" name="page_size">Count of messages on page</param> /// <param name="sortorder">Sort order by date. String parameter: "ascending" - ascended, "descending" - descended.</param> /// <param optional="true" name="from_date">Date from wich conversations search performed</param> /// <param optional="true" name="from_message">Message from wich conversations search performed</param> /// <param optional="true" name="with_calendar">Message has calendar flag. bool flag.</param> /// <param optional="true" name="user_folder_id">id of user's folder</param> /// <param name="prev_flag"></param> /// <returns>List of filtered chains</returns> /// <short>Gets filtered conversations</short> /// <category>Conversations</category> [Read(@"conversations")] public IEnumerable<MailMessageData> GetFilteredConversations(int? folder, bool? unread, bool? attachments, long? period_from, long? period_to, bool? important, string from_address, string to_address, int? mailbox_id, IEnumerable<int> tags, string search, int? page_size, string sortorder, ApiDateTime from_date, int? from_message, bool? prev_flag, bool? with_calendar, int? user_folder_id) { var primaryFolder = user_folder_id.HasValue ? FolderType.UserFolder : folder.HasValue ? (FolderType) folder.Value : FolderType.Inbox; var filter = new MailSearchFilterData { PrimaryFolder = primaryFolder, Unread = unread, Attachments = attachments, PeriodFrom = period_from, PeriodTo = period_to, Important = important, FromAddress = from_address, ToAddress = to_address, MailboxId = mailbox_id, CustomLabels = new List<int>(tags), SearchText = search, PageSize = page_size.GetValueOrDefault(25), Sort = Defines.ORDER_BY_DATE_CHAIN, SortOrder = sortorder, WithCalendar = with_calendar, UserFolderId = user_folder_id, FromDate = from_date, FromMessage = from_message.GetValueOrDefault(0), PrevFlag = prev_flag.GetValueOrDefault(false) }; bool hasMore; var conversations = MailEngineFactory.ChainEngine.GetConversations(filter, out hasMore); if (hasMore) { _context.SetTotalCount(page_size.GetValueOrDefault(25) + 1); } else { _context.SetTotalCount(conversations.Count); } return conversations; } /// <summary> /// Get list of messages linked into one chain (conversation) /// </summary> /// <param name="id">ID of any message in the chain</param> /// <param name="loadAll">Load content of all messages</param> /// <param optional="true" name="markRead">Mark conversation as read</param> /// <param optional="true" name="needSanitize">Flag specifies is needed to prepare html for FCKeditor</param> /// <returns>List messages linked in one chain</returns> /// <category>Conversations</category> /// <exception cref="ArgumentException">Exception happens when in parameters is invalid. Text description contains parameter name and text description.</exception> [Read(@"conversation/{id:[0-9]+}")] public IEnumerable<MailMessageData> GetConversation(int id, bool? loadAll, bool? markRead, bool? needSanitize) { if (id <= 0) throw new ArgumentException(@"id must be positive integer", "id"); #if DEBUG var watch = new Stopwatch(); watch.Start(); #endif var list = MailEngineFactory.ChainEngine.GetConversationMessages(TenantId, Username, id, loadAll.GetValueOrDefault(false), Defines.NeedProxyHttp, needSanitize.GetValueOrDefault(false), markRead.GetValueOrDefault(false)); #if DEBUG watch.Stop(); Logger.DebugFormat("Mail->GetConversation(id={0})->Elapsed {1}ms (NeedProxyHttp={2}, NeedSanitizer={3})", id, watch.Elapsed.TotalMilliseconds, Defines.NeedProxyHttp, needSanitize.GetValueOrDefault(false)); #endif var item = list.FirstOrDefault(m => m.Id == id); if (item == null || item.Folder != FolderType.UserFolder) return list; var userFolder = GetUserFolderByMailId((uint)item.Id); if (userFolder != null) { list.ForEach(m => m.UserFolderId = userFolder.Id); } return list; } /// <summary> /// Get previous or next conversation id. /// </summary> /// <param name="id">Head message id of current conversation.</param> /// <param name="direction">String parameter for determine prev or next conversation needed. "prev" for previous, "next" for next.</param> /// <param optional="true" name="folder">Folder ID - integer. 1 - inbox, 2 - sent, 5 - spam.</param> /// <param optional="true" name="unread">Message unread status. bool flag. Search in unread(true), read(false) or all(null) messages.</param> /// <param optional="true" name="attachments">Message attachments status. bool flag. Search messages with attachments(true), without attachments(false) or all(null) messages.</param> /// <param optional="true" name="period_from">Begin search period date</param> /// <param optional="true" name="period_to">End search period date</param> /// <param optional="true" name="important">Message has importance flag. bool flag.</param> /// <param optional="true" name="from_address">Address to find 'From' field</param> /// <param optional="true" name="to_address">Address to find 'To' field</param> /// <param optional="true" name="mailbox_id">Recipient mailbox id.</param> /// <param optional="true" name="tags">Messages tags. Id of tags linked with target messages.</param> /// <param optional="true" name="search">Text to search in messages body and subject.</param> /// <param optional="true" name="page_size">Count on messages on page</param> /// <param name="sortorder">Sort order by date. String parameter: "ascending" - ascended, "descending" - descended.</param> /// <param optional="true" name="with_calendar">Message has with_calendar flag. bool flag.</param> /// <param optional="true" name="user_folder_id">id of user's folder</param> /// <returns>Head message id of previous or next conversation.</returns> /// <category>Conversations</category> [Read(@"conversation/{id:[0-9]+}/{direction:(next|prev)}")] public long GetPrevNextConversationId(int id, string direction, int? folder, bool? unread, bool? attachments, long? period_from, long? period_to, bool? important, string from_address, string to_address, int? mailbox_id, IEnumerable<int> tags, string search, int? page_size, string sortorder, bool? with_calendar, int? user_folder_id) { // inverse sort order if prev message require if ("prev" == direction) sortorder = Defines.ASCENDING == sortorder ? Defines.DESCENDING : Defines.ASCENDING; var primaryFolder = folder.HasValue ? (FolderType)folder.Value : FolderType.Inbox; var filter = new MailSearchFilterData { PrimaryFolder = primaryFolder, Unread = unread, Attachments = attachments, PeriodFrom = period_from, PeriodTo = period_to, Important = important, FromAddress = from_address, ToAddress = to_address, MailboxId = mailbox_id, CustomLabels = new List<int>(tags), SearchText = search, PageSize = page_size.GetValueOrDefault(25), Sort = Defines.ORDER_BY_DATE_CHAIN, SortOrder = sortorder, WithCalendar = with_calendar, UserFolderId = user_folder_id }; return MailEngineFactory.ChainEngine.GetNextConversationId(id, filter); } /// <summary> /// Moves conversation specified in ids to the folder. /// </summary> /// <param name="ids">List of mesasges ids from conversations.</param> /// <param name="folder">Folder ID - integer. 1 - inbox, 2 - sent, 3 - drafts, 4 - trash, 5 - spam.</param> /// <param optional="true" name="userFolderId">User Folder Id</param> /// <returns>List of mesasges ids from conversations.</returns> /// <short>Move conversations to folder</short> /// <category>Conversations</category> [Update(@"conversations/move")] public IEnumerable<int> MoveConversations(List<int> ids, int folder, uint? userFolderId = null) { if (!ids.Any()) throw new ArgumentException(@"Empty ids collection", "ids"); var toFolder = (FolderType) folder; if (!MailFolder.IsIdOk(toFolder)) throw new ArgumentException(@"Invalid folder id", "folder"); MailEngineFactory.ChainEngine.SetConversationsFolder(ids, toFolder, userFolderId); if (toFolder != FolderType.Spam) return ids; //TODO: Try to move message (IMAP only) to spam folder on original server (need new separated operation) var scheme = HttpContext.Current == null ? Uri.UriSchemeHttp : HttpContext.Current.Request.GetUrlRewriter().Scheme; MailEngineFactory.SpamEngine.SendConversationsToSpamTrainer(TenantId, Username, ids, true, scheme); return ids; } /// <summary> /// Restores all the conversations previously moved to specific folders to their original folders. /// </summary> /// <param name="ids">List of conversation ids for restore.</param> /// <param optional="true" name="learnSpamTrainer">send messages tp spam training</param> /// <returns>List of restored conversations ids</returns> /// <short>Restore conversations to original folders</short> /// <category>Conversations</category> [Update(@"conversations/restore")] public IEnumerable<int> RestoreConversations(List<int> ids, bool learnSpamTrainer = false) { if (!ids.Any()) throw new ArgumentException(@"Empty ids collection", "ids"); MailEngineFactory.ChainEngine.RestoreConversations(TenantId, Username, ids); if (learnSpamTrainer) { var scheme = HttpContext.Current == null ? Uri.UriSchemeHttp : HttpContext.Current.Request.GetUrlRewriter().Scheme; MailEngineFactory.SpamEngine.SendConversationsToSpamTrainer(TenantId, Username, ids, false, scheme); } return ids; } /// <summary> /// Removes conversations from folders /// </summary> /// <param name="ids">List of conversation ids for remove.</param> /// <returns>List of removed conversation ids</returns> /// <short>Remove conversations</short> /// <category>Conversations</category> [Update(@"conversations/remove")] public IEnumerable<int> RemoveConversations(List<int> ids) { if (!ids.Any()) throw new ArgumentException(@"Empty ids collection", "ids"); MailEngineFactory.ChainEngine.DeleteConversations(TenantId, Username, ids); return ids; } /// <summary> /// Sets the status for the conversations specified by ids. /// </summary> /// <param name="ids">List of conversation ids for status changing.</param> /// <param name="status">String parameter specifies status for changing. Values: "read", "unread", "important" and "normal"</param> /// <returns>List of status changed conversations.</returns> /// <short>Set conversations status</short> /// <category>Conversations</category> [Update(@"conversations/mark")] public IEnumerable<int> MarkConversations(List<int> ids, string status) { if (!ids.Any()) throw new ArgumentException(@"Empty ids collection", "ids"); switch (status) { case "read": MailEngineFactory.MessageEngine.SetUnread(ids, false, true); break; case "unread": MailEngineFactory.MessageEngine.SetUnread(ids, true, true); break; case "important": MailEngineFactory.ChainEngine.SetConversationsImportanceFlags(TenantId, Username, true, ids); break; case "normal": MailEngineFactory.ChainEngine.SetConversationsImportanceFlags(TenantId, Username, false, ids); break; } return ids; } /// <summary> /// Add the specified tag to conversations. /// </summary> /// <param name="tag_id">Tag id for adding.</param> /// <param name="messages">List of conversation ids for tag adding.</param> /// <returns>Added tag_id</returns> /// <short>Add tag to conversations</short> /// <category>Conversations</category> ///<exception cref="ArgumentException">Exception happens when in parameters is invalid. Text description contains parameter name and text description.</exception> [Update(@"conversations/tag/{tag_id}/set")] public int SetConversationsTag(int tag_id, List<int> messages) { if (!messages.Any()) throw new ArgumentException(@"Message ids are empty", "messages"); MailEngineFactory.TagEngine.SetConversationsTag(messages, tag_id); return tag_id; } /// <summary> /// Removes the specified tag from conversations. /// </summary> /// <param name="tag_id">Tag id to removing.</param> /// <param name="messages">List of conversation ids for tag removing.</param> /// <returns>Removed tag_id</returns> /// <short>Remove tag from conversations</short> /// <category>Conversations</category> ///<exception cref="ArgumentException">Exception happens when in parameters is invalid. Text description contains parameter name and text description.</exception> [Update(@"conversations/tag/{tag_id}/unset")] public int UnsetConversationsTag(int tag_id, List<int> messages) { if (!messages.Any()) throw new ArgumentException(@"Message ids are empty", "messages"); MailEngineFactory.TagEngine.UnsetConversationsTag(messages, tag_id); return tag_id; } /// <summary> /// Marks conversation as CRM linked. All new mail will be added to CRM history. /// </summary> /// <param name="id_message">Id of any messages from the chain</param> /// <param name="crm_contact_ids">List of CrmContactEntity. List item format: {entity_id: 0, entity_type: 0}. /// Entity types: 1 - Contact, 2 - Case, 3 - Opportunity. /// </param> /// <returns>none</returns> /// <category>Conversations</category> /// <exception cref="ArgumentException">Exception happens when in parameters is invalid. Text description contains parameter name and text description.</exception> [Update(@"conversations/crm/link")] public void LinkConversationToCrm(int id_message, IEnumerable<CrmContactData> crm_contact_ids) { if (id_message < 0) throw new ArgumentException(@"Invalid message id", "id_message"); if (crm_contact_ids == null) throw new ArgumentException(@"Invalid contact ids list", "crm_contact_ids"); var scheme = HttpContext.Current == null ? Uri.UriSchemeHttp : HttpContext.Current.Request.GetUrlRewriter().Scheme; MailEngineFactory.CrmLinkEngine.LinkChainToCrm(id_message, crm_contact_ids.ToList(), scheme); } /// <summary> /// Marks conversation as CRM linked. All new mail will be added to CRM history. /// </summary> /// <param name="id_message">Id of any messages from the chain</param> /// <param name="crm_contact_ids">List of CrmContactEntity. List item format: {entity_id: 0, entity_type: 0}. /// Entity types: 1 - Contact, 2 - Case, 3 - Opportunity. /// </param> /// <returns>none</returns> /// <category>Conversations</category> /// <exception cref="ArgumentException">Exception happens when in parameters is invalid. Text description contains parameter name and text description.</exception> [Update(@"conversations/crm/mark")] public void MarkConversationAsCrmLinked(int id_message, IEnumerable<CrmContactData> crm_contact_ids) { if (id_message < 0) throw new ArgumentException(@"Invalid message id", "id_message"); if (crm_contact_ids == null) throw new ArgumentException(@"Invalid contact ids list", "crm_contact_ids"); MailEngineFactory.CrmLinkEngine.MarkChainAsCrmLinked(id_message, crm_contact_ids.ToList()); } /// <summary> /// Method tears conversation link with crm. /// </summary> /// <param name="id_message">Id of any messages from the chain</param> /// <param name="crm_contact_ids">List of CrmContactEntity. List item format: {entity_id: 0, entity_type: 0}. /// Entity types: 1 - Contact, 2 - Case, 3 - Opportunity. /// </param> /// <returns>none</returns> /// <category>Conversations</category> /// <exception cref="ArgumentException">Exception happens when in parameters is invalid. Text description contains parameter name and text description.</exception> [Update(@"conversations/crm/unmark")] public void UnmarkConversationAsCrmLinked(int id_message, IEnumerable<CrmContactData> crm_contact_ids) { if (id_message < 0) throw new ArgumentException(@"Invalid message id", "id_message"); if(crm_contact_ids == null) throw new ArgumentException(@"Invalid contact ids list", "crm_contact_ids"); MailEngineFactory.CrmLinkEngine.UnmarkChainAsCrmLinked(id_message, crm_contact_ids); } /// <summary> /// Method checks is chain crm linked by message_id. /// </summary> /// <param name="message_id">Id of any messages from the chain</param> /// <returns>MailCrmStatus</returns> /// <category>Conversations</category> /// <exception cref="ArgumentException">Exception happens when in parameters is invalid. Text description contains parameter name and text description.</exception> [Read(@"conversations/link/crm/status")] public MailCrmStatus IsConversationLinkedWithCrm(int message_id) { if(message_id < 0) throw new ArgumentException(@"Invalid message id", "message_id"); var entities = GetLinkedCrmEntitiesInfo(message_id); var result = new MailCrmStatus(message_id, entities.Any()); return result; } } } <file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/DNS/Client/RCODE.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.Dns.Client { /// <summary> /// Dns server reply codes. /// </summary> public enum RCODE { /// <summary> /// No error condition. /// </summary> NO_ERROR = 0, /// <summary> /// Format error - The name server was unable to interpret the query. /// </summary> FORMAT_ERRROR = 1, /// <summary> /// Server failure - The name server was unable to process this query due to a problem with the name server. /// </summary> SERVER_FAILURE = 2, /// <summary> /// Name Error - Meaningful only for responses from an authoritative name server, this code signifies that the /// domain name referenced in the query does not exist. /// </summary> NAME_ERROR = 3, /// <summary> /// Not Implemented - The name server does not support the requested kind of query. /// </summary> NOT_IMPLEMENTED = 4, /// <summary> /// Refused - The name server refuses to perform the specified operation for policy reasons. /// </summary> REFUSED = 5, } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/RTP/RTCP_Packet_ReportBlock.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.RTP { #region usings using System; #endregion /// <summary> /// This class represents RTCP sender report(SR) or reciver report(RR) packet report block. /// </summary> public class RTCP_Packet_ReportBlock { #region Members private uint m_CumulativePacketsLost; private uint m_DelaySinceLastSR; private uint m_ExtHighestSeqNumber; private uint m_FractionLost; private uint m_Jitter; private uint m_LastSR; private uint m_SSRC; #endregion #region Properties /// <summary> /// Gets the SSRC identifier of the source to which the information in this reception report block pertains. /// </summary> public uint SSRC { get { return m_SSRC; } } /// <summary> /// Gets or sets the fraction of RTP data packets from source SSRC lost since the previous SR or /// RR packet was sent. /// </summary> public uint FractionLost { get { return m_FractionLost; } set { m_FractionLost = value; } } /// <summary> /// Gets or sets total number of RTP data packets from source SSRC that have /// been lost since the beginning of reception. /// </summary> public uint CumulativePacketsLost { get { return m_CumulativePacketsLost; } set { m_CumulativePacketsLost = value; } } /// <summary> /// Gets or sets extended highest sequence number received. /// </summary> public uint ExtendedHighestSeqNo { get { return m_ExtHighestSeqNumber; } set { m_ExtHighestSeqNumber = value; } } /// <summary> /// Gets or sets an estimate of the statistical variance of the RTP data packet /// interarrival time, measured in timestamp units and expressed as an unsigned integer. /// </summary> public uint Jitter { get { return m_Jitter; } set { m_Jitter = value; } } /// <summary> /// Gets or sets The middle 32 bits out of 64 in the NTP timestamp (as explained in Section 4) received as part of /// the most recent RTCP sender report (SR) packet from source SSRC_n. If no SR has been received yet, the field is set to zero. /// </summary> public uint LastSR { get { return m_LastSR; } set { m_LastSR = value; } } /// <summary> /// Gets or sets the delay, expressed in units of 1/65536 seconds, between receiving the last SR packet from /// source SSRC_n and sending this reception report block. If no SR packet has been received yet from SSRC_n, /// the DLSR field is set to zero. /// </summary> public uint DelaySinceLastSR { get { return m_DelaySinceLastSR; } set { m_DelaySinceLastSR = value; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="ssrc">Source ID.</param> internal RTCP_Packet_ReportBlock(uint ssrc) { m_SSRC = ssrc; } /// <summary> /// Default constructor. /// </summary> internal RTCP_Packet_ReportBlock() {} #endregion #region Methods /// <summary> /// Parses RTCP report block (part of SR or RR packet) from specified buffer. /// </summary> /// <param name="buffer">Buffer from where to read report block.</param> /// <param name="offset">Offset in buffer.</param> /// <exception cref="ArgumentNullException">Is raised when <b>buffer</b> is null.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> public void Parse(byte[] buffer, int offset) { /* RFC 3550 6.4.1. +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ report | SSRC_1 (SSRC of first source) | block +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 1 | fraction lost | cumulative number of packets lost | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | extended highest sequence number received | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | interarrival jitter | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | last SR (LSR) | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | delay since last SR (DLSR) | +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ */ if (buffer == null) { throw new ArgumentNullException("buffer"); } if (offset < 0) { throw new ArgumentException("Argument 'offset' value must be >= 0."); } m_SSRC = (uint) (buffer[offset++] << 24 | buffer[offset++] << 16 | buffer[offset++] << 8 | buffer[offset++]); m_FractionLost = buffer[offset++]; m_CumulativePacketsLost = (uint) (buffer[offset++] << 16 | buffer[offset++] << 8 | buffer[offset++]); m_ExtHighestSeqNumber = (uint) (buffer[offset++] << 24 | buffer[offset++] << 16 | buffer[offset++] << 8 | buffer[offset++]); m_Jitter = (uint) (buffer[offset++] << 24 | buffer[offset++] << 16 | buffer[offset++] << 8 | buffer[offset++]); m_LastSR = (uint) (buffer[offset++] << 24 | buffer[offset++] << 16 | buffer[offset++] << 8 | buffer[offset++]); m_DelaySinceLastSR = (uint) (buffer[offset++] << 24 | buffer[offset++] << 16 | buffer[offset++] << 8 | buffer[offset++]); } /// <summary> /// Stores report block to the specified buffer. /// </summary> /// <param name="buffer">Buffer where to store data.</param> /// <param name="offset">Offset in buffer.</param> /// <exception cref="ArgumentNullException">Is raised when <b>buffer</b> is null.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> public void ToByte(byte[] buffer, ref int offset) { /* RFC 3550 6.4.1. +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ report | SSRC_1 (SSRC of first source) | block +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 1 | fraction lost | cumulative number of packets lost | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | extended highest sequence number received | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | interarrival jitter | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | last SR (LSR) | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | delay since last SR (DLSR) | +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ */ if (buffer == null) { throw new ArgumentNullException("buffer"); } if (offset < 0) { throw new ArgumentException("Argument 'offset' must be >= 0."); } if (offset + 24 > buffer.Length) { throw new ArgumentException("Argument 'buffer' has not enough room to store report block."); } // SSRC buffer[offset++] = (byte) ((m_SSRC >> 24) | 0xFF); buffer[offset++] = (byte) ((m_SSRC >> 16) | 0xFF); buffer[offset++] = (byte) ((m_SSRC >> 8) | 0xFF); buffer[offset++] = (byte) ((m_SSRC) | 0xFF); // fraction lost buffer[offset++] = (byte) m_FractionLost; // cumulative packets lost buffer[offset++] = (byte) ((m_CumulativePacketsLost >> 16) | 0xFF); buffer[offset++] = (byte) ((m_CumulativePacketsLost >> 8) | 0xFF); buffer[offset++] = (byte) ((m_CumulativePacketsLost) | 0xFF); // extended highest sequence number buffer[offset++] = (byte) ((m_ExtHighestSeqNumber >> 24) | 0xFF); buffer[offset++] = (byte) ((m_ExtHighestSeqNumber >> 16) | 0xFF); buffer[offset++] = (byte) ((m_ExtHighestSeqNumber >> 8) | 0xFF); buffer[offset++] = (byte) ((m_ExtHighestSeqNumber) | 0xFF); // jitter buffer[offset++] = (byte) ((m_Jitter >> 24) | 0xFF); buffer[offset++] = (byte) ((m_Jitter >> 16) | 0xFF); buffer[offset++] = (byte) ((m_Jitter >> 8) | 0xFF); buffer[offset++] = (byte) ((m_Jitter) | 0xFF); // last SR buffer[offset++] = (byte) ((m_LastSR >> 24) | 0xFF); buffer[offset++] = (byte) ((m_LastSR >> 16) | 0xFF); buffer[offset++] = (byte) ((m_LastSR >> 8) | 0xFF); buffer[offset++] = (byte) ((m_LastSR) | 0xFF); // delay since last SR buffer[offset++] = (byte) ((m_DelaySinceLastSR >> 24) | 0xFF); buffer[offset++] = (byte) ((m_DelaySinceLastSR >> 16) | 0xFF); buffer[offset++] = (byte) ((m_DelaySinceLastSR >> 8) | 0xFF); buffer[offset++] = (byte) ((m_DelaySinceLastSR) | 0xFF); } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/ABNF/ABNF_CharVal.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.ABNF { #region usings using System; using System.IO; using System.Text; #endregion /// <summary> /// This class represent ABNF "char-val". Defined in RFC 5234 4. /// </summary> public class ABNF_CharVal : ABNF_Element { #region Members private readonly string m_Value = ""; #endregion #region Properties /// <summary> /// Gets value. /// </summary> public string Value { get { return m_Value; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="value">The prose-val value.</param> /// <exception cref="ArgumentNullException">Is raised when <b>value</b> is null reference.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> public ABNF_CharVal(string value) { if (value == null) { throw new ArgumentNullException("value"); } if (!Validate(value)) { //throw new ArgumentException("Invalid argument 'value' value. Value must be: 'DQUOTE *(%x20-21 / %x23-7E) DQUOTE'."); } m_Value = value; } #endregion #region Methods /// <summary> /// /// </summary> /// <param name="reader"></param> /// <returns></returns> public static ABNF_CharVal Parse(StringReader reader) { if (reader == null) { throw new ArgumentNullException("reader"); } /* char-val = DQUOTE *(%x20-21 / %x23-7E) DQUOTE ; quoted string of SP and VCHAR ; without DQUOTE */ if (reader.Peek() != '\"') { throw new ParseException("Invalid ABNF 'char-val' value '" + reader.ReadToEnd() + "'."); } // Eat DQUOTE reader.Read(); // TODO: *c-wsp StringBuilder value = new StringBuilder(); while (true) { // We reached end of stream, no closing DQUOTE. if (reader.Peek() == -1) { throw new ParseException("Invalid ABNF 'char-val' value '" + reader.ReadToEnd() + "'."); } // We have closing DQUOTE. else if (reader.Peek() == '\"') { reader.Read(); break; } // Allowed char. else if ((reader.Peek() >= 0x20 && reader.Peek() <= 0x21) || (reader.Peek() >= 0x23 && reader.Peek() <= 0x7E)) { value.Append((char) reader.Read()); } // Invalid value. else { throw new ParseException("Invalid ABNF 'char-val' value '" + reader.ReadToEnd() + "'."); } } return new ABNF_CharVal(value.ToString()); } #endregion #region Utility methods /// <summary> /// Validates "prose-val" value. /// </summary> /// <param name="value">The "prose-val" value.</param> /// <returns>Returns if value is "prose-val" value, otherwise false.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>value</b> is null reference.</exception> private bool Validate(string value) { if (value == null) { throw new ArgumentNullException("value"); } // RFC 5234 4. // char-val = DQUOTE *(%x20-21 / %x23-7E) DQUOTE if (value.Length < 2) { return false; } for (int i = 0; i < value.Length; i++) { char c = value[i]; if (i == 0 && c != '\"') { return false; } else if (i == (value.Length - 1) && c != '\"') { return false; } else if (!((c >= 0x20 && c <= 0x21) || (c >= 0x23 && c <= 0x7E))) { return false; } } return true; } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/SDP/SDP_Media.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.SDP { #region usings using System.Collections.Generic; using System.Text; #endregion /// <summary> /// SDP media. /// </summary> public class SDP_Media { #region Members private readonly List<SDP_Attribute> m_pAttributes; #endregion #region Properties /// <summary> /// Gets or sets media description. /// </summary> public SDP_MediaDescription MediaDescription { get; set; } /// <summary> /// Gets or sets media title. /// </summary> public string Title { get; set; } /// <summary> /// Gets or sets connection data. This is optional value if SDP message specifies this value, /// null means not specified. /// </summary> public SDP_ConnectionData ConnectionData { get; set; } /// <summary> /// Gets or sets media encryption key info. /// </summary> public string EncryptionKey { get; set; } /// <summary> /// Gets media attributes collection. This is optional value, Count == 0 means not specified. /// </summary> public List<SDP_Attribute> Attributes { get { return m_pAttributes; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> public SDP_Media() { m_pAttributes = new List<SDP_Attribute>(); } #endregion #region Methods /// <summary> /// Converts media entity to corresponding media lines. Attributes included. /// </summary> /// <returns></returns> public string ToValue() { /* m= (media name and transport address) i=* (media title) c=* (connection information -- optional if included at session level) b=* (zero or more bandwidth information lines) k=* (encryption key) a=* (zero or more media attribute lines) */ StringBuilder retVal = new StringBuilder(); // m Media description if (MediaDescription != null) { retVal.Append(MediaDescription.ToValue()); } // i media title if (!string.IsNullOrEmpty(Title)) { retVal.AppendLine("i=" + Title); } // c Connection Data if (ConnectionData != null) { retVal.Append(ConnectionData.ToValue()); } // a Attributes foreach (SDP_Attribute attribute in Attributes) { retVal.Append(attribute.ToValue()); } return retVal.ToString(); } #endregion } }<file_sep>/module/ASC.Socket.IO/app/hubs/files.js module.exports = (io) => { const log = require("../log.js"); const files = io.of("/files"); files.on("connection", (socket) => { const request = socket.client.request; if (!request.user || !request.user.id) { return; } const tenantId = request.portal.tenantId; socket .on("subscribeChangeEditors", (fileIds) => { if (typeof fileIds != "object") { fileIds = [fileIds]; } fileIds.forEach(function(fileId) { let room = `${tenantId}-${fileId}`; socket.join(room); }); }); }); function changeEditors({ tenantId, fileId, finish } = {}) { if (typeof tenantId === "undefined" || typeof fileId === "undefined") { log.error(`files: changeEditors without arguments`); return; } let room = `${tenantId}-${fileId}`; files.to(room).emit("changeEditors", fileId); if (finish) { files.in(room).clients((error, clients) => { if (error) throw error; clients.forEach(function(client) { let clientSocket = files.connected[client]; if(clientSocket){ clientSocket.leave(room); } }); }); } } return { changeEditors }; };<file_sep>/module/ASC.AuditTrail/Mappers/CrmActionMapper.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System.Collections.Generic; using ASC.MessagingSystem; namespace ASC.AuditTrail.Mappers { internal class CrmActionMapper { public static Dictionary<MessageAction, MessageMaps> GetMaps() { return new Dictionary<MessageAction, MessageMaps> { #region companies { MessageAction.CompanyCreated, new MessageMaps { ActionTypeTextResourceName = "CreateActionType", ActionTextResourceName = "CompanyCreated", ProductResourceName = "CrmProduct", ModuleResourceName = "CompaniesModule" } }, { MessageAction.CompanyCreatedWithWebForm, new MessageMaps { ActionTypeTextResourceName = "CreateActionType", ActionTextResourceName = "CompanyCreatedWithWebForm", ProductResourceName = "CrmProduct", ModuleResourceName = "CompaniesModule" } }, { MessageAction.CompanyUpdated, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "CompanyUpdated", ProductResourceName = "CrmProduct", ModuleResourceName = "CompaniesModule" } }, { MessageAction.CompanyUpdatedPrincipalInfo, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "CompanyUpdatedPrincipalInfo", ProductResourceName = "CrmProduct", ModuleResourceName = "CompaniesModule" } }, { MessageAction.CompanyUpdatedPhoto, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "CompanyUpdatedPhoto", ProductResourceName = "CrmProduct", ModuleResourceName = "CompaniesModule" } }, { MessageAction.CompanyUpdatedTemperatureLevel, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "CompanyUpdatedTemperatureLevel", ProductResourceName = "CrmProduct", ModuleResourceName = "CompaniesModule" } }, { MessageAction.CompanyUpdatedPersonsTemperatureLevel, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "CompanyUpdatedPersonsTemperatureLevel", ProductResourceName = "CrmProduct", ModuleResourceName = "CompaniesModule" } }, { MessageAction.CompanyCreatedTag, new MessageMaps { ActionTypeTextResourceName = "CreateActionType", ActionTextResourceName = "CompanyCreatedTag", ProductResourceName = "CrmProduct", ModuleResourceName = "CompaniesModule" } }, { MessageAction.CompanyCreatedPersonsTag, new MessageMaps { ActionTypeTextResourceName = "CreateActionType", ActionTextResourceName = "CompanyCreatedPersonsTag", ProductResourceName = "CrmProduct", ModuleResourceName = "CompaniesModule" } }, { MessageAction.CompanyDeletedTag, new MessageMaps { ActionTypeTextResourceName = "DeleteActionType", ActionTextResourceName = "CompanyDeletedTag", ProductResourceName = "CrmProduct", ModuleResourceName = "CompaniesModule" } }, { MessageAction.CompanyCreatedHistoryEvent, new MessageMaps { ActionTypeTextResourceName = "CreateActionType", ActionTextResourceName = "CompanyCreatedHistoryEvent", ProductResourceName = "CrmProduct", ModuleResourceName = "CompaniesModule" } }, { MessageAction.CompanyDeletedHistoryEvent, new MessageMaps { ActionTypeTextResourceName = "DeleteActionType", ActionTextResourceName = "CompanyDeletedHistoryEvent", ProductResourceName = "CrmProduct", ModuleResourceName = "CompaniesModule" } }, { MessageAction.CompanyLinkedPerson, new MessageMaps { ActionTypeTextResourceName = "LinkActionType", ActionTextResourceName = "CompanyLinkedPerson", ProductResourceName = "CrmProduct", ModuleResourceName = "CompaniesModule" } }, { MessageAction.CompanyUnlinkedPerson, new MessageMaps { ActionTypeTextResourceName = "UnlinkActionType", ActionTextResourceName = "CompanyUnlinkedPerson", ProductResourceName = "CrmProduct", ModuleResourceName = "CompaniesModule" } }, { MessageAction.CompanyLinkedProject, new MessageMaps { ActionTypeTextResourceName = "LinkActionType", ActionTextResourceName = "CompanyLinkedProject", ProductResourceName = "CrmProduct", ModuleResourceName = "CompaniesModule" } }, { MessageAction.CompanyUnlinkedProject, new MessageMaps { ActionTypeTextResourceName = "UnlinkActionType", ActionTextResourceName = "CompanyUnlinkedProject", ProductResourceName = "CrmProduct", ModuleResourceName = "CompaniesModule" } }, { MessageAction.CompanyAttachedFiles, new MessageMaps { ActionTypeTextResourceName = "AttachActionType", ActionTextResourceName = "CompanyAttachedFiles", ProductResourceName = "CrmProduct", ModuleResourceName = "CompaniesModule" } }, { MessageAction.CompanyDetachedFile, new MessageMaps { ActionTypeTextResourceName = "DetachActionType", ActionTextResourceName = "CompanyDetachedFile", ProductResourceName = "CrmProduct", ModuleResourceName = "CompaniesModule" } }, { MessageAction.CompaniesMerged, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "CompaniesMerged", ProductResourceName = "CrmProduct", ModuleResourceName = "CompaniesModule" } }, { MessageAction.CompanyDeleted, new MessageMaps { ActionTypeTextResourceName = "DeleteActionType", ActionTextResourceName = "CompanyDeleted", ProductResourceName = "CrmProduct", ModuleResourceName = "CompaniesModule" } }, #endregion #region persons { MessageAction.PersonCreated, new MessageMaps { ActionTypeTextResourceName = "CreateActionType", ActionTextResourceName = "PersonCreated", ProductResourceName = "CrmProduct", ModuleResourceName = "PersonsModule" } }, { MessageAction.PersonCreatedWithWebForm, new MessageMaps { ActionTypeTextResourceName = "CreateActionType", ActionTextResourceName = "PersonCreatedWithWebForm", ProductResourceName = "CrmProduct", ModuleResourceName = "PersonsModule" } }, { MessageAction.PersonsCreated, new MessageMaps { ActionTypeTextResourceName = "CreateActionType", ActionTextResourceName = "PersonsCreated", ProductResourceName = "CrmProduct", ModuleResourceName = "PersonsModule" } }, { MessageAction.PersonUpdated, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "PersonUpdated", ProductResourceName = "CrmProduct", ModuleResourceName = "PersonsModule" } }, { MessageAction.PersonUpdatedPrincipalInfo, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "PersonUpdatedPrincipalInfo", ProductResourceName = "CrmProduct", ModuleResourceName = "PersonsModule" } }, { MessageAction.PersonUpdatedPhoto, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "PersonUpdatedPhoto", ProductResourceName = "CrmProduct", ModuleResourceName = "PersonsModule" } }, { MessageAction.PersonUpdatedTemperatureLevel, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "PersonUpdatedTemperatureLevel", ProductResourceName = "CrmProduct", ModuleResourceName = "PersonsModule" } }, { MessageAction.PersonUpdatedCompanyTemperatureLevel, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "PersonUpdatedCompanyTemperatureLevel", ProductResourceName = "CrmProduct", ModuleResourceName = "PersonsModule" } }, { MessageAction.PersonCreatedTag, new MessageMaps { ActionTypeTextResourceName = "CreateActionType", ActionTextResourceName = "PersonCreatedTag", ProductResourceName = "CrmProduct", ModuleResourceName = "PersonsModule" } }, { MessageAction.PersonCreatedCompanyTag, new MessageMaps { ActionTypeTextResourceName = "CreateActionType", ActionTextResourceName = "PersonCreatedCompanyTag", ProductResourceName = "CrmProduct", ModuleResourceName = "PersonsModule" } }, { MessageAction.PersonDeletedTag, new MessageMaps { ActionTypeTextResourceName = "DeleteActionType", ActionTextResourceName = "PersonDeletedTag", ProductResourceName = "CrmProduct", ModuleResourceName = "PersonsModule" } }, { MessageAction.PersonCreatedHistoryEvent, new MessageMaps { ActionTypeTextResourceName = "CreateActionType", ActionTextResourceName = "PersonCreatedHistoryEvent", ProductResourceName = "CrmProduct", ModuleResourceName = "PersonsModule" } }, { MessageAction.PersonDeletedHistoryEvent, new MessageMaps { ActionTypeTextResourceName = "DeleteActionType", ActionTextResourceName = "PersonDeletedHistoryEvent", ProductResourceName = "CrmProduct", ModuleResourceName = "PersonsModule" } }, { MessageAction.PersonLinkedProject, new MessageMaps { ActionTypeTextResourceName = "LinkActionType", ActionTextResourceName = "PersonLinkedProject", ProductResourceName = "CrmProduct", ModuleResourceName = "PersonsModule" } }, { MessageAction.PersonUnlinkedProject, new MessageMaps { ActionTypeTextResourceName = "UnlinkActionType", ActionTextResourceName = "PersonUnlinkedProject", ProductResourceName = "CrmProduct", ModuleResourceName = "PersonsModule" } }, { MessageAction.PersonAttachedFiles, new MessageMaps { ActionTypeTextResourceName = "AttachActionType", ActionTextResourceName = "PersonAttachedFiles", ProductResourceName = "CrmProduct", ModuleResourceName = "PersonsModule" } }, { MessageAction.PersonDetachedFile, new MessageMaps { ActionTypeTextResourceName = "DetachActionType", ActionTextResourceName = "PersonDetachedFile", ProductResourceName = "CrmProduct", ModuleResourceName = "PersonsModule" } }, { MessageAction.PersonsMerged, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "PersonsMerged", ProductResourceName = "CrmProduct", ModuleResourceName = "PersonsModule" } }, { MessageAction.PersonDeleted, new MessageMaps { ActionTypeTextResourceName = "DeleteActionType", ActionTextResourceName = "PersonDeleted", ProductResourceName = "CrmProduct", ModuleResourceName = "PersonsModule" } }, #endregion #region contacts { MessageAction.ContactsDeleted, new MessageMaps { ActionTypeTextResourceName = "DeleteActionType", ActionTextResourceName = "ContactsDeleted", ProductResourceName = "CrmProduct", ModuleResourceName = "ContactsModule" } }, { MessageAction.CrmSmtpMailSent, new MessageMaps { ActionTypeTextResourceName = "SendActionType", ActionTextResourceName = "CrmSmtpMailSent", ProductResourceName = "CrmProduct", ModuleResourceName = "ContactsModule" } }, #endregion #region tasks { MessageAction.CrmTaskCreated, new MessageMaps { ActionTypeTextResourceName = "CreateActionType", ActionTextResourceName = "CrmTaskCreated", ProductResourceName = "CrmProduct", ModuleResourceName = "CrmTasksModule" } }, { MessageAction.ContactsCreatedCrmTasks, new MessageMaps { ActionTypeTextResourceName = "CreateActionType", ActionTextResourceName = "ContactsCreatedCrmTasks", ProductResourceName = "CrmProduct", ModuleResourceName = "CrmTasksModule" } }, { MessageAction.CrmTaskUpdated, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "CrmTaskUpdated", ProductResourceName = "CrmProduct", ModuleResourceName = "CrmTasksModule" } }, { MessageAction.CrmTaskOpened, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "CrmTaskOpened", ProductResourceName = "CrmProduct", ModuleResourceName = "CrmTasksModule" } }, { MessageAction.CrmTaskClosed, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "CrmTaskClosed", ProductResourceName = "CrmProduct", ModuleResourceName = "CrmTasksModule" } }, { MessageAction.CrmTaskDeleted, new MessageMaps { ActionTypeTextResourceName = "DeleteActionType", ActionTextResourceName = "CrmTaskDeleted", ProductResourceName = "CrmProduct", ModuleResourceName = "CrmTasksModule" } }, #endregion #region opportunities { MessageAction.OpportunityCreated, new MessageMaps { ActionTypeTextResourceName = "CreateActionType", ActionTextResourceName = "OpportunityCreated", ProductResourceName = "CrmProduct", ModuleResourceName = "OpportunitiesModule" } }, { MessageAction.OpportunityUpdated, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "OpportunityUpdated", ProductResourceName = "CrmProduct", ModuleResourceName = "OpportunitiesModule" } }, { MessageAction.OpportunityUpdatedStage, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "OpportunityUpdatedStage", ProductResourceName = "CrmProduct", ModuleResourceName = "OpportunitiesModule" } }, { MessageAction.OpportunityCreatedTag, new MessageMaps { ActionTypeTextResourceName = "CreateActionType", ActionTextResourceName = "OpportunityCreatedTag", ProductResourceName = "CrmProduct", ModuleResourceName = "OpportunitiesModule" } }, { MessageAction.OpportunityDeletedTag, new MessageMaps { ActionTypeTextResourceName = "DeleteActionType", ActionTextResourceName = "OpportunityDeletedTag", ProductResourceName = "CrmProduct", ModuleResourceName = "OpportunitiesModule" } }, { MessageAction.OpportunityCreatedHistoryEvent, new MessageMaps { ActionTypeTextResourceName = "CreateActionType", ActionTextResourceName = "OpportunityCreatedHistoryEvent", ProductResourceName = "CrmProduct", ModuleResourceName = "OpportunitiesModule" } }, { MessageAction.OpportunityDeletedHistoryEvent, new MessageMaps { ActionTypeTextResourceName = "DeleteActionType", ActionTextResourceName = "OpportunityDeletedHistoryEvent", ProductResourceName = "CrmProduct", ModuleResourceName = "OpportunitiesModule" } }, { MessageAction.OpportunityLinkedCompany, new MessageMaps { ActionTypeTextResourceName = "LinkActionType", ActionTextResourceName = "OpportunityLinkedCompany", ProductResourceName = "CrmProduct", ModuleResourceName = "OpportunitiesModule" } }, { MessageAction.OpportunityUnlinkedCompany, new MessageMaps { ActionTypeTextResourceName = "UnlinkActionType", ActionTextResourceName = "OpportunityUnlinkedCompany", ProductResourceName = "CrmProduct", ModuleResourceName = "OpportunitiesModule" } }, { MessageAction.OpportunityLinkedPerson, new MessageMaps { ActionTypeTextResourceName = "LinkActionType", ActionTextResourceName = "OpportunityLinkedPerson", ProductResourceName = "CrmProduct", ModuleResourceName = "OpportunitiesModule" } }, { MessageAction.OpportunityUnlinkedPerson, new MessageMaps { ActionTypeTextResourceName = "UnlinkActionType", ActionTextResourceName = "OpportunityUnlinkedPerson", ProductResourceName = "CrmProduct", ModuleResourceName = "OpportunitiesModule" } }, { MessageAction.OpportunityAttachedFiles, new MessageMaps { ActionTypeTextResourceName = "AttachActionType", ActionTextResourceName = "OpportunityAttachedFiles", ProductResourceName = "CrmProduct", ModuleResourceName = "OpportunitiesModule" } }, { MessageAction.OpportunityDetachedFile, new MessageMaps { ActionTypeTextResourceName = "DetachActionType", ActionTextResourceName = "OpportunityDetachedFile", ProductResourceName = "CrmProduct", ModuleResourceName = "OpportunitiesModule" } }, { MessageAction.OpportunityOpenedAccess, new MessageMaps { ActionTypeTextResourceName = "UpdateAccessActionType", ActionTextResourceName = "OpportunityOpenedAccess", ProductResourceName = "CrmProduct", ModuleResourceName = "OpportunitiesModule" } }, { MessageAction.OpportunityRestrictedAccess, new MessageMaps { ActionTypeTextResourceName = "UpdateAccessActionType", ActionTextResourceName = "OpportunityRestrictedAccess", ProductResourceName = "CrmProduct", ModuleResourceName = "OpportunitiesModule" } }, { MessageAction.OpportunityDeleted, new MessageMaps { ActionTypeTextResourceName = "DeleteActionType", ActionTextResourceName = "OpportunityDeleted", ProductResourceName = "CrmProduct", ModuleResourceName = "OpportunitiesModule" } }, { MessageAction.OpportunitiesDeleted, new MessageMaps { ActionTypeTextResourceName = "DeleteActionType", ActionTextResourceName = "OpportunitiesDeleted", ProductResourceName = "CrmProduct", ModuleResourceName = "OpportunitiesModule" } }, #endregion #region invoices { MessageAction.InvoiceCreated, new MessageMaps { ActionTypeTextResourceName = "CreateActionType", ActionTextResourceName = "InvoiceCreated", ProductResourceName = "CrmProduct", ModuleResourceName = "InvoicesModule" } }, { MessageAction.InvoiceUpdated, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "InvoiceUpdated", ProductResourceName = "CrmProduct", ModuleResourceName = "InvoicesModule" } }, { MessageAction.InvoicesUpdatedStatus, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "InvoicesUpdatedStatus", ProductResourceName = "CrmProduct", ModuleResourceName = "InvoicesModule" } }, { MessageAction.InvoiceDeleted, new MessageMaps { ActionTypeTextResourceName = "DeleteActionType", ActionTextResourceName = "InvoiceDeleted", ProductResourceName = "CrmProduct", ModuleResourceName = "InvoicesModule" } }, { MessageAction.InvoicesDeleted, new MessageMaps { ActionTypeTextResourceName = "DeleteActionType", ActionTextResourceName = "InvoicesDeleted", ProductResourceName = "CrmProduct", ModuleResourceName = "InvoicesModule" } }, { MessageAction.CurrencyRateUpdated, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "CurrencyRateUpdated", ProductResourceName = "CrmProduct", ModuleResourceName = "InvoicesModule" } }, { MessageAction.InvoiceDefaultTermsUpdated, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "InvoiceDefaultTermsUpdated", ProductResourceName = "CrmProduct", ModuleResourceName = "InvoicesModule" } }, { MessageAction.InvoiceDownloaded, new MessageMaps { ActionTypeTextResourceName = "DownloadActionType", ActionTextResourceName = "InvoiceDownloaded", ProductResourceName = "CrmProduct", ModuleResourceName = "InvoicesModule" } }, #endregion #region cases { MessageAction.CaseCreated, new MessageMaps { ActionTypeTextResourceName = "CreateActionType", ActionTextResourceName = "CaseCreated", ProductResourceName = "CrmProduct", ModuleResourceName = "CasesModule" } }, { MessageAction.CaseUpdated, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "CaseUpdated", ProductResourceName = "CrmProduct", ModuleResourceName = "CasesModule" } }, { MessageAction.CaseOpened, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "CaseOpened", ProductResourceName = "CrmProduct", ModuleResourceName = "CasesModule" } }, { MessageAction.CaseClosed, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "CaseClosed", ProductResourceName = "CrmProduct", ModuleResourceName = "CasesModule" } }, { MessageAction.CaseCreatedTag, new MessageMaps { ActionTypeTextResourceName = "CreateActionType", ActionTextResourceName = "CaseCreatedTag", ProductResourceName = "CrmProduct", ModuleResourceName = "CasesModule" } }, { MessageAction.CaseDeletedTag, new MessageMaps { ActionTypeTextResourceName = "DeleteActionType", ActionTextResourceName = "CaseDeletedTag", ProductResourceName = "CrmProduct", ModuleResourceName = "CasesModule" } }, { MessageAction.CaseCreatedHistoryEvent, new MessageMaps { ActionTypeTextResourceName = "CreateActionType", ActionTextResourceName = "CaseCreatedHistoryEvent", ProductResourceName = "CrmProduct", ModuleResourceName = "CasesModule" } }, { MessageAction.CaseDeletedHistoryEvent, new MessageMaps { ActionTypeTextResourceName = "DeleteActionType", ActionTextResourceName = "CaseDeletedHistoryEvent", ProductResourceName = "CrmProduct", ModuleResourceName = "CasesModule" } }, { MessageAction.CaseLinkedCompany, new MessageMaps { ActionTypeTextResourceName = "LinkActionType", ActionTextResourceName = "CaseLinkedCompany", ProductResourceName = "CrmProduct", ModuleResourceName = "CasesModule" } }, { MessageAction.CaseUnlinkedCompany, new MessageMaps { ActionTypeTextResourceName = "UnlinkActionType", ActionTextResourceName = "CaseUnlinkedCompany", ProductResourceName = "CrmProduct", ModuleResourceName = "CasesModule" } }, { MessageAction.CaseLinkedPerson, new MessageMaps { ActionTypeTextResourceName = "LinkActionType", ActionTextResourceName = "CaseLinkedPerson", ProductResourceName = "CrmProduct", ModuleResourceName = "CasesModule" } }, { MessageAction.CaseUnlinkedPerson, new MessageMaps { ActionTypeTextResourceName = "UnlinkActionType", ActionTextResourceName = "CaseUnlinkedPerson", ProductResourceName = "CrmProduct", ModuleResourceName = "CasesModule" } }, { MessageAction.CaseAttachedFiles, new MessageMaps { ActionTypeTextResourceName = "AttachActionType", ActionTextResourceName = "CaseAttachedFiles", ProductResourceName = "CrmProduct", ModuleResourceName = "CasesModule" } }, { MessageAction.CaseDetachedFile, new MessageMaps { ActionTypeTextResourceName = "DetachActionType", ActionTextResourceName = "CaseDetachedFile", ProductResourceName = "CrmProduct", ModuleResourceName = "CasesModule" } }, { MessageAction.CaseOpenedAccess, new MessageMaps { ActionTypeTextResourceName = "UpdateAccessActionType", ActionTextResourceName = "CaseOpenedAccess", ProductResourceName = "CrmProduct", ModuleResourceName = "CasesModule" } }, { MessageAction.CaseRestrictedAccess, new MessageMaps { ActionTypeTextResourceName = "UpdateAccessActionType", ActionTextResourceName = "CaseRestrictedAccess", ProductResourceName = "CrmProduct", ModuleResourceName = "CasesModule" } }, { MessageAction.CaseDeleted, new MessageMaps { ActionTypeTextResourceName = "DeleteActionType", ActionTextResourceName = "CaseDeleted", ProductResourceName = "CrmProduct", ModuleResourceName = "CasesModule" } }, { MessageAction.CasesDeleted, new MessageMaps { ActionTypeTextResourceName = "DeleteActionType", ActionTextResourceName = "CasesDeleted", ProductResourceName = "CrmProduct", ModuleResourceName = "CasesModule" } }, #endregion #region common settings { MessageAction.CrmSmtpSettingsUpdated, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "CrmSmtpSettingsUpdated", ProductResourceName = "CrmProduct", ModuleResourceName = "CommonCrmSettingsModule" } }, { MessageAction.CrmTestMailSent, new MessageMaps { ActionTypeTextResourceName = "SendActionType", ActionTextResourceName = "CrmTestMailSent", ProductResourceName = "CrmProduct", ModuleResourceName = "CommonCrmSettingsModule" } }, { MessageAction.CrmDefaultCurrencyUpdated, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "CrmDefaultCurrencyUpdated", ProductResourceName = "CrmProduct", ModuleResourceName = "CommonCrmSettingsModule" } }, { MessageAction.CrmAllDataExported, new MessageMaps { ActionTypeTextResourceName = "ExportActionType", ActionTextResourceName = "CrmAllDataExported", ProductResourceName = "CrmProduct", ModuleResourceName = "CommonCrmSettingsModule" } }, #endregion #region contact settings { MessageAction.ContactTemperatureLevelCreated, new MessageMaps { ActionTypeTextResourceName = "CreateActionType", ActionTextResourceName = "ContactTemperatureLevelCreated", ProductResourceName = "CrmProduct", ModuleResourceName = "ContactsSettingsModule" } }, { MessageAction.ContactTemperatureLevelUpdated, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "ContactTemperatureLevelUpdated", ProductResourceName = "CrmProduct", ModuleResourceName = "ContactsSettingsModule" } }, { MessageAction.ContactTemperatureLevelUpdatedColor, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "ContactTemperatureLevelUpdatedColor", ProductResourceName = "CrmProduct", ModuleResourceName = "ContactsSettingsModule" } }, { MessageAction.ContactTemperatureLevelsUpdatedOrder, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "ContactTemperatureLevelsUpdatedOrder", ProductResourceName = "CrmProduct", ModuleResourceName = "ContactsSettingsModule" } }, { MessageAction.ContactTemperatureLevelDeleted, new MessageMaps { ActionTypeTextResourceName = "DeleteActionType", ActionTextResourceName = "ContactTemperatureLevelDeleted", ProductResourceName = "CrmProduct", ModuleResourceName = "ContactsSettingsModule" } }, { MessageAction.ContactTemperatureLevelSettingsUpdated, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "ContactTemperatureLevelSettingsUpdated", ProductResourceName = "CrmProduct", ModuleResourceName = "CommonCrmSettingsModule" } }, { MessageAction.ContactTypeCreated, new MessageMaps { ActionTypeTextResourceName = "CreateActionType", ActionTextResourceName = "ContactTypeCreated", ProductResourceName = "CrmProduct", ModuleResourceName = "ContactTypesModule" } }, { MessageAction.ContactTypeUpdated, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "ContactTypeUpdated", ProductResourceName = "CrmProduct", ModuleResourceName = "ContactTypesModule" } }, { MessageAction.ContactTypesUpdatedOrder, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "ContactTypesUpdatedOrder", ProductResourceName = "CrmProduct", ModuleResourceName = "ContactTypesModule" } }, { MessageAction.ContactTypeDeleted, new MessageMaps { ActionTypeTextResourceName = "DeleteActionType", ActionTextResourceName = "ContactTypeDeleted", ProductResourceName = "CrmProduct", ModuleResourceName = "ContactTypesModule" } }, #endregion #region invoice settings { MessageAction.InvoiceItemCreated, new MessageMaps { ActionTypeTextResourceName = "CreateActionType", ActionTextResourceName = "InvoiceItemCreated", ProductResourceName = "CrmProduct", ModuleResourceName = "InvoiceSettingsModule" } }, { MessageAction.InvoiceItemUpdated, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "InvoiceItemUpdated", ProductResourceName = "CrmProduct", ModuleResourceName = "InvoiceSettingsModule" } }, { MessageAction.InvoiceItemDeleted, new MessageMaps { ActionTypeTextResourceName = "DeleteActionType", ActionTextResourceName = "InvoiceItemDeleted", ProductResourceName = "CrmProduct", ModuleResourceName = "InvoiceSettingsModule" } }, { MessageAction.InvoiceItemsDeleted, new MessageMaps { ActionTypeTextResourceName = "DeleteActionType", ActionTextResourceName = "InvoiceItemsDeleted", ProductResourceName = "CrmProduct", ModuleResourceName = "InvoiceSettingsModule" } }, { MessageAction.InvoiceTaxCreated, new MessageMaps { ActionTypeTextResourceName = "CreateActionType", ActionTextResourceName = "InvoiceTaxCreated", ProductResourceName = "CrmProduct", ModuleResourceName = "InvoiceSettingsModule" } }, { MessageAction.InvoiceTaxUpdated, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "InvoiceTaxUpdated", ProductResourceName = "CrmProduct", ModuleResourceName = "InvoiceSettingsModule" } }, { MessageAction.InvoiceTaxDeleted, new MessageMaps { ActionTypeTextResourceName = "DeleteActionType", ActionTextResourceName = "InvoiceTaxDeleted", ProductResourceName = "CrmProduct", ModuleResourceName = "InvoiceSettingsModule" } }, { MessageAction.OrganizationProfileUpdatedCompanyName, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "OrganizationProfileUpdatedCompanyName", ProductResourceName = "CrmProduct", ModuleResourceName = "InvoiceSettingsModule" } }, { MessageAction.OrganizationProfileUpdatedInvoiceLogo, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "OrganizationProfileUpdatedInvoiceLogo", ProductResourceName = "CrmProduct", ModuleResourceName = "InvoiceSettingsModule" } }, { MessageAction.OrganizationProfileUpdatedAddress, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "OrganizationProfileUpdatedAddress", ProductResourceName = "CrmProduct", ModuleResourceName = "InvoiceSettingsModule" } }, { MessageAction.InvoiceNumberFormatUpdated, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "InvoiceNumberFormatUpdated", ProductResourceName = "CrmProduct", ModuleResourceName = "InvoiceSettingsModule" } }, #endregion #region user fields settings { MessageAction.ContactUserFieldCreated, new MessageMaps { ActionTypeTextResourceName = "CreateActionType", ActionTextResourceName = "ContactUserFieldCreated", ProductResourceName = "CrmProduct", ModuleResourceName = "OtherCrmSettingsModule" } }, { MessageAction.ContactUserFieldUpdated, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "ContactUserFieldUpdated", ProductResourceName = "CrmProduct", ModuleResourceName = "OtherCrmSettingsModule" } }, { MessageAction.ContactUserFieldsUpdatedOrder, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "ContactUserFieldsUpdatedOrder", ProductResourceName = "CrmProduct", ModuleResourceName = "OtherCrmSettingsModule" } }, { MessageAction.ContactUserFieldDeleted, new MessageMaps { ActionTypeTextResourceName = "DeleteActionType", ActionTextResourceName = "ContactUserFieldDeleted", ProductResourceName = "CrmProduct", ModuleResourceName = "OtherCrmSettingsModule" } }, { MessageAction.CompanyUserFieldCreated, new MessageMaps { ActionTypeTextResourceName = "CreateActionType", ActionTextResourceName = "CompanyUserFieldCreated", ProductResourceName = "CrmProduct", ModuleResourceName = "OtherCrmSettingsModule" } }, { MessageAction.CompanyUserFieldUpdated, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "CompanyUserFieldUpdated", ProductResourceName = "CrmProduct", ModuleResourceName = "OtherCrmSettingsModule" } }, { MessageAction.CompanyUserFieldsUpdatedOrder, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "CompanyUserFieldsUpdatedOrder", ProductResourceName = "CrmProduct", ModuleResourceName = "OtherCrmSettingsModule" } }, { MessageAction.CompanyUserFieldDeleted, new MessageMaps { ActionTypeTextResourceName = "DeleteActionType", ActionTextResourceName = "CompanyUserFieldDeleted", ProductResourceName = "CrmProduct", ModuleResourceName = "OtherCrmSettingsModule" } }, { MessageAction.PersonUserFieldCreated, new MessageMaps { ActionTypeTextResourceName = "CreateActionType", ActionTextResourceName = "PersonUserFieldCreated", ProductResourceName = "CrmProduct", ModuleResourceName = "OtherCrmSettingsModule" } }, { MessageAction.PersonUserFieldUpdated, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "PersonUserFieldUpdated", ProductResourceName = "CrmProduct", ModuleResourceName = "OtherCrmSettingsModule" } }, { MessageAction.PersonUserFieldsUpdatedOrder, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "PersonUserFieldsUpdatedOrder", ProductResourceName = "CrmProduct", ModuleResourceName = "OtherCrmSettingsModule" } }, { MessageAction.PersonUserFieldDeleted, new MessageMaps { ActionTypeTextResourceName = "DeleteActionType", ActionTextResourceName = "PersonUserFieldDeleted", ProductResourceName = "CrmProduct", ModuleResourceName = "OtherCrmSettingsModule" } }, { MessageAction.OpportunityUserFieldCreated, new MessageMaps { ActionTypeTextResourceName = "CreateActionType", ActionTextResourceName = "OpportunityUserFieldCreated", ProductResourceName = "CrmProduct", ModuleResourceName = "OtherCrmSettingsModule" } }, { MessageAction.OpportunityUserFieldUpdated, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "OpportunityUserFieldUpdated", ProductResourceName = "CrmProduct", ModuleResourceName = "OtherCrmSettingsModule" } }, { MessageAction.OpportunityUserFieldsUpdatedOrder, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "OpportunityUserFieldsUpdatedOrder", ProductResourceName = "CrmProduct", ModuleResourceName = "OtherCrmSettingsModule" } }, { MessageAction.OpportunityUserFieldDeleted, new MessageMaps { ActionTypeTextResourceName = "DeleteActionType", ActionTextResourceName = "OpportunityUserFieldDeleted", ProductResourceName = "CrmProduct", ModuleResourceName = "OtherCrmSettingsModule" } }, { MessageAction.CaseUserFieldCreated, new MessageMaps { ActionTypeTextResourceName = "CreateActionType", ActionTextResourceName = "CaseUserFieldCreated", ProductResourceName = "CrmProduct", ModuleResourceName = "OtherCrmSettingsModule" } }, { MessageAction.CaseUserFieldUpdated, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "CaseUserFieldUpdated", ProductResourceName = "CrmProduct", ModuleResourceName = "OtherCrmSettingsModule" } }, { MessageAction.CaseUserFieldsUpdatedOrder, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "CaseUserFieldsUpdatedOrder", ProductResourceName = "CrmProduct", ModuleResourceName = "OtherCrmSettingsModule" } }, { MessageAction.CaseUserFieldDeleted, new MessageMaps { ActionTypeTextResourceName = "DeleteActionType", ActionTextResourceName = "CaseUserFieldDeleted", ProductResourceName = "CrmProduct", ModuleResourceName = "OtherCrmSettingsModule" } }, #endregion #region history events categories settings { MessageAction.HistoryEventCategoryCreated, new MessageMaps { ActionTypeTextResourceName = "CreateActionType", ActionTextResourceName = "HistoryEventCategoryCreated", ProductResourceName = "CrmProduct", ModuleResourceName = "OtherCrmSettingsModule" } }, { MessageAction.HistoryEventCategoryUpdated, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "HistoryEventCategoryUpdated", ProductResourceName = "CrmProduct", ModuleResourceName = "OtherCrmSettingsModule" } }, { MessageAction.HistoryEventCategoryUpdatedIcon, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "HistoryEventCategoryUpdatedIcon", ProductResourceName = "CrmProduct", ModuleResourceName = "OtherCrmSettingsModule" } }, { MessageAction.HistoryEventCategoriesUpdatedOrder, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "HistoryEventCategoriesUpdatedOrder", ProductResourceName = "CrmProduct", ModuleResourceName = "OtherCrmSettingsModule" } }, { MessageAction.HistoryEventCategoryDeleted, new MessageMaps { ActionTypeTextResourceName = "DeleteActionType", ActionTextResourceName = "HistoryEventCategoryDeleted", ProductResourceName = "CrmProduct", ModuleResourceName = "OtherCrmSettingsModule" } }, #endregion #region task actegories settings { MessageAction.CrmTaskCategoryCreated, new MessageMaps { ActionTypeTextResourceName = "CreateActionType", ActionTextResourceName = "CrmTaskCategoryCreated", ProductResourceName = "CrmProduct", ModuleResourceName = "OtherCrmSettingsModule" } }, { MessageAction.CrmTaskCategoryUpdated, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "CrmTaskCategoryUpdated", ProductResourceName = "CrmProduct", ModuleResourceName = "OtherCrmSettingsModule" } }, { MessageAction.CrmTaskCategoryUpdatedIcon, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "CrmTaskCategoryUpdatedIcon", ProductResourceName = "CrmProduct", ModuleResourceName = "OtherCrmSettingsModule" } }, { MessageAction.CrmTaskCategoriesUpdatedOrder, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "CrmTaskCategoriesUpdatedOrder", ProductResourceName = "CrmProduct", ModuleResourceName = "OtherCrmSettingsModule" } }, { MessageAction.CrmTaskCategoryDeleted, new MessageMaps { ActionTypeTextResourceName = "DeleteActionType", ActionTextResourceName = "CrmTaskCategoryDeleted", ProductResourceName = "CrmProduct", ModuleResourceName = "OtherCrmSettingsModule" } }, #endregion #region opportunity stages settings { MessageAction.OpportunityStageCreated, new MessageMaps { ActionTypeTextResourceName = "CreateActionType", ActionTextResourceName = "OpportunityStageCreated", ProductResourceName = "CrmProduct", ModuleResourceName = "OtherCrmSettingsModule" } }, { MessageAction.OpportunityStageUpdated, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "OpportunityStageUpdated", ProductResourceName = "CrmProduct", ModuleResourceName = "OtherCrmSettingsModule" } }, { MessageAction.OpportunityStageUpdatedColor, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "OpportunityStageUpdatedColor", ProductResourceName = "CrmProduct", ModuleResourceName = "OtherCrmSettingsModule" } }, { MessageAction.OpportunityStagesUpdatedOrder, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "OpportunityStagesUpdatedOrder", ProductResourceName = "CrmProduct", ModuleResourceName = "OtherCrmSettingsModule" } }, { MessageAction.OpportunityStageDeleted, new MessageMaps { ActionTypeTextResourceName = "DeleteActionType", ActionTextResourceName = "OpportunityStageDeleted", ProductResourceName = "CrmProduct", ModuleResourceName = "OtherCrmSettingsModule" } }, #endregion #region tags settings { MessageAction.ContactsCreatedTag, new MessageMaps { ActionTypeTextResourceName = "CreateActionType", ActionTextResourceName = "ContactsCreatedTag", ProductResourceName = "CrmProduct", ModuleResourceName = "OtherCrmSettingsModule" } }, { MessageAction.ContactsDeletedTag, new MessageMaps { ActionTypeTextResourceName = "DeleteActionType", ActionTextResourceName = "ContactsDeletedTag", ProductResourceName = "CrmProduct", ModuleResourceName = "OtherCrmSettingsModule" } }, { MessageAction.OpportunitiesCreatedTag, new MessageMaps { ActionTypeTextResourceName = "CreateActionType", ActionTextResourceName = "OpportunitiesCreatedTag", ProductResourceName = "CrmProduct", ModuleResourceName = "OtherCrmSettingsModule" } }, { MessageAction.OpportunitiesDeletedTag, new MessageMaps { ActionTypeTextResourceName = "DeleteActionType", ActionTextResourceName = "OpportunitiesDeletedTag", ProductResourceName = "CrmProduct", ModuleResourceName = "OtherCrmSettingsModule" } }, { MessageAction.CasesCreatedTag, new MessageMaps { ActionTypeTextResourceName = "CreateActionType", ActionTextResourceName = "CasesCreatedTag", ProductResourceName = "CrmProduct", ModuleResourceName = "OtherCrmSettingsModule" } }, { MessageAction.CasesDeletedTag, new MessageMaps { ActionTypeTextResourceName = "DeleteActionType", ActionTextResourceName = "CasesDeletedTag", ProductResourceName = "CrmProduct", ModuleResourceName = "OtherCrmSettingsModule" } }, { MessageAction.ContactsTagSettingsUpdated, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "ContactsTagSettingsUpdated", ProductResourceName = "CrmProduct", ModuleResourceName = "CommonCrmSettingsModule" } }, #endregion #region other settings { MessageAction.WebsiteContactFormUpdatedKey, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "WebsiteContactFormUpdatedKey", ProductResourceName = "CrmProduct", ModuleResourceName = "OtherCrmSettingsModule" } }, #endregion #region import { MessageAction.ContactsImportedFromCSV, new MessageMaps { ActionTypeTextResourceName = "ImportActionType", ActionTextResourceName = "ContactsImportedFromCSV", ProductResourceName = "CrmProduct", ModuleResourceName = "ContactsModule" } }, { MessageAction.CrmTasksImportedFromCSV, new MessageMaps { ActionTypeTextResourceName = "ImportActionType", ActionTextResourceName = "CrmTasksImportedFromCSV", ProductResourceName = "CrmProduct", ModuleResourceName = "CrmTasksModule" } }, { MessageAction.OpportunitiesImportedFromCSV, new MessageMaps { ActionTypeTextResourceName = "ImportActionType", ActionTextResourceName = "OpportunitiesImportedFromCSV", ProductResourceName = "CrmProduct", ModuleResourceName = "OpportunitiesModule" } }, { MessageAction.CasesImportedFromCSV, new MessageMaps { ActionTypeTextResourceName = "ImportActionType", ActionTextResourceName = "CasesImportedFromCSV", ProductResourceName = "CrmProduct", ModuleResourceName = "CasesModule" } }, #endregion #region export { MessageAction.ContactsExportedToCsv, new MessageMaps { ActionTypeTextResourceName = "ExportActionType", ActionTextResourceName = "ContactsExportedToCsv", ProductResourceName = "CrmProduct", ModuleResourceName = "ContactsModule" } }, { MessageAction.CrmTasksExportedToCsv, new MessageMaps { ActionTypeTextResourceName = "ExportActionType", ActionTextResourceName = "CrmTasksExportedToCsv", ProductResourceName = "CrmProduct", ModuleResourceName = "CrmTasksModule" } }, { MessageAction.OpportunitiesExportedToCsv, new MessageMaps { ActionTypeTextResourceName = "ExportActionType", ActionTextResourceName = "OpportunitiesExportedToCsv", ProductResourceName = "CrmProduct", ModuleResourceName = "OpportunitiesModule" } }, { MessageAction.CasesExportedToCsv, new MessageMaps { ActionTypeTextResourceName = "ExportActionType", ActionTextResourceName = "CasesExportedToCsv", ProductResourceName = "CrmProduct", ModuleResourceName = "CasesModule" } }, #endregion }; } } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/RTP/RTCP_Report_Receiver.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.RTP { #region usings using System; #endregion /// <summary> /// This class holds receiver report info. /// </summary> public class RTCP_Report_Receiver { #region Members private readonly uint m_CumulativePacketsLost; private readonly uint m_DelaySinceLastSR; private readonly uint m_ExtHigestSeqNumber; private readonly uint m_FractionLost; private readonly uint m_Jitter; private readonly uint m_LastSR; #endregion #region Properties /// <summary> /// Gets the fraction of RTP data packets from source SSRC lost since the previous SR or /// RR packet was sent. /// </summary> public uint FractionLost { get { return m_FractionLost; } } /// <summary> /// Gets total number of RTP data packets from source SSRC that have /// been lost since the beginning of reception. /// </summary> public uint CumulativePacketsLost { get { return m_CumulativePacketsLost; } } /// <summary> /// Gets extended highest sequence number received. /// </summary> public uint ExtendedSequenceNumber { get { return m_ExtHigestSeqNumber; } } /// <summary> /// Gets an estimate of the statistical variance of the RTP data packet /// interarrival time, measured in timestamp units and expressed as an /// unsigned integer. /// </summary> public uint Jitter { get { return m_Jitter; } } /// <summary> /// Gets when last sender report(SR) was recieved. /// </summary> public uint LastSR { get { return m_LastSR; } } /// <summary> /// Gets delay since last sender report(SR) was received. /// </summary> public uint DelaySinceLastSR { get { return m_DelaySinceLastSR; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="rr">RTCP RR report.</param> /// <exception cref="ArgumentNullException">Is raised when <b>rr</b> is null reference.</exception> internal RTCP_Report_Receiver(RTCP_Packet_ReportBlock rr) { if (rr == null) { throw new ArgumentNullException("rr"); } m_FractionLost = rr.FractionLost; m_CumulativePacketsLost = rr.CumulativePacketsLost; m_ExtHigestSeqNumber = rr.ExtendedHighestSeqNo; m_Jitter = rr.Jitter; m_LastSR = rr.LastSR; m_DelaySinceLastSR = rr.DelaySinceLastSR; } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/IMAP/Server/IMAP_Server.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using ASC.Mail.Net.TCP; namespace ASC.Mail.Net.IMAP.Server { #region usings using System; using System.Net; using System.Net.Sockets; using System.Text; using AUTH; #endregion #region Event delegates /// <summary> /// Represents the method that will handle the AuthUser event for SMTP_Server. /// </summary> /// <param name="sender">The source of the event. </param> /// <param name="e">A AuthUser_EventArgs that contains the event data.</param> public delegate void AuthUserEventHandler(object sender, AuthUser_EventArgs e); /// <summary> /// /// </summary> public delegate void FolderEventHandler(object sender, Mailbox_EventArgs e); /// <summary> /// /// </summary> public delegate void FoldersEventHandler(object sender, IMAP_Folders e); /// <summary> /// /// </summary> public delegate void MessagesEventHandler(object sender, IMAP_eArgs_GetMessagesInfo e); /// <summary> /// /// </summary> public delegate void MessagesItemsEventHandler(object sender, IMAP_eArgs_MessageItems e); public delegate byte[] FiletGetDelegate(IMAP_Session session); public delegate void FiletSetDelegate(IMAP_Session session, byte[] buffer); /// <summary> /// /// </summary> public delegate void MessageEventHandler(object sender, Message_EventArgs e); /* /// <summary> /// /// </summary> public delegate void SearchEventHandler(object sender,IMAP_eArgs_Search e);*/ /// <summary> /// /// </summary> public delegate void SharedRootFoldersEventHandler(object sender, SharedRootFolders_EventArgs e); /// <summary> /// /// </summary> public delegate void GetFolderACLEventHandler(object sender, IMAP_GETACL_eArgs e); /// <summary> /// /// </summary> public delegate void DeleteFolderACLEventHandler(object sender, IMAP_DELETEACL_eArgs e); /// <summary> /// /// </summary> public delegate void SetFolderACLEventHandler(object sender, IMAP_SETACL_eArgs e); /// <summary> /// /// </summary> public delegate void GetUserACLEventHandler(object sender, IMAP_GetUserACL_eArgs e); /// <summary> /// /// </summary> public delegate void GetUserQuotaHandler(object sender, IMAP_eArgs_GetQuota e); #endregion /// <summary> /// IMAP server componet. /// </summary> public class IMAP_Server : TCP_Server<IMAP_Session> { #region Events /// <summary> /// Occurs when connected user tryes to authenticate. /// </summary> public event AuthUserEventHandler AuthUser = null; /// <summary> /// Occurs when server requests to copy message to new location. /// </summary> public event MessageEventHandler CopyMessage = null; /// <summary> /// Occurs when server requests to create folder. /// </summary> public event FolderEventHandler CreateFolder = null; /// <summary> /// Occurs when server requests to delete folder. /// </summary> public event FolderEventHandler DeleteFolder = null; /// <summary> /// Occurs when IMAP server requests to delete folder ACL. /// </summary> public event DeleteFolderACLEventHandler DeleteFolderACL = null; /// <summary> /// Occurs when server requests to delete message. /// </summary> public event MessageEventHandler DeleteMessage = null; /// <summary> /// Occurs when IMAP server requests folder ACL. /// </summary> public event GetFolderACLEventHandler GetFolderACL = null; /// <summary> /// Occurs when server requests all available folders. /// </summary> public event FoldersEventHandler GetFolders = null; /// <summary> /// Occurs when server requests to get message items. /// </summary> public event MessagesItemsEventHandler GetMessageItems = null; /// <summary> /// Occurs when server requests to folder messages info. /// </summary> public event MessagesEventHandler GetMessagesInfo = null; /// <summary> /// Occurs when IMAP server requests shared root folders info. /// </summary> public event SharedRootFoldersEventHandler GetSharedRootFolders = null; /// <summary> /// Occurs when server requests subscribed folders. /// </summary> public event FoldersEventHandler GetSubscribedFolders = null; /// <summary> /// Occurs when IMAP server requests to get user ACL for specified folder. /// </summary> public event GetUserACLEventHandler GetUserACL = null; /// <summary> /// Occurs when IMAP server requests to get user quota. /// </summary> public event GetUserQuotaHandler GetUserQuota = null; /// <summary> /// Occurs when server requests to rename folder. /// </summary> public event FolderEventHandler RenameFolder = null; /// <summary> /// Occurs when IMAP session has finished and session log is available. /// </summary> public event LogEventHandler SessionLog = null; /// <summary> /// Occurs when IMAP server requests to set folder ACL. /// </summary> public event SetFolderACLEventHandler SetFolderACL = null; /// <summary> /// Occurs when server requests to store message. /// </summary> public event MessageEventHandler StoreMessage = null; /* /// <summary> /// Occurs when server requests to search specified folder messages. /// </summary> public event SearchEventHandler Search = null;*/ /// <summary> /// Occurs when server requests to store message flags. /// </summary> public event MessageEventHandler StoreMessageFlags = null; /// <summary> /// Occurs when server requests to subscribe folder. /// </summary> public event FolderEventHandler SubscribeFolder = null; /// <summary> /// Occurs when server requests to unsubscribe folder. /// </summary> public event FolderEventHandler UnSubscribeFolder = null; /// <summary> /// Occurs when new computer connected to IMAP server. /// </summary> public event ValidateIPHandler ValidateIPAddress = null; internal delegate void FolderChangedHandler(string folderName, string username); internal event FolderChangedHandler FolderChanged = null; public void OnFolderChanged(string folderName, string username) { if (FolderChanged!=null) { FolderChanged(folderName, username); } } #endregion #region Members private string m_GreetingText = ""; private int m_MaxConnectionsPerIP; private int m_MaxMessageSize = 1000000; private SaslAuthTypes m_SupportedAuth = SaslAuthTypes.All; #endregion #region Properties /// <summary> /// Gets or sets server supported authentication types. /// </summary> public SaslAuthTypes SupportedAuthentications { get { return m_SupportedAuth; } set { m_SupportedAuth = value; } } /// <summary> /// Gets or sets server greeting text. /// </summary> public string GreetingText { get { return m_GreetingText; } set { m_GreetingText = value; } } /// <summary> /// Gets or sets maximum allowed conncurent connections from 1 IP address. Value 0 means unlimited connections. /// </summary> public new int MaxConnectionsPerIP { get { return m_MaxConnectionsPerIP; } set { m_MaxConnectionsPerIP = value; } } /// <summary> /// Maximum message size. /// </summary> public int MaxMessageSize { get { return m_MaxMessageSize; } set { m_MaxMessageSize = value; } } public int MaxBadCommands { get; set; } #endregion #region Constructor #endregion #region Overrides protected override void OnMaxConnectionsPerIPExceeded(IMAP_Session session) { base.OnMaxConnectionsPerIPExceeded(session); session.TcpStream.WriteLine("* NO Maximum connections from your IP address is exceeded, try again later !\r\n"); } protected override void OnMaxConnectionsExceeded(IMAP_Session session) { session.TcpStream.WriteLine("* NO Maximum connections is exceeded"); } /// <summary> /// Initialize and start new session here. Session isn't added to session list automatically, /// session must add itself to server session list by calling AddSession(). /// </summary> /// <param name="socket">Connected client socket.</param> /// <param name="bindInfo">BindInfo what accepted socket.</param> //protected override void InitNewSession(Socket socket, IPBindInfo bindInfo) //{ // // Check maximum conncurent connections from 1 IP. // if (m_MaxConnectionsPerIP > 0) // { // lock (Sessions) // { // int nSessions = 0; // foreach (SocketServerSession s in Sessions) // { // IPEndPoint ipEndpoint = s.RemoteEndPoint; // if (ipEndpoint != null) // { // if (ipEndpoint.Address.Equals(((IPEndPoint) socket.RemoteEndPoint).Address)) // { // nSessions++; // } // } // // Maimum allowed exceeded // if (nSessions >= m_MaxConnectionsPerIP) // { // socket.Send( // Encoding.ASCII.GetBytes( // "* NO Maximum connections from your IP address is exceeded, try again later !\r\n")); // socket.Shutdown(SocketShutdown.Both); // socket.Close(); // return; // } // } // } // } // string sessionID = Guid.NewGuid().ToString(); // SocketEx socketEx = new SocketEx(socket); // if (LogCommands) // { // socketEx.Logger = new SocketLogger(socket, SessionLog); // socketEx.Logger.SessionID = sessionID; // } // IMAP_Session session = new IMAP_Session(sessionID, socketEx, bindInfo, this); // FolderChanged += session.OnFolderChanged; //} #endregion #region Internal methods /// <summary> /// Raises event ValidateIP event. /// </summary> /// <param name="localEndPoint">Server IP.</param> /// <param name="remoteEndPoint">Connected client IP.</param> /// <returns>Returns true if connection allowed.</returns> internal bool OnValidate_IpAddress(IPEndPoint localEndPoint, IPEndPoint remoteEndPoint) { ValidateIP_EventArgs oArg = new ValidateIP_EventArgs(localEndPoint, remoteEndPoint); if (ValidateIPAddress != null) { ValidateIPAddress(this, oArg); } return oArg.Validated; } /// <summary> /// Raises event AuthUser. /// </summary> /// <param name="session">Reference to current IMAP session.</param> /// <param name="userName">User name.</param> /// <param name="passwordData">Password compare data,it depends of authentication type.</param> /// <param name="data">For md5 eg. md5 calculation hash.It depends of authentication type.</param> /// <param name="authType">Authentication type.</param> /// <returns>Returns true if user is authenticated ok.</returns> internal AuthUser_EventArgs OnAuthUser(IMAP_Session session, string userName, string passwordData, string data, AuthType authType) { AuthUser_EventArgs oArgs = new AuthUser_EventArgs(session, userName, passwordData, data, authType); if (AuthUser != null) { AuthUser(this, oArgs); } return oArgs; } /// <summary> /// Raises event 'SubscribeMailbox'. /// </summary> /// <param name="session">Reference to IMAP session.</param> /// <param name="mailbox">Mailbox which to subscribe.</param> /// <returns></returns> internal string OnSubscribeMailbox(IMAP_Session session, string mailbox) { if (SubscribeFolder != null) { Mailbox_EventArgs eArgs = new Mailbox_EventArgs(mailbox); SubscribeFolder(session, eArgs); return eArgs.ErrorText; } return null; } /// <summary> /// Raises event 'UnSubscribeMailbox'. /// </summary> /// <param name="session">Reference to IMAP session.</param> /// <param name="mailbox">Mailbox which to unsubscribe.</param> /// <returns></returns> internal string OnUnSubscribeMailbox(IMAP_Session session, string mailbox) { if (UnSubscribeFolder != null) { Mailbox_EventArgs eArgs = new Mailbox_EventArgs(mailbox); UnSubscribeFolder(session, eArgs); return eArgs.ErrorText; } return null; } /// <summary> /// Raises event 'GetSubscribedMailboxes'. /// </summary> /// <param name="session">Reference to IMAP session.</param> /// <param name="referenceName">Mailbox reference.</param> /// <param name="mailBox">Mailbox search pattern or mailbox.</param> /// <returns></returns> internal IMAP_Folders OnGetSubscribedMailboxes(IMAP_Session session, string referenceName, string mailBox) { IMAP_Folders retVal = new IMAP_Folders(session, referenceName, mailBox); if (GetSubscribedFolders != null) { GetSubscribedFolders(session, retVal); } return retVal; } /// <summary> /// Raises event 'GetMailboxes'. /// </summary> /// <param name="session">Reference to IMAP session.</param> /// <param name="referenceName">Mailbox reference.</param> /// <param name="mailBox">Mailbox search pattern or mailbox.</param> /// <returns></returns> internal IMAP_Folders OnGetMailboxes(IMAP_Session session, string referenceName, string mailBox) { IMAP_Folders retVal = new IMAP_Folders(session, referenceName, mailBox); if (GetFolders != null) { GetFolders(session, retVal); } return retVal; } /// <summary> /// Raises event 'CreateMailbox'. /// </summary> /// <param name="session">Reference to IMAP session.</param> /// <param name="mailbox">Mailbox to create.</param> /// <returns></returns> internal string OnCreateMailbox(IMAP_Session session, string mailbox) { if (CreateFolder != null) { Mailbox_EventArgs eArgs = new Mailbox_EventArgs(mailbox); CreateFolder(session, eArgs); return eArgs.ErrorText; } return null; } /// <summary> /// Raises event 'DeleteMailbox'. /// </summary> /// <param name="session">Reference to IMAP session.</param> /// <param name="mailbox">Mailbox which to delete.</param> /// <returns></returns> internal string OnDeleteMailbox(IMAP_Session session, string mailbox) { if (DeleteFolder != null) { Mailbox_EventArgs eArgs = new Mailbox_EventArgs(mailbox); DeleteFolder(session, eArgs); return eArgs.ErrorText; } return null; } /// <summary> /// Raises event 'RenameMailbox'. /// </summary> /// <param name="session">Reference to IMAP session.</param> /// <param name="mailbox">Mailbox which to rename.</param> /// <param name="newMailboxName">New mailbox name.</param> /// <returns></returns> internal string OnRenameMailbox(IMAP_Session session, string mailbox, string newMailboxName) { if (RenameFolder != null) { Mailbox_EventArgs eArgs = new Mailbox_EventArgs(mailbox, newMailboxName); RenameFolder(session, eArgs); return eArgs.ErrorText; } return null; } /// <summary> /// Raises event 'GetMessagesInfo'. /// </summary> /// <param name="session">Reference to IMAP session.</param> /// <param name="folder">Folder which messages info to get.</param> /// <returns></returns> internal IMAP_eArgs_GetMessagesInfo OnGetMessagesInfo(IMAP_Session session, IMAP_SelectedFolder folder) { IMAP_eArgs_GetMessagesInfo eArgs = new IMAP_eArgs_GetMessagesInfo(session, folder); if (GetMessagesInfo != null) { GetMessagesInfo(session, eArgs); } return eArgs; } /// <summary> /// Raises event 'DeleteMessage'. /// </summary> /// <param name="session">Reference to IMAP session.</param> /// <param name="message">Message which to delete.</param> /// <returns></returns> internal string OnDeleteMessage(IMAP_Session session, IMAP_Message message) { Message_EventArgs eArgs = new Message_EventArgs(Core.Decode_IMAP_UTF7_String(session.SelectedMailbox), message); if (DeleteMessage != null) { DeleteMessage(session, eArgs); } return eArgs.ErrorText; } /// <summary> /// Raises event 'CopyMessage'. /// </summary> /// <param name="session">Reference to IMAP session.</param> /// <param name="msg">Message which to copy.</param> /// <param name="location">New message location.</param> /// <returns></returns> internal string OnCopyMessage(IMAP_Session session, IMAP_Message msg, string location) { Message_EventArgs eArgs = new Message_EventArgs(Core.Decode_IMAP_UTF7_String(session.SelectedMailbox), msg, location); if (CopyMessage != null) { CopyMessage(session, eArgs); } return eArgs.ErrorText; } /// <summary> /// Raises event 'StoreMessage'. /// </summary> /// <param name="session">Reference to IMAP session.</param> /// <param name="folder">Folder where to store.</param> /// <param name="msg">Message which to store.</param> /// <param name="messageData">Message data which to store.</param> /// <returns></returns> internal string OnStoreMessage(IMAP_Session session, string folder, IMAP_Message msg, byte[] messageData) { Message_EventArgs eArgs = new Message_EventArgs(folder, msg); eArgs.MessageData = messageData; if (StoreMessage != null) { StoreMessage(session, eArgs); } return eArgs.ErrorText; } /* /// <summary> /// Raises event 'Search'. /// </summary> /// <param name="session">IMAP session what calls this search.</param> /// <param name="folder">Folder what messages to search.</param> /// <param name="matcher">Matcher what must be used to check if message matches searching criterial.</param> /// <returns></returns> internal IMAP_eArgs_Search OnSearch(IMAP_Session session,string folder,IMAP_SearchMatcher matcher) { IMAP_eArgs_Search eArgs = new IMAP_eArgs_Search(session,folder,matcher); if(this.Search != null){ this.Search(session,eArgs); } return eArgs; }*/ /// <summary> /// Raises event 'StoreMessageFlags'. /// </summary> /// <param name="session">Reference to IMAP session.</param> /// <param name="msg">Message which flags to store.</param> /// <returns></returns> internal string OnStoreMessageFlags(IMAP_Session session, IMAP_Message msg) { Message_EventArgs eArgs = new Message_EventArgs(Core.Decode_IMAP_UTF7_String(session.SelectedMailbox), msg); if (StoreMessageFlags != null) { StoreMessageFlags(session, eArgs); } return eArgs.ErrorText; } internal SharedRootFolders_EventArgs OnGetSharedRootFolders(IMAP_Session session) { SharedRootFolders_EventArgs eArgs = new SharedRootFolders_EventArgs(session); if (GetSharedRootFolders != null) { GetSharedRootFolders(session, eArgs); } return eArgs; } internal IMAP_GETACL_eArgs OnGetFolderACL(IMAP_Session session, string folderName) { IMAP_GETACL_eArgs eArgs = new IMAP_GETACL_eArgs(session, folderName); if (GetFolderACL != null) { GetFolderACL(session, eArgs); } return eArgs; } internal IMAP_SETACL_eArgs OnSetFolderACL(IMAP_Session session, string folderName, string userName, IMAP_Flags_SetType flagsSetType, IMAP_ACL_Flags aclFlags) { IMAP_SETACL_eArgs eArgs = new IMAP_SETACL_eArgs(session, folderName, userName, flagsSetType, aclFlags); if (SetFolderACL != null) { SetFolderACL(session, eArgs); } return eArgs; } internal IMAP_DELETEACL_eArgs OnDeleteFolderACL(IMAP_Session session, string folderName, string userName) { IMAP_DELETEACL_eArgs eArgs = new IMAP_DELETEACL_eArgs(session, folderName, userName); if (DeleteFolderACL != null) { DeleteFolderACL(session, eArgs); } return eArgs; } internal IMAP_GetUserACL_eArgs OnGetUserACL(IMAP_Session session, string folderName, string userName) { IMAP_GetUserACL_eArgs eArgs = new IMAP_GetUserACL_eArgs(session, folderName, userName); if (GetUserACL != null) { GetUserACL(session, eArgs); } return eArgs; } internal IMAP_eArgs_GetQuota OnGetUserQuota(IMAP_Session session) { IMAP_eArgs_GetQuota eArgs = new IMAP_eArgs_GetQuota(session); if (GetUserQuota != null) { GetUserQuota(session, eArgs); } return eArgs; } #endregion /// <summary> /// Raises event GetMessageItems. /// </summary> /// <param name="session">Reference to IMAP session.</param> /// <param name="messageInfo">Message info what message items to get.</param> /// <param name="messageItems">Specifies message items what must be filled.</param> /// <returns></returns> protected internal IMAP_eArgs_MessageItems OnGetMessageItems(IMAP_Session session, IMAP_Message messageInfo, IMAP_MessageItems_enum messageItems) { IMAP_eArgs_MessageItems eArgs = new IMAP_eArgs_MessageItems(session, messageInfo, messageItems); if (GetMessageItems != null) { GetMessageItems(session, eArgs); } return eArgs; } public event FiletSetDelegate SetFilterSet = null; public event FiletGetDelegate GetFilterSet = null; public byte[] GetFilter(IMAP_Session session) { if (GetFilterSet != null) { return GetFilterSet(session); } return null; } public void SetFilter(IMAP_Session session, byte[] filter) { if (SetFilterSet != null) { SetFilterSet(session, filter); } } public void OnSysError(string text, Exception exception) { OnError(exception); } } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/SIP/Message/SIP_t_ReasonValue.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.SIP.Message { #region usings using System; using System.Text; #endregion /// <summary> /// Implements SIP "reason-value" value. Defined in rfc 3326. /// </summary> /// <remarks> /// <code> /// RFC 3326 Syntax: /// reason-value = protocol *(SEMI reason-params) /// protocol = "SIP" / "Q.850" / token /// reason-params = protocol-cause / reason-text / reason-extension /// protocol-cause = "cause" EQUAL cause /// cause = 1*DIGIT /// reason-text = "text" EQUAL quoted-string /// reason-extension = generic-param /// </code> /// </remarks> public class SIP_t_ReasonValue : SIP_t_ValueWithParams { #region Members private string m_Protocol = ""; #endregion #region Properties /// <summary> /// Gets or sets protocol. /// </summary> /// <exception cref="ArgumentNullException">Is raised when null value is passed.</exception> public string Protocol { get { return m_Protocol; } set { if (value == null) { throw new ArgumentNullException("Protocol"); } m_Protocol = value; } } /// <summary> /// Gets or sets 'cause' parameter value. The cause parameter contains a SIP status code. /// Value -1 means not specified. /// </summary> public int Cause { get { if (Parameters["cause"] == null) { return -1; } else { return Convert.ToInt32(Parameters["cause"].Value); } } set { if (value < 0) { Parameters.Remove("cause"); } else { Parameters.Set("cause", value.ToString()); } } } /// <summary> /// Gets or sets 'text' parameter value. Value null means not specified. /// </summary> public string Text { get { SIP_Parameter parameter = Parameters["text"]; if (parameter != null) { return parameter.Value; } else { return null; } } set { if (value == null) { Parameters.Remove("text"); } else { Parameters.Set("text", value); } } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> public SIP_t_ReasonValue() {} /// <summary> /// Default constructor. /// </summary> /// <param name="value">SIP reason-value value.</param> public SIP_t_ReasonValue(string value) { Parse(value); } #endregion #region Methods /// <summary> /// Parses "reason-value" from specified value. /// </summary> /// <param name="value">SIP "reason-value" value.</param> /// <exception cref="ArgumentNullException">Raised when <b>value</b> is null.</exception> /// <exception cref="SIP_ParseException">Raised when invalid SIP message.</exception> public void Parse(string value) { if (value == null) { throw new ArgumentNullException("value"); } Parse(new StringReader(value)); } /// <summary> /// Parses "reason-value" from specified reader. /// </summary> /// <param name="reader">Reader from where to parse.</param> /// <exception cref="ArgumentNullException">Raised when <b>reader</b> is null.</exception> /// <exception cref="SIP_ParseException">Raised when invalid SIP message.</exception> public override void Parse(StringReader reader) { /* reason-value = protocol *(SEMI reason-params) protocol = "SIP" / "Q.850" / token reason-params = protocol-cause / reason-text / reason-extension protocol-cause = "cause" EQUAL cause cause = 1*DIGIT reason-text = "text" EQUAL quoted-string reason-extension = generic-param */ if (reader == null) { throw new ArgumentNullException("reader"); } // protocol string word = reader.ReadWord(); if (word == null) { throw new SIP_ParseException("SIP reason-value 'protocol' value is missing !"); } m_Protocol = word; // Parse parameters ParseParameters(reader); } /// <summary> /// Converts this to valid "reason-value" value. /// </summary> /// <returns>Returns "reason-value" value.</returns> public override string ToStringValue() { /* reason-value = protocol *(SEMI reason-params) protocol = "SIP" / "Q.850" / token reason-params = protocol-cause / reason-text / reason-extension protocol-cause = "cause" EQUAL cause cause = 1*DIGIT reason-text = "text" EQUAL quoted-string reason-extension = generic-param */ StringBuilder retVal = new StringBuilder(); // Add protocol retVal.Append(m_Protocol); // Add parameters retVal.Append(ParametersToString()); return retVal.ToString(); } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/SIP/Stack/SIP_RequestLine.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.SIP.Stack { #region usings using System; #endregion /// <summary> /// Implements SIP Request-Line. Defined in RFC 3261. /// </summary> public class SIP_RequestLine { #region Members private string m_Method = ""; private AbsoluteUri m_pUri; private string m_Version = ""; #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="method">SIP method.</param> /// <param name="uri">Request URI.</param> /// <exception cref="ArgumentNullException">Is raised when <b>method</b> or <b>uri</b> is null reference.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> public SIP_RequestLine(string method, AbsoluteUri uri) { if (method == null) { throw new ArgumentNullException("method"); } if (!SIP_Utils.IsToken(method)) { throw new ArgumentException("Argument 'method' value must be token."); } if (uri == null) { throw new ArgumentNullException("uri"); } m_Method = method.ToUpper(); m_pUri = uri; m_Version = "SIP/2.0"; } #endregion #region Properties /// <summary> /// Gets or sets request method. This value is always in upper-case. /// </summary> /// <exception cref="ArgumentNullException">Is raised when <b>value</b> is null reference.</exception> /// <exception cref="ArgumentException">Is raised when <b>value</b> has invalid value.</exception> public string Method { get { return m_Method; } set { if (value == null) { throw new ArgumentNullException("Method"); } if (!SIP_Utils.IsToken(value)) { throw new ArgumentException("Property 'Method' value must be token."); } m_Method = value.ToUpper(); } } /// <summary> /// Gets or sets request URI. /// </summary> /// <exception cref="ArgumentNullException">Is raised when <b>value</b> is null reference.</exception> public AbsoluteUri Uri { get { return m_pUri; } set { if (value == null) { throw new ArgumentNullException("Uri"); } m_pUri = value; } } /// <summary> /// Gets or sets SIP version. /// </summary> /// <exception cref="ArgumentNullException">Is raised when <b>value</b> is null reference.</exception> /// <exception cref="ArgumentException">Is raised when <b>value</b> has invalid value.</exception> public string Version { get { return m_Version; } set { if (value == null) { throw new ArgumentNullException("Version"); } if (value == "") { throw new ArgumentException("Property 'Version' value must be specified."); } m_Version = value; } } #endregion #region Methods /// <summary> /// Returns Request-Line string. /// </summary> /// <returns>Returns Request-Line string.</returns> public override string ToString() { // RFC 3261 25. // Request-Line = Method SP Request-URI SP SIP-Version CRLF return m_Method + " " + m_pUri + " " + m_Version + "\r\n"; } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/SIP/Message/SIP_HeaderField.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.SIP.Message { /// <summary> /// Represents SIP message header field. /// </summary> public class SIP_HeaderField { #region Members private readonly string m_Name = ""; private bool m_IsMultiValue; private string m_Value = ""; #endregion #region Properties /// <summary> /// Gets header field name. /// </summary> public string Name { get { return m_Name; } } /// <summary> /// Gets or sets header field value. /// </summary> public virtual string Value { get { return m_Value; } set { m_Value = value; } } /// <summary> /// Gets if header field is multi value header field. /// </summary> public bool IsMultiValue { get { return m_IsMultiValue; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="name">Header field name.</param> /// <param name="value">Header field value.</param> internal SIP_HeaderField(string name, string value) { m_Name = name; m_Value = value; } #endregion #region Internal methods /// <summary> /// Sets property IsMultiValue value. /// </summary> /// <param name="value">Value to set.</param> internal void SetMultiValue(bool value) { m_IsMultiValue = value; } #endregion } }<file_sep>/module/ASC.Thrdparty/ASC.FederatedLogin/LoginProviders/TwitterLoginProvider.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections.Generic; using System.Globalization; using System.Web; using ASC.FederatedLogin.Profile; using Twitterizer; namespace ASC.FederatedLogin.LoginProviders { public class TwitterLoginProvider : BaseLoginProvider<TwitterLoginProvider> { public static string TwitterKey { get { return Instance.ClientID; } } public static string TwitterSecret { get { return Instance.ClientSecret; } } public static string TwitterDefaultAccessToken { get { return Instance["twitterAccessToken_Default"]; } } public static string TwitterAccessTokenSecret { get { return Instance["twitterAccessTokenSecret_Default"]; } } public override string AccessTokenUrl { get { return "https://api.twitter.com/oauth/access_token"; } } public override string RedirectUri { get { return this["twitterRedirectUrl"]; } } public override string ClientID { get { return this["twitterKey"]; } } public override string ClientSecret { get { return this["twitterSecret"]; } } public override string CodeUrl { get { return "https://api.twitter.com/oauth/request_token"; } } public override bool IsEnabled { get { return !string.IsNullOrEmpty(ClientID) && !string.IsNullOrEmpty(ClientSecret); } } public TwitterLoginProvider() { } public TwitterLoginProvider(string name, int order, Dictionary<string, string> props, Dictionary<string, string> additional = null) : base(name, order, props, additional) { } public override LoginProfile ProcessAuthoriztion(HttpContext context, IDictionary<string, string> @params) { if (!string.IsNullOrEmpty(context.Request["denied"])) { return LoginProfile.FromError(new Exception("Canceled at provider")); } if (string.IsNullOrEmpty(context.Request["oauth_token"])) { var callbackAddress = new UriBuilder(RedirectUri) { Query = "state=" + HttpUtility.UrlEncode(context.Request.GetUrlRewriter().AbsoluteUri) }; var reqToken = OAuthUtility.GetRequestToken(TwitterKey, TwitterSecret, callbackAddress.ToString()); var url = OAuthUtility.BuildAuthorizationUri(reqToken.Token).ToString(); context.Response.Redirect(url, true); return null; } var requestToken = context.Request["oauth_token"]; var pin = context.Request["oauth_verifier"]; var tokens = OAuthUtility.GetAccessToken(TwitterKey, TwitterSecret, requestToken, pin); var accesstoken = new OAuthTokens { AccessToken = tokens.Token, AccessTokenSecret = tokens.TokenSecret, ConsumerKey = TwitterKey, ConsumerSecret = TwitterSecret }; var account = TwitterAccount.VerifyCredentials(accesstoken).ResponseObject; return ProfileFromTwitter(account); } protected override OAuth20Token Auth(HttpContext context, string scopes, Dictionary<string, string> additional = null) { throw new NotImplementedException(); } public override LoginProfile GetLoginProfile(string accessToken) { throw new NotImplementedException(); } internal static LoginProfile ProfileFromTwitter(TwitterUser twitterUser) { return twitterUser == null ? null : new LoginProfile { Name = twitterUser.Name, DisplayName = twitterUser.ScreenName, Avatar = twitterUser.ProfileImageSecureLocation, TimeZone = twitterUser.TimeZone, Locale = twitterUser.Language, Id = twitterUser.Id.ToString(CultureInfo.InvariantCulture), Provider = ProviderConstants.Twitter }; } } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/MIME/MIME_h_ParameterCollection.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.MIME { #region usings using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Text; using System.Web; #endregion /// <summary> /// Represents MIME header field parameters collection. /// </summary> public class MIME_h_ParameterCollection : IEnumerable { #region Members private readonly MIME_h m_pOwner; private readonly Dictionary<string, MIME_h_Parameter> m_pParameters; private bool m_IsModified; #endregion #region Properties /// <summary> /// Gets if this header field parameters are modified since it has loaded. /// </summary> /// <remarks>All new added header fields has <b>IsModified = true</b>.</remarks> /// <exception cref="ObjectDisposedException">Is riased when this class is disposed and this property is accessed.</exception> public bool IsModified { get { if (m_IsModified) { return true; } else { foreach (MIME_h_Parameter parameter in ToArray()) { if (parameter.IsModified) { return true; } } return false; } } } /// <summary> /// Gets owner MIME header field. /// </summary> public MIME_h Owner { get { return m_pOwner; } } /// <summary> /// Gets number of items in the collection. /// </summary> public int Count { get { return m_pParameters.Count; } } /// <summary> /// Gets or sets specified header field parameter value. Value null means not specified. /// </summary> /// <param name="name">Header field name.</param> /// <returns>Returns specified header field value or null if specified parameter doesn't exist.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>name</b> is null reference.</exception> public string this[string name] { get { if (name == null) { throw new ArgumentNullException("name"); } MIME_h_Parameter retVal = null; if (m_pParameters.TryGetValue(name, out retVal)) { return retVal.Value; } else { return null; } } set { if (name == null) { throw new ArgumentNullException("name"); } MIME_h_Parameter retVal = null; if (m_pParameters.TryGetValue(name, out retVal)) { retVal.Value = value; } else { m_pParameters.Add(name, new MIME_h_Parameter(name, value)); } } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="owner">Owner MIME header field.</param> /// <exception cref="ArgumentNullException">Is raised when <b>owner</b> is null reference.</exception> public MIME_h_ParameterCollection(MIME_h owner) { if (owner == null) { throw new ArgumentNullException("owner"); } m_pOwner = owner; m_pParameters = new Dictionary<string, MIME_h_Parameter>(StringComparer.CurrentCultureIgnoreCase); } #endregion #region Methods /// <summary> /// Removes specified parametr from the collection. /// </summary> /// <param name="name">Parameter name.</param> /// <exception cref="ArgumentNullException">Is raised when <b>name</b> is null reference.</exception> public void Remove(string name) { if (name == null) { throw new ArgumentNullException("name"); } if (m_pParameters.Remove(name)) { m_IsModified = true; } } /// <summary> /// Removes all items from the collection. /// </summary> public void Clear() { m_pParameters.Clear(); m_IsModified = true; } /// <summary> /// Copies header fields parameters to new array. /// </summary> /// <returns>Returns header fields parameters array.</returns> public MIME_h_Parameter[] ToArray() { MIME_h_Parameter[] retVal = new MIME_h_Parameter[m_pParameters.Count]; m_pParameters.Values.CopyTo(retVal, 0); return retVal; } /// <summary> /// Returns header field parameters as string. /// </summary> /// <returns>Returns header field parameters as string.</returns> public override string ToString() { return ToString(null); } /// <summary> /// Returns header field parameters as string. /// </summary> /// <param name="charset">Charset to use to encode 8-bit characters. Value null means parameters not encoded.</param> /// <returns>Returns header field parameters as string.</returns> public string ToString(Encoding charset) { /* RFC 2231. * If parameter conatins 8-bit byte, we need to encode parameter value * If parameter value length bigger than MIME maximum allowed line length, * we need split value. */ if (charset == null) { charset = Encoding.Default; } StringBuilder retVal = new StringBuilder(); foreach (MIME_h_Parameter parameter in ToArray()) { if (string.IsNullOrEmpty(parameter.Value)) { retVal.Append(";\r\n\t" + parameter.Name); } // We don't need to encode or split value. else if ((charset == null || Core.IsAscii(parameter.Value)) && parameter.Value.Length < 76) { retVal.Append(";\r\n\t" + parameter.Name + "=" + TextUtils.QuoteString(parameter.Value)); } // We need to encode/split value. else { byte[] byteValue = charset.GetBytes(parameter.Value); List<string> values = new List<string>(); // Do encoding/splitting. int offset = 0; char[] valueBuff = new char[50]; foreach (byte b in byteValue) { // We need split value as RFC 2231 says. if (offset >= (50 - 3)) { values.Add(new string(valueBuff, 0, offset)); offset = 0; } // Normal char, we don't need to encode. if (MIME_Reader.IsAttributeChar((char) b)) { valueBuff[offset++] = (char) b; } // We need to encode byte as %X2. else { valueBuff[offset++] = '%'; valueBuff[offset++] = (b >> 4).ToString("X")[0]; valueBuff[offset++] = (b & 0xF).ToString("X")[0]; } } // Add pending buffer value. if (offset > 0) { values.Add(new string(valueBuff, 0, offset)); } for (int i = 0; i < values.Count; i++) { // Only fist value entry has charset and language info. if (charset != null && i == 0) { retVal.Append(";\r\n\t" + parameter.Name + "*" + i + "*=" + charset.WebName + "''" + values[i]); } else { retVal.Append(";\r\n\t" + parameter.Name + "*" + i + "*=" + values[i]); } } } } return retVal.ToString(); } /// <summary> /// Parses parameters from the specified value. /// </summary> /// <param name="value">Header field parameters string.</param> /// <exception cref="ArgumentNullException">Is raised when <b>value</b> is null reference.</exception> public void Parse(string value) { if (value == null) { throw new ArgumentNullException("value"); } Parse(new MIME_Reader(value)); } /// <summary> /// Parses parameters from the specified reader. /// </summary> /// <param name="reader">MIME reader.</param> /// <exception cref="ArgumentNullException">Is raised when <b>reader</b> is null reference.</exception> public void Parse(MIME_Reader reader) { if (reader == null) { throw new ArgumentNullException("reader"); } /* RFC 2231. */ while (true) { // End os stream reached. if (reader.Peek(true) == -1) { break; } // Next parameter start, just eat that char. else if (reader.Peek(true) == ';') { reader.Char(false); } else { string name = reader.Token(); if (name == null) break; string value = ""; // Parameter value specified. if (reader.Peek(true) == '=') { reader.Char(false); string v = reader.Word(); // Normally value may not be null, but following case: paramName=EOS. if (v != null) { value = v; } } // RFC 2231 encoded/splitted parameter. if (name.IndexOf('*') > -1) { string[] name_x_no_x = name.Split('*'); name = name_x_no_x[0]; Encoding charset = Encoding.ASCII; StringBuilder valueBuffer = new StringBuilder(); // We must have charset'language'value. // Examples: // URL*=utf-8''test; // URL*0*=utf-8''"test"; if ((name_x_no_x.Length == 2 && name_x_no_x[1] == "") || name_x_no_x.Length == 3) { string[] charset_language_value = value.Split('\''); charset = EncodingTools.GetEncodingByCodepageName(charset_language_value[0]) ?? Encoding.ASCII; valueBuffer.Append(charset_language_value[2]); } // No encoding, probably just splitted ASCII value. // Example: // URL*0="value1"; // URL*1="value2"; else { valueBuffer.Append(value); } // Read while value continues. while (true) { // End os stream reached. if (reader.Peek(true) == -1) { break; } // Next parameter start, just eat that char. else if (reader.Peek(true) == ';') { reader.Char(false); } else { if (!reader.StartsWith(name + "*")) { break; } reader.Token(); // Parameter value specified. if (reader.Peek(true) == '=') { reader.Char(false); string v = reader.Word(); // Normally value may not be null, but following case: paramName=EOS. if (v != null) { valueBuffer.Append(v); } } } } this[name] = DecodeExtOctet(valueBuffer.ToString(),charset); } // Regular parameter. else { this[name] = value; } } } m_IsModified = false; } /// <summary> /// Gets enumerator. /// </summary> /// <returns></returns> public IEnumerator GetEnumerator() { return m_pParameters.GetEnumerator(); } #endregion #region Utility methods /// <summary> /// Decodes non-ascii text with MIME <b>ext-octet</b> method. Defined in RFC 2231 7. /// </summary> /// <param name="text">Text to decode,</param> /// <param name="charset">Charset to use.</param> /// <returns>Returns decoded text.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>text</b> or <b>charset</b> is null.</exception> private static string DecodeExtOctet(string text, Encoding charset) { if (text == null) { throw new ArgumentNullException("text"); } if (charset == null) { throw new ArgumentNullException("charset"); } return HttpUtility.UrlDecode(text, charset); /* int offset = 0; byte[] decodedBuffer = new byte[text.Length]; for (int i = 0; i < text.Length; i++) { if (text[i] == '%') { decodedBuffer[offset++] = byte.Parse(text[i + 1] + text[i + 2].ToString(), NumberStyles.HexNumber); i += 2; } else { decodedBuffer[offset++] = (byte) text[i]; } } return charset.GetString(decodedBuffer, 0, offset);*/ } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/_Obsolete/MIME/MimeUtils.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.Mime { #region usings using System; using System.Globalization; using System.IO; using System.Text; using StringReader=ASC.Mail.Net.StringReader; #endregion /// <summary> /// Provides mime related utility methods. /// </summary> [Obsolete("See LumiSoft.Net.MIME or LumiSoft.Net.Mail namepaces for replacement.")] public class MimeUtils { // TODO get rid of this method, only IMAP uses it #region Methods /// <summary> /// Parses rfc 2822 datetime. /// </summary> /// <param name="date">Date string.</param> /// <returns></returns> public static DateTime ParseDate(string date) { /* Rfc 2822 3.3. Date and Time Specification. date-time = [ day-of-week "," ] date FWS time [CFWS] date = day month year time = hour ":" minute [ ":" second ] FWS zone */ /* IMAP date format. date-time = date FWS time [CFWS] date = day-month-year time = hour ":" minute [ ":" second ] FWS zone */ // zone = (( "+" / "-" ) 4DIGIT) //--- Replace timezone constants -------// /* UT -0000 GMT -0000 EDT -0400 EST -0500 CDT -0500 CST -0600 MDT -0600 MST -0700 PDT -0700 PST -0800 BST +0100 British Summer Time */ date = date.ToLower(); date = date.Replace("ut", "-0000"); date = date.Replace("gmt", "-0000"); date = date.Replace("edt", "-0400"); date = date.Replace("est", "-0500"); date = date.Replace("cdt", "-0500"); date = date.Replace("cst", "-0600"); date = date.Replace("mdt", "-0600"); date = date.Replace("mst", "-0700"); date = date.Replace("pdt", "-0700"); date = date.Replace("pst", "-0800"); date = date.Replace("bst", "+0100"); //----------------------------------------// //--- Replace month constants ---// date = date.Replace("jan", "01"); date = date.Replace("feb", "02"); date = date.Replace("mar", "03"); date = date.Replace("apr", "04"); date = date.Replace("may", "05"); date = date.Replace("jun", "06"); date = date.Replace("jul", "07"); date = date.Replace("aug", "08"); date = date.Replace("sep", "09"); date = date.Replace("oct", "10"); date = date.Replace("nov", "11"); date = date.Replace("dec", "12"); //-------------------------------// // If date contains optional "day-of-week,", remove it if (date.IndexOf(',') > -1) { date = date.Substring(date.IndexOf(',') + 1); } // Remove () from date. "Mon, 13 Oct 2003 20:50:57 +0300 (EEST)" if (date.IndexOf(" (") > -1) { date = date.Substring(0, date.IndexOf(" (")); } int year = 1900; int month = 1; int day = 1; int hour = -1; int minute = -1; int second = -1; int zoneMinutes = -1; StringReader s = new StringReader(date); //--- Pase date --------------------------------------------------------------------// try { day = Convert.ToInt32(s.ReadWord(true, new[] {'.', '-', ' '}, true)); } catch { throw new Exception("Invalid date value '" + date + "', invalid day value !"); } try { month = Convert.ToInt32(s.ReadWord(true, new[] {'.', '-', ' '}, true)); } catch { throw new Exception("Invalid date value '" + date + "', invalid month value !"); } try { year = Convert.ToInt32(s.ReadWord(true, new[] {'.', '-', ' '}, true)); } catch { throw new Exception("Invalid date value '" + date + "', invalid year value !"); } //----------------------------------------------------------------------------------// //--- Parse time -------------------------------------------------------------------// // Time is optional, so parse it if its included. if (s.Available > 0) { try { hour = Convert.ToInt32(s.ReadWord(true, new[] {':'}, true)); } catch { throw new Exception("Invalid date value '" + date + "', invalid hour value !"); } try { minute = Convert.ToInt32(s.ReadWord(true, new[] {':'}, false)); } catch { throw new Exception("Invalid date value '" + date + "', invalid minute value !"); } s.ReadToFirstChar(); if (s.StartsWith(":")) { s.ReadSpecifiedLength(1); try { string secondString = s.ReadWord(true, new[] {' '}, true); // Milli seconds specified, remove them. if (secondString.IndexOf('.') > -1) { secondString = secondString.Substring(0, secondString.IndexOf('.')); } second = Convert.ToInt32(secondString); } catch { throw new Exception("Invalid date value '" + date + "', invalid second value !"); } } s.ReadToFirstChar(); if (s.Available > 3) { string timezone = s.SourceString.Replace(":", ""); if (timezone.StartsWith("+") || timezone.StartsWith("-")) { bool utc_add_time = timezone.StartsWith("+"); // Remove +/- sign timezone = timezone.Substring(1); // padd time zone to 4 symbol. For example 200, will be 0200. while (timezone.Length < 4) { timezone = "0" + timezone; } try { // time zone format hours|minutes int h = Convert.ToInt32(timezone.Substring(0, 2)); int m = Convert.ToInt32(timezone.Substring(2)); if (utc_add_time) { zoneMinutes = 0 - ((h*60) + m); } else { zoneMinutes = (h*60) + m; } } catch { // Just skip time zone, if can't parse } } } } //---------------------------------------------------------------------------------// // Convert time to UTC if (hour != -1 && minute != -1 && second != -1) { DateTime d = new DateTime(year, month, day, hour, minute, second).AddMinutes(zoneMinutes); return new DateTime(d.Year, d.Month, d.Day, d.Hour, d.Minute, d.Second, DateTimeKind.Utc). ToLocalTime(); } else { return new DateTime(year, month, day); } } /// <summary> /// Converts date to rfc 2822 date time string. /// </summary> /// <param name="dateTime">Date time value.</param> /// <returns></returns> public static string DateTimeToRfc2822(DateTime dateTime) { return dateTime.ToUniversalTime().ToString("r", DateTimeFormatInfo.InvariantInfo); } /// <summary> /// Parses headers from message or mime entry. /// </summary> /// <param name="entryStrm">Stream from where to read headers.</param> /// <returns>Returns header lines.</returns> public static string ParseHeaders(Stream entryStrm) { /* Rfc 2822 3.1. GENERAL DESCRIPTION A message consists of header fields and, optionally, a body. The body is simply a sequence of lines containing ASCII charac- ters. It is separated from the headers by a null line (i.e., a line with nothing preceding the CRLF). */ byte[] crlf = new[] {(byte) '\r', (byte) '\n'}; MemoryStream msHeaders = new MemoryStream(); StreamLineReader r = new StreamLineReader(entryStrm); byte[] lineData = r.ReadLine(); while (lineData != null) { if (lineData.Length == 0) { break; } msHeaders.Write(lineData, 0, lineData.Length); msHeaders.Write(crlf, 0, crlf.Length); lineData = r.ReadLine(); } return Encoding.Default.GetString(msHeaders.ToArray()); } /// <summary> /// Parse header specified header field value. /// /// Use this method only if you need to get only one header field, otherwise use /// MimeParser.ParseHeaderField(string fieldName,string headers). /// This avoid parsing headers multiple times. /// </summary> /// <param name="fieldName">Header field which to parse. Eg. Subject: .</param> /// <param name="entryStrm">Stream from where to read headers.</param> /// <returns></returns> public static string ParseHeaderField(string fieldName, Stream entryStrm) { return ParseHeaderField(fieldName, ParseHeaders(entryStrm)); } /// <summary> /// Parse header specified header field value. /// </summary> /// <param name="fieldName">Header field which to parse. Eg. Subject: .</param> /// <param name="headers">Full headers string. Use MimeParser.ParseHeaders() to get this value.</param> public static string ParseHeaderField(string fieldName, string headers) { /* Rfc 2822 2.2 Header Fields Header fields are lines composed of a field name, followed by a colon (":"), followed by a field body, and terminated by CRLF. A field name MUST be composed of printable US-ASCII characters (i.e., characters that have values between 33 and 126, inclusive), except colon. A field body may be composed of any US-ASCII characters, except for CR and LF. However, a field body may contain CRLF when used in header "folding" and "unfolding" as described in section 2.2.3. All field bodies MUST conform to the syntax described in sections 3 and 4 of this standard. Rfc 2822 2.2.3 (Multiline header fields) The process of moving from this folded multiple-line representation of a header field to its single line representation is called "unfolding". Unfolding is accomplished by simply removing any CRLF that is immediately followed by WSP. Each header field should be treated in its unfolded form for further syntactic and semantic evaluation. Example: Subject: aaaaa<CRLF> <TAB or SP>aaaaa<CRLF> */ using (TextReader r = new StreamReader(new MemoryStream(Encoding.Default.GetBytes(headers)))) { string line = r.ReadLine(); while (line != null) { // Find line where field begins if (line.ToUpper().StartsWith(fieldName.ToUpper())) { // Remove field name and start reading value string fieldValue = line.Substring(fieldName.Length).Trim(); // see if multi line value. See commnt above. line = r.ReadLine(); while (line != null && (line.StartsWith("\t") || line.StartsWith(" "))) { fieldValue += line; line = r.ReadLine(); } return fieldValue; } line = r.ReadLine(); } } return ""; } /// <summary> /// Parses header field parameter value. /// For example: CONTENT-TYPE: application\octet-stream; name="yourFileName.xxx", /// fieldName="CONTENT-TYPE:" and subFieldName="name". /// </summary> /// <param name="fieldName">Main header field name.</param> /// <param name="parameterName">Header field's parameter name.</param> /// <param name="headers">Full headrs string.</param> /// <returns></returns> public static string ParseHeaderFiledParameter(string fieldName, string parameterName, string headers) { string mainFiled = ParseHeaderField(fieldName, headers); // Parse sub field value if (mainFiled.Length > 0) { int index = mainFiled.ToUpper().IndexOf(parameterName.ToUpper()); if (index > -1) { mainFiled = mainFiled.Substring(index + parameterName.Length + 1); // Remove "subFieldName=" // subFieldName value may be in "" and without if (mainFiled.StartsWith("\"")) { return mainFiled.Substring(1, mainFiled.IndexOf("\"", 1) - 1); } // value without "" else { int endIndex = mainFiled.Length; if (mainFiled.IndexOf(" ") > -1) { endIndex = mainFiled.IndexOf(" "); } return mainFiled.Substring(0, endIndex); } } } return ""; } /// <summary> /// Parses MediaType_enum from <b>Content-Type:</b> header field value. /// </summary> /// <param name="headerFieldValue"><b>Content-Type:</b> header field value. This value can be null, then MediaType_enum.NotSpecified.</param> /// <returns></returns> public static MediaType_enum ParseMediaType(string headerFieldValue) { if (headerFieldValue == null) { return MediaType_enum.NotSpecified; } string contentType = TextUtils.SplitString(headerFieldValue, ';')[0].ToLower(); //--- Text/xxx --------------------------------// if (contentType.IndexOf("text/plain") > -1) { return MediaType_enum.Text_plain; } else if (contentType.IndexOf("text/html") > -1) { return MediaType_enum.Text_html; } else if (contentType.IndexOf("text/xml") > -1) { return MediaType_enum.Text_xml; } else if (contentType.IndexOf("text/rtf") > -1) { return MediaType_enum.Text_rtf; } else if (contentType.IndexOf("text") > -1) { return MediaType_enum.Text; } //---------------------------------------------// //--- Image/xxx -------------------------------// else if (contentType.IndexOf("image/gif") > -1) { return MediaType_enum.Image_gif; } else if (contentType.IndexOf("image/tiff") > -1) { return MediaType_enum.Image_tiff; } else if (contentType.IndexOf("image/jpeg") > -1) { return MediaType_enum.Image_jpeg; } else if (contentType.IndexOf("image") > -1) { return MediaType_enum.Image; } //---------------------------------------------// //--- Audio/xxx -------------------------------// else if (contentType.IndexOf("audio") > -1) { return MediaType_enum.Audio; } //---------------------------------------------// //--- Video/xxx -------------------------------// else if (contentType.IndexOf("video") > -1) { return MediaType_enum.Video; } //---------------------------------------------// //--- Application/xxx -------------------------// else if (contentType.IndexOf("application/octet-stream") > -1) { return MediaType_enum.Application_octet_stream; } else if (contentType.IndexOf("application") > -1) { return MediaType_enum.Application; } //---------------------------------------------// //--- Multipart/xxx ---------------------------// else if (contentType.IndexOf("multipart/mixed") > -1) { return MediaType_enum.Multipart_mixed; } else if (contentType.IndexOf("multipart/alternative") > -1) { return MediaType_enum.Multipart_alternative; } else if (contentType.IndexOf("multipart/parallel") > -1) { return MediaType_enum.Multipart_parallel; } else if (contentType.IndexOf("multipart/related") > -1) { return MediaType_enum.Multipart_related; } else if (contentType.IndexOf("multipart/signed") > -1) { return MediaType_enum.Multipart_signed; } else if (contentType.IndexOf("multipart") > -1) { return MediaType_enum.Multipart; } //---------------------------------------------// //--- Message/xxx -----------------------------// else if (contentType.IndexOf("message/rfc822") > -1) { return MediaType_enum.Message_rfc822; } else if (contentType.IndexOf("message") > -1) { return MediaType_enum.Message; } //---------------------------------------------// else { return MediaType_enum.Unknown; } } /// <summary> /// Converts MediaType_enum to string. NOTE: Returns null for MediaType_enum.NotSpecified. /// </summary> /// <param name="mediaType">MediaType_enum value to convert.</param> /// <returns></returns> public static string MediaTypeToString(MediaType_enum mediaType) { //--- Text/xxx --------------------------------// if (mediaType == MediaType_enum.Text_plain) { return "text/plain"; } else if (mediaType == MediaType_enum.Text_html) { return "text/html"; } else if (mediaType == MediaType_enum.Text_xml) { return "text/xml"; } else if (mediaType == MediaType_enum.Text_rtf) { return "text/rtf"; } else if (mediaType == MediaType_enum.Text) { return "text"; } //---------------------------------------------// //--- Image/xxx -------------------------------// else if (mediaType == MediaType_enum.Image_gif) { return "image/gif"; } else if (mediaType == MediaType_enum.Image_tiff) { return "image/tiff"; } else if (mediaType == MediaType_enum.Image_jpeg) { return "image/jpeg"; } else if (mediaType == MediaType_enum.Image) { return "image"; } //---------------------------------------------// //--- Audio/xxx -------------------------------// else if (mediaType == MediaType_enum.Audio) { return "audio"; } //---------------------------------------------// //--- Video/xxx -------------------------------// else if (mediaType == MediaType_enum.Video) { return "video"; } //---------------------------------------------// //--- Application/xxx -------------------------// else if (mediaType == MediaType_enum.Application_octet_stream) { return "application/octet-stream"; } else if (mediaType == MediaType_enum.Application) { return "application"; } //---------------------------------------------// //--- Multipart/xxx ---------------------------// else if (mediaType == MediaType_enum.Multipart_mixed) { return "multipart/mixed"; } else if (mediaType == MediaType_enum.Multipart_alternative) { return "multipart/alternative"; } else if (mediaType == MediaType_enum.Multipart_parallel) { return "multipart/parallel"; } else if (mediaType == MediaType_enum.Multipart_related) { return "multipart/related"; } else if (mediaType == MediaType_enum.Multipart_signed) { return "multipart/signed"; } else if (mediaType == MediaType_enum.Multipart) { return "multipart"; } //---------------------------------------------// //--- Message/xxx -----------------------------// else if (mediaType == MediaType_enum.Message_rfc822) { return "message/rfc822"; } else if (mediaType == MediaType_enum.Message) { return "message"; } //---------------------------------------------// else if (mediaType == MediaType_enum.Unknown) { return "unknown"; } else { return null; } } /// <summary> /// Parses ContentTransferEncoding_enum from <b>Content-Transfer-Encoding:</b> header field value. /// </summary> /// <param name="headerFieldValue"><b>Content-Transfer-Encoding:</b> header field value. This value can be null, then ContentTransferEncoding_enum.NotSpecified.</param> /// <returns></returns> public static ContentTransferEncoding_enum ParseContentTransferEncoding(string headerFieldValue) { if (headerFieldValue == null) { return ContentTransferEncoding_enum.NotSpecified; } string encoding = headerFieldValue.ToLower(); if (encoding == "7bit") { return ContentTransferEncoding_enum._7bit; } else if (encoding == "quoted-printable") { return ContentTransferEncoding_enum.QuotedPrintable; } else if (encoding == "base64") { return ContentTransferEncoding_enum.Base64; } else if (encoding == "8bit") { return ContentTransferEncoding_enum._8bit; } else if (encoding == "binary") { return ContentTransferEncoding_enum.Binary; } else { return ContentTransferEncoding_enum.Unknown; } } /// <summary> /// Converts ContentTransferEncoding_enum to string. NOTE: Returns null for ContentTransferEncoding_enum.NotSpecified. /// </summary> /// <param name="encoding">ContentTransferEncoding_enum value to convert.</param> /// <returns></returns> public static string ContentTransferEncodingToString(ContentTransferEncoding_enum encoding) { if (encoding == ContentTransferEncoding_enum._7bit) { return "7bit"; } else if (encoding == ContentTransferEncoding_enum.QuotedPrintable) { return "quoted-printable"; } else if (encoding == ContentTransferEncoding_enum.Base64) { return "base64"; } else if (encoding == ContentTransferEncoding_enum._8bit) { return "8bit"; } else if (encoding == ContentTransferEncoding_enum.Binary) { return "binary"; } else if (encoding == ContentTransferEncoding_enum.Unknown) { return "unknown"; } else { return null; } } /// <summary> /// Parses ContentDisposition_enum from <b>Content-Disposition:</b> header field value. /// </summary> /// <param name="headerFieldValue"><b>Content-Disposition:</b> header field value. This value can be null, then ContentDisposition_enum.NotSpecified.</param> /// <returns></returns> public static ContentDisposition_enum ParseContentDisposition(string headerFieldValue) { if (headerFieldValue == null) { return ContentDisposition_enum.NotSpecified; } string disposition = headerFieldValue.ToLower(); if (disposition.IndexOf("attachment") > -1) { return ContentDisposition_enum.Attachment; } else if (disposition.IndexOf("inline") > -1) { return ContentDisposition_enum.Inline; } else { return ContentDisposition_enum.Unknown; } } /// <summary> /// Converts ContentDisposition_enum to string. NOTE: Returns null for ContentDisposition_enum.NotSpecified. /// </summary> /// <param name="disposition">ContentDisposition_enum value to convert.</param> /// <returns></returns> public static string ContentDispositionToString(ContentDisposition_enum disposition) { if (disposition == ContentDisposition_enum.Attachment) { return "attachment"; } else if (disposition == ContentDisposition_enum.Inline) { return "inline"; } else if (disposition == ContentDisposition_enum.Unknown) { return "unknown"; } else { return null; } } /// <summary> /// Encodes specified text as "encoded-word" if encode is required. For more information see RFC 2047. /// </summary> /// <param name="text">Text to encode.</param> /// <returns>Returns encoded word.</returns> public static string EncodeWord(string text) { if (text == null) { return null; } if (Core.IsAscii(text)) { return text; } /* RFC 2047 2. Syntax of encoded-words. An 'encoded-word' is defined by the following ABNF grammar. The notation of RFC 822 is used, with the exception that white space characters MUST NOT appear between components of an 'encoded-word'. encoded-word = "=?" charset "?" encoding "?" encoded-text "?=" charset = token ; see section 3 encoding = token ; see section 4 token = 1*<Any CHAR except SPACE, CTLs, and especials> especials = "(" / ")" / "<" / ">" / "@" / "," / ";" / ":" / " <"> / "/" / "[" / "]" / "?" / "." / "=" encoded-text = 1*<Any printable ASCII character other than "?" or SPACE> ; (but see "Use of encoded-words in message headers", section 5) Both 'encoding' and 'charset' names are case-independent. Thus the charset name "ISO-8859-1" is equivalent to "iso-8859-1", and the encoding named "Q" may be spelled either "Q" or "q". An 'encoded-word' may not be more than 75 characters long, including 'charset', 'encoding', 'encoded-text', and delimiters. If it is desirable to encode more text than will fit in an 'encoded-word' of 75 characters, multiple 'encoded-word's (separated by CRLF SPACE) may be used. IMPORTANT: 'encoded-word's are designed to be recognized as 'atom's by an RFC 822 parser. As a consequence, unencoded white space characters (such as SPACE and HTAB) are FORBIDDEN within an 'encoded-word'. For example, the character sequence =?iso-8859-1?q?this is some text?= would be parsed as four 'atom's, rather than as a single 'atom' (by an RFC 822 parser) or 'encoded-word' (by a parser which understands 'encoded-words'). The correct way to encode the string "this is some text" is to encode the SPACE characters as well, e.g. =?iso-8859-1?q?this=20is=20some=20text?= */ /* char[] especials = new char[]{'(',')','<','>','@',',',';',':','"','/','[',']','?','.','='}; // See if need to enode. if(!Core.IsAscii(text)){ }*/ return Core.CanonicalEncode(text, "utf-8"); } /// <summary> /// Decodes "encoded-word"'s from the specified text. For more information see RFC 2047. /// </summary> /// <param name="text">Text to decode.</param> /// <returns>Returns decoded text.</returns> public static string DecodeWords(string text) { if (text == null) { return null; } /* RFC 2047 2. Syntax of encoded-words. An 'encoded-word' is defined by the following ABNF grammar. The notation of RFC 822 is used, with the exception that white space characters MUST NOT appear between components of an 'encoded-word'. encoded-word = "=?" charset "?" encoding "?" encoded-text "?=" charset = token ; see section 3 encoding = token ; see section 4 token = 1*<Any CHAR except SPACE, CTLs, and especials> especials = "(" / ")" / "<" / ">" / "@" / "," / ";" / ":" / " <"> / "/" / "[" / "]" / "?" / "." / "=" encoded-text = 1*<Any printable ASCII character other than "?" or SPACE> ; (but see "Use of encoded-words in message headers", section 5) Both 'encoding' and 'charset' names are case-independent. Thus the charset name "ISO-8859-1" is equivalent to "iso-8859-1", and the encoding named "Q" may be spelled either "Q" or "q". An 'encoded-word' may not be more than 75 characters long, including 'charset', 'encoding', 'encoded-text', and delimiters. If it is desirable to encode more text than will fit in an 'encoded-word' of 75 characters, multiple 'encoded-word's (separated by CRLF SPACE) may be used. IMPORTANT: 'encoded-word's are designed to be recognized as 'atom's by an RFC 822 parser. As a consequence, unencoded white space characters (such as SPACE and HTAB) are FORBIDDEN within an 'encoded-word'. For example, the character sequence =?iso-8859-1?q?this is some text?= would be parsed as four 'atom's, rather than as a single 'atom' (by an RFC 822 parser) or 'encoded-word' (by a parser which understands 'encoded-words'). The correct way to encode the string "this is some text" is to encode the SPACE characters as well, e.g. =?iso-8859-1?q?this=20is=20some=20text?= */ StringReader r = new StringReader(text); StringBuilder retVal = new StringBuilder(); // We need to loop all words, if encoded word, decode it, othwerwise just append to return value. bool lastIsEncodedWord = false; while (r.Available > 0) { string whiteSpaces = r.ReadToFirstChar(); // Probably is encoded-word, we try to parse it. if (r.StartsWith("=?") && r.SourceString.IndexOf("?=") > -1) { StringBuilder encodedWord = new StringBuilder(); string decodedWord = null; try { // NOTE: We can't read encoded word and then split !!!, we need to read each part. // Remove =? encodedWord.Append(r.ReadSpecifiedLength(2)); // Read charset string charset = r.QuotedReadToDelimiter('?'); encodedWord.Append(charset + "?"); // Read encoding string encoding = r.QuotedReadToDelimiter('?'); encodedWord.Append(encoding + "?"); // Read text string encodedText = r.QuotedReadToDelimiter('?'); encodedWord.Append(encodedText + "?"); // We must have remaining '=' here if (r.StartsWith("=")) { encodedWord.Append(r.ReadSpecifiedLength(1)); Encoding c = EncodingTools.GetEncodingByCodepageName(charset); if (c != null) { if (encoding.ToLower() == "q") { decodedWord = Core.QDecode(c, encodedText); } else if (encoding.ToLower() == "b") { decodedWord = c.GetString(Core.Base64Decode(Encoding.Default.GetBytes(encodedText))); } } } } catch { // Not encoded-word or contains unknwon charset/encoding, so leave // encoded-word as is. } /* RFC 2047 6.2. When displaying a particular header field that contains multiple 'encoded-word's, any 'linear-white-space' that separates a pair of adjacent 'encoded-word's is ignored. (This is to allow the use of multiple 'encoded-word's to represent long strings of unencoded text, without having to separate 'encoded-word's where spaces occur in the unencoded text.) */ if (!lastIsEncodedWord) { retVal.Append(whiteSpaces); } // Decoding failed for that encoded-word, leave encoded-word as is. if (decodedWord == null) { retVal.Append(encodedWord.ToString()); } // We deocded encoded-word successfully. else { retVal.Append(decodedWord); } lastIsEncodedWord = true; } // Normal word. else if (r.StartsWithWord()) { retVal.Append(whiteSpaces + r.ReadWord(false)); lastIsEncodedWord = false; } // We have some separator or parenthesize. else { retVal.Append(whiteSpaces + r.ReadSpecifiedLength(1)); } } return retVal.ToString(); } /// <summary> /// Encodes header field with quoted-printable encoding, if value contains ANSI or UNICODE chars. /// </summary> /// <param name="text">Text to encode.</param> /// <returns></returns> public static string EncodeHeaderField(string text) { if (Core.IsAscii(text)) { return text; } // First try to encode quoted strings("unicode-text") only, if no // quoted strings, encode full text. if (text.IndexOf("\"") > -1) { string retVal = text; int offset = 0; while (offset < retVal.Length - 1) { int quoteStartIndex = retVal.IndexOf("\"", offset); // There is no more qouted strings, but there are some text left if (quoteStartIndex == -1) { break; } int quoteEndIndex = retVal.IndexOf("\"", quoteStartIndex + 1); // If there isn't closing quote, encode full text if (quoteEndIndex == -1) { break; } string leftPart = retVal.Substring(0, quoteStartIndex); string rightPart = retVal.Substring(quoteEndIndex + 1); string quotedString = retVal.Substring(quoteStartIndex + 1, quoteEndIndex - quoteStartIndex - 1); // Encode only not ASCII text if (!Core.IsAscii(quotedString)) { string quotedStringCEncoded = Core.CanonicalEncode(quotedString, "utf-8"); retVal = leftPart + "\"" + quotedStringCEncoded + "\"" + rightPart; offset += quoteEndIndex + 1 + quotedStringCEncoded.Length - quotedString.Length; } else { offset += quoteEndIndex + 1; } } // See if all encoded ok, if not encode all text if (Core.IsAscii(retVal)) { return retVal; } else { // REMOVE ME:(12.10.2006) Fixed, return Core.CanonicalEncode(retVal,"utf-8"); return Core.CanonicalEncode(text, "utf-8"); } } return Core.CanonicalEncode(text, "utf-8"); } /// <summary> /// Creates Rfc 2822 3.6.4 message-id. Syntax: '&lt;' id-left '@' id-right '&gt;'. /// </summary> /// <returns></returns> public static string CreateMessageID() { return "<" + Guid.NewGuid().ToString().Replace("-", "") + "@" + Guid.NewGuid().ToString().Replace("-", "") + ">"; } /// <summary> /// Folds long data line to folded lines. /// </summary> /// <param name="data">Data to fold.</param> /// <returns></returns> public static string FoldData(string data) { /* Folding rules: *) Line may not be bigger than 76 chars. *) If possible fold between TAB or SP *) If no fold point, just fold from char 76 */ // Data line too big, we need to fold data. if (data.Length > 76) { int startPosition = 0; int lastPossibleFoldPos = -1; StringBuilder retVal = new StringBuilder(); for (int i = 0; i < data.Length; i++) { char c = data[i]; // We have possible fold point if (c == ' ' || c == '\t') { lastPossibleFoldPos = i; } // End of data reached if (i == (data.Length - 1)) { retVal.Append(data.Substring(startPosition)); } // We need to fold else if ((i - startPosition) >= 76) { // There wasn't any good fold point(word is bigger than line), just fold from current position. if (lastPossibleFoldPos == -1) { lastPossibleFoldPos = i; } retVal.Append(data.Substring(startPosition, lastPossibleFoldPos - startPosition) + "\r\n\t"); i = lastPossibleFoldPos; lastPossibleFoldPos = -1; startPosition = i; } } return retVal.ToString(); } else { return data; } } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/IMAP/IMAP_MessageFlags.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.IMAP { using System; /// <summary> /// IMAP message flags. /// </summary> [Flags] public enum IMAP_MessageFlags { /// <summary> /// No flags defined. /// </summary> None = 0, /// <summary> /// Message has been read. /// </summary> Seen = 2, /// <summary> /// Message has been answered. /// </summary> Answered = 4, /// <summary> /// Message is "flagged" for urgent/special attention. /// </summary> Flagged = 8, /// <summary> /// Message is "deleted" for removal by later EXPUNGE. /// </summary> Deleted = 16, /// <summary> /// Message has not completed composition. /// </summary> Draft = 32, /// <summary> /// Message is "recently" arrived in this mailbox. /// </summary> Recent = 64, } }<file_sep>/module/ASC.Api/ASC.Api.Mail/MailApi.Filters.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections.Generic; using System.Threading; using ASC.Api.Attributes; using ASC.Mail.Core.Engine.Operations.Base; using ASC.Mail.Data.Contracts; using ASC.Web.Mail.Resources; namespace ASC.Api.Mail { public partial class MailApi { /// <summary> /// Returns list of the tags used in Mail /// </summary> /// <returns>Filters list. Filters represented as JSON.</returns> /// <short>Get filters list</short> /// <category>Filters</category> [Read(@"filters")] public IEnumerable<MailSieveFilterData> GetFilters() { var filters = MailEngineFactory.FilterEngine.GetList(); return filters; } /// <summary> /// Creates a new filter /// </summary> /// <param name="filter"></param> /// <returns>Filter</returns> /// <short>Create filter</short> /// <category>Filters</category> /// <exception cref="ArgumentException">Exception happens when in parameters is invalid. Text description contains parameter name and text description.</exception> [Create(@"filters")] public MailSieveFilterData CreateFilter(MailSieveFilterData filter) { var id = MailEngineFactory.FilterEngine.Create(filter); filter.Id = id; return filter; } /// <summary> /// Updates the selected filter /// </summary> /// <param name="filter"></param> /// <returns>Updated filter</returns> /// <short>Update filter</short> /// <category>Filters</category> /// <exception cref="ArgumentException">Exception happens when in parameters is invalid. Text description contains parameter name and text description.</exception> [Update(@"filters")] public MailSieveFilterData UpdateFilter(MailSieveFilterData filter) { MailEngineFactory.FilterEngine.Update(filter); return filter; } /// <summary> /// Deletes the selected filter /// </summary> /// <param name="id">Filter id</param> /// <returns>Deleted Filter id</returns> /// <short>Delete filter</short> /// <category>Filters</category> /// <exception cref="ArgumentException">Exception happens when in parameters is invalid. Text description contains parameter name and text description.</exception> [Delete(@"filters/{id}")] public int DeleteFilter(int id) { MailEngineFactory.FilterEngine.Delete(id); return id; } /// <summary> /// Check filter result /// </summary> /// <param name="filter"></param> /// <param optional="true" name="page">Page number</param> /// <param optional="true" name="pageSize">Number of messages on page</param> /// <returns>List messages</returns> /// <short>Check filter</short> /// <category>Filters</category> /// <exception cref="ArgumentException">Exception happens when in parameters is invalid. Text description contains parameter name and text description.</exception> [Read(@"filters/check")] public List<MailMessageData> CheckFilter(MailSieveFilterData filter, int? page, int? pageSize) { if (!page.HasValue) page = 0; if (!pageSize.HasValue) pageSize = 10; long total; var messages = MailEngineFactory.MessageEngine.GetFilteredMessages(filter, page.Value, pageSize.Value, out total); _context.SetTotalCount(total); return messages; } /// <summary> /// Apply filter to existing messages /// </summary> /// <param name="id">Filter id</param> /// <returns>MailOperationResult object</returns> /// <short>Check filter</short> /// <category>Filters</category> /// <exception cref="ArgumentException">Exception happens when in parameters is invalid. Text description contains parameter name and text description.</exception> [Read(@"filters/{id}/apply")] public MailOperationStatus ApplyFilter(int id) { Thread.CurrentThread.CurrentCulture = CurrentCulture; Thread.CurrentThread.CurrentUICulture = CurrentCulture; try { return MailEngineFactory.OperationEngine.ApplyFilter(id, TranslateMailOperationStatus); } catch (Exception) { throw new Exception(MailApiErrorsResource.ErrorInternalServer); } } } } <file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/POP3/Server/POP3_Message.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.POP3.Server { /// <summary> /// Holds POP3_Message info (ID,Size,...). /// </summary> public class POP3_Message { #region Members private string m_ID = ""; // Holds message ID. private POP3_MessageCollection m_pOwner; private string m_UID = ""; #endregion #region Properties /// <summary> /// Gets or sets message ID. /// </summary> public string ID { get { return m_ID; } set { m_ID = value; } } /// <summary> /// Gets or sets message UID. This UID is reported in UIDL command. /// </summary> public string UID { get { return m_UID; } set { m_UID = value; } } /// <summary> /// Gets or sets message size in bytes. /// </summary> public long Size { get; set; } /// <summary> /// Gets or sets message state flag. /// </summary> public bool MarkedForDelete { get; set; } /// <summary> /// Gets or sets user data for message. /// </summary> public object Tag { get; set; } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="onwer">Owner collection.</param> /// <param name="id">Message ID.</param> /// <param name="uid">Message UID.</param> /// <param name="size">Message size in bytes.</param> internal POP3_Message(POP3_MessageCollection onwer, string id, string uid, long size) { m_pOwner = onwer; m_ID = id; m_UID = uid; Size = size; } #endregion } }<file_sep>/common/ASC.Common/Logging/SelfCleaningTarget.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System.Collections.Generic; using NLog; using NLog.Common; using NLog.Targets; using System; using System.IO; using System.Linq; namespace ASC.Common.Logging { [Target("SelfCleaning")] public class SelfCleaningTarget : FileTarget { private static DateTime _lastCleanDate; private static int? _cleanPeriod; private static int GetCleanPeriod() { if (_cleanPeriod != null) return _cleanPeriod.Value; var value = 30; const string key = "cleanPeriod"; if (NLog.LogManager.Configuration.Variables.Keys.Contains(key)) { var variable = NLog.LogManager.Configuration.Variables[key]; if (variable != null && !string.IsNullOrEmpty(variable.Text)) { int.TryParse(variable.Text, out value); } } _cleanPeriod = value; return value; } private void Clean() { var filePath = string.Empty; var dirPath = string.Empty; try { if (FileName == null) return; filePath = ((NLog.Layouts.SimpleLayout)FileName).Text; if (string.IsNullOrEmpty(filePath)) return; dirPath = Path.GetDirectoryName(filePath); if (string.IsNullOrEmpty(dirPath)) return; if (!Path.IsPathRooted(dirPath)) dirPath = Path.Combine(Environment.CurrentDirectory, dirPath); var directory = new DirectoryInfo(dirPath); if (!directory.Exists) return; var files = directory.GetFiles(); var cleanPeriod = GetCleanPeriod(); foreach (var file in files.Where(file => (DateTime.UtcNow.Date - file.CreationTimeUtc.Date).Days > cleanPeriod)) { file.Delete(); } } catch (Exception err) { base.Write(new LogEventInfo { Exception = err, Level = LogLevel.Error, Message = String.Format("file: {0}, dir: {1}, mess: {2}", filePath, dirPath, err.Message), LoggerName = "SelfCleaningTarget" }); } } protected override void Write(IList<AsyncLogEventInfo> logEvents) { if (DateTime.UtcNow.Date > _lastCleanDate.Date) { _lastCleanDate = DateTime.UtcNow.Date; Clean(); } var buffer = new List<AsyncLogEventInfo>(); foreach (var logEvent in logEvents) { buffer.Add(logEvent); if (buffer.Count < 10) continue; base.Write(buffer); buffer.Clear(); } base.Write(buffer); } protected override void Write(LogEventInfo logEvent) { if (DateTime.UtcNow.Date > _lastCleanDate.Date) { _lastCleanDate = DateTime.UtcNow.Date; Clean(); } base.Write(logEvent); } } } <file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/EventArgs.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net { #region usings using System; #endregion /// <summary> /// This class universal event arguments for transporting single value. /// </summary> /// <typeparam name="T">Event data.</typeparam> public class EventArgs<T> : EventArgs { #region Members private readonly T m_pValue; #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="value">Event data.</param> public EventArgs(T value) { m_pValue = value; } #endregion #region Properties /// <summary> /// Gets event data. /// </summary> public T Value { get { return m_pValue; } } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/RTP/RTP_ParticipantEventArgs.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.RTP { #region usings using System; #endregion /// <summary> /// This claass provides data for <b>RTP_MultimediaSession.NewParticipant</b> event. /// </summary> public class RTP_ParticipantEventArgs : EventArgs { #region Members private readonly RTP_Participant_Remote m_pParticipant; #endregion #region Properties /// <summary> /// Gets participant. /// </summary> public RTP_Participant_Remote Participant { get { return m_pParticipant; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="participant">RTP participant.</param> /// <exception cref="ArgumentNullException">Is raised when <b>participant</b> is null reference.</exception> public RTP_ParticipantEventArgs(RTP_Participant_Remote participant) { if (participant == null) { throw new ArgumentNullException("participant"); } m_pParticipant = participant; } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/_Obsolete/ReadLine_EventArgs.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.IO { #region usings using System; using System.Text; #endregion /// <summary> /// This class proviedes data to asynchronous read line callback method. /// NOTE: ReadLine_EventArgs is reused for next read line call, so don't store references to this class. /// </summary> public class ReadLine_EventArgs { #region Members private int m_Count; private Exception m_pException; private byte[] m_pLineBuffer; private object m_pTag; private int m_ReadedCount; #endregion #region Properties /// <summary> /// Gets exception what happened while reading line. Returns null if read line completed sucessfully. /// </summary> public Exception Exception { get { return m_pException; } } /// <summary> /// Gets number of bytes actualy readed from source stream. Returns 0 if end of stream reached /// and no more data. This value includes any readed byte, including line feed, ... . /// </summary> public int ReadedCount { get { return m_ReadedCount; } } /// <summary> /// Gets <b>buffer</b> argumnet what was passed to BeginReadLine mehtod. /// </summary> public byte[] LineBuffer { get { return m_pLineBuffer; } } /// <summary> /// Gets number of bytes stored to <b>LineBuffer</b>. /// </summary> public int Count { get { return m_Count; } } /// <summary> /// Gets readed line data or null if end of stream reached and no more data. /// </summary> public byte[] Data { get { byte[] retVal = new byte[m_Count]; Array.Copy(m_pLineBuffer, retVal, m_Count); return retVal; } } /// <summary> /// Gets readed line data as string with system <b>default</b> encoding or returns null if end of stream reached and no more data. /// </summary> public string DataStringDefault { get { return DataToString(Encoding.Default); } } /// <summary> /// Gets readed line data as string with <b>ASCII</b> encoding or returns null if end of stream reached and no more data. /// </summary> public string DataStringAscii { get { return DataToString(Encoding.ASCII); } } /// <summary> /// Gets readed line data as string with <b>UTF8</b> encoding or returns null if end of stream reached and no more data. /// </summary> public string DataStringUtf8 { get { return DataToString(Encoding.UTF8); } } /// <summary> /// Gets <b>tag</b> argument what was pased to BeginReadLine method. /// </summary> public object Tag { get { return m_pTag; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> internal ReadLine_EventArgs() {} /// <summary> /// Default constructor. /// </summary> /// <param name="exception">Exception what happened while reading data or null if read line was successfull.</param> /// <param name="readedCount">Specifies how many raw bytes was readed.</param> /// <param name="data">Line data buffer.</param> /// <param name="count">Specifies how many bytes stored to <b>data</b>.</param> /// <param name="tag">User data.</param> internal ReadLine_EventArgs(Exception exception, int readedCount, byte[] data, int count, object tag) { m_pException = exception; m_ReadedCount = readedCount; m_pLineBuffer = data; m_Count = count; m_pTag = tag; } #endregion #region Methods /// <summary> /// Converts byte[] line data to the specified encoding string. /// </summary> /// <param name="encoding">Encoding to use for convert.</param> /// <returns>Returns line data as string.</returns> public string DataToString(Encoding encoding) { if (encoding == null) { throw new ArgumentNullException("encoding"); } if (m_pLineBuffer == null) { return null; } else { return encoding.GetString(m_pLineBuffer, 0, m_Count); } } #endregion #region Internal methods internal void Reuse(Exception exception, int readedCount, byte[] data, int count, object tag) { m_pException = exception; m_ReadedCount = readedCount; m_pLineBuffer = data; m_Count = count; m_pTag = tag; } #endregion } }<file_sep>/web/studio/ASC.Web.Studio/HttpHandlers/TenantLogoHandler.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #region Usings using ASC.Web.Core.WhiteLabel; using ASC.Web.Studio.Utility; using System; using System.Web; #endregion namespace ASC.Web.Studio.HttpHandlers { public class TenantLogoHandler : IHttpHandler { public bool IsReusable { get { return true; } } public void ProcessRequest(HttpContext context) { var type = context.Request["logotype"]; if (string.IsNullOrEmpty(type)) return; var whiteLabelType = (WhiteLabelLogoTypeEnum)Convert.ToInt32(type); var general = Convert.ToBoolean(context.Request["general"] ?? "true"); var isDefIfNoWhiteLabel = Convert.ToBoolean(context.Request["defifnoco"] ?? "false"); var imgUrl = TenantLogoHelper.GetLogo(whiteLabelType, general, isDefIfNoWhiteLabel); context.Response.ContentType = "image"; context.Response.Redirect(imgUrl); } } } <file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/IO/LineReader.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.IO { #region usings using System; using System.IO; using System.Text; #endregion /// <summary> /// This class implements "line" reader, LF and CRLF lines are supported. /// </summary> public class LineReader : IDisposable { #region Members private readonly int m_BufferSize = Workaround.Definitions.MaxStreamLineLength; private readonly bool m_Owner; private readonly byte[] m_pLineBuffer; private readonly byte[] m_pReadBuffer; private readonly Stream m_pSource; private bool m_IsDisposed; private int m_OffsetInBuffer; private Encoding m_pCharset; private int m_StoredInBuffer; #endregion #region Properties /// <summary> /// Gets if this object is disposed. /// </summary> public bool IsDisposed { get { return m_IsDisposed; } } /// <summary> /// Gets source stream. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> public Stream Stream { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_pSource; } } /// <summary> /// Gets if line reader is <b>Stream</b> owner. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> public bool IsStreamOwner { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_Owner; } } /// <summary> /// Gets or sets charset to us for deocoding bytes. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> /// <exception cref="ArgumentNullException">Is raised when null reference is passed.</exception> public Encoding Charset { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_pCharset; } set { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (value == null) { throw new ArgumentNullException("value"); } m_pCharset = value; } } /// <summary> /// Gets number of bytes in read buffer. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> public int AvailableInBuffer { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_StoredInBuffer - m_OffsetInBuffer; } } /// <summary> /// Gets if line reader can synchronize source stream to actual readed data position. /// </summary> public bool CanSyncStream { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_pSource.CanSeek; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="stream">Stream from where to read lines.</param> /// <param name="owner">Specifies if <b>LineReader</b> is owner of <b>stream</b>. /// <param name="bufferSize">Read buffer size, value 1 means no buffering.</param> /// If this value is true, closing reader will close <b>stream</b>.</param> /// <exception cref="ArgumentNullException">Is raised when <b>stream</b> is null.</exception> public LineReader(Stream stream, bool owner, int bufferSize) { if (stream == null) { throw new ArgumentNullException("stream"); } if (bufferSize < 1) { throw new ArgumentException("Argument 'bufferSize' value must be >= 1."); } m_pSource = stream; m_Owner = owner; m_BufferSize = bufferSize; m_pReadBuffer = new byte[bufferSize]; m_pLineBuffer = new byte[Workaround.Definitions.MaxStreamLineLength]; m_pCharset = Encoding.UTF8; } #endregion #region Methods /// <summary> /// Cleans up any resources being used. /// </summary> public void Dispose() { if (m_IsDisposed) { return; } m_IsDisposed = true; if (m_Owner) { m_pSource.Dispose(); } } /// <summary> /// Reads line from source stream. Returns null if end of stream(EOS) reached. /// </summary> /// <returns>Returns readed line or null if end of stream reached.</returns> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> public string ReadLine() { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } int storedCount = ReadLine(m_pLineBuffer, 0, m_pLineBuffer.Length, SizeExceededAction.ThrowException); if (storedCount == -1) { return null; } else { return m_pCharset.GetString(m_pLineBuffer, 0, storedCount); } } /// <summary> /// Reads binary line and stores it to the specified buffer. /// </summary> /// <param name="buffer">Buffer where to store line data.</param> /// <param name="offset">Start offset in the buffer.</param> /// <param name="count">Maximum number of bytes store to the buffer.</param> /// <param name="exceededAction">Specifies how reader acts when line buffer too small.</param> /// <returns>Returns number of bytes stored to <b>buffer</b> or -1 if end of stream reached.</returns> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="ArgumentNullException">Is raised when <b>buffer</b> is null.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> /// <exception cref="LineSizeExceededException">Is raised when line is bigger than <b>buffer</b> can store.</exception> public int ReadLine(byte[] buffer, int offset, int count, SizeExceededAction exceededAction) { int rawBytesReaded = 0; return ReadLine(buffer, offset, count, exceededAction, out rawBytesReaded); } /// <summary> /// Reads binary line and stores it to the specified buffer. /// </summary> /// <param name="buffer">Buffer where to store line data.</param> /// <param name="offset">Start offset in the buffer.</param> /// <param name="count">Maximum number of bytes store to the buffer.</param> /// <param name="exceededAction">Specifies how reader acts when line buffer too small.</param> /// <param name="rawBytesReaded">Gets raw number of bytes readed from source.</param> /// <returns>Returns number of bytes stored to <b>buffer</b> or -1 if end of stream reached.</returns> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="ArgumentNullException">Is raised when <b>buffer</b> is null.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> /// <exception cref="LineSizeExceededException">Is raised when line is bigger than <b>buffer</b> can store.</exception> public virtual int ReadLine(byte[] buffer, int offset, int count, SizeExceededAction exceededAction, out int rawBytesReaded) { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (buffer == null) { throw new ArgumentNullException("buffer"); } if (offset < 0) { throw new ArgumentException("Argument 'offset' value must be >= 0."); } if (count < 0) { throw new ArgumentException("Argument 'count' value must be >= 0."); } if (buffer.Length < (count + offset)) { throw new ArgumentException( "Argument 'count' value is bigger than specified 'buffer' can store."); } int maxStoreCount = buffer.Length - offset; int storedCount = 0; rawBytesReaded = 0; bool sizeExceeded = false; while (true) { // No data in buffer, buffer next block. if (m_StoredInBuffer == m_OffsetInBuffer) { m_OffsetInBuffer = 0; m_StoredInBuffer = m_pSource.Read(m_pReadBuffer, 0, m_BufferSize); // We reached end of stream, no more data. if (m_StoredInBuffer == 0) { break; } } byte currentByte = m_pReadBuffer[m_OffsetInBuffer++]; rawBytesReaded++; // We have LF, we got a line. if (currentByte == '\n') { break; } // We just skip CR, because CR must be with LF, otherwise it's invalid CR. else if (currentByte == '\r') {} // Normal byte. else { // Line buffer full. if (storedCount == maxStoreCount) { sizeExceeded = true; if (exceededAction == SizeExceededAction.ThrowException) { throw new LineSizeExceededException(); } } else { buffer[offset + storedCount] = currentByte; storedCount++; } } } // Line buffer is not big enough to store whole line data. if (sizeExceeded) { throw new LineSizeExceededException(); } // We haven't readed nothing, we are end of stream. else if (rawBytesReaded == 0) { return -1; } else { return storedCount; } } /// <summary> /// Sets stream position to the place we have consumed from stream and clears buffer data. /// For example if we have 10 byets in buffer, stream position is actually +10 bigger than /// we readed, the result is that stream.Position -= 10 and buffer is cleared. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when source stream won't support seeking.</exception> public virtual void SyncStream() { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (!m_pSource.CanSeek) { throw new InvalidOperationException("Source stream does not support seeking, can't sync."); } if (AvailableInBuffer > 0) { m_pSource.Position -= AvailableInBuffer; m_OffsetInBuffer = 0; m_StoredInBuffer = 0; } } #endregion } }<file_sep>/redistributable/ShrapBox/Src/AppLimit.CloudComputing.SharpBox/UI/Controler/ListViewColumnSorter.cs using System.Collections; using System.Windows.Forms; namespace AppLimit.CloudComputing.SharpBox.UI { /// <summary> /// Class to sort a listview control by column /// </summary> public class ListViewColumnSorter : IComparer { private int ColumnToSort; private SortOrder OrderOfSort; private CaseInsensitiveComparer ObjectCompare; /// <summary> /// Constructor /// </summary> public ListViewColumnSorter() { ColumnToSort = 0; OrderOfSort = SortOrder.Ascending; ObjectCompare = new CaseInsensitiveComparer(); } /// <summary> /// Compare two objects /// </summary> /// <param name="x">Object 1</param> /// <param name="y">Object 2</param> /// <returns> /// 0 if equals /// 1 if object X is before object Y /// -1 if object X is after object Y /// </returns> public int Compare(object x, object y) { int compareResult = 0; ListViewItem listviewX, listviewY; ListViewItem.ListViewSubItem subItemX, subItemY; listviewX = (ListViewItem)x; listviewY = (ListViewItem)y; subItemX = listviewX.SubItems[ColumnToSort]; subItemY = listviewY.SubItems[ColumnToSort]; // If tag is null, compare by text based. Else compare tag if (subItemX.Tag == null) { compareResult = ObjectCompare.Compare(subItemX.Text, subItemY.Text); } else { compareResult = ObjectCompare.Compare(subItemX.Tag, subItemY.Tag); } if (OrderOfSort == SortOrder.Ascending) { return compareResult; } else if (OrderOfSort == SortOrder.Descending) { return (-compareResult); } else { return 0; } } /// <summary> /// Last sorted column /// </summary> public int SortColumn { set { ColumnToSort = value; } get { return ColumnToSort; } } /// <summary> /// Last sort order /// </summary> public SortOrder Order { set { OrderOfSort = value; } get { return OrderOfSort; } } } } <file_sep>/redistributable/Twitterizer2/Twitterizer2/Core/ConversionUtility.cs //----------------------------------------------------------------------- // <copyright file="ConversionUtility.cs" company="Patrick 'Ricky' Smith"> // This file is part of the Twitterizer library (http://www.twitterizer.net/) // // Copyright (c) 2010, Patrick "Ricky" Smith (<EMAIL>) // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, are // permitted provided that the following conditions are met: // // - Redistributions of source code must retain the above copyright notice, this list // of conditions and the following disclaimer. // - Redistributions in binary form must reproduce the above copyright notice, this list // of conditions and the following disclaimer in the documentation and/or other // materials provided with the distribution. // - Neither the name of the Twitterizer nor the names of its contributors may be // used to endorse or promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. // IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, // INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT // NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // </copyright> // <author><NAME></author> // <summary>The color translation helper class.</summary> //----------------------------------------------------------------------- namespace Twitterizer { #if !SILVERLIGHT using System.Drawing; #endif using System.IO; using System.Text.RegularExpressions; /// <summary> /// Provides common color converstion methods /// </summary> /// <tocexclude /> internal static class ConversionUtility { #if !SILVERLIGHT /// <summary> /// Converts the color string to a <see cref="System.Drawing.Color"/> /// </summary> /// <param name="value">The value.</param> /// <returns>A <see cref="System.Drawing.Color"/> representation of the color, or null.</returns> internal static Color FromTwitterString(string value) { if (string.IsNullOrEmpty(value)) { return new Color(); } if (Regex.IsMatch(value, @"^#?[a-f0-9]{6}$", RegexOptions.IgnoreCase)) { return ColorTranslator.FromHtml(Regex.Replace(value, "^#?([a-f0-9]{6})$", "#$1", RegexOptions.IgnoreCase)); } return Color.FromName(value); } #endif /// <summary> /// Reads the stream into a byte array. /// </summary> /// <param name="responseStream">The response stream.</param> /// <returns>A byte array.</returns> internal static byte[] ReadStream(Stream responseStream) { byte[] data = new byte[32768]; byte[] buffer = new byte[32768]; using (MemoryStream ms = new MemoryStream()) { bool exit = false; while (!exit) { int read = responseStream.Read(buffer, 0, buffer.Length); if (read <= 0) { data = ms.ToArray(); exit = true; } else { ms.Write(buffer, 0, read); } } } return data; } } } <file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/DNS/Client/QTYPE.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.Dns.Client { /// <summary> /// Query type. /// </summary> public enum QTYPE { /// <summary> /// IPv4 host address /// </summary> A = 1, /// <summary> /// An authoritative name server. /// </summary> NS = 2, // MD = 3, Obsolete // MF = 4, Obsolete /// <summary> /// The canonical name for an alias. /// </summary> CNAME = 5, /// <summary> /// Marks the start of a zone of authority. /// </summary> SOA = 6, // MB = 7, EXPERIMENTAL // MG = 8, EXPERIMENTAL // MR = 9, EXPERIMENTAL // NULL = 10, EXPERIMENTAL /* /// <summary> /// A well known service description. /// </summary> WKS = 11, */ /// <summary> /// A domain name pointer. /// </summary> PTR = 12, /// <summary> /// Host information. /// </summary> HINFO = 13, /* /// <summary> /// Mailbox or mail list information. /// </summary> MINFO = 14, */ /// <summary> /// Mail exchange. /// </summary> MX = 15, /// <summary> /// Text strings. /// </summary> TXT = 16, /// <summary> /// IPv6 host address. /// </summary> AAAA = 28, /// <summary> /// SRV record specifies the location of services. /// </summary> SRV = 33, /// <summary> /// NAPTR(Naming Authority Pointer) record. /// </summary> NAPTR = 35, /// <summary> /// All records what server returns. /// </summary> ANY = 255, /* /// <summary> /// UnKnown /// </summary> UnKnown = 9999, */ } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/MIME/MIME_TransferEncodings.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.MIME { /// <summary> /// This class holds MIME content transfer encodings. Defined in RFC 2045 6. /// </summary> public class MIME_TransferEncodings { #region Members /// <summary> /// Used to encode arbitrary octet sequences into a form that satisfies the rules of 7bit. Has a fixed overhead and is /// intended for non text data and text that is not ASCII heavy. /// Defined in RFC 2045 6.8. /// </summary> public static readonly string Base64 = "base64"; /// <summary> /// Any sequence of octets. This type is not widely used. Defined in RFC 3030. /// </summary> public static readonly string Binary = "binary"; /// <summary> /// Up to 998 octets per line with CR and LF (codes 13 and 10 respectively) only allowed to appear as part of a CRLF line ending. /// Defined in RFC 2045 6.2. /// </summary> public static readonly string EightBit = "8bit"; /// <summary> /// Used to encode arbitrary octet sequences into a form that satisfies the rules of 7bit. /// Designed to be efficient and mostly human readable when used for text data consisting primarily of US-ASCII characters /// but also containing a small proportion of bytes with values outside that range. /// Defined in RFC 2045 6.7. /// </summary> public static readonly string QuotedPrintable = "quoted-printable"; /// <summary> /// Up to 998 octets per line of the code range 1..127 with CR and LF (codes 13 and 10 respectively) only allowed to /// appear as part of a CRLF line ending. This is the default value. /// Defined in RFC 2045 6.2. /// </summary> public static readonly string SevenBit = "7bit"; #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/_Obsolete/MIME/GroupAddress.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.Mime { #region usings using System; #endregion /// <summary> /// RFC 2822 3.4. (Address Specification) Group address. /// <p/> /// Syntax: display-name':'[mailbox *(',' mailbox)]';' /// </summary> [Obsolete("See LumiSoft.Net.MIME or LumiSoft.Net.Mail namepaces for replacement.")] public class GroupAddress : Address { #region Members private readonly MailboxAddressCollection m_pGroupMembers; private string m_DisplayName = ""; #endregion #region Properties /// <summary> /// Gets Group as RFC 2822(3.4. Address Specification) string. Syntax: display-name':'[mailbox *(',' mailbox)]';' /// </summary> public string GroupString { get { return TextUtils.QuoteString(DisplayName) + ":" + GroupMembers.ToMailboxListString() + ";"; } } /// <summary> /// Gets or sets display name. /// </summary> public string DisplayName { get { return m_DisplayName; } set { m_DisplayName = value; OnChanged(); } } /// <summary> /// Gets group members collection. /// </summary> public MailboxAddressCollection GroupMembers { get { return m_pGroupMembers; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> public GroupAddress() : base(true) { m_pGroupMembers = new MailboxAddressCollection(); m_pGroupMembers.Owner = this; } #endregion #region Methods /// <summary> /// Parses Rfc 2822 3.4 group address from group address string. Syntax: display-name':'[mailbox *(',' mailbox)]';' /// </summary> /// <param name="group">Group address string.</param> /// <returns></returns> public static GroupAddress Parse(string group) { GroupAddress g = new GroupAddress(); // Syntax: display-name':'[mailbox *(',' mailbox)]';' string[] parts = TextUtils.SplitQuotedString(group, ':'); if (parts.Length > -1) { g.DisplayName = TextUtils.UnQuoteString(parts[0]); } if (parts.Length > 1) { g.GroupMembers.Parse(parts[1]); } return g; } #endregion #region Internal methods /// <summary> /// This called when group address has changed. /// </summary> internal void OnChanged() { if (Owner != null) { if (Owner is AddressList) { ((AddressList) Owner).OnCollectionChanged(); } } } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/SIP/Message/SIP_t_ACValue.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.SIP.Message { #region usings using System; using System.Text; #endregion /// <summary> /// Implements SIP "ac-value" value. Defined in RFC 3841. /// </summary> /// <remarks> /// <code> /// RFC 3841 Syntax: /// ac-value = "*" *(SEMI ac-params) /// ac-params = feature-param / req-param / explicit-param / generic-param /// ;;feature param from RFC 3840 /// ;;generic-param from RFC 3261 /// req-param = "require" /// explicit-param = "explicit" /// </code> /// </remarks> public class SIP_t_ACValue : SIP_t_ValueWithParams { #region Properties /// <summary> /// Gets or sets 'require' parameter value. /// </summary> public bool Require { get { SIP_Parameter parameter = Parameters["require"]; if (parameter != null) { return true; } else { return false; } } set { if (!value) { Parameters.Remove("require"); } else { Parameters.Set("require", null); } } } /// <summary> /// Gets or sets 'explicit' parameter value. /// </summary> public bool Explicit { get { SIP_Parameter parameter = Parameters["explicit"]; if (parameter != null) { return true; } else { return false; } } set { if (!value) { Parameters.Remove("explicit"); } else { Parameters.Set("explicit", null); } } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> public SIP_t_ACValue() {} /// <summary> /// Default constructor. /// </summary> /// <param name="value">SIP 'ac-value' value.</param> public SIP_t_ACValue(string value) { Parse(value); } #endregion #region Methods /// <summary> /// Parses "ac-value" from specified value. /// </summary> /// <param name="value">SIP "ac-value" value.</param> /// <exception cref="ArgumentNullException">Raised when <b>value</b> is null.</exception> /// <exception cref="SIP_ParseException">Raised when invalid SIP message.</exception> public void Parse(string value) { if (value == null) { throw new ArgumentNullException("value"); } Parse(new StringReader(value)); } /// <summary> /// Parses "ac-value" from specified reader. /// </summary> /// <param name="reader">Reader from where to parse.</param> /// <exception cref="ArgumentNullException">Raised when <b>reader</b> is null.</exception> /// <exception cref="SIP_ParseException">Raised when invalid SIP message.</exception> public override void Parse(StringReader reader) { /* ac-value = "*" *(SEMI ac-params) ac-params = feature-param / req-param / explicit-param / generic-param ;;feature param from RFC 3840 ;;generic-param from RFC 3261 req-param = "require" explicit-param = "explicit" */ if (reader == null) { throw new ArgumentNullException("reader"); } string word = reader.ReadWord(); if (word == null) { throw new SIP_ParseException("Invalid 'ac-value', '*' is missing !"); } // Parse parameters ParseParameters(reader); } /// <summary> /// Converts this to valid "ac-value" value. /// </summary> /// <returns>Returns "ac-value" value.</returns> public override string ToStringValue() { /* ac-value = "*" *(SEMI ac-params) ac-params = feature-param / req-param / explicit-param / generic-param ;;feature param from RFC 3840 ;;generic-param from RFC 3261 req-param = "require" explicit-param = "explicit" */ StringBuilder retVal = new StringBuilder(); // * retVal.Append("*"); // Add parameters retVal.Append(ParametersToString()); return retVal.ToString(); } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/SMTP/SMTP_t_Mailbox.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.SMTP { #region usings using System; using MIME; #endregion /// <summary> /// This class represents SMTP "Mailbox" address. Defined in RFC 5321 4.1.2. /// </summary> /// <example> /// <code> /// RFC 5321 4.1.2. /// Mailbox = Local-part "@" ( Domain / address-literal ) /// Local-part = Dot-string / Quoted-string /// ; MAY be case-sensitive /// </code> /// </example> public class SMTP_t_Mailbox { #region Members private readonly string m_Domain; private readonly string m_LocalPart; #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="localPart">Local part of mailbox.</param> /// <param name="domain">Domain of mailbox.</param> /// <exception cref="ArgumentNullException">Is raised when <b>localPart</b> or <b>domain</b> is null reference.</exception> public SMTP_t_Mailbox(string localPart, string domain) { if (localPart == null) { throw new ArgumentNullException("localPart"); } if (domain == null) { throw new ArgumentNullException("domain"); } m_LocalPart = localPart; m_Domain = domain; } #endregion #region Properties /// <summary> /// Gets domain of mailbox. /// </summary> /// <remarks>If domain is <b>address-literal</b>, surrounding bracets will be removed.</remarks> public string Domain { get { return m_Domain; } } /// <summary> /// Gets local-part of mailbox. /// </summary> /// <remarks>If local-part is <b>Quoted-string</b>, quotes will not returned.</remarks> public string LocalPart { get { return m_LocalPart; } } #endregion /* /// <summary> /// Parses SMTP mailbox from the specified string. /// </summary> /// <param name="value">Mailbox string.</param> /// <returns>Returns parsed SMTP mailbox.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>value</b> is null reference.</exception> public static SMTP_t_Mailbox Parse(string value) { if(value == null){ throw new ArgumentNullException("value"); } return Parse(new ABNF_Reader(value)); } /// <summary> /// Parses SMTP mailbox from the specified reader. /// </summary> /// <param name="reader">Source reader.</param> /// <returns>Returns parsed SMTP mailbox.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>reader</b> is null reference.</exception> public static SMTP_t_Mailbox Parse(ABNF_Reader reader) { if(reader == null){ throw new ArgumentNullException("reader"); } // TODO: return null; } */ #region Methods /// <summary> /// Returns mailbox as string. /// </summary> /// <returns>Returns mailbox as string.</returns> public override string ToString() { if (MIME_Reader.IsDotAtom(m_LocalPart)) { return m_LocalPart + "@" + (Net_Utils.IsIPAddress(m_Domain) ? "[" + m_Domain + "]" : m_Domain); } else { return TextUtils.QuoteString(m_LocalPart) + "@" + (Net_Utils.IsIPAddress(m_Domain) ? "[" + m_Domain + "]" : m_Domain); } } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Autoreply/Configuration.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Configuration; namespace ASC.Mail.Autoreply { public class AutoreplyServiceConfiguration : ConfigurationSection { [ConfigurationProperty("debug")] public bool IsDebug { get { return (bool)this["debug"]; } set { this["debug"] = value; } } [ConfigurationProperty("mailFolder", DefaultValue = "..\\MailDebug")] public string MailFolder { get { return (string)this["mailFolder"]; } set { this["mailFolder"] = value; } } [ConfigurationProperty("https", DefaultValue = false)] public bool Https { get { return (bool)this["https"]; } set { this["https"] = value; } } [ConfigurationProperty("smtp")] public SmtpConfigurationElement SmtpConfiguration { get { return (SmtpConfigurationElement)this["smtp"]; } set { this["smtp"] = value; } } [ConfigurationProperty("cooldown")] public CooldownConfigurationElement CooldownConfiguration { get { return (CooldownConfigurationElement)this["cooldown"]; } set { this["cooldown"] = value; } } public static AutoreplyServiceConfiguration GetSection() { return (AutoreplyServiceConfiguration)ConfigurationManager.GetSection("autoreply"); } } public class SmtpConfigurationElement : ConfigurationElement { [ConfigurationProperty("maxTransactions", DefaultValue = 0)] public int MaxTransactions { get { return (int)this["maxTransactions"]; } set { this["maxTransactions"] = value; } } [ConfigurationProperty("maxBadCommands", DefaultValue = 0)] public int MaxBadCommands { get { return (int)this["maxBadCommands"]; } set { this["maxBadCommands"] = value; } } [ConfigurationProperty("maxMessageSize", DefaultValue = 15 * 1024 * 1024)] public int MaxMessageSize { get { return (int)this["maxMessageSize"]; } set { this["maxMessageSize"] = value; } } [ConfigurationProperty("maxRecipients", DefaultValue = 1)] public int MaxRecipients { get { return (int)this["maxRecipients"]; } set { this["maxRecipients"] = value; } } [ConfigurationProperty("maxConnectionsPerIP", DefaultValue = 0)] public int MaxConnectionsPerIP { get { return (int)this["maxConnectionsPerIP"]; } set { this["maxConnectionsPerIP"] = value; } } [ConfigurationProperty("maxConnections", DefaultValue = 0)] public int MaxConnections { get { return (int)this["maxConnections"]; } set { this["maxConnections"] = value; } } [ConfigurationProperty("port", DefaultValue = 25)] public int Port { get { return (int)this["port"]; } set { this["port"] = value; } } } public class CooldownConfigurationElement : ConfigurationElement { [ConfigurationProperty("length", DefaultValue = "0:10:0")] public TimeSpan Length { get { return (TimeSpan)this["length"]; } set { this["length"] = value; } } [ConfigurationProperty("allowedRequests", DefaultValue = 5)] public int AllowedRequests { get { return (int)this["allowedRequests"]; } set { this["allowedRequests"] = value; } } [ConfigurationProperty("duringInterval", DefaultValue = "0:5:0")] public TimeSpan DuringTimeInterval { get { return (TimeSpan)this["duringInterval"]; } set { this["duringInterval"] = value; } } } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/SMTP/Server/SMTP_Session.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.SMTP.Server { #region usings using System; using System.Collections.Generic; using System.IO; using System.Net.Sockets; using System.Security.Principal; using System.Text; using AUTH; using IO; using Mail; using TCP; #endregion /// <summary> /// This class implements SMTP session. Defined RFC 5321. /// </summary> public class SMTP_Session : TCP_ServerSession { #region Events /// <summary> /// Is raised when EHLO command received. /// </summary> public event EventHandler<SMTP_e_Ehlo> Ehlo = null; /// <summary> /// Is raised when SMTP server needs to get stream where to store incoming message. /// </summary> public event EventHandler<SMTP_e_Message> GetMessageStream = null; /// <summary> /// Is raised when MAIL FROM: command received. /// </summary> public event EventHandler<SMTP_e_MailFrom> MailFrom = null; /// <summary> /// Is raised when SMTP server has canceled message storing. /// </summary> /// <remarks>This can happen on 2 cases: on session timeout and if between BDAT chunks RSET issued.</remarks> public event EventHandler<SMTP_e_MessageStored> MessageStoringCanceled = null; /// <summary> /// Is raised when SMTP server has completed message storing. /// </summary> public event EventHandler<SMTP_e_MessageStored> MessageStoringCompleted = null; /// <summary> /// Is raised when RCPT TO: command received. /// </summary> public event EventHandler<SMTP_e_RcptTo> RcptTo = null; /// <summary> /// Is raised when session has started processing and needs to send 220 greeting or 554 error resposne to the connected client. /// </summary> public event EventHandler<SMTP_e_Started> Started = null; #endregion #region Members private int m_BadCommands; private int m_BDatReadedCount; private string m_EhloHost; private Dictionary<string, AUTH_SASL_ServerMechanism> m_pAuthentications; private SMTP_MailFrom m_pFrom; private Stream m_pMessageStream; private Dictionary<string, SMTP_RcptTo> m_pTo; private GenericIdentity m_pUser; private bool m_SessionRejected; private int m_Transactions; #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> public SMTP_Session() { m_pAuthentications = new Dictionary<string, AUTH_SASL_ServerMechanism>(StringComparer.CurrentCultureIgnoreCase); m_pTo = new Dictionary<string, SMTP_RcptTo>(); } #endregion #region Properties /// <summary> /// Gets authenticated user identity or null if user has not authenticated. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> public override GenericIdentity AuthenticatedUserIdentity { get { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_pUser; } } /// <summary> /// Gets supported authentications collection. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> public Dictionary<string, AUTH_SASL_ServerMechanism> Authentications { get { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_pAuthentications; } } /// <summary> /// Gets number of bad commands happened on SMTP session. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> public int BadCommands { get { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_BadCommands; } } /// <summary> /// Gets client reported EHLO host name. Returns null if EHLO/HELO is not issued yet. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> public string EhloHost { get { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_EhloHost; } } /// <summary> /// Gets MAIL FROM: value. Returns null if MAIL FROM: is not issued yet. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> public SMTP_MailFrom From { get { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_pFrom; } } /// <summary> /// Gets session owner SMTP server. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> public new SMTP_Server Server { get { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return (SMTP_Server) base.Server; } } /// <summary> /// Gets RCPT TO: values. Returns null if RCPT TO: is not issued yet. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> public SMTP_RcptTo[] To { get { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } lock (m_pTo) { SMTP_RcptTo[] retVal = new SMTP_RcptTo[m_pTo.Count]; m_pTo.Values.CopyTo(retVal, 0); return retVal; } } } /// <summary> /// Gets number of mail transactions processed by this SMTP session. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> public int Transactions { get { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_Transactions; } } #endregion #region Methods /// <summary> /// Cleans up any resource being used. /// </summary> public override void Dispose() { if (IsDisposed) { return; } base.Dispose(); m_pAuthentications = null; m_EhloHost = null; m_pUser = null; m_pFrom = null; m_pTo = null; m_pMessageStream = null; } #endregion #region Overrides /// <summary> /// Starts session processing. /// </summary> protected internal override void Start() { base.Start(); /* RFC 5321 3.1. The SMTP protocol allows a server to formally reject a mail session while still allowing the initial connection as follows: a 554 response MAY be given in the initial connection opening message instead of the 220. A server taking this approach MUST still wait for the client to send a QUIT (see Section 172.16.58.3) before closing the connection and SHOULD respond to any intervening commands with "503 bad sequence of commands". Since an attempt to make an SMTP connection to such a system is probably in error, a server returning a 554 response on connection opening SHOULD provide enough information in the reply text to facilitate debugging of the sending system. */ try { SMTP_Reply reply = null; if (string.IsNullOrEmpty(Server.GreetingText)) { reply = new SMTP_Reply(220, "<" + Net_Utils.GetLocalHostName(LocalHostName) + "> Simple Mail Transfer Service Ready."); } else { reply = new SMTP_Reply(220, Server.GreetingText); } reply = OnStarted(reply); WriteLine(reply.ToString()); // Setup rejected flag, so we respond "503 bad sequence of commands" any command except QUIT. if (reply.ReplyCode >= 300) { m_SessionRejected = true; } BeginReadCmd(); } catch (Exception x) { OnError(x); } } /// <summary> /// Is called when session has processing error. /// </summary> /// <param name="x">Exception happened.</param> protected override void OnError(Exception x) { if (IsDisposed) { return; } if (x == null) { return; } /* Error handling: IO and Socket exceptions are permanent, so we must end session. */ try { LogAddText("Exception: " + x.Message); // Permanent error. if (x is IOException || x is SocketException) { Dispose(); } // xx error, may be temporary. else { // Raise SMTP_Server.Error event. base.OnError(x); // Try to send "500 Internal server error." try { WriteLine("500 Internal server error."); } catch { // Error is permanent. Dispose(); } } } catch {} } /// <summary> /// This method is called when specified session times out. /// </summary> /// <remarks> /// This method allows inhereted classes to report error message to connected client. /// Session will be disconnected after this method completes. /// </remarks> protected override void OnTimeout() { try { if (m_pMessageStream != null) { OnMessageStoringCanceled(); } WriteLine("421 Idle timeout, closing connection."); } catch { // Skip errors. } } #endregion #region Utility methods /// <summary> /// Starts reading incoming command from the connected client. /// </summary> private void BeginReadCmd() { if (IsDisposed) { return; } try { SmartStream.ReadLineAsyncOP readLineOP = new SmartStream.ReadLineAsyncOP(new byte[Workaround.Definitions.MaxStreamLineLength], SizeExceededAction. JunkAndThrowException); // This event is raised only if read period-terminated opeartion completes asynchronously. readLineOP.Completed += delegate { if (ProcessCmd(readLineOP)) { BeginReadCmd(); } }; // Process incoming commands while, command reading completes synchronously. while (TcpStream.ReadLine(readLineOP, true)) { if (!ProcessCmd(readLineOP)) { break; } } } catch (Exception x) { OnError(x); } } /// <summary> /// Completes command reading operation. /// </summary> /// <param name="op">Operation.</param> /// <returns>Returns true if server should start reading next command.</returns> private bool ProcessCmd(SmartStream.ReadLineAsyncOP op) { bool readNextCommand = true; // Check errors. if (op.Error != null) { OnError(op.Error); } try { if (IsDisposed) { return false; } // Log. if (Server.Logger != null) { Server.Logger.AddRead(ID, AuthenticatedUserIdentity, op.BytesInBuffer, op.LineUtf8, LocalEndPoint, RemoteEndPoint); } string[] cmd_args = Encoding.UTF8.GetString(op.Buffer, 0, op.LineBytesInBuffer).Split(new[] {' '}, 2); string cmd = cmd_args[0].ToUpperInvariant(); string args = cmd_args.Length == 2 ? cmd_args[1] : ""; if (cmd == "EHLO") { EHLO(args); } else if (cmd == "HELO") { HELO(args); } else if (cmd == "STARTTLS") { STARTTLS(args); } else if (cmd == "AUTH") { AUTH(args); } else if (cmd == "MAIL") { MAIL(args); } else if (cmd == "RCPT") { RCPT(args); } else if (cmd == "DATA") { readNextCommand = DATA(args); } else if (cmd == "BDAT") { readNextCommand = BDAT(args); } else if (cmd == "RSET") { RSET(args); } else if (cmd == "NOOP") { NOOP(args); } else if (cmd == "QUIT") { QUIT(args); readNextCommand = false; } else { m_BadCommands++; // Maximum allowed bad commands exceeded. if (Server.MaxBadCommands != 0 && m_BadCommands > Server.MaxBadCommands) { WriteLine("421 Too many bad commands, closing transmission channel."); Disconnect(); return false; } WriteLine("502 Error: command '" + cmd + "' not recognized."); } } catch (Exception x) { OnError(x); } return readNextCommand; } private void EHLO(string cmdText) { // RFC 5321 3.1. if (m_SessionRejected) { WriteLine("503 bad sequence of commands: Session rejected."); return; } /* RFC 5321 4.1.1.1. ehlo = "EHLO" SP ( Domain / address-literal ) CRLF ehlo-ok-rsp = ( "250" SP Domain [ SP ehlo-greet ] CRLF ) / ( "250-" Domain [ SP ehlo-greet ] CRLF *( "250-" ehlo-line CRLF ) "250" SP ehlo-line CRLF ) ehlo-greet = 1*(%d0-9 / %d11-12 / %d14-127) ; string of any characters other than CR or LF ehlo-line = ehlo-keyword *( SP ehlo-param ) ehlo-keyword = (ALPHA / DIGIT) *(ALPHA / DIGIT / "-") ; additional syntax of ehlo-params depends on ehlo-keyword ehlo-param = 1*(%d33-126) ; any CHAR excluding <SP> and all control characters (US-ASCII 0-31 and 127 inclusive) */ if (string.IsNullOrEmpty(cmdText) || cmdText.Split(' ').Length != 1) { WriteLine("501 Syntax error, syntax: \"EHLO\" SP hostname CRLF"); return; } List<string> ehloLines = new List<string>(); ehloLines.Add(Net_Utils.GetLocalHostName(LocalHostName)); if (Server.Extentions.Contains(SMTP_ServiceExtensions.PIPELINING)) { ehloLines.Add(SMTP_ServiceExtensions.PIPELINING); } if (Server.Extentions.Contains(SMTP_ServiceExtensions.SIZE)) { ehloLines.Add(SMTP_ServiceExtensions.SIZE + " " + Server.MaxMessageSize); } if (Server.Extentions.Contains(SMTP_ServiceExtensions.STARTTLS) && !IsSecureConnection && Certificate != null) { ehloLines.Add(SMTP_ServiceExtensions.STARTTLS); } if (Server.Extentions.Contains(SMTP_ServiceExtensions._8BITMIME)) { ehloLines.Add(SMTP_ServiceExtensions._8BITMIME); } if (Server.Extentions.Contains(SMTP_ServiceExtensions.BINARYMIME)) { ehloLines.Add(SMTP_ServiceExtensions.BINARYMIME); } if (Server.Extentions.Contains(SMTP_ServiceExtensions.CHUNKING)) { ehloLines.Add(SMTP_ServiceExtensions.CHUNKING); } if (Server.Extentions.Contains(SMTP_ServiceExtensions.DSN)) { ehloLines.Add(SMTP_ServiceExtensions.DSN); } StringBuilder sasl = new StringBuilder(); foreach (AUTH_SASL_ServerMechanism authMechanism in Authentications.Values) { if (!authMechanism.RequireSSL || (authMechanism.RequireSSL && IsSecureConnection)) { sasl.Append(authMechanism.Name + " "); } } if (sasl.Length > 0) { ehloLines.Add(SMTP_ServiceExtensions.AUTH + " " + sasl.ToString().Trim()); } SMTP_Reply reply = new SMTP_Reply(250, ehloLines.ToArray()); reply = OnEhlo(cmdText, reply); // EHLO accepted. if (reply.ReplyCode < 300) { m_EhloHost = cmdText; /* RFC 5321 4.1.4. An EHLO command MAY be issued by a client later in the session. If it is issued after the session begins and the EHLO command is acceptable to the SMTP server, the SMTP server MUST clear all buffers and reset the state exactly as if a RSET command had been issued. In other words, the sequence of RSET followed immediately by EHLO is redundant, but not harmful other than in the performance cost of executing unnecessary commands. */ Reset(); } WriteLine(reply.ToString()); } private void HELO(string cmdText) { // RFC 5321 3.1. if (m_SessionRejected) { WriteLine("503 bad sequence of commands: Session rejected."); return; } /* RFC 5321 4.1.1.1. helo = "HELO" SP Domain CRLF response = "250" SP Domain [ SP ehlo-greet ] CRLF */ if (string.IsNullOrEmpty(cmdText) || cmdText.Split(' ').Length != 1) { WriteLine("501 Syntax error, syntax: \"HELO\" SP hostname CRLF"); return; } SMTP_Reply reply = new SMTP_Reply(250, Net_Utils.GetLocalHostName(LocalHostName)); reply = OnEhlo(cmdText, reply); // HELO accepted. if (reply.ReplyCode < 300) { m_EhloHost = cmdText; /* RFC 5321 4.1.4. An EHLO command MAY be issued by a client later in the session. If it is issued after the session begins and the EHLO command is acceptable to the SMTP server, the SMTP server MUST clear all buffers and reset the state exactly as if a RSET command had been issued. In other words, the sequence of RSET followed immediately by EHLO is redundant, but not harmful other than in the performance cost of executing unnecessary commands. */ Reset(); } WriteLine(reply.ToString()); } private void STARTTLS(string cmdText) { // RFC 5321 3.1. if (m_SessionRejected) { WriteLine("503 Bad sequence of commands: Session rejected."); return; } /* RFC 3207 STARTTLS 4. The format for the STARTTLS command is: STARTTLS with no parameters. After the client gives the STARTTLS command, the server responds with one of the following reply codes: 220 Ready to start TLS 501 Syntax error (no parameters allowed) 454 TLS not available due to temporary reason 4.2 Result of the STARTTLS Command Upon completion of the TLS handshake, the SMTP protocol is reset to the initial state (the state in SMTP after a server issues a 220 service ready greeting). The server MUST discard any knowledge obtained from the client, such as the argument to the EHLO command, which was not obtained from the TLS negotiation itself. The client MUST discard any knowledge obtained from the server, such as the list of SMTP service extensions, which was not obtained from the TLS negotiation itself. The client SHOULD send an EHLO command as the first command after a successful TLS negotiation. Both the client and the server MUST know if there is a TLS session active. A client MUST NOT attempt to start a TLS session if a TLS session is already active. A server MUST NOT return the STARTTLS extension in response to an EHLO command received after a TLS handshake has completed. RFC 2246 7.2.2. Error alerts. Error handling in the TLS Handshake protocol is very simple. When an error is detected, the detecting party sends a message to the other party. Upon transmission or receipt of an fatal alert message, both parties immediately close the connection. <...> */ if (!string.IsNullOrEmpty(cmdText)) { WriteLine("501 Syntax error: No parameters allowed."); return; } if (IsSecureConnection) { WriteLine("503 Bad sequence of commands: Connection is already secure."); return; } if (Certificate == null) { WriteLine("454 TLS not available: Server has no SSL certificate."); return; } WriteLine("220 Ready to start TLS."); try { SwitchToSecure(); // Log LogAddText("TLS negotiation completed successfully."); m_EhloHost = null; Reset(); } catch (Exception x) { // Log LogAddText("TLS negotiation failed: " + x.Message + "."); Disconnect(); } } private void AUTH(string cmdText) { // RFC 5321 3.1. if (m_SessionRejected) { WriteLine("503 Bad sequence of commands: Session rejected."); return; } /* RFC 4954 AUTH mechanism [initial-response] Arguments: mechanism: A string identifying a [SASL] authentication mechanism. initial-response: An optional initial client response. If present, this response MUST be encoded as described in Section 4 of [BASE64] or contain a single character "=". Restrictions: After an AUTH command has been successfully completed, no more AUTH commands may be issued in the same session. After a successful AUTH command completes, a server MUST reject any further AUTH commands with a 503 reply. The AUTH command is not permitted during a mail transaction. An AUTH command issued during a mail transaction MUST be rejected with a 503 reply. A server challenge is sent as a 334 reply with the text part containing the [BASE64] encoded string supplied by the SASL mechanism. This challenge MUST NOT contain any text other than the BASE64 encoded challenge. In SMTP, a server challenge that contains no data is defined as a 334 reply with no text part. Note that there is still a space following the reply code, so the complete response line is "334 ". If the client wishes to cancel the authentication exchange, it issues a line with a single "*". If the server receives such a response, it MUST reject the AUTH command by sending a 501 reply. */ if (IsAuthenticated) { WriteLine("503 Bad sequence of commands: you are already authenticated."); return; } if (m_pFrom != null) { WriteLine( "503 Bad sequence of commands: The AUTH command is not permitted during a mail transaction."); return; } #region Parse parameters string[] arguments = cmdText.Split(' '); if (arguments.Length > 2) { WriteLine("501 Syntax error, syntax: AUTH SP mechanism [SP initial-response] CRLF"); return; } string initialClientResponse = ""; if (arguments.Length == 2) { if (arguments[1] == "=") { // Skip. } else { try { initialClientResponse = Encoding.UTF8.GetString(Convert.FromBase64String(arguments[1])); } catch { WriteLine( "501 Syntax error: Parameter 'initial-response' value must be BASE64 or contain a single character '='."); return; } } } string mechanism = arguments[0]; #endregion if (!Authentications.ContainsKey(mechanism)) { WriteLine("501 Not supported authentication mechanism."); return; } string clientResponse = initialClientResponse; AUTH_SASL_ServerMechanism auth = Authentications[mechanism]; while (true) { string serverResponse = auth.Continue(clientResponse); // Authentication completed. if (auth.IsCompleted) { if (auth.IsAuthenticated) { m_pUser = new GenericIdentity(auth.UserName, "SASL-" + auth.Name); WriteLine("235 2.7.0 Authentication succeeded."); } else { WriteLine("535 5.7.8 Authentication credentials invalid."); } break; } // Authentication continues. else { // Send server challange. if (string.IsNullOrEmpty(serverResponse)) { WriteLine("334 "); } else { WriteLine("334 " + Convert.ToBase64String(Encoding.UTF8.GetBytes(serverResponse))); } // Read client response. SmartStream.ReadLineAsyncOP readLineOP = new SmartStream.ReadLineAsyncOP(new byte[Workaround.Definitions.MaxStreamLineLength], SizeExceededAction . JunkAndThrowException); TcpStream.ReadLine(readLineOP, false); if (readLineOP.Error != null) { throw readLineOP.Error; } clientResponse = readLineOP.LineUtf8; // Log if (Server.Logger != null) { Server.Logger.AddRead(ID, AuthenticatedUserIdentity, readLineOP.BytesInBuffer, "base64 auth-data", LocalEndPoint, RemoteEndPoint); } // Client canceled authentication. if (clientResponse == "*") { WriteLine("501 Authentication canceled."); return; } // We have base64 client response, decode it. else { try { clientResponse = Encoding.UTF8.GetString(Convert.FromBase64String(clientResponse)); } catch { WriteLine("501 Invalid client response '" + clientResponse + "'."); return; } } } } } private void MAIL(string cmdText) { // RFC 5321 3.1. if (m_SessionRejected) { WriteLine("503 bad sequence of commands: Session rejected."); return; } // RFC 5321 4.1.4. if (string.IsNullOrEmpty(m_EhloHost)) { WriteLine("503 Bad sequence of commands: send EHLO/HELO first."); return; } // RFC 5321 4.1.4. if (m_pFrom != null) { WriteLine("503 Bad sequence of commands: nested MAIL command."); return; } // RFC 3030 BDAT. if (m_pMessageStream != null) { WriteLine("503 Bad sequence of commands: BDAT command is pending."); return; } if (Server.MaxTransactions != 0 && m_Transactions >= Server.MaxTransactions) { WriteLine("503 Bad sequence of commands: Maximum allowed mail transactions exceeded."); return; } /* RFC 5321 4.1.1.2. mail = "MAIL FROM:" Reverse-path [SP Mail-parameters] CRLF Mail-parameters = esmtp-param *(SP esmtp-param) esmtp-param = esmtp-keyword ["=" esmtp-value] esmtp-keyword = (ALPHA / DIGIT) *(ALPHA / DIGIT / "-") esmtp-value = 1*(%d33-60 / %d62-126) ; any CHAR excluding "=", SP, and control ; characters. If this string is an email address, ; i.e., a Mailbox, then the "xtext" syntax [32] SHOULD be used. Reverse-path = Path / "<>" Path = "<" [ A-d-l ":" ] Mailbox ">" 192.168.127.12. If the server SMTP does not recognize or cannot implement one or more of the parameters associated with a particular MAIL FROM or RCPT TO command, it will return code 555. */ if (cmdText.ToUpper().StartsWith("FROM:")) { // Remove FROM: from command text. cmdText = cmdText.Substring(5).Trim(); } else { WriteLine( "501 Syntax error, syntax: \"MAIL FROM:\" \"<\" address \">\" / \"<>\" [SP Mail-parameters] CRLF"); return; } string address = ""; int size = -1; string body = null; string ret = null; string envID = null; // Mailbox not between <>. if (!cmdText.StartsWith("<") || cmdText.IndexOf('>') == -1) { WriteLine( "501 Syntax error, syntax: \"MAIL FROM:\" \"<\" address \">\" / \"<>\" [SP Mail-parameters] CRLF"); return; } // Parse mailbox. else { address = cmdText.Substring(1, cmdText.IndexOf('>') - 1).Trim(); cmdText = cmdText.Substring(cmdText.IndexOf('>') + 1).Trim(); } #region Parse parameters string[] parameters = string.IsNullOrEmpty(cmdText) ? new string[0] : cmdText.Split(' '); foreach (string parameter in parameters) { string[] name_value = parameter.Split(new[] {'='}, 2); // SIZE if (Server.Extentions.Contains(SMTP_ServiceExtensions.SIZE) && name_value[0].ToUpper() == "SIZE") { // RFC 1870. // size-value ::= 1*20DIGIT if (name_value.Length == 1) { WriteLine("501 Syntax error: SIZE parameter value must be specified."); return; } if (!int.TryParse(name_value[1], out size)) { WriteLine("501 Syntax error: SIZE parameter value must be integer."); return; } // Message size exceeds maximum allowed message size. if (size > Server.MaxMessageSize) { WriteLine("552 Message exceeds fixed maximum message size."); return; } } // BODY else if (Server.Extentions.Contains(SMTP_ServiceExtensions._8BITMIME) && name_value[0].ToUpper() == "BODY") { // RFC 1652. // body-value ::= "7BIT" / "8BITMIME" / "BINARYMIME" // // BINARYMIME - defined in RFC 3030. if (name_value.Length == 1) { WriteLine("501 Syntax error: BODY parameter value must be specified."); return; } if (name_value[1].ToUpper() != "7BIT" && name_value[1].ToUpper() != "8BITMIME" && name_value[1].ToUpper() != "BINARYMIME") { WriteLine( "501 Syntax error: BODY parameter value must be \"7BIT\",\"8BITMIME\" or \"BINARYMIME\"."); return; } body = name_value[1].ToUpper(); } // RET else if (Server.Extentions.Contains(SMTP_ServiceExtensions.DSN) && name_value[0].ToUpper() == "RET") { // RFC 1891 5.3. // ret-value = "FULL" / "HDRS" if (name_value.Length == 1) { WriteLine("501 Syntax error: RET parameter value must be specified."); return; } if (name_value[1].ToUpper() != "FULL" && name_value[1].ToUpper() != "HDRS") { WriteLine( "501 Syntax error: RET parameter value must be \"FULL\" or \"HDRS\"."); return; } ret = name_value[1].ToUpper(); } // ENVID else if (Server.Extentions.Contains(SMTP_ServiceExtensions.DSN) && name_value[0].ToUpper() == "ENVID") { if (name_value.Length == 1) { WriteLine("501 Syntax error: ENVID parameter value must be specified."); return; } envID = name_value[1].ToUpper(); } // Unsupported parameter. else { WriteLine("555 Unsupported parameter: " + parameter); return; } } #endregion SMTP_MailFrom from = new SMTP_MailFrom(address, size, body, ret, envID); SMTP_Reply reply = new SMTP_Reply(250, "OK."); reply = OnMailFrom(from, reply); // MAIL accepted. if (reply.ReplyCode < 300) { m_pFrom = from; m_Transactions++; } WriteLine(reply.ToString()); } private void RCPT(string cmdText) { // RFC 5321 3.1. if (m_SessionRejected) { WriteLine("503 bad sequence of commands: Session rejected."); return; } // RFC 5321 4.1.4. if (string.IsNullOrEmpty(m_EhloHost)) { WriteLine("503 Bad sequence of commands: send EHLO/HELO first."); return; } // RFC 5321 4.1.4. if (m_pFrom == null) { WriteLine("503 Bad sequence of commands: send 'MAIL FROM:' first."); return; } // RFC 3030 BDAT. if (m_pMessageStream != null) { WriteLine("503 Bad sequence of commands: BDAT command is pending."); return; } /* RFC 5321 4.1.1.3. rcpt = "RCPT TO:" ( "<Postmaster@" Domain ">" / "<Postmaster>" / Forward-path ) [SP Rcpt-parameters] CRLF Rcpt-parameters = esmtp-param *(SP esmtp-param) esmtp-param = esmtp-keyword ["=" esmtp-value] esmtp-keyword = (ALPHA / DIGIT) *(ALPHA / DIGIT / "-") esmtp-value = 1*(%d33-60 / %d62-126) ; any CHAR excluding "=", SP, and control ; characters. If this string is an email address, ; i.e., a Mailbox, then the "xtext" syntax [32] SHOULD be used. Note that, in a departure from the usual rules for local-parts, the "Postmaster" string shown above is treated as case-insensitive. Forward-path = Path Path = "<" [ A-d-l ":" ] Mailbox ">" 192.168.127.12. If the server SMTP does not recognize or cannot implement one or more of the parameters associated with a particular MAIL FROM or RCPT TO command, it will return code 555. */ if (cmdText.ToUpper().StartsWith("TO:")) { // Remove TO: from command text. cmdText = cmdText.Substring(3).Trim(); } else { WriteLine( "501 Syntax error, syntax: \"RCPT TO:\" \"<\" address \">\" [SP Rcpt-parameters] CRLF"); return; } string address = ""; SMTP_Notify notify = SMTP_Notify.NotSpecified; string orcpt = null; // Mailbox not between <>. if (!cmdText.StartsWith("<") || cmdText.IndexOf('>') == -1) { WriteLine( "501 Syntax error, syntax: \"RCPT TO:\" \"<\" address \">\" [SP Rcpt-parameters] CRLF"); return; } // Parse mailbox. else { address = cmdText.Substring(1, cmdText.IndexOf('>') - 1).Trim(); cmdText = cmdText.Substring(cmdText.IndexOf('>') + 1).Trim(); } if (address == string.Empty) { WriteLine( "501 Syntax error('address' value must be specified), syntax: \"RCPT TO:\" \"<\" address \">\" [SP Rcpt-parameters] CRLF"); return; } #region Parse parameters string[] parameters = string.IsNullOrEmpty(cmdText) ? new string[0] : cmdText.Split(' '); foreach (string parameter in parameters) { string[] name_value = parameter.Split(new[] {'='}, 2); // NOTIFY if (Server.Extentions.Contains(SMTP_ServiceExtensions.DSN) && name_value[0].ToUpper() == "NOTIFY") { /* RFC 1891 5.1. notify-esmtp-value = "NEVER" / 1#notify-list-element notify-list-element = "SUCCESS" / "FAILURE" / "DELAY" a. Multiple notify-list-elements, separated by commas, MAY appear in a NOTIFY parameter; however, the NEVER keyword MUST appear by itself. */ if (name_value.Length == 1) { WriteLine("501 Syntax error: NOTIFY parameter value must be specified."); return; } string[] notifyItems = name_value[1].ToUpper().Split(','); foreach (string notifyItem in notifyItems) { if (notifyItem.Trim().ToUpper() == "NEVER") { notify |= SMTP_Notify.Never; } else if (notifyItem.Trim().ToUpper() == "SUCCESS") { notify |= SMTP_Notify.Success; } else if (notifyItem.Trim().ToUpper() == "FAILURE") { notify |= SMTP_Notify.Failure; } else if (notifyItem.Trim().ToUpper() == "DELAY") { notify |= SMTP_Notify.Delay; } // Invalid or not supported notify item. else { WriteLine("501 Syntax error: Not supported NOTIFY parameter value '" + notifyItem + "'."); return; } } } // ORCPT else if (Server.Extentions.Contains(SMTP_ServiceExtensions.DSN) && name_value[0].ToUpper() == "ORCPT") { if (name_value.Length == 1) { WriteLine("501 Syntax error: ORCPT parameter value must be specified."); return; } orcpt = name_value[1].ToUpper(); } // Unsupported parameter. else { WriteLine("555 Unsupported parameter: " + parameter); } } #endregion // Maximum allowed recipients exceeded. if (m_pTo.Count >= Server.MaxRecipients) { WriteLine("452 Too many recipients"); return; } SMTP_RcptTo to = new SMTP_RcptTo(address, notify, orcpt); SMTP_Reply reply = new SMTP_Reply(250, "OK."); reply = OnRcptTo(to, reply); // RCPT accepted. if (reply.ReplyCode < 300) { if (!m_pTo.ContainsKey(address.ToLower())) { m_pTo.Add(address.ToLower(), to); } } WriteLine(reply.ToString()); } private bool DATA(string cmdText) { // RFC 5321 3.1. if (m_SessionRejected) { WriteLine("503 bad sequence of commands: Session rejected."); return true; } // RFC 5321 4.1.4. if (string.IsNullOrEmpty(m_EhloHost)) { WriteLine("503 Bad sequence of commands: send EHLO/HELO first."); return true; } // RFC 5321 4.1.4. if (m_pFrom == null) { WriteLine("503 Bad sequence of commands: send 'MAIL FROM:' first."); return true; } // RFC 5321 4.1.4. if (m_pTo.Count == 0) { WriteLine("503 Bad sequence of commands: send 'RCPT TO:' first."); return true; } // RFC 3030 BDAT. if (m_pMessageStream != null) { WriteLine( "503 Bad sequence of commands: DATA and BDAT commands cannot be used in the same transaction."); return true; } /* RFC 5321 4.1.1.4. The receiver normally sends a 354 response to DATA, and then treats the lines (strings ending in <CRLF> sequences, as described in Section 2.3.7) following the command as mail data from the sender. This command causes the mail data to be appended to the mail data buffer. The mail data may contain any of the 128 ASCII character codes, although experience has indicated that use of control characters other than SP, HT, CR, and LF may cause problems and SHOULD be avoided when possible. The custom of accepting lines ending only in <LF>, as a concession to non-conforming behavior on the part of some UNIX systems, has proven to cause more interoperability problems than it solves, and SMTP server systems MUST NOT do this, even in the name of improved robustness. In particular, the sequence "<LF>.<LF>" (bare line feeds, without carriage returns) MUST NOT be treated as equivalent to <CRLF>.<CRLF> as the end of mail data indication. Receipt of the end of mail data indication requires the server to process the stored mail transaction information. This processing consumes the information in the reverse-path buffer, the forward-path buffer, and the mail data buffer, and on the completion of this command these buffers are cleared. If the processing is successful, the receiver MUST send an OK reply. If the processing fails, the receiver MUST send a failure reply. The SMTP model does not allow for partial failures at this point: either the message is accepted by the server for delivery and a positive response is returned or it is not accepted and a failure reply is returned. In sending a positive "250 OK" completion reply to the end of data indication, the receiver takes full responsibility for the message (see Section 6.1). Errors that are diagnosed subsequently MUST be reported in a mail message, as discussed in Section 4.4. When the SMTP server accepts a message either for relaying or for final delivery, it inserts a trace record (also referred to interchangeably as a "time stamp line" or "Received" line) at the top of the mail data. This trace record indicates the identity of the host that sent the message, the identity of the host that received the message (and is inserting this time stamp), and the date and time the message was received. Relayed messages will have multiple time stamp lines. Details for formation of these lines, including their syntax, is specified in Section 4.4. */ DateTime startTime = DateTime.Now; m_pMessageStream = OnGetMessageStream(); if (m_pMessageStream == null) { m_pMessageStream = new MemoryStream(); } // RFC 5321.4.4 trace info. byte[] recevived = CreateReceivedHeader(); m_pMessageStream.Write(recevived, 0, recevived.Length); WriteLine("354 Start mail input; end with <CRLF>.<CRLF>"); // Create asynchronous read period-terminated opeartion. SmartStream.ReadPeriodTerminatedAsyncOP readPeriodTermOP = new SmartStream.ReadPeriodTerminatedAsyncOP(m_pMessageStream, Server.MaxMessageSize, SizeExceededAction.JunkAndThrowException); // This event is raised only if read period-terminated opeartion completes asynchronously. readPeriodTermOP.Completed += delegate { DATA_End(startTime, readPeriodTermOP); }; // Read period-terminated completed synchronously. if (TcpStream.ReadPeriodTerminated(readPeriodTermOP, true)) { DATA_End(startTime, readPeriodTermOP); return true; } // Read period-terminated completed asynchronously, Completed event will be raised once operation completes. // else{ return false; } /// <summary> /// Completes DATA command. /// </summary> /// <param name="startTime">Time DATA command started.</param> /// <param name="op">Read period-terminated opeartion.</param> private void DATA_End(DateTime startTime, SmartStream.ReadPeriodTerminatedAsyncOP op) { try { if (op.Error != null) { if (op.Error is LineSizeExceededException) { WriteLine("500 Line too long."); } else if (op.Error is DataSizeExceededException) { WriteLine("552 Too much mail data."); } else { OnError(op.Error); } OnMessageStoringCanceled(); } else { SMTP_Reply reply = new SMTP_Reply(250, "DATA completed in " + (DateTime.Now - startTime).TotalSeconds.ToString("f2") + " seconds."); reply = OnMessageStoringCompleted(reply); WriteLine(reply.ToString()); } } catch (Exception x) { OnError(x); } Reset(); BeginReadCmd(); } private bool BDAT(string cmdText) { // RFC 5321 3.1. if (m_SessionRejected) { WriteLine("503 bad sequence of commands: Session rejected."); return true; } // RFC 5321 4.1.4. if (string.IsNullOrEmpty(m_EhloHost)) { WriteLine("503 Bad sequence of commands: send EHLO/HELO first."); return true; } // RFC 5321 4.1.4. if (m_pFrom == null) { WriteLine("503 Bad sequence of commands: send 'MAIL FROM:' first."); return true; } // RFC 5321 4.1.4. if (m_pTo.Count == 0) { WriteLine("503 Bad sequence of commands: send 'RCPT TO:' first."); return true; } /* RFC 3030 2 The BDAT verb takes two arguments.The first argument indicates the length, in octets, of the binary data chunk. The second optional argument indicates that the data chunk is the last. The message data is sent immediately after the trailing <CR> <LF> of the BDAT command line. Once the receiver-SMTP receives the specified number of octets, it will return a 250 reply code. The optional LAST parameter on the BDAT command indicates that this is the last chunk of message data to be sent. The last BDAT command MAY have a byte-count of zero indicating there is no additional data to be sent. Any BDAT command sent after the BDAT LAST is illegal and MUST be replied to with a 503 "Bad sequence of commands" reply code. The state resulting from this error is indeterminate. A RSET command MUST be sent to clear the transaction before continuing. A 250 response MUST be sent to each successful BDAT data block within a mail transaction. bdat-cmd ::= "BDAT" SP chunk-size [ SP end-marker ] CR LF chunk-size ::= 1*DIGIT end-marker ::= "LAST" */ DateTime startTime = DateTime.Now; int chunkSize = 0; bool last = false; string[] args = cmdText.Split(' '); if (cmdText == string.Empty || args.Length > 2) { WriteLine("501 Syntax error, syntax: \"BDAT\" SP chunk-size [SP \"LAST\"] CRLF"); return true; } if (!int.TryParse(args[0], out chunkSize)) { WriteLine( "501 Syntax error(chunk-size must be integer), syntax: \"BDAT\" SP chunk-size [SP \"LAST\"] CRLF"); return true; } if (args.Length == 2) { if (args[1].ToUpperInvariant() != "LAST") { WriteLine("501 Syntax error, syntax: \"BDAT\" SP chunk-size [SP \"LAST\"] CRLF"); return true; } last = true; } // First BDAT block in transaction. if (m_pMessageStream == null) { m_pMessageStream = OnGetMessageStream(); if (m_pMessageStream == null) { m_pMessageStream = new MemoryStream(); } // RFC 5321.4.4 trace info. byte[] recevived = CreateReceivedHeader(); m_pMessageStream.Write(recevived, 0, recevived.Length); } Stream storeStream = m_pMessageStream; // Maximum allowed message size exceeded. if ((m_BDatReadedCount + chunkSize) > Server.MaxMessageSize) { storeStream = new JunkingStream(); } // Read data block. TcpStream.BeginReadFixedCount(storeStream, chunkSize, delegate(IAsyncResult ar) { try { TcpStream.EndReadFixedCount(ar); m_BDatReadedCount += chunkSize; // Maximum allowed message size exceeded. if (m_BDatReadedCount > Server.MaxMessageSize) { WriteLine("552 Too much mail data."); OnMessageStoringCanceled(); } else { SMTP_Reply reply = new SMTP_Reply(250, chunkSize + " bytes received in " + (DateTime.Now - startTime). TotalSeconds. ToString("f2") + " seconds."); if (last) { reply = OnMessageStoringCompleted(reply); } WriteLine(reply.ToString()); } if (last) { // Accoring RFC 3030, client should send RSET and we must wait it and reject transaction commands. // If we reset internally, then all works as specified. Reset(); } } catch (Exception x) { OnError(x); } BeginReadCmd(); }, null); return false; } private void RSET(string cmdText) { // RFC 5321 3.1. if (m_SessionRejected) { WriteLine("503 bad sequence of commands: Session rejected."); return; } /* RFC 5321 4.1.1.5. This command specifies that the current mail transaction will be aborted. Any stored sender, recipients, and mail data MUST be discarded, and all buffers and state tables cleared. The receiver MUST send a "250 OK" reply to a RSET command with no arguments. A reset command may be issued by the client at any time. It is effectively equivalent to a NOOP (i.e., it has no effect) if issued immediately after EHLO, before EHLO is issued in the session, after an end of data indicator has been sent and acknowledged, or immediately before a QUIT. An SMTP server MUST NOT close the connection as the result of receiving a RSET; that action is reserved for QUIT (see Section 172.16.58.3). */ if (m_pMessageStream != null) { OnMessageStoringCanceled(); } Reset(); WriteLine("250 OK."); } private void NOOP(string cmdText) { // RFC 5321 3.1. if (m_SessionRejected) { WriteLine("503 bad sequence of commands: Session rejected."); return; } /* RFC 5321 172.16.58.3. This command does not affect any parameters or previously entered commands. It specifies no action other than that the receiver send a "250 OK" reply. This command has no effect on the reverse-path buffer, the forward- path buffer, or the mail data buffer, and it may be issued at any time. If a parameter string is specified, servers SHOULD ignore it. Syntax: noop = "NOOP" [ SP String ] CRLF */ WriteLine("250 OK."); } private void QUIT(string cmdText) { /* RFC 5321 172.16.58.3. This command specifies that the receiver MUST send a "221 OK" reply, and then close the transmission channel. The QUIT command may be issued at any time. Any current uncompleted mail transaction will be aborted. quit = "QUIT" CRLF */ try { WriteLine("221 <" + Net_Utils.GetLocalHostName(LocalHostName) + "> Service closing transmission channel."); } catch {} Disconnect(); Dispose(); } /// <summary> /// Does reset as specified in RFC 5321. /// </summary> private void Reset() { if (IsDisposed) { return; } m_pFrom = null; m_pTo.Clear(); m_pMessageStream = null; m_BDatReadedCount = 0; } /// <summary> /// Creates "Received:" header field. For more info see RFC 5321.4.4. /// </summary> /// <returns>Returns "Received:" header field.</returns> private byte[] CreateReceivedHeader() { /* 5321 4.4. Trace Information. When an SMTP server receives a message for delivery or further processing, it MUST insert trace ("time stamp" or "Received") information at the beginning of the message content, as discussed in Section 4.1.1.4. RFC 4954.7. Additional Requirements on Servers. As described in Section 4.4 of [SMTP], an SMTP server that receives a message for delivery or further processing MUST insert the "Received:" header field at the beginning of the message content. This document places additional requirements on the content of a generated "Received:" header field. Upon successful authentication, a server SHOULD use the "ESMTPA" or the "ESMTPSA" [SMTP-TT] (when appropriate) keyword in the "with" clause of the Received header field. http://www.iana.org/assignments/mail-parameters ESMTP SMTP with Service Extensions [RFC5321] ESMTPA ESMTP with SMTP AUTH [RFC3848] ESMTPS ESMTP with STARTTLS [RFC3848] ESMTPSA ESMTP with both STARTTLS and SMTP AUTH [RFC3848] */ Mail_h_Received received = new Mail_h_Received(EhloHost, Net_Utils.GetLocalHostName(LocalHostName), DateTime.Now); received.From_TcpInfo = new Mail_t_TcpInfo(RemoteEndPoint.Address, null); received.Via = "TCP"; if (!IsAuthenticated && !IsSecureConnection) { received.With = "ESMTP"; } else if (IsAuthenticated && !IsSecureConnection) { received.With = "ESMTPA"; } else if (!IsAuthenticated && IsSecureConnection) { received.With = "ESMTPS"; } else if (IsAuthenticated && IsSecureConnection) { received.With = "ESMTPSA"; } return Encoding.UTF8.GetBytes(received.ToString()); } /// <summary> /// Sends and logs specified line to connected host. /// </summary> /// <param name="line">Line to send.</param> private void WriteLine(string line) { if (line == null) { throw new ArgumentNullException("line"); } int countWritten = TcpStream.WriteLine(line); // Log. if (Server.Logger != null) { Server.Logger.AddWrite(ID, AuthenticatedUserIdentity, countWritten, line, LocalEndPoint, RemoteEndPoint); } } /// <summary> /// Logs specified text. /// </summary> /// <param name="text">text to log.</param> /// <exception cref="ArgumentNullException">Is raised when <b>text</b> is null reference.</exception> private void LogAddText(string text) { if (text == null) { throw new ArgumentNullException("text"); } // Log if (Server.Logger != null) { Server.Logger.AddText(ID, text); } } /// <summary> /// Raises <b>Started</b> event. /// </summary> /// <param name="reply">Default SMTP server reply.</param> /// <returns>Returns SMTP server reply what must be sent to the connected client.</returns> private SMTP_Reply OnStarted(SMTP_Reply reply) { if (Started != null) { SMTP_e_Started eArgs = new SMTP_e_Started(this, reply); Started(this, eArgs); return eArgs.Reply; } return reply; } /// <summary> /// Raises <b>Ehlo</b> event. /// </summary> /// <param name="domain">Ehlo/Helo domain.</param> /// <param name="reply">Default SMTP server reply.</param> /// <returns>Returns SMTP server reply what must be sent to the connected client.</returns> private SMTP_Reply OnEhlo(string domain, SMTP_Reply reply) { if (Ehlo != null) { SMTP_e_Ehlo eArgs = new SMTP_e_Ehlo(this, domain, reply); Ehlo(this, eArgs); return eArgs.Reply; } return reply; } /// <summary> /// Raises <b>MailFrom</b> event. /// </summary> /// <param name="from">MAIL FROM: value.</param> /// <param name="reply">Default SMTP server reply.</param> /// <returns>Returns SMTP server reply what must be sent to the connected client.</returns> private SMTP_Reply OnMailFrom(SMTP_MailFrom from, SMTP_Reply reply) { if (MailFrom != null) { SMTP_e_MailFrom eArgs = new SMTP_e_MailFrom(this, from, reply); MailFrom(this, eArgs); return eArgs.Reply; } return reply; } /// <summary> /// Raises <b>RcptTo</b> event. /// </summary> /// <param name="to">RCPT TO: value.</param> /// <param name="reply">Default SMTP server reply.</param> /// <returns>Returns SMTP server reply what must be sent to the connected client.</returns> private SMTP_Reply OnRcptTo(SMTP_RcptTo to, SMTP_Reply reply) { if (RcptTo != null) { SMTP_e_RcptTo eArgs = new SMTP_e_RcptTo(this, to, reply); RcptTo(this, eArgs); return eArgs.Reply; } return reply; } /// <summary> /// Raises <b>GetMessageStream</b> event. /// </summary> /// <returns>Returns message store stream.</returns> private Stream OnGetMessageStream() { if (GetMessageStream != null) { SMTP_e_Message eArgs = new SMTP_e_Message(this); GetMessageStream(this, eArgs); return eArgs.Stream; } return null; } /// <summary> /// Raises <b>MessageStoringCanceled</b> event. /// </summary> private void OnMessageStoringCanceled() { if (MessageStoringCanceled != null) { MessageStoringCanceled(this, new SMTP_e_MessageStored(this,m_pMessageStream, null)); } } /// <summary> /// Raises <b>MessageStoringCompleted</b> event. /// </summary> /// <param name="reply">Default SMTP server reply.</param> /// <returns>Returns SMTP server reply what must be sent to the connected client.</returns> private SMTP_Reply OnMessageStoringCompleted(SMTP_Reply reply) { if (MessageStoringCompleted != null) { SMTP_e_MessageStored eArgs = new SMTP_e_MessageStored(this, m_pMessageStream, reply); MessageStoringCompleted(this, eArgs); return eArgs.Reply; } return reply; } #endregion } }<file_sep>/web/studio/ASC.Web.Studio/HttpHandlers/KeepSessionAliveHandler.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Web; using System.Web.SessionState; namespace ASC.Web.Studio.HttpHandlers { /// <summary> /// This method is called from common.js file when document is loaded and the page contains FCKEditor. /// It is used to keep session alive while FCKEditor is opened and not empty. /// </summary> public class KeepSessionAliveHandler : IHttpHandler, IRequiresSessionState { public void ProcessRequest(HttpContext context) { context.Session["KeepSessionAlive"] = DateTime.Now; } public bool IsReusable { get { return false; } } } }<file_sep>/common/ASC.Core.Common/Notify/ReplyToTagProvider.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Text.RegularExpressions; using ASC.Notify.Patterns; namespace ASC.Core.Common.Notify { /// <summary> /// Class that generates 'mail to' addresses to create new TeamLab entities from post client /// </summary> public static class ReplyToTagProvider { private static readonly Regex EntityType = new Regex(@"blog|forum.topic|event|photo|file|wiki|bookmark|project\.milestone|project\.task|project\.message"); private const string TagName = "replyto"; /// <summary> /// Creates 'replyto' tag that can be used to comment some TeamLab entity /// </summary> /// <param name="entity">Name of entity e.g. 'blog', 'project.task', etc.</param> /// <param name="entityId">Uniq id of the entity</param> /// <returns>New TeamLab tag</returns> public static TagValue Comment(string entity, string entityId) { return Comment(entity, entityId, null); } /// <summary> /// Creates 'replyto' tag that can be used to comment some TeamLab entity /// </summary> /// <param name="entity">Name of entity e.g. 'blog', 'project.task', etc.</param> /// <param name="entityId">Uniq id of the entity</param> /// <param name="parentId">Comment's parent comment id</param> /// <returns>New TeamLab tag</returns> public static TagValue Comment(string entity, string entityId, string parentId) { if (String.IsNullOrEmpty(entity) || !EntityType.Match(entity).Success) throw new ArgumentException(@"Not supported entity type", entity); if (String.IsNullOrEmpty(entityId)) throw new ArgumentException(@"Entity Id is null or empty", entityId); string pId = parentId != Guid.Empty.ToString() && parentId != null ? parentId : String.Empty; return new TagValue(TagName, String.Format("reply_{0}_{1}_{2}@{3}", entity, entityId, pId, AutoreplyDomain)); } /// <summary> /// Creates 'replyto' tag that can be used to create TeamLab project message /// </summary> /// <param name="projectId">Id of the project to create message</param> /// <returns>New TeamLab tag</returns> public static TagValue Message(int projectId) { return new TagValue(TagName, String.Format("message_{0}@{1}", projectId, AutoreplyDomain)); } private static string AutoreplyDomain { get { // we use mapped domains for standalone portals because it is the only way to reach autoreply service // mapped domains are no allowed for SAAS because of http(s) problem var tenant = CoreContext.TenantManager.GetCurrentTenant(); return tenant.GetTenantDomain(CoreContext.Configuration.Standalone); } } } } <file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/_Obsolete/SIP_Target.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections.Generic; using System.Text; namespace LumiSoft.Net.SIP.Stack { /// <summary> /// This class represents remote SIP target info. /// </summary> public class SIP_Target { private SIP_EndPointInfo m_pLocalEndPoint = null; private string m_Transport = SIP_Transport.UDP; private string m_Host = ""; private int m_Port = 5060; /// <summary> /// Default constructor. /// </summary> /// <param name="transport">Transport to use.</param> /// <param name="host">Host name or IP.</param> /// <param name="port">Host port.</param> public SIP_Target(string transport,string host,int port) { m_Transport = transport; m_Host = host; m_Port = port; } /// <summary> /// Default constructor. /// </summary> /// <param name="destination">Remote destination URI.</param> public SIP_Target(SIP_Uri destination) : this(null,destination) { } /// <summary> /// Default constructor. /// </summary> /// <param name="localEP">Local end point to use to connect remote destination.</param> /// <param name="destination">Remote destination URI.</param> public SIP_Target(SIP_EndPointInfo localEP,SIP_Uri destination) { m_pLocalEndPoint = localEP; if(destination.Param_Transport != null){ m_Transport = destination.Param_Transport; } else{ // If SIPS, use always TLS. if(destination.IsSecure){ m_Transport = SIP_Transport.TLS; } else{ m_Transport = SIP_Transport.UDP; } } m_Host = destination.Host; if(destination.Port != -1){ m_Port = destination.Port; } else{ if(m_Transport == SIP_Transport.TLS){ m_Port = 5061; } else{ m_Port = 5060; } } } #region Properties Implementation /// <summary> /// Gets local destination to use to connect remote destination. /// Value null means not specified. NOTE This is used only by UDP. /// </summary> public SIP_EndPointInfo LocalEndPoint { get{ return m_pLocalEndPoint; } } /// <summary> /// Gets transport to use. /// </summary> public string Transport { get{ return m_Transport; } } /// <summary> /// Gets remote host name or IP address. /// </summary> public string Host { get{ return m_Host; } } /// <summary> /// Gets remote host port. /// </summary> public int Port { get{ return m_Port; } } #endregion } } <file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/Multilang/IMLangStringWStr.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #pragma warning disable 0108 namespace MultiLanguage { using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Security; [ComImport, InterfaceType((short) 1), ComConversionLoss, Guid("C04D65D0-B70D-11D0-B188-00AA0038C969")] public interface IMLangStringWStr : IMLangString { [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void Sync([In] int fNoAccess); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] int GetLength(); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void SetMLStr([In] int lDestPos, [In] int lDestLen, [In, MarshalAs(UnmanagedType.IUnknown)] object pSrcMLStr, [In] int lSrcPos, [In] int lSrcLen); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetMLStr([In] int lSrcPos, [In] int lSrcLen, [In, MarshalAs(UnmanagedType.IUnknown)] object pUnkOuter, [In] uint dwClsContext, [In] ref Guid piid, [MarshalAs(UnmanagedType.IUnknown)] out object ppDestMLStr, out int plDestPos, out int plDestLen); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void SetWStr([In] int lDestPos, [In] int lDestLen, [In] ref ushort pszSrc, [In] int cchSrc, out int pcchActual, out int plActualLen); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void SetStrBufW([In] int lDestPos, [In] int lDestLen, [In, MarshalAs(UnmanagedType.Interface)] IMLangStringBufW pSrcBuf, out int pcchActual, out int plActualLen); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetWStr([In] int lSrcPos, [In] int lSrcLen, out ushort pszDest, [In] int cchDest, out int pcchActual, out int plActualLen); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetStrBufW([In] int lSrcPos, [In] int lSrcMaxLen, [MarshalAs(UnmanagedType.Interface)] out IMLangStringBufW ppDestBuf, out int plDestLen); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void LockWStr([In] int lSrcPos, [In] int lSrcLen, [In] int lFlags, [In] int cchRequest, [Out] IntPtr ppszDest, out int pcchDest, out int plDestLen); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void UnlockWStr([In] ref ushort pszSrc, [In] int cchSrc, out int pcchActual, out int plActualLen); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void SetLocale([In] int lDestPos, [In] int lDestLen, [In] uint locale); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetLocale([In] int lSrcPos, [In] int lSrcMaxLen, out uint plocale, out int plLocalePos, out int plLocaleLen); } } #pragma warning restore 0108<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/AUTH/AuthType.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; namespace LumiSoft.Net.AUTH { /// <summary> /// Authentication type. /// </summary> public enum AuthType { /// <summary> /// Clear text username/password authentication. /// </summary> PLAIN = 0, /// <summary> /// APOP.This is used by POP3 only. RFC 1939 7. APOP. /// </summary> APOP = 1, /// <summary> /// CRAM-MD5 authentication. RFC 2195 AUTH CRAM-MD5. /// </summary> CRAM_MD5 = 3, /// <summary> /// DIGEST-MD5 authentication. RFC 2831 AUTH DIGEST-MD5. /// </summary> DIGEST_MD5 = 4, } } <file_sep>/module/ASC.Socket.IO/app/portalManager.js const portalInternalUrl = require('../config').get("portal.internal.url") module.exports = (req) => { if(portalInternalUrl) return portalInternalUrl; const xRewriterUrlInternalHeader = 'x-rewriter-url-internal'; if (req.headers && req.headers[xRewriterUrlInternalHeader]) { return req.headers[xRewriterUrlInternalHeader]; } const xRewriterUrlHeader = 'x-rewriter-url'; if (req.headers && req.headers[xRewriterUrlHeader]) { return req.headers[xRewriterUrlHeader]; } return ""; };<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/MIME/MIME_h_Provider.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.MIME { #region usings using System; using System.Collections.Generic; #endregion /// <summary> /// This class represents MIME headers provider. /// </summary> public class MIME_h_Provider { #region Members private readonly Dictionary<string, Type> m_pHeadrFields; private Type m_pDefaultHeaderField; #endregion #region Properties /// <summary> /// Gets or sets default header field what is used to reperesent unknown header fields. /// </summary> /// <remarks>This property value value must be based on <see cref="MIME_h"/> class.</remarks> /// <exception cref="ArgumentNullException">Is raised when null reference passed.</exception> /// <exception cref="ArgumentException">Is raised when invalid value is passed.</exception> public Type DefaultHeaderField { get { return m_pDefaultHeaderField; } set { if (value == null) { throw new ArgumentNullException("DefaultHeaderField"); } if (!value.GetType().IsSubclassOf(typeof (MIME_h))) { throw new ArgumentException( "Property 'DefaultHeaderField' value must be based on MIME_h class."); } m_pDefaultHeaderField = value; } } /// <summary> /// Gets header fields parsers collection. /// </summary> public Dictionary<string, Type> HeaderFields { get { return m_pHeadrFields; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> public MIME_h_Provider() { m_pDefaultHeaderField = typeof (MIME_h_Unstructured); m_pHeadrFields = new Dictionary<string, Type>(StringComparer.CurrentCultureIgnoreCase); m_pHeadrFields.Add("content-type", typeof (MIME_h_ContentType)); m_pHeadrFields.Add("content-disposition", typeof (MIME_h_ContentDisposition)); //BUG: was there } #endregion #region Methods /// <summary> /// Parses specified header field. /// </summary> /// <param name="field">Header field string (Name: value).</param> /// <returns>Returns parsed header field.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>field</b> is null reference.</exception> /// <exception cref="ParseException">Is raised when header field parsing errors.</exception> public MIME_h Parse(string field) { if (field == null) { throw new ArgumentNullException("field"); } MIME_h headerField = null; string[] name_value = field.Split(new[] {':'}, 2); string name = name_value[0].Trim().ToLowerInvariant(); if (name == string.Empty) { throw new ParseException("Invalid header field value '" + field + "'."); } else { try { if (m_pHeadrFields.ContainsKey(name)) { headerField = (MIME_h) m_pHeadrFields[name].GetMethod("Parse").Invoke(null, new object[] {field}); } else { headerField = (MIME_h) m_pDefaultHeaderField.GetMethod("Parse").Invoke(null, new object[] {field}); } } catch (Exception x) { headerField = new MIME_h_Unparsed(field, x.InnerException); } } return headerField; } #endregion } }<file_sep>/module/ASC.MessagingSystem/MessageTarget.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections.Generic; using System.Linq; using ASC.Common.Logging; namespace ASC.MessagingSystem { public class MessageTarget { private IEnumerable<string> _items; public static MessageTarget Create<T>(T value) { try { var res = new List<string>(); var ids = value as System.Collections.IEnumerable; if (ids != null) { res.AddRange(from object id in ids select id.ToString()); } else { res.Add(value.ToString()); } return new MessageTarget { _items = res.Distinct() }; } catch (Exception e) { LogManager.GetLogger("ASC.Messaging").Error("EventMessageTarget exception", e); return null; } } public static MessageTarget Parse(string value) { if (string.IsNullOrEmpty(value)) return null; var items = value.Split(','); if (!items.Any()) return null; return new MessageTarget { _items = items }; } public override string ToString() { return string.Join(",", _items); } } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/RTP/RTCP_Packet_SR.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.RTP { #region usings using System; using System.Collections.Generic; #endregion /// <summary> /// This class represents SR: Sender Report RTCP Packet. /// </summary> public class RTCP_Packet_SR : RTCP_Packet { #region Members private readonly List<RTCP_Packet_ReportBlock> m_pReportBlocks; private ulong m_NtpTimestamp; private uint m_RtpTimestamp; private uint m_SenderOctetCount; private uint m_SenderPacketCount; private uint m_SSRC; private int m_Version = 2; #endregion #region Properties /// <summary> /// Gets RTCP version. /// </summary> public override int Version { get { return m_Version; } } /// <summary> /// Gets RTCP packet type. /// </summary> public override int Type { get { return RTCP_PacketType.SR; } } /// <summary> /// Gets sender synchronization source identifier. /// </summary> public uint SSRC { get { return m_SSRC; } } /// <summary> /// Gets or sets the wallclock time (see Section 4) when this report was sent. /// </summary> public ulong NtpTimestamp { get { return m_NtpTimestamp; } set { m_NtpTimestamp = value; } } /// <summary> /// Gets RTP timestamp. /// </summary> public uint RtpTimestamp { get { return m_RtpTimestamp; } set { m_RtpTimestamp = value; } } /// <summary> /// Gets how many packets sender has sent. /// </summary> public uint SenderPacketCount { get { return m_SenderPacketCount; } set { m_SenderPacketCount = value; } } /// <summary> /// Gets how many bytes sender has sent. /// </summary> public uint SenderOctetCount { get { return m_SenderOctetCount; } set { m_SenderOctetCount = value; } } /// <summary> /// Gets reports blocks. /// </summary> public List<RTCP_Packet_ReportBlock> ReportBlocks { get { return m_pReportBlocks; } } /// <summary> /// Gets number of bytes needed for this packet. /// </summary> public override int Size { get { return 28 + (24*m_pReportBlocks.Count); } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="ssrc">Source(sender) ID.</param> internal RTCP_Packet_SR(uint ssrc) { m_SSRC = ssrc; m_pReportBlocks = new List<RTCP_Packet_ReportBlock>(); } /// <summary> /// Default constructor. /// </summary> internal RTCP_Packet_SR() { m_pReportBlocks = new List<RTCP_Packet_ReportBlock>(); } #endregion #region Methods /// <summary> /// Stores sender report(SR) packet to the specified buffer. /// </summary> /// <param name="buffer">Buffer where to store SR packet.</param> /// <param name="offset">Offset in buffer.</param> /// <exception cref="ArgumentNullException">Is raised when <b>buffer</b> is null.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> public override void ToByte(byte[] buffer, ref int offset) { /* RFC 3550 6.4.1 SR: Sender Report RTCP Packet. 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ header |V=2|P| RC | PT=SR=200 | length | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | SSRC of sender | +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ sender | NTP timestamp, most significant word | info +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | NTP timestamp, least significant word | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | RTP timestamp | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | sender's packet count | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | sender's octet count | +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ report | SSRC_1 (SSRC of first source) | block +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 1 | fraction lost | cumulative number of packets lost | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | extended highest sequence number received | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | interarrival jitter | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | last SR (LSR) | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | delay since last SR (DLSR) | +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ report | SSRC_2 (SSRC of second source) | block +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 2 : ... : +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ | profile-specific extensions | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ if (buffer == null) { throw new ArgumentNullException("buffer"); } if (offset < 0) { throw new ArgumentException("Argument 'offset' value must be >= 0."); } // NOTE: Size in 32-bit boundary, header not included. int length = (24 + (m_pReportBlocks.Count*24))/4; // V P RC buffer[offset++] = (byte) (2 << 6 | 0 << 5 | (m_pReportBlocks.Count & 0x1F)); // PT=SR=200 buffer[offset++] = 200; // length buffer[offset++] = (byte) ((length >> 8) & 0xFF); buffer[offset++] = (byte) ((length) & 0xFF); // SSRC buffer[offset++] = (byte) ((m_SSRC >> 24) & 0xFF); buffer[offset++] = (byte) ((m_SSRC >> 16) & 0xFF); buffer[offset++] = (byte) ((m_SSRC >> 8) & 0xFF); buffer[offset++] = (byte) ((m_SSRC) & 0xFF); // NTP timestamp buffer[offset++] = (byte) ((m_NtpTimestamp >> 56) & 0xFF); buffer[offset++] = (byte) ((m_NtpTimestamp >> 48) & 0xFF); buffer[offset++] = (byte) ((m_NtpTimestamp >> 40) & 0xFF); buffer[offset++] = (byte) ((m_NtpTimestamp >> 32) & 0xFF); buffer[offset++] = (byte) ((m_NtpTimestamp >> 24) & 0xFF); buffer[offset++] = (byte) ((m_NtpTimestamp >> 16) & 0xFF); buffer[offset++] = (byte) ((m_NtpTimestamp >> 8) & 0xFF); buffer[offset++] = (byte) ((m_NtpTimestamp) & 0xFF); // RTP timestamp buffer[offset++] = (byte) ((m_RtpTimestamp >> 24) & 0xFF); buffer[offset++] = (byte) ((m_RtpTimestamp >> 16) & 0xFF); buffer[offset++] = (byte) ((m_RtpTimestamp >> 8) & 0xFF); buffer[offset++] = (byte) ((m_RtpTimestamp) & 0xFF); // sender's packet count buffer[offset++] = (byte) ((m_SenderPacketCount >> 24) & 0xFF); buffer[offset++] = (byte) ((m_SenderPacketCount >> 16) & 0xFF); buffer[offset++] = (byte) ((m_SenderPacketCount >> 8) & 0xFF); buffer[offset++] = (byte) ((m_SenderPacketCount) & 0xFF); // sender's octet count buffer[offset++] = (byte) ((m_SenderOctetCount >> 24) & 0xFF); buffer[offset++] = (byte) ((m_SenderOctetCount >> 16) & 0xFF); buffer[offset++] = (byte) ((m_SenderOctetCount >> 8) & 0xFF); buffer[offset++] = (byte) ((m_SenderOctetCount) & 0xFF); // Report blocks foreach (RTCP_Packet_ReportBlock block in m_pReportBlocks) { block.ToByte(buffer, ref offset); } } #endregion #region Overrides /// <summary> /// Parses RTCP sender report(SR) from specified data buffer. /// </summary> /// <param name="buffer">Buffer which contains sender report.</param> /// <param name="offset">Offset in buffer.</param> /// <exception cref="ArgumentNullException">Is raised when <b>buffer</b> is null.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> protected override void ParseInternal(byte[] buffer, ref int offset) { /* RFC 3550 6.4.1 SR: Sender Report RTCP Packet. 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ header |V=2|P| RC | PT=SR=200 | length | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | SSRC of sender | +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ sender | NTP timestamp, most significant word | info +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | NTP timestamp, least significant word | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | RTP timestamp | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | sender's packet count | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | sender's octet count | +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ report | SSRC_1 (SSRC of first source) | block +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 1 | fraction lost | cumulative number of packets lost | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | extended highest sequence number received | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | interarrival jitter | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | last SR (LSR) | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | delay since last SR (DLSR) | +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ report | SSRC_2 (SSRC of second source) | block +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 2 : ... : +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ | profile-specific extensions | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ if (buffer == null) { throw new ArgumentNullException("buffer"); } if (offset < 0) { throw new ArgumentException("Argument 'offset' value must be >= 0."); } m_Version = buffer[offset] >> 6; bool isPadded = Convert.ToBoolean((buffer[offset] >> 5) & 0x1); int reportBlockCount = buffer[offset++] & 0x1F; int type = buffer[offset++]; int length = buffer[offset++] << 8 | buffer[offset++]; if (isPadded) { PaddBytesCount = buffer[offset + length]; } m_SSRC = (uint) (buffer[offset++] << 24 | buffer[offset++] << 16 | buffer[offset++] << 8 | buffer[offset++]); m_NtpTimestamp = (ulong) (buffer[offset++] << 56 | buffer[offset++] << 48 | buffer[offset++] << 40 | buffer[offset++] << 32 | buffer[offset++] << 24 | buffer[offset++] << 16 | buffer[offset++] << 8 | buffer[offset++]); m_RtpTimestamp = (uint) (buffer[offset++] << 24 | buffer[offset++] << 16 | buffer[offset++] << 8 | buffer[offset++]); m_SenderPacketCount = (uint) (buffer[offset++] << 24 | buffer[offset++] << 16 | buffer[offset++] << 8 | buffer[offset++]); m_SenderOctetCount = (uint) (buffer[offset++] << 24 | buffer[offset++] << 16 | buffer[offset++] << 8 | buffer[offset++]); for (int i = 0; i < reportBlockCount; i++) { RTCP_Packet_ReportBlock reportBlock = new RTCP_Packet_ReportBlock(); reportBlock.Parse(buffer, offset); m_pReportBlocks.Add(reportBlock); offset += 24; } } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/DNS/Client/DNS_rr_SRV.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.Dns.Client { #region usings using System; #endregion /// <summary> /// DNS SRV record. SRV record specifies the location of services. Defined in RFC 2782. /// </summary> [Serializable] public class DNS_rr_SRV : DNS_rr_base { #region Members private readonly int m_Port; private readonly int m_Priority = 1; private readonly string m_Target = ""; private readonly int m_Weight = 1; #endregion #region Properties /// <summary> /// Gets service priority. Lowest value means greater priority. /// </summary> public int Priority { get { return m_Priority; } } /// <summary> /// Gets weight. The weight field specifies a relative weight for entries with the same priority. /// Larger weights SHOULD be given a proportionately higher probability of being selected. /// </summary> public int Weight { get { return m_Weight; } } /// <summary> /// Port where service runs. /// </summary> public int Port { get { return m_Port; } } /// <summary> /// Service provider host name or IP address. /// </summary> public string Target { get { return m_Target; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="priority">Service priority.</param> /// <param name="weight">Weight value.</param> /// <param name="port">Service port.</param> /// <param name="target">Service provider host name or IP address.</param> /// <param name="ttl">Time to live value in seconds.</param> public DNS_rr_SRV(int priority, int weight, int port, string target, int ttl) : base(QTYPE.SRV, ttl) { m_Priority = priority; m_Weight = weight; m_Port = port; m_Target = target; } #endregion #region Methods /// <summary> /// Parses resource record from reply data. /// </summary> /// <param name="reply">DNS server reply data.</param> /// <param name="offset">Current offset in reply data.</param> /// <param name="rdLength">Resource record data length.</param> /// <param name="ttl">Time to live in seconds.</param> public static DNS_rr_SRV Parse(byte[] reply, ref int offset, int rdLength, int ttl) { // Priority Weight Port Target // Priority int priority = reply[offset++] << 8 | reply[offset++]; // Weight int weight = reply[offset++] << 8 | reply[offset++]; // Port int port = reply[offset++] << 8 | reply[offset++]; // Target string target = ""; Dns_Client.GetQName(reply, ref offset, ref target); return new DNS_rr_SRV(priority, weight, port, target, ttl); } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/SIP/Message/SIP_t_Directive.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.SIP.Message { #region usings using System; #endregion /// <summary> /// Implements SIP "directive" value. Defined in RFC 3841. /// </summary> /// <remarks> /// <code> /// RFC 3841 Syntax: /// directive = proxy-directive / cancel-directive / fork-directive / recurse-directive / /// parallel-directive / queue-directive /// proxy-directive = "proxy" / "redirect" /// cancel-directive = "cancel" / "no-cancel" /// fork-directive = "fork" / "no-fork" /// recurse-directive = "recurse" / "no-recurse" /// parallel-directive = "parallel" / "sequential" /// queue-directive = "queue" / "no-queue" /// </code> /// </remarks> public class SIP_t_Directive : SIP_t_Value { #region DirectiveType enum /// <summary> /// Proccess directives. Defined in rfc 3841 9.1. /// </summary> public enum DirectiveType { /// <summary> /// This directive indicates whether the caller would like each server to proxy request. /// </summary> Proxy, /// <summary> /// This directive indicates whether the caller would like each server to redirect request. /// </summary> Redirect, /// <summary> /// This directive indicates whether the caller would like each proxy server to send a CANCEL /// request to forked branches. /// </summary> Cancel, /// <summary> /// This directive indicates whether the caller would NOT want each proxy server to send a CANCEL /// request to forked branches. /// </summary> NoCancel, /// <summary> /// This type of directive indicates whether a proxy should fork a request. /// </summary> Fork, /// <summary> /// This type of directive indicates whether a proxy should proxy to only a single address. /// The server SHOULD proxy the request to the "best" address (generally the one with the highest q-value). /// </summary> NoFork, /// <summary> /// This directive indicates whether a proxy server receiving a 3xx response should send /// requests to the addresses listed in the response. /// </summary> Recurse, /// <summary> /// This directive indicates whether a proxy server receiving a 3xx response should forward /// the list of addresses upstream towards the caller. /// </summary> NoRecurse, /// <summary> /// This directive indicates whether the caller would like the proxy server to proxy /// the request to all known addresses at once. /// </summary> Parallel, /// <summary> /// This directive indicates whether the caller would like the proxy server to go through /// all known addresses sequentially, contacting the next address only after it has received /// a non-2xx or non-6xx final response for the previous one. /// </summary> Sequential, /// <summary> /// This directive indicates whether if the called party is temporarily unreachable, caller /// wants to have its call queued. /// </summary> Queue, /// <summary> /// This directive indicates whether if the called party is temporarily unreachable, caller /// don't want its call to be queued. /// </summary> NoQueue } #endregion #region Members private DirectiveType m_Directive = DirectiveType.Fork; #endregion #region Properties /// <summary> /// Gets or sets directive. /// </summary> public DirectiveType Directive { get { return m_Directive; } set { m_Directive = value; } } #endregion #region Methods /// <summary> /// Parses "directive" from specified value. /// </summary> /// <param name="value">SIP "directive" value.</param> /// <exception cref="ArgumentNullException">Raised when <b>value</b> is null.</exception> /// <exception cref="SIP_ParseException">Raised when invalid SIP message.</exception> public void Parse(string value) { if (value == null) { throw new ArgumentNullException("value"); } Parse(new StringReader(value)); } /// <summary> /// Parses "directive" from specified reader. /// </summary> /// <param name="reader">Reader from where to parse.</param> /// <exception cref="ArgumentNullException">Raised when <b>reader</b> is null.</exception> /// <exception cref="SIP_ParseException">Raised when invalid SIP message.</exception> public override void Parse(StringReader reader) { /* directive = proxy-directive / cancel-directive / fork-directive / recurse-directive / parallel-directive / queue-directive proxy-directive = "proxy" / "redirect" cancel-directive = "cancel" / "no-cancel" fork-directive = "fork" / "no-fork" recurse-directive = "recurse" / "no-recurse" parallel-directive = "parallel" / "sequential" queue-directive = "queue" / "no-queue" */ if (reader == null) { throw new ArgumentNullException("reader"); } // Get Method string word = reader.ReadWord(); if (word == null) { throw new SIP_ParseException("'directive' value is missing !"); } if (word.ToLower() == "proxy") { m_Directive = DirectiveType.Proxy; } else if (word.ToLower() == "redirect") { m_Directive = DirectiveType.Redirect; } else if (word.ToLower() == "cancel") { m_Directive = DirectiveType.Cancel; } else if (word.ToLower() == "no-cancel") { m_Directive = DirectiveType.NoCancel; } else if (word.ToLower() == "fork") { m_Directive = DirectiveType.Fork; } else if (word.ToLower() == "no-fork") { m_Directive = DirectiveType.NoFork; } else if (word.ToLower() == "recurse") { m_Directive = DirectiveType.Recurse; } else if (word.ToLower() == "no-recurse") { m_Directive = DirectiveType.NoRecurse; } else if (word.ToLower() == "parallel") { m_Directive = DirectiveType.Parallel; } else if (word.ToLower() == "sequential") { m_Directive = DirectiveType.Sequential; } else if (word.ToLower() == "queue") { m_Directive = DirectiveType.Queue; } else if (word.ToLower() == "no-queue") { m_Directive = DirectiveType.NoQueue; } else { throw new SIP_ParseException("Invalid 'directive' value !"); } } /// <summary> /// Converts this to valid "directive" value. /// </summary> /// <returns>Returns "directive" value.</returns> public override string ToStringValue() { /* directive = proxy-directive / cancel-directive / fork-directive / recurse-directive / parallel-directive / queue-directive proxy-directive = "proxy" / "redirect" cancel-directive = "cancel" / "no-cancel" fork-directive = "fork" / "no-fork" recurse-directive = "recurse" / "no-recurse" parallel-directive = "parallel" / "sequential" queue-directive = "queue" / "no-queue" */ if (m_Directive == DirectiveType.Proxy) { return "proxy"; } else if (m_Directive == DirectiveType.Redirect) { return "redirect"; } else if (m_Directive == DirectiveType.Cancel) { return "cancel"; } else if (m_Directive == DirectiveType.NoCancel) { return "no-cancel"; } else if (m_Directive == DirectiveType.Fork) { return "fork"; } else if (m_Directive == DirectiveType.NoFork) { return "no-fork"; } else if (m_Directive == DirectiveType.Recurse) { return "recurse"; } else if (m_Directive == DirectiveType.NoRecurse) { return "no-recurse"; } else if (m_Directive == DirectiveType.Parallel) { return "parallel"; } else if (m_Directive == DirectiveType.Sequential) { return "sequential"; } else if (m_Directive == DirectiveType.Queue) { return "queue"; } else if (m_Directive == DirectiveType.NoQueue) { return "no-queue"; } else { throw new ArgumentException("Invalid property Directive value, this should never happen !"); } } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/vCard/DeliveryAddressCollection.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.Mime.vCard { #region usings using System.Collections; using System.Collections.Generic; #endregion /// <summary> /// vCard delivery address collection implementation. /// </summary> public class DeliveryAddressCollection : IEnumerable { #region Members private readonly List<DeliveryAddress> m_pCollection; private readonly vCard m_pOwner; #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="owner">Owner vCard.</param> internal DeliveryAddressCollection(vCard owner) { m_pOwner = owner; m_pCollection = new List<DeliveryAddress>(); foreach (Item item in owner.Items.Get("ADR")) { m_pCollection.Add(DeliveryAddress.Parse(item)); } } #endregion #region Properties /// <summary> /// Gets number of items in the collection. /// </summary> public int Count { get { return m_pCollection.Count; } } /// <summary> /// Gets item at the specified index. /// </summary> /// <param name="index">Index of item which to get.</param> /// <returns></returns> public DeliveryAddress this[int index] { get { return m_pCollection[index]; } } #endregion #region Methods /// <summary> /// Add new delivery address to the collection. /// </summary> /// <param name="type">Delivery address type. Note: This value can be flagged value !</param> /// <param name="postOfficeAddress">Post office address.</param> /// <param name="extendedAddress">Extended address.</param> /// <param name="street">Street name.</param> /// <param name="locality">Locality(city).</param> /// <param name="region">Region.</param> /// <param name="postalCode">Postal code.</param> /// <param name="country">Country.</param> public void Add(DeliveryAddressType_enum type, string postOfficeAddress, string extendedAddress, string street, string locality, string region, string postalCode, string country) { string value = "" + postOfficeAddress + ";" + extendedAddress + ";" + street + ";" + locality + ";" + region + ";" + postalCode + ";" + country; Item item = m_pOwner.Items.Add("ADR", DeliveryAddress.AddressTypeToString(type), ""); item.SetDecodedValue(value); m_pCollection.Add(new DeliveryAddress(item, type, postOfficeAddress, extendedAddress, street, locality, region, postalCode, country)); } /// <summary> /// Removes specified item from the collection. /// </summary> /// <param name="item">Item to remove.</param> public void Remove(DeliveryAddress item) { m_pOwner.Items.Remove(item.Item); m_pCollection.Remove(item); } /// <summary> /// Removes all items from the collection. /// </summary> public void Clear() { foreach (DeliveryAddress email in m_pCollection) { m_pOwner.Items.Remove(email.Item); } m_pCollection.Clear(); } /// <summary> /// Gets enumerator. /// </summary> /// <returns></returns> public IEnumerator GetEnumerator() { return m_pCollection.GetEnumerator(); } #endregion } }<file_sep>/web/studio/ASC.Web.Studio/js/asc/plugins/countries.js /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ var CountriesManager = new function () { var countriesList = [ { title: ASC.Resources.Countries.Afghanistan, key: "AF", country_code: "+93" }, { title: ASC.Resources.Countries.Albania, key: "AL", country_code: "+355" }, { title: ASC.Resources.Countries.Algeria, key: "DZ", country_code: "+213" }, { title: ASC.Resources.Countries.AmericanSamoa, key: "AS", country_code: "+1684" }, { title: ASC.Resources.Countries.Andorra, key: "AD", country_code: "+376" }, { title: ASC.Resources.Countries.Angola, key: "AO", country_code: "+244" }, { title: ASC.Resources.Countries.Anguilla, key: "AI", country_code: "+1264" }, { title: ASC.Resources.Countries.AntiguaAndBarbuda, key: "AG", country_code: "+1268" }, { title: ASC.Resources.Countries.Argentina, key: "AR", country_code: "+54" }, { title: ASC.Resources.Countries.Armenia, key: "AM", country_code: "+374" }, { title: ASC.Resources.Countries.Aruba, key: "AW", country_code: "+297" }, { title: ASC.Resources.Countries.AscensionIsland, key: "AC", country_code: "+247" }, { title: ASC.Resources.Countries.Australia, key: "AU", country_code: "+61" }, { title: ASC.Resources.Countries.Austria, key: "AT", country_code: "+43", vat: true }, { title: ASC.Resources.Countries.Azerbaijan, key: "AZ", country_code: "+994" }, { title: ASC.Resources.Countries.Bahamas, key: "BS", country_code: "+1242" }, { title: ASC.Resources.Countries.Bahrain, key: "BH", country_code: "+973" }, { title: ASC.Resources.Countries.Bangladesh, key: "BD", country_code: "+880" }, { title: ASC.Resources.Countries.Barbados, key: "BB", country_code: "+1246" }, { title: ASC.Resources.Countries.Belarus, key: "BY", country_code: "+375" }, { title: ASC.Resources.Countries.Belgium, key: "BE", country_code: "+32", vat: true }, { title: ASC.Resources.Countries.Belize, key: "BZ", country_code: "+501" }, { title: ASC.Resources.Countries.Benin, key: "BJ", country_code: "+229" }, { title: ASC.Resources.Countries.Bermuda, key: "BM", country_code: "+1441" }, { title: ASC.Resources.Countries.Bhutan, key: "BT", country_code: "+975" }, { title: ASC.Resources.Countries.Bolivia, key: "BO", country_code: "+591" }, { title: ASC.Resources.Countries.BonaireSintEustatiusAndSaba, key: "BQ", country_code: "+599" }, { title: ASC.Resources.Countries.BosniaAndHerzegovina, key: "BA", country_code: "+387" }, { title: ASC.Resources.Countries.Botswana, key: "BW", country_code: "+267" }, { title: ASC.Resources.Countries.Brazil, key: "BR", country_code: "+55" }, { title: ASC.Resources.Countries.BritishIndianOceanTerritory, key: "IO", country_code: "+246" }, { title: ASC.Resources.Countries.BritishVirginIslands, key: "VG", country_code: "+1284" }, { title: ASC.Resources.Countries.BruneiDarussalam, key: "BN", country_code: "+673" }, { title: ASC.Resources.Countries.Bulgaria, key: "BG", country_code: "+359", vat: true }, { title: ASC.Resources.Countries.BurkinaFaso, key: "BF", country_code: "+226" }, { title: ASC.Resources.Countries.Burundi, key: "BI", country_code: "+257" }, { title: ASC.Resources.Countries.Cambodia, key: "KH", country_code: "+855" }, { title: ASC.Resources.Countries.Cameroon, key: "CM", country_code: "+237" }, { title: ASC.Resources.Countries.Canada, key: "CA", country_code: "+1" }, { title: ASC.Resources.Countries.CapeVerde, key: "CV", country_code: "+238" }, { title: ASC.Resources.Countries.CaymanIslands, key: "KY", country_code: "+1345" }, { title: ASC.Resources.Countries.CentralAfricanRepublic, key: "CF", country_code: "+236" }, { title: ASC.Resources.Countries.Chad, key: "TD", country_code: "+235" }, { title: ASC.Resources.Countries.Chile, key: "CL", country_code: "+56" }, { title: ASC.Resources.Countries.China, key: "CN", country_code: "+86" }, { title: ASC.Resources.Countries.Colombia, key: "CO", country_code: "+57" }, { title: ASC.Resources.Countries.Comoros, key: "KM", country_code: "+269" }, { title: ASC.Resources.Countries.CongoBrazzaville, key: "CG", country_code: "+242" }, { title: ASC.Resources.Countries.CookIslands, key: "CK", country_code: "+682" }, { title: ASC.Resources.Countries.CostaRica, key: "CR", country_code: "+506" }, { title: ASC.Resources.Countries.Croatia, key: "HR", country_code: "+385", vat: true }, { title: ASC.Resources.Countries.Cuba, key: "CU", country_code: "+53" }, { title: ASC.Resources.Countries.Curacao, key: "CW", country_code: "+599" }, { title: ASC.Resources.Countries.Cyprus, key: "CY", country_code: "+357", vat: true }, { title: ASC.Resources.Countries.CzechRepublic, key: "CZ", country_code: "+420", vat: true }, { title: ASC.Resources.Countries.Denmark, key: "DK", country_code: "+45", vat: true }, { title: ASC.Resources.Countries.Djibouti, key: "DJ", country_code: "+253" }, { title: ASC.Resources.Countries.Dominica, key: "DM", country_code: "+1767" }, { title: ASC.Resources.Countries.DominicanRepublic, key: "DO", country_code: "+1809" }, { title: ASC.Resources.Countries.Ecuador, key: "EC", country_code: "+593" }, { title: ASC.Resources.Countries.Egypt, key: "EG", country_code: "+20" }, { title: ASC.Resources.Countries.ElSalvador, key: "SV", country_code: "+503" }, { title: ASC.Resources.Countries.EquatorialGuinea, key: "GQ", country_code: "+240" }, { title: ASC.Resources.Countries.Eritrea, key: "ER", country_code: "+291" }, { title: ASC.Resources.Countries.Estonia, key: "EE", country_code: "+372", vat: true }, { title: ASC.Resources.Countries.Ethiopia, key: "ET", country_code: "+251" }, { title: ASC.Resources.Countries.FaroeIslands, key: "FO", country_code: "+298" }, { title: ASC.Resources.Countries.Fiji, key: "FJ", country_code: "+679" }, { title: ASC.Resources.Countries.Finland, key: "FI", country_code: "+358", vat: true }, { title: ASC.Resources.Countries.France, key: "FR", country_code: "+33", vat: true }, { title: ASC.Resources.Countries.FrenchGuiana, key: "GF", country_code: "+594" }, { title: ASC.Resources.Countries.FrenchPolynesia, key: "PF", country_code: "+689" }, { title: ASC.Resources.Countries.Gabon, key: "GA", country_code: "+241" }, { title: ASC.Resources.Countries.Gambia, key: "GM", country_code: "+220" }, { title: ASC.Resources.Countries.Georgia, key: "GE", country_code: "+995" }, { title: ASC.Resources.Countries.Germany, key: "DE", country_code: "+49", vat: true }, { title: ASC.Resources.Countries.Ghana, key: "GH", country_code: "+233" }, { title: ASC.Resources.Countries.Gibraltar, key: "GI", country_code: "+350" }, { title: ASC.Resources.Countries.Greece, key: "GR", country_code: "+30", vat: true }, { title: ASC.Resources.Countries.Greenland, key: "GL", country_code: "+299" }, { title: ASC.Resources.Countries.Grenada, key: "GD", country_code: "+1473" }, { title: ASC.Resources.Countries.Guadeloupe, key: "GP", country_code: "+590" }, { title: ASC.Resources.Countries.Guam, key: "GU", country_code: "+1671" }, { title: ASC.Resources.Countries.Guatemala, key: "GT", country_code: "+502" }, { title: ASC.Resources.Countries.Guinea, key: "GN", country_code: "+224" }, { title: ASC.Resources.Countries.GuineaBissau, key: "GW", country_code: "+245" }, { title: ASC.Resources.Countries.Guyana, key: "GY", country_code: "+592" }, { title: ASC.Resources.Countries.Haiti, key: "HT", country_code: "+509" }, { title: ASC.Resources.Countries.Honduras, key: "HN", country_code: "+504" }, { title: ASC.Resources.Countries.HongKong, key: "HK", country_code: "+852" }, { title: ASC.Resources.Countries.Hungary, key: "HU", country_code: "+36", vat: true }, { title: ASC.Resources.Countries.Iceland, key: "IS", country_code: "+354" }, { title: ASC.Resources.Countries.India, key: "IN", country_code: "+91" }, { title: ASC.Resources.Countries.Indonesia, key: "ID", country_code: "+62" }, { title: ASC.Resources.Countries.Iran, key: "IR", country_code: "+98" }, { title: ASC.Resources.Countries.Iraq, key: "IQ", country_code: "+964" }, { title: ASC.Resources.Countries.Ireland, key: "IE", country_code: "+353", vat: true }, { title: ASC.Resources.Countries.Israel, key: "IL", country_code: "+972" }, { title: ASC.Resources.Countries.Italy, key: "IT", country_code: "+39", vat: true }, { title: ASC.Resources.Countries.IvoryCoast, key: "CI", country_code: "+225" }, { title: ASC.Resources.Countries.Jamaica, key: "JM", country_code: "+1876" }, { title: ASC.Resources.Countries.Japan, key: "JP", country_code: "+81" }, { title: ASC.Resources.Countries.Jordan, key: "JO", country_code: "+962" }, { title: ASC.Resources.Countries.Kazakhstan, key: "KZ", country_code: "+7" }, { title: ASC.Resources.Countries.Kenya, key: "KE", country_code: "+254" }, { title: ASC.Resources.Countries.Kiribati, key: "KI", country_code: "+686" }, { title: ASC.Resources.Countries.Kuwait, key: "KW", country_code: "+965" }, { title: ASC.Resources.Countries.Kyrgyzstan, key: "KG", country_code: "+996" }, { title: ASC.Resources.Countries.Laos, key: "LA", country_code: "+856" }, { title: ASC.Resources.Countries.Latvia, key: "LV", country_code: "+371", vat: true }, { title: ASC.Resources.Countries.Lebanon, key: "LB", country_code: "+961" }, { title: ASC.Resources.Countries.Lesotho, key: "LS", country_code: "+266" }, { title: ASC.Resources.Countries.Liberia, key: "LR", country_code: "+231" }, { title: ASC.Resources.Countries.Libya, key: "LY", country_code: "+218" }, { title: ASC.Resources.Countries.Liechtenstein, key: "LI", country_code: "+423" }, { title: ASC.Resources.Countries.Lithuania, key: "LT", country_code: "+370", vat: true }, { title: ASC.Resources.Countries.Luxembourg, key: "LU", country_code: "+352", vat: true }, { title: ASC.Resources.Countries.Macau, key: "MO", country_code: "+853" }, { title: ASC.Resources.Countries.Macedonia, key: "MK", country_code: "+389" }, { title: ASC.Resources.Countries.Madagascar, key: "MG", country_code: "+261" }, { title: ASC.Resources.Countries.Malawi, key: "MW", country_code: "+265" }, { title: ASC.Resources.Countries.Malaysia, key: "MY", country_code: "+60" }, { title: ASC.Resources.Countries.Maldives, key: "MV", country_code: "+960" }, { title: ASC.Resources.Countries.Mali, key: "ML", country_code: "+223" }, { title: ASC.Resources.Countries.Malta, key: "MT", country_code: "+356", vat: true }, { title: ASC.Resources.Countries.Malvinas, key: "FK", country_code: "+500" }, { title: ASC.Resources.Countries.MarshallIslands, key: "MH", country_code: "+692" }, { title: ASC.Resources.Countries.Martinique, key: "MQ", country_code: "+596" }, { title: ASC.Resources.Countries.Mauritania, key: "MR", country_code: "+222" }, { title: ASC.Resources.Countries.Mauritius, key: "MU", country_code: "+230" }, { title: ASC.Resources.Countries.Mexico, key: "MX", country_code: "+52" }, { title: ASC.Resources.Countries.Micronesia, key: "FM", country_code: "+691" }, { title: ASC.Resources.Countries.Moldova, key: "MD", country_code: "+373" }, { title: ASC.Resources.Countries.Monaco, key: "MC", country_code: "+377" }, { title: ASC.Resources.Countries.Mongolia, key: "MN", country_code: "+976" }, { title: ASC.Resources.Countries.Montenegro, key: "ME", country_code: "+382" }, { title: ASC.Resources.Countries.Montserrat, key: "MS", country_code: "+1664" }, { title: ASC.Resources.Countries.Morocco, key: "MA", country_code: "+212" }, { title: ASC.Resources.Countries.Mozambique, key: "MZ", country_code: "+258" }, { title: ASC.Resources.Countries.Myanmar, key: "MM", country_code: "+95" }, { title: ASC.Resources.Countries.Namibia, key: "NA", country_code: "+264" }, { title: ASC.Resources.Countries.Nauru, key: "NR", country_code: "+674" }, { title: ASC.Resources.Countries.Nepal, key: "NP", country_code: "+977" }, { title: ASC.Resources.Countries.Netherlands, key: "NL", country_code: "+31", vat: true }, { title: ASC.Resources.Countries.NewCaledonia, key: "NC", country_code: "+687" }, { title: ASC.Resources.Countries.NewZealand, key: "NZ", country_code: "+64" }, { title: ASC.Resources.Countries.Nicaragua, key: "NI", country_code: "+505" }, { title: ASC.Resources.Countries.Niger, key: "NE", country_code: "+227" }, { title: ASC.Resources.Countries.Nigeria, key: "NG", country_code: "+234" }, { title: ASC.Resources.Countries.Niue, key: "NU", country_code: "+683" }, { title: ASC.Resources.Countries.NorfolkIsland, key: "NF", country_code: "+6723" }, { title: ASC.Resources.Countries.NorthernMarianaIslands, key: "KP", country_code: "+1" }, { title: ASC.Resources.Countries.NorthKorea, key: "MP", country_code: "+850" }, { title: ASC.Resources.Countries.Norway, key: "NO", country_code: "+47" }, { title: ASC.Resources.Countries.Oman, key: "OM", country_code: "+968" }, { title: ASC.Resources.Countries.Pakistan, key: "PK", country_code: "+92" }, { title: ASC.Resources.Countries.Palau, key: "PW", country_code: "+680" }, { title: ASC.Resources.Countries.Palestine, key: "PS", country_code: "+970" }, { title: ASC.Resources.Countries.Panama, key: "PA", country_code: "+507" }, { title: ASC.Resources.Countries.PapuaNewGuinea, key: "PG", country_code: "+675" }, { title: ASC.Resources.Countries.Paraguay, key: "PY", country_code: "+595" }, { title: ASC.Resources.Countries.Peru, key: "PE", country_code: "+51" }, { title: ASC.Resources.Countries.Philippines, key: "PH", country_code: "+63" }, { title: ASC.Resources.Countries.Poland, key: "PL", country_code: "+48", vat: true }, { title: ASC.Resources.Countries.Portugal, key: "PT", country_code: "+351", vat: true }, { title: ASC.Resources.Countries.PuertoRico, key: "PR", country_code: "+1787" }, { title: ASC.Resources.Countries.Qatar, key: "QA", country_code: "+974" }, { title: ASC.Resources.Countries.RepublicOfKorea, key: "KR", country_code: "+82" }, { title: ASC.Resources.Countries.Reunion, key: "RE", country_code: "+262" }, { title: ASC.Resources.Countries.Romania, key: "RO", country_code: "+40", vat: true }, { title: ASC.Resources.Countries.Russia, key: "RU", country_code: "+7" }, { title: ASC.Resources.Countries.Rwanda, key: "RW", country_code: "+250" }, { title: ASC.Resources.Countries.SaintBarthelemy, key: "BL", country_code: "+590" }, { title: ASC.Resources.Countries.SaintHelena, key: "SH", country_code: "+290" }, { title: ASC.Resources.Countries.SaintKittsAndNevis, key: "KN", country_code: "+1869" }, { title: ASC.Resources.Countries.SaintLucia, key: "LC", country_code: "+1758" }, { title: ASC.Resources.Countries.SaintMartinIsland, key: "MF", country_code: "+590" }, { title: ASC.Resources.Countries.SaintPierreAndMiquelon, key: "PM", country_code: "+508" }, { title: ASC.Resources.Countries.SaintVincentAndTheGrenadines, key: "VC", country_code: "+1784" }, { title: ASC.Resources.Countries.Samoa, key: "WS", country_code: "+685" }, { title: ASC.Resources.Countries.SanMarino, key: "SM", country_code: "+378" }, { title: ASC.Resources.Countries.SaoTomeAndPrincipe, key: "ST", country_code: "+239" }, { title: ASC.Resources.Countries.SaudiArabia, key: "SA", country_code: "+966" }, { title: ASC.Resources.Countries.Senegal, key: "SN", country_code: "+221" }, { title: ASC.Resources.Countries.Serbia, key: "RS", country_code: "+381" }, { title: ASC.Resources.Countries.Seychelles, key: "SC", country_code: "+248" }, { title: ASC.Resources.Countries.SierraLeone, key: "SL", country_code: "+232" }, { title: ASC.Resources.Countries.Singapore, key: "SG", country_code: "+65" }, { title: ASC.Resources.Countries.SintMaarten, key: "SX", country_code: "+1721" }, { title: ASC.Resources.Countries.Slovakia, key: "SK", country_code: "+421", vat: true }, { title: ASC.Resources.Countries.Slovenia, key: "SI", country_code: "+386", vat: true }, { title: ASC.Resources.Countries.SolomonIslands, key: "SB", country_code: "+677" }, { title: ASC.Resources.Countries.Somalia, key: "SO", country_code: "+252" }, { title: ASC.Resources.Countries.SouthAfrica, key: "ZA", country_code: "+27" }, { title: ASC.Resources.Countries.SouthSudan, key: "SS", country_code: "+211" }, { title: ASC.Resources.Countries.Spain, key: "ES", country_code: "+34", vat: true }, { title: ASC.Resources.Countries.SriLanka, key: "LK", country_code: "+94" }, { title: ASC.Resources.Countries.Sudan, key: "SD", country_code: "+249" }, { title: ASC.Resources.Countries.Suriname, key: "SR", country_code: "+597" }, { title: ASC.Resources.Countries.Swaziland, key: "SZ", country_code: "+268" }, { title: ASC.Resources.Countries.Sweden, key: "SE", country_code: "+46", vat: true }, { title: ASC.Resources.Countries.Switzerland, key: "CH", country_code: "+41" }, { title: ASC.Resources.Countries.Syria, key: "SY", country_code: "+963" }, { title: ASC.Resources.Countries.Taiwan, key: "TW", country_code: "+886" }, { title: ASC.Resources.Countries.Tajikistan, key: "TJ", country_code: "+992" }, { title: ASC.Resources.Countries.Tanzania, key: "TZ", country_code: "+255" }, { title: ASC.Resources.Countries.Thailand, key: "TH", country_code: "+66" }, { title: ASC.Resources.Countries.TheDemocraticRepublicOfTheCongo, key: "CD", country_code: "+243" }, { title: ASC.Resources.Countries.TimorLeste, key: "TL", country_code: "+670" }, { title: ASC.Resources.Countries.Togo, key: "TG", country_code: "+228" }, { title: ASC.Resources.Countries.Tokelau, key: "TK", country_code: "+690" }, { title: ASC.Resources.Countries.Tonga, key: "TO", country_code: "+676" }, { title: ASC.Resources.Countries.TrinidadAndTobago, key: "TT", country_code: "+1868" }, { title: ASC.Resources.Countries.Tunisia, key: "TN", country_code: "+216" }, { title: ASC.Resources.Countries.Turkey, key: "TR", country_code: "+90" }, { title: ASC.Resources.Countries.Turkmenistan, key: "TM", country_code: "+993" }, { title: ASC.Resources.Countries.TurksAndCaicosIslands, key: "TC", country_code: "+1649" }, { title: ASC.Resources.Countries.Tuvalu, key: "TV", country_code: "+688" }, { title: ASC.Resources.Countries.UK, key: "GB", country_code: "+44", vat: true }, { title: ASC.Resources.Countries.USVirginIslands, key: "VI", country_code: "+1340" }, { title: ASC.Resources.Countries.Uganda, key: "UG", country_code: "+256" }, { title: ASC.Resources.Countries.Ukraine, key: "UA", country_code: "+380" }, { title: ASC.Resources.Countries.UnitedArabEmirates, key: "AE", country_code: "+971" }, { title: ASC.Resources.Countries.UnitedStates, key: "US", country_code: "+1" }, { title: ASC.Resources.Countries.Uruguay, key: "UY", country_code: "+598" }, { title: ASC.Resources.Countries.Uzbekistan, key: "UZ", country_code: "+998" }, { title: ASC.Resources.Countries.Vanuatu, key: "VU", country_code: "+678" }, { title: ASC.Resources.Countries.VaticanCity, key: "VA", country_code: "+379" }, { title: ASC.Resources.Countries.Venezuela, key: "VE", country_code: "+58" }, { title: ASC.Resources.Countries.Vietnam, key: "VN", country_code: "+84" }, { title: ASC.Resources.Countries.WallisAndFutuna, key: "WF", country_code: "+681" }, { title: ASC.Resources.Countries.Yemen, key: "YE", country_code: "+967" }, { title: ASC.Resources.Countries.Zambia, key: "ZM", country_code: "+260" }, { title: ASC.Resources.Countries.Zimbabwe, key: "ZW", country_code: "+263" } ]; var vm = { countriesList: countriesList }; return vm; }<file_sep>/web/studio/ASC.Web.Studio/UserControls/Management/LdapSettings/js/ldapsettings.js /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ var LdapSettings = new function () { var NULL_PERCENT = 0, DEFAULT_LDAP_PORT = 389, alreadyChecking = false, already = false, progressBarIntervalId = null, objectSettings = null, isRestoreDefault = jq(".ldap-settings-main-container").hasClass("ldap-settings-is-default"), isMono = jq(".ldap-settings-main-container").hasClass("ldap-settings-is-mono"); jq("#ldapSettingsCheckbox").click(function () { var $ldapSettingsMainContainer = jq(".ldap-settings-main-container"), $ldapSettingsUserContainer = jq(".ldap-settings-user-container"), $ldapSettingsGroupContainer = jq(".ldap-settings-group-container"), $ldapSettingsAuthContainer = jq(".ldap-settings-auth-container"), $ldapSettingsGroupCheckbox = jq("#ldapSettingsGroupCheckbox"), $ldapSettingsAuthCheckbox = jq("#ldapSettingsAuthenticationCheckbox"); if (jq(this).is(":checked")) { $ldapSettingsUserContainer.find("input").removeAttr("disabled"); $ldapSettingsGroupCheckbox.removeAttr("disabled"); $ldapSettingsUserContainer.removeClass("ldap-settings-disabled"); jq(".ldap-settings-label-checkbox:not(.ldap-settings-never-disable)").removeClass("ldap-settings-disabled"); if ($ldapSettingsGroupCheckbox.is(":checked")) { $ldapSettingsGroupContainer.find("input").removeAttr("disabled"); $ldapSettingsGroupContainer.removeClass("ldap-settings-disabled"); } $ldapSettingsAuthCheckbox.removeAttr("disabled"); if ($ldapSettingsAuthCheckbox.is(":checked") || isMono) { $ldapSettingsAuthContainer.find("input").removeAttr("disabled"); $ldapSettingsAuthContainer.removeClass("ldap-settings-disabled"); } } else { $ldapSettingsMainContainer.find("input:not(#ldapSettingsCheckbox)").attr("disabled", ""); jq(".ldap-settings-label-checkbox:not(.ldap-settings-never-disable)").addClass("ldap-settings-disabled"); $ldapSettingsUserContainer.addClass("ldap-settings-disabled"); $ldapSettingsGroupContainer.addClass("ldap-settings-disabled"); $ldapSettingsAuthContainer.addClass("ldap-settings-disabled"); } }); jq("#ldapSettingsGroupCheckbox").click(function () { var $ldapSettingsGroupContainer = jq(".ldap-settings-group-container"); if (jq(this).is(":checked")) { $ldapSettingsGroupContainer.find("input").removeAttr("disabled"); $ldapSettingsGroupContainer.removeClass("ldap-settings-disabled"); } else { $ldapSettingsGroupContainer.find("input").attr("disabled", ""); $ldapSettingsGroupContainer.addClass("ldap-settings-disabled"); } }); jq("#ldapSettingsAuthenticationCheckbox").click(function () { var $ldapSettingsAuthContainer = jq(".ldap-settings-auth-container"); if (jq(this).is(":checked")) { $ldapSettingsAuthContainer.find("input").removeAttr("disabled"); $ldapSettingsAuthContainer.removeClass("ldap-settings-disabled"); } else { $ldapSettingsAuthContainer.find("input").attr("disabled", ""); $ldapSettingsAuthContainer.addClass("ldap-settings-disabled"); } }); function restoreDefaultSettings() { var $ldapSettingsSave = jq(".ldap-settings-save"), $ldapSettingsMainContainer = jq(".ldap-settings-main-container"); PopupKeyUpActionProvider.CloseDialog(); Teamlab.getLdapDefaultSettings({}, { success: function(params, result) { HideRequiredError(); loadSettings(result); jq("#ldapSettingsError").addClass("display-none"); jq(".ldap-settings-progressbar-container").addClass("display-none"); setPercentsExactly(NULL_PERCENT); jq(".ldap-settings-restore-default-settings").addClass("disable"); $ldapSettingsMainContainer.off("click", ".ldap-settings-restore-default-settings"); $ldapSettingsSave.removeClass("disable"); $ldapSettingsMainContainer.on("click", ".ldap-settings-save", saveSettings); jq(".ldap-settings-sync-users").addClass("disable"); isRestoreDefault = true; }, error: function(params, response) { } }); } function syncUsersLDAP() { if (already) { return; } already = true; HideRequiredError(); jq("#ldapSettingsError").addClass("display-none"); PopupKeyUpActionProvider.CloseDialog(); disableInterface(); Teamlab.syncLdap({}, { success: function(params, response) { progressBarIntervalId = setInterval(checkStatus, 600); }, error: function(params, response) { } }); } function cancelDialog() { PopupKeyUpActionProvider.CloseDialog(); already = false; } function isInt(str) { var n = ~~Number(str); return String(n) === str && n >= 0; } function restoreDefault() { StudioBlockUIManager.blockUI("#ldapSettingsInviteDialog", 500); PopupKeyUpActionProvider.EnterAction = "LdapSettings.restoreDefaultSettings();"; } function disableInterface() { var $ldapSettingsMainContainer = jq(".ldap-settings-main-container"); setPercentsExactly(NULL_PERCENT); jq("#ldapSettingsError").addClass("display-none"); jq(".ldap-settings-progressbar-container").removeClass("display-none"); jq(".ldap-settings-save").addClass("disable"); jq(".ldap-settings-restore-default-settings").addClass("disable"); jq(".ldap-settings-sync-users").addClass("disable"); $ldapSettingsMainContainer.addClass("ldap-settings-disabled-all"); $ldapSettingsMainContainer.find("input").attr("disabled", ""); $ldapSettingsMainContainer.off("click", ".ldap-settings-save"); $ldapSettingsMainContainer.off("click", ".ldap-settings-restore-default-settings"); $ldapSettingsMainContainer.off("click", ".ldap-settings-sync-users"); } function enableInterface() { var $ldapSettingsCheckbox = jq("#ldapSettingsCheckbox"), $ldapSettingsGroupCheckbox = jq("#ldapSettingsGroupCheckbox"), $ldapSettingsAuthCheckbox = jq("#ldapSettingsAuthenticationCheckbox"), $ldapSettingsMainContainer = jq(".ldap-settings-main-container"); jq(".ldap-settings-save").removeClass("disable"); jq(".ldap-settings-restore-default-settings").removeClass("disable"); $ldapSettingsMainContainer.removeClass("ldap-settings-disabled-all"); $ldapSettingsCheckbox.removeAttr("disabled"); if ($ldapSettingsCheckbox.is(":checked")) { jq(".ldap-settings-user-container").find("input").removeAttr("disabled"); $ldapSettingsGroupCheckbox.removeAttr("disabled"); if ($ldapSettingsGroupCheckbox.is(":checked")) { jq(".ldap-settings-group-container").find("input").removeAttr("disabled"); } $ldapSettingsAuthCheckbox.removeAttr("disabled"); if ($ldapSettingsAuthCheckbox.is(":checked") || isMono) { jq(".ldap-settings-auth-container").find("input").removeAttr("disabled"); } } $ldapSettingsMainContainer.on("click", ".ldap-settings-save", saveSettings); $ldapSettingsMainContainer.on("click", ".ldap-settings-restore-default-settings", restoreDefault); $ldapSettingsMainContainer.on("click", ".ldap-settings-sync-users", syncUsersLDAP); } function saveSettings() { if (already) { return; } already = true; HideRequiredError(); var $ldapSettingsMainContainer = jq(".ldap-settings-main-container"), result = false, enableLdapAuthentication = jq("#ldapSettingsCheckbox").is(":checked"), server = jq("#ldapSettingsServer").val(), userDN = jq("#ldapSettingsUserDN").val(), portNumber = jq("#ldapSettingsPortNumber").val(), userFilter = jq("#ldapSettingsUserFilter").val(), loginAttribute = jq("#ldapSettingsLoginAttribute").val(), firstNameAttribute = jq("#ldapSettingsFirstNameAttribute").val(), secondNameAttribute = jq("#ldapSettingsSecondNameAttribute").val(), mailAttribute = jq("#ldapSettingsMailAttribute").val(), titleAttribute = jq("#ldapSettingsTitleAttribute").val(), mobilePhoneAttribute = jq("#ldapSettingsMobilePhoneAttribute").val(), locationAttribute = jq("#ldapSettingsLocationAttribute").val(), groupMembership = jq("#ldapSettingsGroupCheckbox").is(":checked"), groupDN = jq("#ldapSettingsGroupDN").val(), userAttribute = jq("#ldapSettingsUserAttribute").val(), groupFilter = jq("#ldapSettingsGroupFilter").val(), groupAttribute = jq("#ldapSettingsGroupAttribute").val(), groupNameAttribute = jq("#ldapSettingsGroupNameAttribute").val(), authentication = jq("#ldapSettingsAuthenticationCheckbox").is(":checked"), login = jq("#ldapSettingsLogin").val(), password = jq("#ldapSettingsPassword").val(); $ldapSettingsMainContainer.find(".ldap-settings-empty-field").addClass("display-none"); $ldapSettingsMainContainer.find(".ldap-settings-incorrect-number").addClass("display-none"); if (enableLdapAuthentication) { if (server == "") { result = true; ShowRequiredError(jq("#ldapSettingsServer")); } if (userDN == "") { result = true; ShowRequiredError(jq("#ldapSettingsUserDN")); } if (portNumber == "") { result = true; jq("#ldapSettingsPortNumberError").text(ASC.Resources.Master.Resource.LdapSettingsEmptyField); ShowRequiredError(jq("#ldapSettingsPortNumber")); } else if (!isInt(portNumber)) { result = true; jq("#ldapSettingsPortNumberError").text(ASC.Resources.Master.Resource.LdapSettingsIncorrectPortNumber); ShowRequiredError(jq("#ldapSettingsPortNumber")); } if (loginAttribute == "") { result = true; ShowRequiredError(jq("#ldapSettingsLoginAttribute")); } if (groupMembership) { if (groupDN == "") { result = true; ShowRequiredError(jq("#ldapSettingsGroupDN")); } if (userAttribute == "") { result = true; ShowRequiredError(jq("#ldapSettingsUserAttribute")); } if (groupAttribute == "") { result = true; ShowRequiredError(jq("#ldapSettingsGroupAttribute")); } if (groupNameAttribute == "") { result = true; ShowRequiredError(jq("#ldapSettingsGroupNameAttribute")); } } if (authentication || isMono) { if (login == "") { result = true; ShowRequiredError(jq("#ldapSettingsLogin")); } if (password == "") { result = true; ShowRequiredError(jq("#ldapSettingsPassword")); } } } if (result) { already = false; return; } if (portNumber == "") { portNumber = DEFAULT_LDAP_PORT; } objectSettings = { EnableLdapAuthentication: enableLdapAuthentication, Server: server, UserDN: userDN, PortNumber: portNumber, UserFilter: userFilter, LoginAttribute: loginAttribute, FirstNameAttribute: firstNameAttribute, SecondNameAttribute: secondNameAttribute, MailAttribute: mailAttribute, TitleAttribute: titleAttribute, MobilePhoneAttribute: mobilePhoneAttribute, LocationAttribute: locationAttribute, GroupMembership: groupMembership, GroupDN: groupDN, UserAttribute: userAttribute, GroupFilter: groupFilter, GroupAttribute: groupAttribute, GroupNameAttribute: groupNameAttribute, Authentication: authentication, Login: login, Password: <PASSWORD> } if (jq("#ldapSettingsCheckbox").is(":checked")) { StudioBlockUIManager.blockUI("#ldapSettingsImportUserLimitPanel", 500); PopupKeyUpActionProvider.EnableEsc = false; PopupKeyUpActionProvider.EnterAction = "LdapSettings.continueSaveSettings();"; } else { continueSaveSettings(); } } function continueSaveSettings() { PopupKeyUpActionProvider.CloseDialog(); disableInterface(); Teamlab.saveLdapSettings({}, JSON.stringify(objectSettings), { success: function (params, response) { progressBarIntervalId = setInterval(checkStatus, 600); }, error: function(params, response) { } }); } function checkStatus() { if (alreadyChecking) { return; } alreadyChecking = true; Teamlab.getLdapStatus({}, { success: function(params, status) { if (!status) { alreadyChecking = false; return; } setPercents(status.percents); setStatus(status.status); if (!status.completed) { alreadyChecking = false; return; } clearInterval(progressBarIntervalId); enableInterface(); if (status.error) { setTimeout(function() { var $ldapSettingsError = jq("#ldapSettingsError"); $ldapSettingsError.text(status.error); $ldapSettingsError.removeClass("display-none"); setStatus(""); setPercentsExactly(NULL_PERCENT); }, 500); } else { setStatus(ASC.Resources.Master.LdapSettingsSuccess); if (!isRestoreDefault) { jq(".ldap-settings-sync-users").removeClass("disable"); } if (!isRestoreDefault) { jq(".ldap-settings-sync-users").removeClass("disable"); } } jq(".ldap-settings-save").addClass("disable"); jq(".ldap-settings-main-container").off("click", ".ldap-settings-save"); if (isRestoreDefault) { jq(".ldap-settings-restore-default-settings").addClass("disable"); jq(".ldap-settings-main-container").off("click", ".ldap-settings-restore-default-settings"); } already = false; alreadyChecking = false; }, error: function(params, response) { } }); } function setPercentsExactly(percents) { jq(".asc-progress-value").css("width", percents + "%"); jq("#ldapSettingsPercent").text(percents + "% "); } function setPercents(percents) { jq(".asc-progress-value").animate({ "width": percents + "%" }); jq("#ldapSettingsPercent").text(percents + "% "); } function setStatus(status) { jq("#ldapSettingsStatus").text(status); } function loadSettings(settings) { if (!settings || typeof(settings) !== "object") return; jq("#ldapSettingsCheckbox").prop("checked", settings["enableLdapAuthentication"]); jq("#ldapSettingsServer").val(settings["server"]); jq("#ldapSettingsUserDN").val(settings["userDN"]); jq("#ldapSettingsPortNumber").val(settings["portNumber"]); jq("#ldapSettingsUserFilter").val(settings["userFilter"]); jq("#ldapSettingsLoginAttribute").val(settings["loginAttribute"]); jq("#ldapSettingsFirstNameAttribute").val(settings["firstNameAttribute"]); jq("#ldapSettingsSecondNameAttribute").val(settings["secondNameAttribute"]); jq("#ldapSettingsMailAttribute").val(settings["mailAttribute"]); jq("#ldapSettingsTitleAttribute").val(settings["titleAttribute"]); jq("#ldapSettingsMobilePhoneAttribute").val(settings["mobilePhoneAttribute"]); jq("#ldapSettingsLocationAttribute").val(settings["locationAttribute"]); jq("#ldapSettingsGroupCheckbox").prop("checked", settings["groupMembership"]); jq("#ldapSettingsGroupDN").val(settings["groupDN"]); jq("#ldapSettingsUserAttribute").val(settings["userAttribute"]); jq("#ldapSettingsGroupFilter").val(settings["groupFilter"]); jq("#ldapSettingsGroupAttribute").val(settings["groupAttribute"]); jq("#ldapSettingsGroupNameAttribute").val(settings["groupNameAttribute"]); jq("#ldapSettingsAuthenticationCheckbox").prop("checked", settings["authentication"]); jq("#ldapSettingsLogin").val(settings["login"]); jq("#ldapSettingsPassword").val(settings["password"]); disableNeededBlocks(settings["enableLdapAuthentication"], settings["groupMembership"], settings["authentication"]); } function disableNeededBlocks(enableLdapAuthentication, groupMembership, authentication) { var $ldapSettingsGroupContainer = jq(".ldap-settings-group-container"), $ldapSettingsAuthContainer = jq(".ldap-settings-auth-container"); if (!enableLdapAuthentication) { jq(".ldap-settings-main-container").find("input:not(#ldapSettingsCheckbox)").attr("disabled", ""); jq(".ldap-settings-label-checkbox:not(.ldap-settings-never-disable)").addClass("ldap-settings-disabled"); jq(".ldap-settings-user-container").addClass("ldap-settings-disabled"); $ldapSettingsGroupContainer.addClass("ldap-settings-disabled"); $ldapSettingsAuthContainer.addClass("ldap-settings-disabled"); } else { if (!groupMembership) { $ldapSettingsGroupContainer.find("input").attr("disabled", ""); $ldapSettingsGroupContainer.addClass("ldap-settings-disabled"); } if (!authentication) { $ldapSettingsAuthContainer.find("input").attr("disabled", ""); $ldapSettingsAuthContainer.addClass("ldap-settings-disabled"); } } } jq(window).on("load", function () { var $ldapSettingsMainContainer = jq(".ldap-settings-main-container"), $ldapSettingsInviteDialog = jq("#ldapSettingsInviteDialog"), $ldapSettingsImportUserLimitPanel = jq("#ldapSettingsImportUserLimitPanel"), $ldapSettingsSave = jq(".ldap-settings-save"), $ldapSettingsRestoreDefaultSettings = jq(".ldap-settings-restore-default-settings"); $ldapSettingsMainContainer.on("click", ".ldap-settings-restore-default-settings", restoreDefault); $ldapSettingsMainContainer.on("click", ".ldap-settings-sync-users", syncUsersLDAP); $ldapSettingsInviteDialog.on("click", ".ldap-settings-ok", restoreDefaultSettings); $ldapSettingsInviteDialog.on("click", ".ldap-settings-cancel", cancelDialog); $ldapSettingsImportUserLimitPanel.on("click", ".ldap-settings-ok", continueSaveSettings); $ldapSettingsImportUserLimitPanel.on("click", ".ldap-settings-cancel", cancelDialog); $ldapSettingsImportUserLimitPanel.on("click", ".cancelButton", cancelDialog); jq(document).keyup(function (e) { /* Escape Key */ if (!jq("#ldapSettingsImportUserLimitPanel").is(":hidden") && e.keyCode == 27) { cancelDialog(); } }); jq(".ldap-settings-main-container input").change(function () { isRestoreDefault = false; if ($ldapSettingsSave.hasClass("disable")) { $ldapSettingsSave.removeClass("disable"); $ldapSettingsMainContainer.on("click", ".ldap-settings-save", saveSettings); } if ($ldapSettingsRestoreDefaultSettings.hasClass("disable")) { $ldapSettingsRestoreDefaultSettings.removeClass("disable"); $ldapSettingsMainContainer.on("click", ".ldap-settings-restore-default-settings", restoreDefault); } }); jq(".ldap-settings-main-container .textEdit").keyup(function () { isRestoreDefault = false; if ($ldapSettingsSave.hasClass("disable")) { $ldapSettingsSave.removeClass("disable"); $ldapSettingsMainContainer.on("click", ".ldap-settings-save", saveSettings); } if ($ldapSettingsRestoreDefaultSettings.hasClass("disable")) { $ldapSettingsRestoreDefaultSettings.removeClass("disable"); $ldapSettingsMainContainer.on("click", ".ldap-settings-restore-default-settings", restoreDefault); } }); }); return { restoreDefaultSettings: restoreDefaultSettings, continueSaveSettings: continueSaveSettings, syncUsersLDAP: syncUsersLDAP }; };<file_sep>/module/ASC.Api/ASC.Api.Sample/SampleApi.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System.Collections.Generic; using ASC.Api.Attributes; using ASC.Api.Interfaces; using ASC.Web.Sample.Classes; namespace ASC.Api.Sample { /// <summary> /// Sample CRUD Api /// </summary> public class SampleApi : IApiEntryPoint { /// <summary> /// ASC.Api.Interfaces.IApiEntryPoint.Name /// </summary> public string Name { get { return "sample"; } } /// <summary> /// Create item /// </summary> /// <param name="value">item value</param> /// <returns>SampleClass item</returns> [Create("create", false)] public SampleClass Create(string value) { return SampleDao.Create(value); } /// <summary> /// Read item by id /// </summary> /// <param name="id">item id</param> /// <returns>SampleClass item</returns> [Read(@"read/{id:[0-9]+}", false)] public SampleClass Read(int id) { return SampleDao.Read(id); } /// <summary> /// Read all items /// </summary> /// <returns>SampleClass items list</returns> [Read("read", false)] public List<SampleClass> Read() { return SampleDao.Read(); } /// <summary> /// Update item /// </summary> /// <param name="id">item id</param> /// <param name="value">new item value</param> [Update("update", false)] public void Update(int id, string value) { SampleDao.Update(id, value); } /// <summary> /// Update item by id /// </summary> /// <param name="id">item id</param> [Delete("delete/{id:[0-9]+}", false)] public void Delete(int id) { SampleDao.Delete(id); } } } <file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/_AsyncResultState.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net { #region usings using System; using System.Threading; #endregion /// <summary> /// (For internal use only). This class provides holder for IAsyncResult interface and extends it's features. /// </summary> internal class AsyncResultState : IAsyncResult { #region Members private readonly Delegate m_pAsyncDelegate; private readonly object m_pAsyncObject; private readonly AsyncCallback m_pCallback; private readonly object m_pState; private IAsyncResult m_pAsyncResult; #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="asyncObject">Caller's async object.</param> /// <param name="asyncDelegate">Delegate which is called asynchronously.</param> /// <param name="callback">Callback to call when the connect operation is complete.</param> /// <param name="state">User data.</param> public AsyncResultState(object asyncObject, Delegate asyncDelegate, AsyncCallback callback, object state) { m_pAsyncObject = asyncObject; m_pAsyncDelegate = asyncDelegate; m_pCallback = callback; m_pState = state; } #endregion #region Properties /// <summary> /// Gets delegate which is called asynchronously. /// </summary> public Delegate AsyncDelegate { get { return m_pAsyncDelegate; } } /// <summary> /// Gets or sets caller's async object. /// </summary> public object AsyncObject { get { return m_pAsyncObject; } } /// <summary> /// Gets source asynchronous result what we wrap. /// </summary> public IAsyncResult AsyncResult { get { return m_pAsyncResult; } } /// <summary> /// Gets if the user called the End*() method. /// </summary> public bool IsEndCalled { get; set; } #endregion #region Methods /// <summary> /// Sets AsyncResult value. /// </summary> /// <param name="asyncResult">Asycnhronous result to wrap.</param> public void SetAsyncResult(IAsyncResult asyncResult) { if (asyncResult == null) { throw new ArgumentNullException("asyncResult"); } m_pAsyncResult = asyncResult; } /// <summary> /// This method is called by AsyncDelegate when asynchronous operation completes. /// </summary> /// <param name="ar">An IAsyncResult that stores state information and any user defined data for this asynchronous operation.</param> public void CompletedCallback(IAsyncResult ar) { if (m_pCallback != null) { m_pCallback(this); } } #endregion #region IAsyncResult Members /// <summary> /// Gets a user-defined object that qualifies or contains information about an asynchronous operation. /// </summary> public object AsyncState { get { return m_pState; } } /// <summary> /// Gets a WaitHandle that is used to wait for an asynchronous operation to complete. /// </summary> public WaitHandle AsyncWaitHandle { get { return m_pAsyncResult.AsyncWaitHandle; } } /// <summary> /// Gets an indication of whether the asynchronous operation completed synchronously. /// </summary> public bool CompletedSynchronously { get { return m_pAsyncResult.CompletedSynchronously; } } /// <summary> /// Gets an indication whether the asynchronous operation has completed. /// </summary> public bool IsCompleted { get { return m_pAsyncResult.IsCompleted; } } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/Multilang/IMLangString.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace MultiLanguage { using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Security; [ComImport, Guid("C04D65CE-B70D-11D0-B188-00AA0038C969"), InterfaceType((short) 1)] public interface IMLangString { [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void Sync([In] int fNoAccess); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] int GetLength(); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void SetMLStr([In] int lDestPos, [In] int lDestLen, [In, MarshalAs(UnmanagedType.IUnknown)] object pSrcMLStr, [In] int lSrcPos, [In] int lSrcLen); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetMLStr([In] int lSrcPos, [In] int lSrcLen, [In, MarshalAs(UnmanagedType.IUnknown)] object pUnkOuter, [In] uint dwClsContext, [In] ref Guid piid, [MarshalAs(UnmanagedType.IUnknown)] out object ppDestMLStr, out int plDestPos, out int plDestLen); } } <file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/vCard/DeliveryAddress.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.Mime.vCard { /// <summary> /// vCard delivery address implementation. /// </summary> public class DeliveryAddress { #region Members private readonly Item m_pItem; private string m_Country = ""; private string m_ExtendedAddress = ""; private string m_Locality = ""; private string m_PostalCode = ""; private string m_PostOfficeAddress = ""; private string m_Region = ""; private string m_Street = ""; private DeliveryAddressType_enum m_Type = DeliveryAddressType_enum.Ineternational | DeliveryAddressType_enum.Postal | DeliveryAddressType_enum.Parcel | DeliveryAddressType_enum.Work; #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="item">Owner vCard item.</param> /// <param name="addressType">Address type. Note: This value can be flagged value !</param> /// <param name="postOfficeAddress">Post office address.</param> /// <param name="extendedAddress">Extended address.</param> /// <param name="street">Street name.</param> /// <param name="locality">Locality(city).</param> /// <param name="region">Region.</param> /// <param name="postalCode">Postal code.</param> /// <param name="country">Country.</param> internal DeliveryAddress(Item item, DeliveryAddressType_enum addressType, string postOfficeAddress, string extendedAddress, string street, string locality, string region, string postalCode, string country) { m_pItem = item; m_Type = addressType; m_PostOfficeAddress = postOfficeAddress; m_ExtendedAddress = extendedAddress; m_Street = street; m_Locality = locality; m_Region = region; m_PostalCode = postalCode; m_Country = country; } #endregion #region Properties /// <summary> /// Gets or sets address type. Note: This property can be flagged value ! /// </summary> public DeliveryAddressType_enum AddressType { get { return m_Type; } set { m_Type = value; Changed(); } } /// <summary> /// Gets or sets country. /// </summary> public string Country { get { return m_Country; } set { m_Country = value; Changed(); } } /// <summary> /// Gests or sets extended address. /// </summary> public string ExtendedAddress { get { return m_ExtendedAddress; } set { m_ExtendedAddress = value; Changed(); } } /// <summary> /// Gets underlaying vCrad item. /// </summary> public Item Item { get { return m_pItem; } } /// <summary> /// Gets or sets locality(city). /// </summary> public string Locality { get { return m_Locality; } set { m_Locality = value; Changed(); } } /// <summary> /// Gets or sets postal code. /// </summary> public string PostalCode { get { return m_PostalCode; } set { m_PostalCode = value; Changed(); } } /// <summary> /// Gets or sets post office address. /// </summary> public string PostOfficeAddress { get { return m_PostOfficeAddress; } set { m_PostOfficeAddress = value; Changed(); } } /// <summary> /// Gets or sets region. /// </summary> public string Region { get { return m_Region; } set { m_Region = value; Changed(); } } /// <summary> /// Gets or sets street. /// </summary> public string Street { get { return m_Street; } set { m_Street = value; Changed(); } } #endregion #region Internal methods /// <summary> /// Parses delivery address from vCard ADR structure string. /// </summary> /// <param name="item">vCard ADR item.</param> internal static DeliveryAddress Parse(Item item) { DeliveryAddressType_enum type = DeliveryAddressType_enum.NotSpecified; if (item.ParametersString.ToUpper().IndexOf("PREF") != -1) { type |= DeliveryAddressType_enum.Preferred; } if (item.ParametersString.ToUpper().IndexOf("DOM") != -1) { type |= DeliveryAddressType_enum.Domestic; } if (item.ParametersString.ToUpper().IndexOf("INTL") != -1) { type |= DeliveryAddressType_enum.Ineternational; } if (item.ParametersString.ToUpper().IndexOf("POSTAL") != -1) { type |= DeliveryAddressType_enum.Postal; } if (item.ParametersString.ToUpper().IndexOf("PARCEL") != -1) { type |= DeliveryAddressType_enum.Parcel; } if (item.ParametersString.ToUpper().IndexOf("HOME") != -1) { type |= DeliveryAddressType_enum.Home; } if (item.ParametersString.ToUpper().IndexOf("WORK") != -1) { type |= DeliveryAddressType_enum.Work; } string[] items = item.DecodedValue.Split(';'); return new DeliveryAddress(item, type, items.Length >= 1 ? items[0] : "", items.Length >= 2 ? items[1] : "", items.Length >= 3 ? items[2] : "", items.Length >= 4 ? items[3] : "", items.Length >= 5 ? items[4] : "", items.Length >= 6 ? items[5] : "", items.Length >= 7 ? items[6] : ""); } /// <summary> /// Converts DeliveryAddressType_enum to vCard item parameters string. /// </summary> /// <param name="type">Value to convert.</param> /// <returns></returns> internal static string AddressTypeToString(DeliveryAddressType_enum type) { string retVal = ""; if ((type & DeliveryAddressType_enum.Domestic) != 0) { retVal += "DOM,"; } if ((type & DeliveryAddressType_enum.Home) != 0) { retVal += "HOME,"; } if ((type & DeliveryAddressType_enum.Ineternational) != 0) { retVal += "INTL,"; } if ((type & DeliveryAddressType_enum.Parcel) != 0) { retVal += "PARCEL,"; } if ((type & DeliveryAddressType_enum.Postal) != 0) { retVal += "POSTAL,"; } if ((type & DeliveryAddressType_enum.Preferred) != 0) { retVal += "Preferred,"; } if ((type & DeliveryAddressType_enum.Work) != 0) { retVal += "Work,"; } if (retVal.EndsWith(",")) { retVal = retVal.Substring(0, retVal.Length - 1); } return retVal; } #endregion #region Utility methods /// <summary> /// This method is called when some property has changed, we need to update underlaying vCard item. /// </summary> private void Changed() { string value = "" + m_PostOfficeAddress + ";" + m_ExtendedAddress + ";" + m_Street + ";" + m_Locality + ";" + m_Region + ";" + m_PostalCode + ";" + m_Country; m_pItem.ParametersString = AddressTypeToString(m_Type); m_pItem.SetDecodedValue(value); } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/FTP/FTP_TransferMode.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.FTP { /// <summary> /// Specifies FTP data connection transfer mode. /// </summary> public enum FTP_TransferMode { /// <summary> /// Active transfer mode - FTP server opens data connection FTP client. /// </summary> Active, /// <summary> /// Passive transfer mode - FTP client opens data connection FTP server. /// </summary> Passive } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/IMAP/Client/IMAP_Quota.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.IMAP.Client { /// <summary> /// IMAP quota entry. Defined in RFC 2087. /// </summary> public class IMAP_Quota { #region Members private readonly long m_MaxMessages = -1; private readonly long m_MaxStorage = -1; private readonly long m_Messages = -1; private readonly string m_QuotaRootName = ""; private readonly long m_Storage = -1; #endregion #region Properties /// <summary> /// Gets quota root name. /// </summary> public string QuotaRootName { get { return m_QuotaRootName; } } /// <summary> /// Gets current messages count. Returns -1 if messages and maximum messages quota is not defined. /// </summary> public long Messages { get { return m_Messages; } } /// <summary> /// Gets maximum allowed messages count. Returns -1 if messages and maximum messages quota is not defined. /// </summary> public long MaximumMessages { get { return m_MaxMessages; } } /// <summary> /// Gets current storage in bytes. Returns -1 if storage and maximum storage quota is not defined. /// </summary> public long Storage { get { return m_Storage; } } /// <summary> /// Gets maximum allowed storage in bytes. Returns -1 if storage and maximum storage quota is not defined. /// </summary> public long MaximumStorage { get { return m_MaxStorage; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="quotaRootName">Quota root name.</param> /// <param name="messages">Number of current messages.</param> /// <param name="maxMessages">Number of maximum allowed messages.</param> /// <param name="storage">Current storage bytes.</param> /// <param name="maxStorage">Maximum allowed storage bytes.</param> public IMAP_Quota(string quotaRootName, long messages, long maxMessages, long storage, long maxStorage) { m_QuotaRootName = quotaRootName; m_Messages = messages; m_MaxMessages = maxMessages; m_Storage = storage; m_MaxStorage = maxStorage; } #endregion } }<file_sep>/common/ASC.Core.Common/Billing/TariffService.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Reflection; using System.ServiceModel.Configuration; using System.Text; using System.Threading.Tasks; using ASC.Common.Caching; using ASC.Common.Data.Sql; using ASC.Common.Data.Sql.Expressions; using ASC.Common.Logging; using ASC.Core.Data; using ASC.Core.Tenants; namespace ASC.Core.Billing { public class TariffService : DbBaseService, ITariffService { private const int DEFAULT_TRIAL_PERIOD = 30; private static readonly TimeSpan DEFAULT_CACHE_EXPIRATION = TimeSpan.FromMinutes(5); private static readonly TimeSpan STANDALONE_CACHE_EXPIRATION = TimeSpan.FromMinutes(15); private readonly static ICache cache; private readonly static ICacheNotify notify; private readonly static bool billingConfigured = false; private static readonly ILog log = LogManager.GetLogger("ASC"); private readonly IQuotaService quotaService; private readonly ITenantService tenantService; private readonly CoreConfiguration config; private readonly bool test; private readonly int paymentDelay; public TimeSpan CacheExpiration { get; set; } static TariffService() { cache = AscCache.Memory; notify = AscCache.Notify; notify.Subscribe<TariffCacheItem>((i, a) => { cache.Remove(GetTariffCacheKey(i.TenantId)); cache.Remove(GetBillingUrlCacheKey(i.TenantId)); cache.Remove(GetBillingPaymentCacheKey(i.TenantId, DateTime.MinValue, DateTime.MaxValue)); // clear all payments }); try { var section = (ClientSection)ConfigurationManagerExtension.GetSection("system.serviceModel/client"); if (section != null) { billingConfigured = section.Endpoints.Cast<ChannelEndpointElement>() .Any(e => e.Contract == typeof(IService).FullName); } } catch (Exception err) { log.Error(err); } } public TariffService(ConnectionStringSettings connectionString, IQuotaService quotaService, ITenantService tenantService) : base(connectionString, "tenant") { this.quotaService = quotaService; this.tenantService = tenantService; config = new CoreConfiguration(tenantService); CacheExpiration = DEFAULT_CACHE_EXPIRATION; test = ConfigurationManagerExtension.AppSettings["core.payment-test"] == "true"; int.TryParse(ConfigurationManagerExtension.AppSettings["core.payment-delay"], out paymentDelay); } public Tariff GetTariff(int tenantId, bool withRequestToPaymentSystem = true) { //single tariff for all portals if (CoreContext.Configuration.Standalone) tenantId = -1; var key = GetTariffCacheKey(tenantId); var tariff = cache.Get<Tariff>(key); if (tariff == null) { tariff = Tariff.CreateDefault(); var cached = GetBillingInfo(tenantId); if (cached != null) { tariff.QuotaId = cached.Item1; tariff.DueDate = cached.Item2; } tariff = CalculateTariff(tenantId, tariff); cache.Insert(key, tariff, DateTime.UtcNow.Add(GetCacheExpiration())); if (billingConfigured && withRequestToPaymentSystem) { Task.Run(() => { try { using (var client = GetBillingClient()) { var p = client.GetLastPayment(GetPortalId(tenantId)); var quota = quotaService.GetTenantQuotas().SingleOrDefault(q => q.AvangateId == p.ProductId); if (quota == null) { throw new InvalidOperationException(string.Format("Quota with id {0} not found for portal {1}.", p.ProductId, GetPortalId(tenantId))); } var asynctariff = Tariff.CreateDefault(); asynctariff.QuotaId = quota.Id; asynctariff.Autorenewal = p.Autorenewal; asynctariff.DueDate = 9999 <= p.EndDate.Year ? DateTime.MaxValue : p.EndDate; if (SaveBillingInfo(tenantId, Tuple.Create(asynctariff.QuotaId, asynctariff.DueDate), false)) { asynctariff = CalculateTariff(tenantId, asynctariff); ClearCache(tenantId); cache.Insert(key, asynctariff, DateTime.UtcNow.Add(GetCacheExpiration())); } } } catch (Exception error) { LogError(error); } }); } } return tariff; } public void SetTariff(int tenantId, Tariff tariff) { if (tariff == null) { throw new ArgumentNullException("tariff"); } var q = quotaService.GetTenantQuota(tariff.QuotaId); if (q == null) return; SaveBillingInfo(tenantId, Tuple.Create(tariff.QuotaId, tariff.DueDate)); if (q.Trial) { // reset trial date var tenant = tenantService.GetTenant(tenantId); if (tenant != null) { tenant.VersionChanged = DateTime.UtcNow; tenantService.SaveTenant(tenant); } } ClearCache(tenantId); } private static string GetTariffCacheKey(int tenantId) { return string.Format("{0}:{1}", tenantId, "tariff"); } private static string GetBillingUrlCacheKey(int tenantId) { return string.Format("{0}:{1}", tenantId, "billing:urls"); } private static string GetBillingPaymentCacheKey(int tenantId, DateTime from, DateTime to) { return string.Format("{0}:{1}:{2}-{3}", tenantId, "billing:payments", from.ToString("yyyyMMddHHmmss"), to.ToString("yyyyMMddHHmmss")); } public void ClearCache(int tenantId) { notify.Publish(new TariffCacheItem { TenantId = tenantId }, CacheNotifyAction.Remove); } public IEnumerable<PaymentInfo> GetPayments(int tenantId, DateTime from, DateTime to) { from = from.Date; to = to.Date.AddTicks(TimeSpan.TicksPerDay - 1); var key = GetBillingPaymentCacheKey(tenantId, from, to); var payments = cache.Get<List<PaymentInfo>>(key); if (payments == null) { payments = new List<PaymentInfo>(); if (billingConfigured) { try { var quotas = quotaService.GetTenantQuotas(); using (var client = GetBillingClient()) { foreach (var pi in client.GetPayments(GetPortalId(tenantId), from, to)) { var quota = quotas.SingleOrDefault(q => q.AvangateId == pi.ProductId); if (quota != null) { pi.QuotaId = quota.Id; } payments.Add(pi); } } } catch (Exception error) { LogError(error); } } cache.Insert(key, payments, DateTime.UtcNow.Add(TimeSpan.FromMinutes(10))); } return payments; } public Uri GetShoppingUri(int? tenant, int quotaId, string affiliateId, string currency = null, string language = null, string customerId = null) { var quota = quotaService.GetTenantQuota(quotaId); if (quota == null) return null; var key = tenant.HasValue ? GetBillingUrlCacheKey(tenant.Value) : String.Format("notenant{0}", !string.IsNullOrEmpty(affiliateId) ? "_" + affiliateId : ""); key += quota.Visible ? "" : "0"; var urls = cache.Get<Dictionary<string, Tuple<Uri, Uri>>>(key) as IDictionary<string, Tuple<Uri, Uri>>; if (urls == null) { urls = new Dictionary<string, Tuple<Uri, Uri>>(); if (billingConfigured) { try { var products = quotaService.GetTenantQuotas() .Where(q => !string.IsNullOrEmpty(q.AvangateId) && q.Visible == quota.Visible) .Select(q => q.AvangateId) .ToArray(); using (var client = GetBillingClient()) { urls = tenant.HasValue ? client.GetPaymentUrls(GetPortalId(tenant.Value), products, GetAffiliateId(tenant.Value), GetCampaign(tenant.Value), "__Currency__", "__Language__", "__CustomerID__") : client.GetPaymentUrls(null, products, !string.IsNullOrEmpty(affiliateId) ? affiliateId : null, null, "__Currency__", "__Language__", "__CustomerID__"); } } catch (Exception error) { log.Error(error); } } cache.Insert(key, urls, DateTime.UtcNow.Add(TimeSpan.FromMinutes(10))); } ResetCacheExpiration(); Tuple<Uri, Uri> tuple; if (!string.IsNullOrEmpty(quota.AvangateId) && urls.TryGetValue(quota.AvangateId, out tuple)) { var result = tuple.Item2; var tariff = tenant.HasValue ? GetTariff(tenant.Value) : null; if (result == null || tariff == null || tariff.QuotaId == quotaId || tariff.State >= TariffState.Delay) { result = tuple.Item1; } result = new Uri(result.ToString() .Replace("__Currency__", currency ?? "") .Replace("__Language__", (language ?? "").ToLower()) .Replace("__CustomerID__", customerId ?? "")); return result; } return null; } public IDictionary<string, IEnumerable<Tuple<string, decimal>>> GetProductPriceInfo(params string[] productIds) { if (productIds == null) { throw new ArgumentNullException("productIds"); } try { var key = "biling-prices" + string.Join(",", productIds); var result = cache.Get<IDictionary<string, IEnumerable<Tuple<string, decimal>>>>(key); if (result == null) { using (var client = GetBillingClient()) { result = client.GetProductPriceInfo(productIds); } cache.Insert(key, result, DateTime.Now.AddHours(1)); } return result; } catch (Exception error) { LogError(error); return productIds .Select(p => new { ProductId = p, Prices = Enumerable.Empty<Tuple<string, decimal>>() }) .ToDictionary(e => e.ProductId, e => e.Prices); } } public Invoice GetInvoice(string paymentId) { var result = new Invoice(); if (billingConfigured) { try { using (var client = GetBillingClient()) { result = client.GetInvoice(paymentId); } } catch (Exception error) { LogError(error); } } return result; } public string GetButton(int tariffId, string partnerId) { var q = new SqlQuery("tenants_buttons") .Select("button_url") .Where(Exp.Eq("tariff_id", tariffId) & Exp.Eq("partner_id", partnerId)) .SetMaxResults(1); return ExecList(q).ConvertAll(r => (string)r[0]).SingleOrDefault(); } public void SaveButton(int tariffId, string partnerId, string buttonUrl) { var q = new SqlInsert("tenants_buttons", true) .InColumnValue("tariff_id", tariffId) .InColumnValue("partner_id", partnerId) .InColumnValue("button_url", buttonUrl); ExecNonQuery(q); } private Tuple<int, DateTime> GetBillingInfo(int tenant) { var q = new SqlQuery("tenants_tariff") .Select("tariff", "stamp") .Where("tenant", tenant) .OrderBy("id", false) .SetMaxResults(1); return ExecList(q) .ConvertAll(r => Tuple.Create(Convert.ToInt32(r[0]), ((DateTime)r[1]).Year < 9999 ? (DateTime)r[1] : DateTime.MaxValue)) .SingleOrDefault(); } private bool SaveBillingInfo(int tenant, Tuple<int, DateTime> bi, bool renewal = true) { var inserted = false; if (!Equals(bi, GetBillingInfo(tenant))) { using (var db = GetDb()) using (var tx = db.BeginTransaction()) { // last record is not the same var q = new SqlQuery("tenants_tariff").SelectCount().Where("tenant", tenant).Where("tariff", bi.Item1).Where("stamp", bi.Item2); if (bi.Item2 == DateTime.MaxValue || renewal || db.ExecuteScalar<int>(q) == 0) { var i = new SqlInsert("tenants_tariff") .InColumnValue("tenant", tenant) .InColumnValue("tariff", bi.Item1) .InColumnValue("stamp", bi.Item2); db.ExecuteNonQuery(i); cache.Remove(GetTariffCacheKey(tenant)); inserted = true; } tx.Commit(); } } if (inserted) { var t = tenantService.GetTenant(tenant); if (t != null) { // update tenant.LastModified to flush cache in documents tenantService.SaveTenant(t); } } return inserted; } public void DeleteDefaultBillingInfo() { const int tenant = Tenant.DEFAULT_TENANT; using (var db = GetDb()) { db.ExecuteNonQuery(new SqlUpdate("tenants_tariff") .Set("tenant", -2) .Where("tenant", tenant)); } ClearCache(tenant); } private Tariff CalculateTariff(int tenantId, Tariff tariff) { tariff.State = TariffState.Paid; var q = quotaService.GetTenantQuota(tariff.QuotaId); if (q == null || q.GetFeature("old")) { tariff.QuotaId = Tenant.DEFAULT_TENANT; q = quotaService.GetTenantQuota(tariff.QuotaId); } var delay = 0; if (q != null && q.Trial) { tariff.State = TariffState.Trial; if (tariff.DueDate == DateTime.MinValue || tariff.DueDate == DateTime.MaxValue) { var tenant = tenantService.GetTenant(tenantId); if (tenant != null) { var fromDate = tenant.CreatedDateTime < tenant.VersionChanged ? tenant.VersionChanged : tenant.CreatedDateTime; var trialPeriod = GetPeriod("TrialPeriod", DEFAULT_TRIAL_PERIOD); if (fromDate == DateTime.MinValue) fromDate = DateTime.UtcNow.Date; tariff.DueDate = trialPeriod != default(int) ? fromDate.Date.AddDays(trialPeriod) : DateTime.MaxValue; } else { tariff.DueDate = DateTime.MaxValue; } } } else { delay = paymentDelay; } if (tariff.DueDate != DateTime.MinValue && tariff.DueDate.Date < DateTime.Today && delay > 0) { tariff.State = TariffState.Delay; tariff.DelayDueDate = tariff.DueDate.Date.AddDays(delay); } if (tariff.DueDate == DateTime.MinValue || tariff.DueDate != DateTime.MaxValue && tariff.DueDate.Date.AddDays(delay) < DateTime.Today) { tariff.State = TariffState.NotPaid; if (config.Standalone) { if (q != null) { var defaultQuota = quotaService.GetTenantQuota(Tenant.DEFAULT_TENANT); defaultQuota.Name = "overdue"; defaultQuota.Features = q.Features; defaultQuota.Support = false; quotaService.SaveTenantQuota(defaultQuota); } var unlimTariff = Tariff.CreateDefault(); unlimTariff.LicenseDate = tariff.DueDate; tariff = unlimTariff; } } tariff.Prolongable = tariff.DueDate == DateTime.MinValue || tariff.DueDate == DateTime.MaxValue || tariff.State == TariffState.Trial || new DateTime(tariff.DueDate.Year, tariff.DueDate.Month, 1) <= new DateTime(DateTime.UtcNow.Year, DateTime.UtcNow.Month, 1).AddMonths(1); return tariff; } private int GetPeriod(string key, int defaultValue) { var settings = tenantService.GetTenantSettings(Tenant.DEFAULT_TENANT, key); return settings != null ? Convert.ToInt32(Encoding.UTF8.GetString(settings)) : defaultValue; } private BillingClient GetBillingClient() { try { return new BillingClient(test); } catch (InvalidOperationException ioe) { throw new BillingNotConfiguredException(ioe.Message, ioe); } catch (ReflectionTypeLoadException rtle) { log.ErrorFormat("{0}{1}LoaderExceptions: {2}", rtle, Environment.NewLine, string.Join(Environment.NewLine, rtle.LoaderExceptions.Select(e => e.ToString()))); throw; } } private string GetPortalId(int tenant) { return config.GetKey(tenant); } private string GetAffiliateId(int tenant) { return config.GetAffiliateId(tenant); } private string GetCampaign(int tenant) { return config.GetCampaign(tenant); } private TimeSpan GetCacheExpiration() { if (config.Standalone && CacheExpiration < STANDALONE_CACHE_EXPIRATION) { CacheExpiration = CacheExpiration.Add(TimeSpan.FromSeconds(30)); } return CacheExpiration; } private void ResetCacheExpiration() { if (config.Standalone) { CacheExpiration = DEFAULT_CACHE_EXPIRATION; } } private static void LogError(Exception error) { if (error is BillingNotFoundException) { log.DebugFormat("Payment not found: {0}", error.Message); } else if (error is BillingNotConfiguredException) { log.DebugFormat("Billing not configured: {0}", error.Message); } else { if (log.IsDebugEnabled) { log.Error(error); } else { log.Error(error.Message); } } } [Serializable] class TariffCacheItem { public int TenantId { get; set; } } } }<file_sep>/module/ASC.AuditTrail/Mappers/LoginActionMapper.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System.Collections.Generic; using ASC.MessagingSystem; namespace ASC.AuditTrail.Mappers { internal class LoginActionsMapper { public static Dictionary<MessageAction, MessageMaps> GetMaps() { return new Dictionary<MessageAction, MessageMaps> { {MessageAction.LoginSuccess, new MessageMaps {ActionTextResourceName = "LoginSuccess"}}, {MessageAction.LoginSuccessViaSocialAccount, new MessageMaps {ActionTextResourceName = "LoginSuccessSocialAccount"}}, {MessageAction.LoginSuccessViaSocialApp, new MessageMaps {ActionTextResourceName = "LoginSuccessSocialApp"}}, {MessageAction.LoginSuccessViaSms, new MessageMaps {ActionTextResourceName = "LoginSuccessViaSms"}}, {MessageAction.LoginSuccessViaApi, new MessageMaps {ActionTextResourceName = "LoginSuccessViaApi"}}, {MessageAction.LoginSuccessViaApiSms, new MessageMaps {ActionTextResourceName = "LoginSuccessViaApiSms"}}, {MessageAction.LoginSuccessViaApiTfa, new MessageMaps {ActionTextResourceName = "LoginSuccessViaApiTfa"}}, {MessageAction.LoginSuccessViaApiSocialAccount, new MessageMaps {ActionTextResourceName = "LoginSuccessViaSocialAccount"}}, {MessageAction.LoginSuccessViaSSO, new MessageMaps {ActionTextResourceName = "LoginSuccessViaSSO"}}, {MessageAction.LoginSuccesViaTfaApp, new MessageMaps {ActionTextResourceName = "LoginSuccesViaTfaApp"}}, {MessageAction.LoginFailInvalidCombination, new MessageMaps {ActionTextResourceName = "LoginFailInvalidCombination"}}, {MessageAction.LoginFailSocialAccountNotFound, new MessageMaps {ActionTextResourceName = "LoginFailSocialAccountNotFound"}}, {MessageAction.LoginFailDisabledProfile, new MessageMaps {ActionTextResourceName = "LoginFailDisabledProfile"}}, {MessageAction.LoginFail, new MessageMaps {ActionTextResourceName = "LoginFail"}}, {MessageAction.LoginFailViaSms, new MessageMaps {ActionTextResourceName = "LoginFailViaSms"}}, {MessageAction.LoginFailViaApi, new MessageMaps {ActionTextResourceName = "LoginFailViaApi"}}, {MessageAction.LoginFailViaApiSms, new MessageMaps {ActionTextResourceName = "LoginFailViaApiSms"}}, {MessageAction.LoginFailViaApiTfa, new MessageMaps {ActionTextResourceName = "LoginFailViaApiTfa"}}, {MessageAction.LoginFailViaApiSocialAccount, new MessageMaps {ActionTextResourceName = "LoginFailViaApiSocialAccount"}}, {MessageAction.LoginFailViaTfaApp, new MessageMaps {ActionTextResourceName = "LoginFailViaTfaApp"}}, {MessageAction.LoginFailIpSecurity, new MessageMaps {ActionTextResourceName = "LoginFailIpSecurity"}}, {MessageAction.LoginFailViaSSO, new MessageMaps {ActionTextResourceName = "LoginFailViaSSO"}}, {MessageAction.LoginFailBruteForce, new MessageMaps {ActionTextResourceName = "LoginFailBruteForce"}}, {MessageAction.LoginFailRecaptcha, new MessageMaps {ActionTextResourceName = "LoginFailRecaptcha"}}, {MessageAction.Logout, new MessageMaps {ActionTextResourceName = "Logout"}}, {MessageAction.SessionStarted, new MessageMaps {ActionTextResourceName = "SessionStarted"}}, {MessageAction.SessionCompleted, new MessageMaps {ActionTextResourceName = "SessionCompleted"}} }; } } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/MIME/MIME_MediaTypes.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.MIME { /// <summary> /// This class holds well known Content-Type header field media types. For example: text/plain, application/octet-stream. /// Full IANA registered list can be found from: http://www.iana.org/assignments/media-types. /// </summary> public class MIME_MediaTypes { #region Nested type: Application /// <summary> /// This class holds well-known application/xxx media types. /// </summary> public class Application { #region Members /// <summary> /// "application/octet-stream". Defined in RFC 2045,2046. /// </summary> public static readonly string octet_stream = "application/octet-stream"; /// <summary> /// "application/pdf". Defined in RFC 3778. /// </summary> public static readonly string pdf = "application/pdf"; /// <summary> /// "application/sdp". Defined in RFC 4566. /// </summary> public static readonly string sdp = "application/sdp"; /// <summary> /// "application/xml". Defined RFC 3023. /// </summary> public static readonly string xml = "application/xml"; /// <summary> /// "application/zip". Defined in RFC 4566. /// </summary> public static readonly string zip = "application/zip"; #endregion } #endregion #region Nested type: Image /// <summary> /// This class holds well-known image/xxx media types. /// </summary> public class Image { #region Members /// <summary> /// "image/gif". /// </summary> public static readonly string gif = "image/gif"; /// <summary> /// "image/jpeg". /// </summary> public static readonly string jpeg = "image/jpeg"; /// <summary> /// "image/tiff". /// </summary> public static readonly string tiff = "image/tiff"; #endregion } #endregion #region Nested type: Message /// <summary> /// This class holds well-known message/xxx media types. /// </summary> public class Message { #region Members /// <summary> /// "message/disposition-notification". /// </summary> public static readonly string disposition_notification = "message/disposition-notification"; /// <summary> /// "message/rfc822". /// </summary> public static readonly string rfc822 = "message/rfc822"; #endregion } #endregion #region Nested type: Multipart /// <summary> /// This class holds well-known multipart/xxx media types. /// </summary> public class Multipart { #region Members /// <summary> /// "multipart/alternative". Defined in RFC 2045,2046. /// </summary> public static readonly string alternative = "multipart/alternative"; /// <summary> /// "multipart/digest". Defined in RFC 2045,2046. /// </summary> public static readonly string digest = "multipart/digest"; /// <summary> /// "multipart/digest". Defined in RFC 1847. /// </summary> public static readonly string encrypted = "multipart/digest"; /// <summary> /// "multipart/form-data". Defined in RFC 2388. /// </summary> public static readonly string form_data = "multipart/form-data"; /// <summary> /// "multipart/mixed". Defined in RFC 2045,2046. /// </summary> public static readonly string mixed = "multipart/mixed"; /// <summary> /// "multipart/parallel". Defined in RFC 2045,2046. /// </summary> public static readonly string parallel = "multipart/parallel"; /// <summary> /// "multipart/related". Defined in RFC 2387. /// </summary> public static readonly string related = "multipart/related"; /// <summary> /// "multipart/report". Defined in RFC 1892. /// </summary> public static readonly string report = "multipart/report"; /// <summary> /// "multipart/signed". Defined in RFC 1847. /// </summary> public static readonly string signed = "multipart/signed"; /// <summary> /// "multipart/voice-message". Defined in RFC 2421,2423. /// </summary> public static readonly string voice_message = "multipart/voice-message"; #endregion } #endregion #region Nested type: Text /// <summary> /// This class holds well-known text/xxx media types. /// </summary> public class Text { #region Members /// <summary> /// "text/calendar". Defined in RFC 2445. /// </summary> public static readonly string calendar = "text/calendar"; /// <summary> /// "text/css". Defined in RFC 2854 /// </summary> public static readonly string css = "text/css"; /// <summary> /// "text/html". Defined in RFC 2854. /// </summary> public static readonly string html = "text/html"; /// <summary> /// "text/plain". Defined in RFC 2646,2046. /// </summary> public static readonly string plain = "text/plain"; /// <summary> /// "text/rfc822-headers". Defined in RFC 1892. /// </summary> public static readonly string rfc822_headers = "text/rfc822-headers"; /// <summary> /// "text/richtext". Defined in RFC 2045,2046. /// </summary> public static readonly string richtext = "text/richtext"; /// <summary> /// "text/xml". Defined in RFC 3023. /// </summary> public static readonly string xml = "text/xml"; #endregion } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/STUN/Client/STUN_NetType.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.STUN.Client { /// <summary> /// Specifies UDP network type. /// </summary> public enum STUN_NetType { /// <summary> /// UDP is always blocked. /// </summary> UdpBlocked, /// <summary> /// No NAT, public IP, no firewall. /// </summary> OpenInternet, /// <summary> /// No NAT, public IP, but symmetric UDP firewall. /// </summary> SymmetricUdpFirewall, /// <summary> /// A full cone NAT is one where all requests from the same internal IP address and port are /// mapped to the same external IP address and port. Furthermore, any external host can send /// a packet to the internal host, by sending a packet to the mapped external address. /// </summary> FullCone, /// <summary> /// A restricted cone NAT is one where all requests from the same internal IP address and /// port are mapped to the same external IP address and port. Unlike a full cone NAT, an external /// host (with IP address X) can send a packet to the internal host only if the internal host /// had previously sent a packet to IP address X. /// </summary> RestrictedCone, /// <summary> /// A port restricted cone NAT is like a restricted cone NAT, but the restriction /// includes port numbers. Specifically, an external host can send a packet, with source IP /// address X and source port P, to the internal host only if the internal host had previously /// sent a packet to IP address X and port P. /// </summary> PortRestrictedCone, /// <summary> /// A symmetric NAT is one where all requests from the same internal IP address and port, /// to a specific destination IP address and port, are mapped to the same external IP address and /// port. If the same host sends a packet with the same source address and port, but to /// a different destination, a different mapping is used. Furthermore, only the external host that /// receives a packet can send a UDP packet back to the internal host. /// </summary> Symmetric } }<file_sep>/web/studio/ASC.Web.Studio/Products/People/Warmup.aspx.cs  using System.Collections.Generic; using ASC.Web.Core; namespace ASC.Web.People { public partial class Warmup : WarmupPage { protected override List<string> Exclude { get { return new List<string>(1) { "Reassigns.aspx" }; } } } }<file_sep>/web/studio/ASC.Web.Studio/Warmup.aspx.cs using System.Collections.Generic; using ASC.Web.Core; namespace ASC.Web.Studio { public partial class Warmup : WarmupPage { protected override List<string> Pages { get { return new List<string>(10) { "Management.aspx?type=1", "Management.aspx?type=2", "Management.aspx?type=3", "Management.aspx?type=4", "Management.aspx?type=5", "Management.aspx?type=6", "Management.aspx?type=7", "Management.aspx?type=10", "Management.aspx?type=11", "Management.aspx?type=15", }; } } protected override List<string> Exclude { get { return new List<string>(5) { "Auth.aspx", "403.aspx", "404.aspx", "500.aspx", "PaymentRequired.aspx", "ServerError.aspx", "Tariffs.aspx", "Terms.aspx", "Wizard.aspx" }; } } } }<file_sep>/redistributable/ShrapBox/Src/AppLimit.CloudComputing.SharpBox/UI/Presentation/LoginControl.cs using System; using System.Windows.Forms; namespace AppLimit.CloudComputing.SharpBox.UI { /// <summary> /// Generic Login control /// </summary> public partial class LoginControl : UserControl { /// <summary> /// Standard constructor /// </summary> public LoginControl() { InitializeComponent(); } /// <summary> /// Username typed /// </summary> public String User { get { return txtUserName.Text; } } /// <summary> /// Password typed /// </summary> public String Password { get { return txtPassword.Text; } } /// <summary> /// End of login event /// </summary> public event EventHandler LoginCompleted; /// <summary> /// Login completed event /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void OnLoginCompleted(Object sender, EventArgs e) { if (LoginCompleted != null) { LoginCompleted(this, new EventArgs()); } } private void btnLogin_Click(object sender, EventArgs e) { OnLoginCompleted(sender, e); } } } <file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/Multilang/IMLangStringBufW.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace MultiLanguage { using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Security; [ComImport, InterfaceType((short) 1), Guid("D24ACD21-BA72-11D0-B188-00AA0038C969"), ComConversionLoss] public interface IMLangStringBufW { [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetStatus(out int plFlags, out int pcchBuf); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void LockBuf([In] int cchOffset, [In] int cchMaxLock, [Out] IntPtr ppszBuf, out int pcchBuf); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void UnlockBuf([In] ref ushort pszBuf, [In] int cchOffset, [In] int cchWrite); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void Insert([In] int cchOffset, [In] int cchMaxInsert, out int pcchActual); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void Delete([In] int cchOffset, [In] int cchDelete); } } <file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/Data/lsDB_FixedLengthRecord.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Data.lsDB { #region usings using System; using System.Text; #endregion /// <summary> /// lsDB_FixedLengthTable table record. /// </summary> public class lsDB_FixedLengthRecord { #region Members private readonly int m_ColumnCount = -1; private readonly int[] m_ColumnDataSizes; private readonly int[] m_ColumnDataStartOffsets; private readonly LDB_DataType[] m_ColumnDataTypes; private long m_Pointer = -1; private lsDB_FixedLengthTable m_pOwnerDb; private byte[] m_RowData; #endregion #region Properties /// <summary> /// Gets or sets specified data column value. /// </summary> /// <param name="columnIndex">Zero based column index.</param> /// <returns></returns> public object this[int columnIndex] { /* Fixed record structure: 1 byte - specified is row is used or free space u - used f - free space x bytes - columns data 2 bytes - CRLF */ get { if (columnIndex < 0) { throw new Exception("The columnIndex can't be negative value !"); } if (columnIndex > m_ColumnCount) { throw new Exception("The columnIndex out of columns count !"); } return ConvertFromInternalData(m_ColumnDataTypes[columnIndex], m_RowData, m_ColumnDataStartOffsets[columnIndex], m_ColumnDataSizes[columnIndex]); } set { if (columnIndex < 0) { throw new Exception("The columnIndex can't be negative value !"); } if (columnIndex > m_ColumnCount) { throw new Exception("The columnIndex out of columns count !"); } byte[] val = LDB_Record.ConvertToInternalData(m_pOwnerDb.Columns[columnIndex], value); // Check that value won't exceed maximum cloumn allowed size if (val.Length > m_ColumnDataSizes[columnIndex]) { throw new Exception("Value exceeds maximum allowed value for column '" + m_pOwnerDb.Columns[columnIndex].ColumnName + "' !"); } // TODO: String, string must be char(0) terminated and padded to column length if (m_ColumnDataTypes[columnIndex] == LDB_DataType.String) { throw new Exception("TODO: String not implemented !"); } // Update value in database file m_pOwnerDb.WriteToFile(m_Pointer + m_ColumnDataStartOffsets[columnIndex], val, 0, val.Length); // Update value in buffer Array.Copy(val, 0, m_RowData, m_ColumnDataStartOffsets[columnIndex], val.Length); } } /// <summary> /// Gets row pointer. /// </summary> internal long Pointer { get { return m_Pointer; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="ownerDb">Table that owns this row.</param> /// <param name="pointer">Row start offset in data base file.</param> /// <param name="rowData">Row data.</param> internal lsDB_FixedLengthRecord(lsDB_FixedLengthTable ownerDb, long pointer, byte[] rowData) { m_pOwnerDb = ownerDb; m_Pointer = pointer; m_RowData = rowData; m_ColumnCount = ownerDb.Columns.Count; m_ColumnDataTypes = new LDB_DataType[m_ColumnCount]; m_ColumnDataSizes = new int[m_ColumnCount]; for (int i = 0; i < m_ColumnDataSizes.Length; i++) { m_ColumnDataTypes[i] = m_pOwnerDb.Columns[i].DataType; m_ColumnDataSizes[i] = m_pOwnerDb.Columns[i].ColumnSize; } m_ColumnDataStartOffsets = new int[m_ColumnCount]; int columnDataStartOffset = 1; for (int i = 0; i < m_ColumnDataStartOffsets.Length; i++) { m_ColumnDataStartOffsets[i] = columnDataStartOffset; columnDataStartOffset += m_pOwnerDb.Columns[i].ColumnSize; } } #endregion #region Methods /// <summary> /// Converts internal data to .NET data type. /// </summary> /// <param name="dataType">Data type.</param> /// <param name="val">Data buffer.</param> /// <param name="offset">Offset in data buffer where to start reading data.</param> /// <param name="length">Lenght of data to read from data buffer.</param> /// <returns></returns> public static object ConvertFromInternalData(LDB_DataType dataType, byte[] val, int offset, int length) { if (dataType == LDB_DataType.Bool) { return Convert.ToBoolean(val[offset + 0]); } else if (dataType == LDB_DataType.DateTime) { /* Data structure 1 byte day 1 byte month 4 byte year (int) 1 byte hour 1 byte minute 1 byte second */ // day int day = val[offset + 0]; // month int month = val[offset + 1]; // year int year = ldb_Utils.ByteToInt(val, offset + 2); // hour int hour = val[offset + 6]; // minute int minute = val[offset + 7]; // second int second = val[offset + 8]; return new DateTime(year, month, day, hour, minute, second); } else if (dataType == LDB_DataType.Long) { return ldb_Utils.ByteToLong(val, offset + 0); } else if (dataType == LDB_DataType.Int) { return ldb_Utils.ByteToInt(val, offset + 0); } else if (dataType == LDB_DataType.String) { return Encoding.UTF8.GetString(val, offset, length); } else { throw new Exception("Invalid column data type, never must reach here !"); } } #endregion #region Internal methods /// <summary> /// Reuses lsDB_FixedLengthRecord object, /// </summary> /// <param name="ownerDb">Table that owns this row.</param> /// <param name="pointer">Row start offset in data base file.</param> /// <param name="rowData">Row data.</param> internal void ReuseRecord(lsDB_FixedLengthTable ownerDb, long pointer, byte[] rowData) { m_pOwnerDb = ownerDb; m_Pointer = pointer; m_RowData = rowData; } #endregion } }<file_sep>/redistributable/SelectelSharp/Requests/CDN/CDNIvalidationResult.cs using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SelectelSharp.Requests.CDN { public class CDNIvalidationResult { [JsonProperty("estimatedSeconds")] public int EstimatedSeconds { get; private set; } [JsonProperty("progressUri")] public Uri ProgressUri { get; private set; } [JsonProperty("supportId")] public String SupportId { get; private set; } [JsonProperty("PurgeId")] public String PurgeId { get; private set; } [JsonProperty("httpStatus")] public int HttpStatus { get; private set; } [JsonProperty("pingAfterSeconds")] public int PingAfterSeconds { get; private set; } [JsonProperty("detail")] public String Detail { get; private set; } } } <file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/SIP/Message/SIP_OptionTags.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.SIP.Message { /// <summary> /// SIP Option Tags. Defined in RFC 3261 27.1, defined values are in: http://www.iana.org/assignments/sip-parameters. /// </summary> /// <remarks> /// Option tags are used in header fields such as Require, Supported, Proxy-Require, and /// Unsupported in support of SIP compatibility mechanisms for extensions (Section 19.2). /// The option tag itself is a string that is associated with a particular SIP option (that is, an extension). /// </remarks> public class SIP_OptionTags { #region Members /// <summary> /// A UA adding the early-session option tag to a message indicates that it understands the /// early-session content disposition. Defined in rfc 3959. /// </summary> public const string early_session = "early-session"; /// <summary> /// Extension to allow subscriptions to lists of resources. Defined in rfc 4662. /// </summary> public const string eventlist = "eventlist"; /// <summary> /// When used with the Supported header, this option tag indicates support for the /// History Information to be captured for requests and returned in subsequent responses. /// This tag is not used in a Proxy-Require or Require header field since support of /// History-Info is optional. Defined in rfc 4244. /// </summary> public const string histinfo = "histinfo"; /// <summary> /// Support for the SIP Join Header. Defined in rfc 3911. /// </summary> public const string join = "join"; /// <summary> /// This option tag specifies a User Agent ability of accepting a REFER request without /// establishing an implicit subscription (compared to the default case defined in RFC3515). /// Defined in rfc 3911. /// </summary> public const string norefersub = "norefersub"; /// <summary> /// A SIP UA that supports the Path extension header field includes this option tag as a /// header field value in a Supported header field in all requests generated by that UA. /// Intermediate proxies may use the presence of this option tag in a REGISTER request to /// determine whether to offer Path service for for that request. If an intermediate proxy /// requires that the registrar support Path for a request, then it includes this option tag /// as a header field value in a Requires header field in that request. Defined in rfc 3327. /// </summary> public const string path = "path"; /// <summary> /// An offerer MUST include this tag in the Require header field if the offer contains /// one or more "mandatory" strength-tags. If all the strength-tags in the description are /// "optional" or "none" the offerer MUST include this tag either in a Supported header field or /// in a Require header field. Defined in rfc 3312. /// </summary> public const string precondition = "precondition"; /// <summary> /// This option tag is used to ensure that a server understands the callee capabilities /// parameters used in the request. Defined in rfc 3840. /// </summary> public const string pref = "pref"; /// <summary> /// This option tag indicates support for the Privacy mechanism. When used in the /// Proxy-Require header, it indicates that proxy servers do not forward the request unless they /// can provide the requested privacy service. This tag is not used in the Require or /// Supported headers. Proxies remove this option tag before forwarding the request if the desired /// privacy function has been performed. Defined in rfc 3323. /// </summary> public const string privacy = "privacy"; /// <summary> /// This option tag indicates support for the SIP Replaces header. Defined in rfc 3891. /// </summary> public const string replaces = "replaces"; /// <summary> /// Indicates or requests support for the resource priority mechanism. Defined in rfc 4412. /// </summary> public const string resource_priority = "resource-priority"; /// <summary> /// The option-tag sdp-anat is defined for use in the Require and Supported SIP [RFC3261] /// header fields. SIP user agents that place this option-tag in a Supported header field understand /// the ANAT semantics as defined in [RFC4091]. Defined in rfc 4092. /// </summary> public const string sdp_anat = "sdp-anat"; /// <summary> /// This option tag indicates support for the Security Agreement mechanism. When used in the /// Require, or Proxy-Require headers, it indicates that proxy servers are required to use the Security /// Agreement mechanism. When used in the Supported header, it indicates that the User Agent Client /// supports the Security Agreement mechanism. When used in the Require header in the 494 (Security Agreement /// Required) or 421 (Extension Required) responses, it indicates that the User Agent Client must use the /// Security Agreement Mechanism. Defined in rfc 3329. /// </summary> public const string sec_agree = "sec-agree"; /// <summary> /// This option tag is used to identify the target dialog header field extension. When used in a /// Require header field, it implies that the recipient needs to support the Target-Dialog header field. /// When used in a Supported header field, it implies that the sender of the message supports it. /// Defined in rfc 4538. /// </summary> public const string tdialog = "tdialog"; /// <summary> /// This option tag is for support of the session timer extension. Inclusion in a Supported /// header field in a request or response indicates that the UA is capable of performing /// refreshes according to that specification. Inclusion in a Require header in a request /// means that the UAS must understand the session timer extension to process the request. /// Inclusion in a Require header field in a response indicates that the UAC must look for the /// Session-Expires header field in the response, and process accordingly. Defined in rfc 4028. /// </summary> public const string timer = "timer"; /// <summary> /// This option tag is for reliability of provisional responses. When present in a /// Supported header, it indicates that the UA can send or receive reliable provisional /// responses. When present in a Require header in a request it indicates that the UAS MUST /// send all provisional responses reliably. When present in a Require header in a /// reliable provisional response, it indicates that the response is to be sent reliably. /// Defined in rfc 3262. /// </summary> public const string x100rel = "100rel"; #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/SIP/Message/SIP_t_ViaParm.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.SIP.Message { #region usings using System; using System.Net; using System.Text; using Stack; #endregion /// <summary> /// Implements SIP "via-parm" value. Defined in RFC 3261. /// </summary> /// <remarks> /// <code> /// RFC 3261 Syntax: /// via-parm = sent-protocol LWS sent-by *( SEMI via-params ) /// via-params = via-ttl / via-maddr / via-received / via-branch / via-extension /// via-ttl = "ttl" EQUAL ttl /// via-maddr = "maddr" EQUAL host /// via-received = "received" EQUAL (IPv4address / IPv6address) /// via-branch = "branch" EQUAL token /// via-extension = generic-param /// sent-protocol = protocol-name SLASH protocol-version SLASH transport /// protocol-name = "SIP" / token /// protocol-version = token /// transport = "UDP" / "TCP" / "TLS" / "SCTP" / other-transport /// sent-by = host [ COLON port ] /// ttl = 1*3DIGIT ; 0 to 255 /// /// Via extentions: /// // RFC 3486 /// via-compression = "comp" EQUAL ("sigcomp" / other-compression) /// // RFC 3581 /// response-port = "rport" [EQUAL 1*DIGIT] /// </code> /// </remarks> public class SIP_t_ViaParm : SIP_t_ValueWithParams { #region Members private string m_ProtocolName = ""; private string m_ProtocolTransport = ""; private string m_ProtocolVersion = ""; private HostEndPoint m_pSentBy; #endregion #region Properties /// <summary> /// Gets sent protocol name. Normally this is always SIP. /// </summary> public string ProtocolName { get { return m_ProtocolName; } set { if (string.IsNullOrEmpty(value)) { throw new ArgumentException("Property ProtocolName can't be null or empty !"); } m_ProtocolName = value; } } /// <summary> /// Gets sent protocol version. /// </summary> public string ProtocolVersion { get { return m_ProtocolVersion; } set { if (string.IsNullOrEmpty(value)) { throw new ArgumentException("Property ProtocolVersion can't be null or empty !"); } m_ProtocolVersion = value; } } /// <summary> /// Gets sent protocol transport. Currently known values are: UDP,TCP,TLS,SCTP. This value is always in upper-case. /// </summary> public string ProtocolTransport { get { return m_ProtocolTransport.ToUpper(); } set { if (string.IsNullOrEmpty(value)) { throw new ArgumentException("Property ProtocolTransport can't be null or empty !"); } m_ProtocolTransport = value; } } /// <summary> /// Gets host name or IP with optional port. Examples: lumiosft.ee,10.0.0.1:80. /// </summary> /// <exception cref="ArgumentNullException">Is raised when null reference passed.</exception> public HostEndPoint SentBy { get { return m_pSentBy; } set { if (value == null) { throw new ArgumentNullException("value"); } m_pSentBy = value; } } /// <summary> /// Gets sent-by port, if no port explicity set, transport default is returned. /// </summary> public int SentByPortWithDefault { get { if (m_pSentBy.Port != -1) { return m_pSentBy.Port; } else { if (ProtocolTransport == SIP_Transport.TLS) { return 5061; } else { return 5060; } } } } /// <summary> /// Gets or sets 'branch' parameter value. The branch parameter in the Via header field values /// serves as a transaction identifier. The value of the branch parameter MUST start /// with the magic cookie "z9hG4bK". Value null means that branch paramter doesn't exist. /// </summary> public string Branch { get { SIP_Parameter parameter = Parameters["branch"]; if (parameter != null) { return parameter.Value; } else { return null; } } set { if (string.IsNullOrEmpty(value)) { Parameters.Remove("branch"); } else { if (!value.StartsWith("z9hG4bK")) { throw new ArgumentException( "Property Branch value must start with magic cookie 'z9hG4bK' !"); } Parameters.Set("branch", value); } } } /// <summary> /// Gets or sets 'comp' parameter value. Value null means not specified. Defined in RFC 3486. /// </summary> public string Comp { get { SIP_Parameter parameter = Parameters["comp"]; if (parameter != null) { return parameter.Value; } else { return null; } } set { if (string.IsNullOrEmpty(value)) { Parameters.Remove("comp"); } else { Parameters.Set("comp", value); } } } /// <summary> /// Gets or sets 'maddr' parameter value. Value null means not specified. /// </summary> public string Maddr { get { SIP_Parameter parameter = Parameters["maddr"]; if (parameter != null) { return parameter.Value; } else { return null; } } set { if (string.IsNullOrEmpty(value)) { Parameters.Remove("maddr"); } else { Parameters.Set("maddr", value); } } } /// <summary> /// Gets or sets 'received' parameter value. Value null means not specified. /// </summary> public IPAddress Received { get { SIP_Parameter parameter = Parameters["received"]; if (parameter != null) { return IPAddress.Parse(parameter.Value); } else { return null; } } set { if (value == null) { Parameters.Remove("received"); } else { Parameters.Set("received", value.ToString()); } } } /// <summary> /// Gets or sets 'rport' parameter value. Value -1 means not specified and value 0 means empty "" rport. /// </summary> public int RPort { get { SIP_Parameter parameter = Parameters["rport"]; if (parameter != null) { if (parameter.Value == "") { return 0; } else { return Convert.ToInt32(parameter.Value); } } else { return -1; } } set { if (value < 0) { Parameters.Remove("rport"); } else if (value == 0) { Parameters.Set("rport", ""); } else { Parameters.Set("rport", value.ToString()); } } } /// <summary> /// Gets or sets 'ttl' parameter value. Value -1 means not specified. /// </summary> public int Ttl { get { SIP_Parameter parameter = Parameters["ttl"]; if (parameter != null) { return Convert.ToInt32(parameter.Value); } else { return -1; } } set { if (value < 0) { Parameters.Remove("ttl"); } else { Parameters.Set("ttl", value.ToString()); } } } #endregion #region Constructor /// <summary> /// Defualt constructor. /// </summary> public SIP_t_ViaParm() { m_ProtocolName = "SIP"; m_ProtocolVersion = "2.0"; m_ProtocolTransport = "UDP"; m_pSentBy = new HostEndPoint("localhost", -1); } #endregion #region Methods /// <summary> /// Creates new branch paramter value. /// </summary> /// <returns></returns> public static string CreateBranch() { // The value of the branch parameter MUST start with the magic cookie "z9hG4bK". return "z9hG4bK-" + Guid.NewGuid().ToString().Replace("-", ""); } /// <summary> /// Parses "via-parm" from specified value. /// </summary> /// <param name="value">SIP "via-parm" value.</param> /// <exception cref="ArgumentNullException">Raised when <b>reader</b> is null.</exception> /// <exception cref="SIP_ParseException">Raised when invalid SIP message.</exception> public void Parse(string value) { if (value == null) { throw new ArgumentNullException("reader"); } Parse(new StringReader(value)); } /// <summary> /// Parses "via-parm" from specified reader. /// </summary> /// <param name="reader">Reader from where to parse.</param> /// <exception cref="ArgumentNullException">Raised when <b>reader</b> is null.</exception> /// <exception cref="SIP_ParseException">Raised when invalid SIP message.</exception> public override void Parse(StringReader reader) { /* via-parm = sent-protocol LWS sent-by *( SEMI via-params ) via-params = via-ttl / via-maddr / via-received / via-branch / via-extension via-ttl = "ttl" EQUAL ttl via-maddr = "maddr" EQUAL host via-received = "received" EQUAL (IPv4address / IPv6address) via-branch = "branch" EQUAL token via-extension = generic-param sent-protocol = protocol-name SLASH protocol-version SLASH transport protocol-name = "SIP" / token protocol-version = token transport = "UDP" / "TCP" / "TLS" / "SCTP" / other-transport sent-by = host [ COLON port ] ttl = 1*3DIGIT ; 0 to 255 Via extentions: // RFC 3486 via-compression = "comp" EQUAL ("sigcomp" / other-compression) // RFC 3581 response-port = "rport" [EQUAL 1*DIGIT] Examples: Via: SIP/2.0/UDP 127.0.0.1:58716;branch=z9hG4bK-d87543-4d7e71216b27df6e-1--d87543- // Specifically, LWS on either side of the ":" or "/" is allowed. Via: SIP / 2.0 / UDP 127.0.0.1:58716;branch=z9hG4bK-d87543-4d7e71216b27df6e-1--d87543- */ if (reader == null) { throw new ArgumentNullException("reader"); } // protocol-name string word = reader.QuotedReadToDelimiter('/'); if (word == null) { throw new SIP_ParseException("Via header field protocol-name is missing !"); } ProtocolName = word.Trim(); // protocol-version word = reader.QuotedReadToDelimiter('/'); if (word == null) { throw new SIP_ParseException("Via header field protocol-version is missing !"); } ProtocolVersion = word.Trim(); // transport word = reader.ReadWord(); if (word == null) { throw new SIP_ParseException("Via header field transport is missing !"); } ProtocolTransport = word.Trim(); // sent-by word = reader.QuotedReadToDelimiter(new[] {';', ','}, false); if (word == null) { throw new SIP_ParseException("Via header field sent-by is missing !"); } SentBy = HostEndPoint.Parse(word.Trim()); // Parse parameters ParseParameters(reader); } /// <summary> /// Converts this to valid "via-parm" value. /// </summary> /// <returns>Returns "via-parm" value.</returns> public override string ToStringValue() { /* Via = ( "Via" / "v" ) HCOLON via-parm *(COMMA via-parm) via-parm = sent-protocol LWS sent-by *( SEMI via-params ) via-params = via-ttl / via-maddr / via-received / via-branch / via-extension via-ttl = "ttl" EQUAL ttl via-maddr = "maddr" EQUAL host via-received = "received" EQUAL (IPv4address / IPv6address) via-branch = "branch" EQUAL token via-extension = generic-param sent-protocol = protocol-name SLASH protocol-version SLASH transport protocol-name = "SIP" / token protocol-version = token transport = "UDP" / "TCP" / "TLS" / "SCTP" / other-transport sent-by = host [ COLON port ] ttl = 1*3DIGIT ; 0 to 255 Via extentions: // RFC 3486 via-compression = "comp" EQUAL ("sigcomp" / other-compression) // RFC 3581 response-port = "rport" [EQUAL 1*DIGIT] Examples: Via: SIP/2.0/UDP 127.0.0.1:58716;branch=z9hG4bK-d87543-4d7e71216b27df6e-1--d87543- // Specifically, LWS on either side of the ":" or "/" is allowed. Via: SIP / 2.0 / UDP 127.0.0.1:58716;branch=z9hG4bK-d87543-4d7e71216b27df6e-1--d87543- */ StringBuilder retVal = new StringBuilder(); retVal.Append(ProtocolName + "/" + ProtocolVersion + "/" + ProtocolTransport + " "); retVal.Append(SentBy.ToString()); retVal.Append(ParametersToString()); return retVal.ToString(); } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/RTP/RTP_PayloadTypes.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.RTP { /// <summary> /// RTP payload specifies data type which is RTP packet. /// IANA registered RTP payload types. Defined in http://www.iana.org/assignments/rtp-parameters. /// </summary> public class RTP_PayloadTypes { #region Members /// <summary> /// CELB video codec. Defined in RFC 2029. /// </summary> public static readonly int CELB = 25; /// <summary> /// DVI4 11025hz audio codec. /// </summary> public static readonly int DVI4_11025 = 16; /// <summary> /// DVI4 16khz audio codec. Defined in RFC 3551. /// </summary> public static readonly int DVI4_16000 = 6; /// <summary> /// DVI4 220505hz audio codec. /// </summary> public static readonly int DVI4_22050 = 17; /// <summary> /// DVI4 8khz audio codec. Defined in RFC 3551. /// </summary> public static readonly int DVI4_8000 = 5; /// <summary> /// G722 audio codec. Defined in RFC 3551. /// </summary> public static readonly int G722 = 9; /// <summary> /// G723 audio codec. /// </summary> public static readonly int G723 = 4; /// <summary> /// G728 audio codec. Defined in RFC 3551. /// </summary> public static readonly int G728 = 15; /// <summary> /// G729 audio codec. /// </summary> public static readonly int G729 = 18; /// <summary> /// GSM audio codec. Defined in RFC 3551. /// </summary> public static readonly int GSM = 3; /// <summary> /// H261 video codec. Defined in RFC 2032. /// </summary> public static readonly int H261 = 31; /// <summary> /// H263 video codec. /// </summary> public static readonly int H263 = 34; /// <summary> /// JPEG video codec. Defined in RFC 2435. /// </summary> public static readonly int JPEG = 26; /// <summary> /// L16 1 channel audio codec. Defined in RFC 3551. /// </summary> public static readonly int L16_1CH = 10; /// <summary> /// L16 2 channel audio codec. Defined in RFC 3551. /// </summary> public static readonly int L16_2CH = 11; /// <summary> /// LPC audio codec. Defined in RFC 3551. /// </summary> public static readonly int LPC = 7; /// <summary> /// MP2T video codec. Defined in RFC 2250. /// </summary> public static readonly int MP2T = 33; /// <summary> /// MPA audio codec. Defined in RFC 3551. /// </summary> public static readonly int MPA = 14; /// <summary> /// H261 video codec. Defined in RFC 2250. /// </summary> public static readonly int MPV = 32; /// <summary> /// NV video codec. Defined in RFC 3551. /// </summary> public static readonly int NV = 28; /// <summary> /// PCMA(a-law) audio codec. Defined in RFC 3551. /// </summary> public static readonly int PCMA = 8; /// <summary> /// PCMU8(u-law) audio codec. Defined in RFC 3551. /// </summary> public static readonly int PCMU; /// <summary> /// QCELP audio codec. /// </summary> public static readonly int QCELP = 12; #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/IMAP/Client/IMAP_FetchItem.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.IMAP.Client { #region usings using System; using System.IO; using System.Text; using Mime; using Server; #endregion /// <summary> /// IMAP fetch item. /// </summary> public class IMAP_FetchItem { #region Members private readonly string m_BodyStructure = ""; private readonly byte[] m_Data; private readonly string m_Envelope = ""; private readonly IMAP_FetchItem_Flags m_FetchFlags = IMAP_FetchItem_Flags.MessageFlags; private readonly IMAP_MessageFlags m_Flags = IMAP_MessageFlags.Recent; private readonly string m_InternalDate = ""; private readonly int m_No; private readonly int m_Size; private readonly int m_UID; #endregion #region Properties /// <summary> /// Specifies what data this IMAP_FetchItem contains. This is flagged value and can contain multiple values. /// </summary> public IMAP_FetchItem_Flags FetchFlags { get { return m_FetchFlags; } } /// <summary> /// Gets number of message in folder. /// </summary> public int MessageNumber { get { return m_No; } } /// <summary> /// Gets message UID. This property is available only if IMAP_FetchItem_Flags.UID was specified, /// otherwise throws exception. /// </summary> public int UID { get { if ((m_FetchFlags & IMAP_FetchItem_Flags.UID) == 0) { throw new Exception( "IMAP_FetchItem_Flags.UID wasn't specified in FetchMessages command, becuse of it this property is unavailable."); } return m_UID; } } /// <summary> /// Gets message size. This property is available only if IMAP_FetchItem_Flags.Size was specified, /// otherwise throws exception. /// </summary> public int Size { get { if ((m_FetchFlags & IMAP_FetchItem_Flags.Size) == 0) { throw new Exception( "IMAP_FetchItem_Flags.Size wasn't specified in FetchMessages command, becuse of it this property is unavailable."); } return m_Size; } } /// <summary> /// Gets message IMAP server INTERNAL date. This property is available only if IMAP_FetchItem_Flags.InternalDate was specified, /// otherwise throws exception. /// </summary> public DateTime InternalDate { get { if ((m_FetchFlags & IMAP_FetchItem_Flags.InternalDate) == 0) { throw new Exception( "IMAP_FetchItem_Flags.InternalDate wasn't specified in FetchMessages command, becuse of it this property is unavailable."); } return IMAP_Utils.ParseDate(m_InternalDate); } } /// <summary> /// Gets message flags. This property is available only if IMAP_FetchItem_Flags.MessageFlags was specified, /// otherwise throws exception. /// </summary> public IMAP_MessageFlags MessageFlags { get { if ((m_FetchFlags & IMAP_FetchItem_Flags.MessageFlags) == 0) { throw new Exception( "IMAP_FetchItem_Flags.MessageFlags wasn't specified in FetchMessages command, becuse of it this property is unavailable."); } return m_Flags; } } /// <summary> /// Gets message IMAP ENVELOPE. This property is available only if IMAP_FetchItem_Flags.Envelope was specified, /// otherwise throws exception. /// </summary> public IMAP_Envelope Envelope { get { if ((m_FetchFlags & IMAP_FetchItem_Flags.Envelope) == 0) { throw new Exception( "IMAP_FetchItem_Flags.Envelope wasn't specified in FetchMessages command, becuse of it this property is unavailable."); } IMAP_Envelope envelope = new IMAP_Envelope(); envelope.Parse(m_Envelope); return envelope; } } /// <summary> /// Gets message IMAP BODYSTRUCTURE. This property is available only if IMAP_FetchItem_Flags.BodyStructure was specified, /// otherwise throws exception. /// </summary> public IMAP_BODY BodyStructure { get { if ((m_FetchFlags & IMAP_FetchItem_Flags.BodyStructure) == 0) { throw new Exception( "IMAP_FetchItem_Flags.BodyStructure wasn't specified in FetchMessages command, becuse of it this property is unavailable."); } IMAP_BODY bodyStructure = new IMAP_BODY(); bodyStructure.Parse(m_BodyStructure); return bodyStructure; } } /// <summary> /// Gets message header data. This property is available only if IMAP_FetchItem_Flags.Header was specified, /// otherwise throws exception. /// </summary> public byte[] HeaderData { get { if ( !((m_FetchFlags & IMAP_FetchItem_Flags.Header) != 0 || (m_FetchFlags & IMAP_FetchItem_Flags.Message) != 0)) { throw new Exception( "IMAP_FetchItem_Flags.Header wasn't specified in FetchMessages command, becuse of it this property is unavailable."); } if ((m_FetchFlags & IMAP_FetchItem_Flags.Message) != 0) { return Encoding.ASCII.GetBytes(MimeUtils.ParseHeaders(new MemoryStream(m_Data))); } else { return m_Data; } } } /// <summary> /// Gets message data. This property is available only if IMAP_FetchItem_Flags.Message was specified, /// otherwise throws exception. /// </summary> public byte[] MessageData { get { if ((m_FetchFlags & IMAP_FetchItem_Flags.Message) == 0) { throw new Exception( "IMAP_FetchItem_Flags.Message wasn't specified in FetchMessages command, becuse of it this property is unavailable."); } return m_Data; } } /// <summary> /// Gets if message is unseen. This property is available only if IMAP_FetchItem_Flags.MessageFlags was specified, /// otherwise throws exception. /// </summary> public bool IsNewMessage { get { if ((m_FetchFlags & IMAP_FetchItem_Flags.MessageFlags) == 0) { throw new Exception( "IMAP_FetchItem_Flags.MessageFlags wasn't specified in FetchMessages command, becuse of it this property is unavailable."); } return (m_Flags & IMAP_MessageFlags.Seen) == 0; } } /// <summary> /// Gets if message is answered. This property is available only if IMAP_FetchItem_Flags.MessageFlags was specified, /// otherwise throws exception. /// </summary> public bool IsAnswered { get { if ((m_FetchFlags & IMAP_FetchItem_Flags.MessageFlags) == 0) { throw new Exception( "IMAP_FetchItem_Flags.MessageFlags wasn't specified in FetchMessages command, becuse of it this property is unavailable."); } return (m_Flags & IMAP_MessageFlags.Answered) != 0; } } /// <summary> /// Gets message data(headers or full message), it depends on HeadersOnly property. /// </summary> [Obsolete("Use HeaderData or MessageData data instead.")] public byte[] Data { get { return m_Data; } } /// <summary> /// Gets if headers or full message requested in fetch. /// </summary> [Obsolete("Use FetchFlags property instead !")] public bool HeadersOnly { get { return (m_FetchFlags & IMAP_FetchItem_Flags.Header) != 0; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="no">Number of message in folder.</param> /// <param name="uid">Message UID.</param> /// <param name="size">Message size.</param> /// <param name="data">Message data.</param> /// <param name="flags">Message flags.</param> /// <param name="internalDate">Message INTERNALDATE.</param> /// <param name="envelope">Envelope string.</param> /// <param name="bodyStructure">BODYSTRUCTURE string.</param> /// <param name="fetchFlags">Specifies what data fetched from IMAP server.</param> internal IMAP_FetchItem(int no, int uid, int size, byte[] data, IMAP_MessageFlags flags, string internalDate, string envelope, string bodyStructure, IMAP_FetchItem_Flags fetchFlags) { m_No = no; m_UID = uid; m_Size = size; m_Data = data; m_Flags = flags; m_InternalDate = internalDate; m_Envelope = envelope; m_FetchFlags = fetchFlags; m_BodyStructure = bodyStructure; } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/RTP/RTCP_Packet_SDES_Chunk.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.RTP { #region usings using System; using System.Text; #endregion /// <summary> /// This class implements RTCP SDES packet one "chunk". /// </summary> public class RTCP_Packet_SDES_Chunk { #region Members private string m_CName; private string m_Email; private string m_Location; private string m_Name; private string m_Note; private string m_Phone; private uint m_Source; private string m_Tool; #endregion #region Properties /// <summary> /// Gets SSRC or CSRC identifier. /// </summary> public uint Source { get { return m_Source; } } /// <summary> /// Gets Canonical End-Point Identifier. /// </summary> public string CName { get { return m_CName; } } /// <summary> /// Gets or sets the real name, eg. "<NAME>". Value null means not specified. /// </summary> /// <exception cref="ArgumentException">Is raised when invalid value is passed.</exception> public string Name { get { return m_Name; } set { if (Encoding.UTF8.GetByteCount(value) > 255) { throw new ArgumentException("Property 'Name' value must be <= 255 bytes."); } m_Name = value; } } /// <summary> /// Gets or sets email address. For example "<EMAIL>". Value null means not specified. /// </summary> /// <exception cref="ArgumentException">Is raised when invalid value is passed.</exception> public string Email { get { return m_Email; } set { if (Encoding.UTF8.GetByteCount(value) > 255) { throw new ArgumentException("Property 'Email' value must be <= 255 bytes."); } m_Email = value; } } /// <summary> /// Gets or sets phone number. For example "+1 908 555 1212". Value null means not specified. /// </summary> /// <exception cref="ArgumentException">Is raised when invalid value is passed.</exception> public string Phone { get { return m_Phone; } set { if (Encoding.UTF8.GetByteCount(value) > 255) { throw new ArgumentException("Property 'Phone' value must be <= 255 bytes."); } m_Phone = value; } } /// <summary> /// Gets or sets location string. It may be geographic address or for example chat room name. /// Value null means not specified. /// </summary> /// <exception cref="ArgumentException">Is raised when invalid value is passed.</exception> public string Location { get { return m_Location; } set { if (Encoding.UTF8.GetByteCount(value) > 255) { throw new ArgumentException("Property 'Location' value must be <= 255 bytes."); } m_Location = value; } } /// <summary> /// Gets or sets streaming application name/version. /// Value null means not specified. /// </summary> /// <exception cref="ArgumentException">Is raised when invalid value is passed.</exception> public string Tool { get { return m_Tool; } set { if (Encoding.UTF8.GetByteCount(value) > 255) { throw new ArgumentException("Property 'Tool' value must be <= 255 bytes."); } m_Tool = value; } } /// <summary> /// Gets or sets note text. The NOTE item is intended for transient messages describing the current state /// of the source, e.g., "on the phone, can't talk". Value null means not specified. /// </summary> /// <exception cref="ArgumentException">Is raised when invalid value is passed.</exception> public string Note { get { return m_Note; } set { if (Encoding.UTF8.GetByteCount(value) > 255) { throw new ArgumentException("Property 'Note' value must be <= 255 bytes."); } m_Note = value; } } /// <summary> /// Gets number of bytes needed for this SDES chunk. /// </summary> public int Size { get { int size = 4; if (!string.IsNullOrEmpty(m_CName)) { size += 2; size += Encoding.UTF8.GetByteCount(m_CName); } if (!string.IsNullOrEmpty(m_Name)) { size += 2; size += Encoding.UTF8.GetByteCount(m_Name); } if (!string.IsNullOrEmpty(m_Email)) { size += 2; size += Encoding.UTF8.GetByteCount(m_Email); } if (!string.IsNullOrEmpty(m_Phone)) { size += 2; size += Encoding.UTF8.GetByteCount(m_Phone); } if (!string.IsNullOrEmpty(m_Location)) { size += 2; size += Encoding.UTF8.GetByteCount(m_Location); } if (!string.IsNullOrEmpty(m_Tool)) { size += 2; size += Encoding.UTF8.GetByteCount(m_Tool); } if (!string.IsNullOrEmpty(m_Note)) { size += 2; size += Encoding.UTF8.GetByteCount(m_Note); } // Add terminate byte and padding bytes. size++; size += size%4; return size; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="source">SSRC or CSRC identifier.</param> /// <param name="cname">Canonical End-Point Identifier.</param> /// <exception cref="ArgumentException">Is raised when invalid value is passed.</exception> public RTCP_Packet_SDES_Chunk(uint source, string cname) { if (source == 0) { throw new ArgumentException("Argument 'source' value must be > 0."); } if (string.IsNullOrEmpty(cname)) { throw new ArgumentException("Argument 'cname' value may not be null or empty."); } m_Source = source; m_CName = cname; } /// <summary> /// Parser constructor. /// </summary> internal RTCP_Packet_SDES_Chunk() {} #endregion #region Methods /// <summary> /// Parses SDES chunk from the specified buffer. /// </summary> /// <param name="buffer">Buffer which contains SDES chunk.</param> /// <param name="offset">Offset in buffer.</param> /// <exception cref="ArgumentNullException">Is raised when <b>buffer</b> is null.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> public void Parse(byte[] buffer, ref int offset) { if (buffer == null) { throw new ArgumentNullException("buffer"); } if (offset < 0) { throw new ArgumentException("Argument 'offset' value must be >= 0."); } /* RFC 3550 6.5. The list of items in each chunk MUST be terminated by one or more null octets, the first of which is interpreted as an item type of zero to denote the end of the list. No length octet follows the null item type octet, but additional null octets MUST be included if needed to pad until the next 32-bit boundary. Note that this padding is separate from that indicated by the P bit in the RTCP header. A chunk with zero items (four null octets) is valid but useless. */ int startOffset = offset; // Read SSRC/CSRC m_Source = (uint) (buffer[offset++] << 24 | buffer[offset++] << 16 | buffer[offset++] << 8 | buffer[offset++]); // Read SDES items while reach end of buffer or we get chunk terminator(\0). while (offset < buffer.Length && buffer[offset] != 0) { int type = buffer[offset++]; int length = buffer[offset++]; // CNAME if (type == 1) { m_CName = Encoding.UTF8.GetString(buffer, offset, length); } // NAME else if (type == 2) { m_Name = Encoding.UTF8.GetString(buffer, offset, length); } // EMAIL else if (type == 3) { m_Email = Encoding.UTF8.GetString(buffer, offset, length); } // PHONE else if (type == 4) { m_Phone = Encoding.UTF8.GetString(buffer, offset, length); } // LOC else if (type == 5) { m_Location = Encoding.UTF8.GetString(buffer, offset, length); } // TOOL else if (type == 6) { m_Tool = Encoding.UTF8.GetString(buffer, offset, length); } // NOTE else if (type == 7) { m_Note = Encoding.UTF8.GetString(buffer, offset, length); } // PRIV else if (type == 8) { // TODO: } offset += length; } // Terminator 0. offset++; // Pad to 32-bit boundary, if it isn't. See not above. offset += (offset - startOffset)%4; } /// <summary> /// Stores SDES junk to the specified buffer. /// </summary> /// <param name="buffer">Buffer where to store data.</param> /// <param name="offset">Offset in buffer.</param> /// <exception cref="ArgumentNullException">Is raised when <b>buffer</b> is null.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> public void ToByte(byte[] buffer, ref int offset) { if (buffer == null) { throw new ArgumentNullException("buffer"); } if (offset < 0) { throw new ArgumentException("Argument 'offset' value must be >= 0."); } int startOffset = offset; // SSRC/SDES buffer[offset++] = (byte) ((m_Source >> 24) & 0xFF); buffer[offset++] = (byte) ((m_Source >> 16) & 0xFF); buffer[offset++] = (byte) ((m_Source >> 8) & 0xFF); buffer[offset++] = (byte) ((m_Source) & 0xFF); //--- SDES items ----------------------------------- if (!string.IsNullOrEmpty(m_CName)) { byte[] b = Encoding.UTF8.GetBytes(m_CName); buffer[offset++] = 1; buffer[offset++] = (byte) b.Length; Array.Copy(b, 0, buffer, offset, b.Length); offset += b.Length; } if (!string.IsNullOrEmpty(m_Name)) { byte[] b = Encoding.UTF8.GetBytes(m_Name); buffer[offset++] = 2; buffer[offset++] = (byte) b.Length; Array.Copy(b, 0, buffer, offset, b.Length); offset += b.Length; } if (!string.IsNullOrEmpty(m_Email)) { byte[] b = Encoding.UTF8.GetBytes(m_Email); buffer[offset++] = 3; buffer[offset++] = (byte) b.Length; Array.Copy(b, 0, buffer, offset, b.Length); offset += b.Length; } if (!string.IsNullOrEmpty(m_Phone)) { byte[] b = Encoding.UTF8.GetBytes(m_Phone); buffer[offset++] = 4; buffer[offset++] = (byte) b.Length; Array.Copy(b, 0, buffer, offset, b.Length); offset += b.Length; } if (!string.IsNullOrEmpty(m_Location)) { byte[] b = Encoding.UTF8.GetBytes(m_Location); buffer[offset++] = 5; buffer[offset++] = (byte) b.Length; Array.Copy(b, 0, buffer, offset, b.Length); offset += b.Length; } if (!string.IsNullOrEmpty(m_Tool)) { byte[] b = Encoding.UTF8.GetBytes(m_Tool); buffer[offset++] = 6; buffer[offset++] = (byte) b.Length; Array.Copy(b, 0, buffer, offset, b.Length); offset += b.Length; } if (!string.IsNullOrEmpty(m_Note)) { byte[] b = Encoding.UTF8.GetBytes(m_Note); buffer[offset++] = 7; buffer[offset++] = (byte) b.Length; Array.Copy(b, 0, buffer, offset, b.Length); offset += b.Length; } // Terminate chunk buffer[offset++] = 0; // Pad to 4(32-bit) bytes boundary. while ((offset - startOffset)%4 > 0) { buffer[offset++] = 0; } } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/RTP/RTP_Clock.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.RTP { #region usings using System; #endregion /// <summary> /// Implements RTP media clock. /// </summary> public class RTP_Clock { #region Members private readonly int m_BaseValue; private readonly DateTime m_CreateTime; private readonly int m_Rate = 1; #endregion #region Properties /// <summary> /// Gets clock base value from where clock started. /// </summary> public int BaseValue { get { return m_BaseValue; } } /// <summary> /// Gets current clock rate in Hz. /// </summary> public int Rate { get { return m_Rate; } } /// <summary> /// Gets current RTP timestamp. /// </summary> public uint RtpTimestamp { get { /* m_Rate -> 1000ms elapsed -> x */ long elapsed = (long) ((DateTime.Now - m_CreateTime)).TotalMilliseconds; return (uint) (m_BaseValue + ((m_Rate*elapsed)/1000)); } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="baseValue">Clock base value from where clock starts.</param> /// <param name="rate">Clock rate in Hz.</param> public RTP_Clock(int baseValue, int rate) { if (rate < 1) { throw new ArgumentException("Argument 'rate' value must be between 1 and 100 000.", "rate"); } m_BaseValue = baseValue; m_Rate = rate; m_CreateTime = DateTime.Now; } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/HTTP/Server/HTTP_Server.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections.Generic; using System.Text; using System.Net; using System.Net.Sockets; namespace LumiSoft.Net.HTTP.Server { /// <summary> /// HTTP server component. /// </summary> public class HTTP_Server : SocketServer { /// <summary> /// Defalut constructor. /// </summary> public HTTP_Server() : base() { this.BindInfo = new BindInfo[]{new BindInfo(IPAddress.Any,80,false,null)}; } #region override InitNewSession /// <summary> /// Initialize and start new session here. Session isn't added to session list automatically, /// session must add itself to server session list by calling AddSession(). /// </summary> /// <param name="socket">Connected client socket.</param> /// <param name="bindInfo">BindInfo what accepted socket.</param> protected override void InitNewSession(Socket socket,BindInfo bindInfo) {/* // Check maximum conncurent connections from 1 IP. if(m_MaxConnectionsPerIP > 0){ lock(this.Sessions){ int nSessions = 0; foreach(SocketServerSession s in this.Sessions){ IPEndPoint ipEndpoint = s.RemoteEndPoint; if(ipEndpoint != null){ if(ipEndpoint.Address.Equals(((IPEndPoint)socket.RemoteEndPoint).Address)){ nSessions++; } } // Maximum allowed exceeded if(nSessions >= m_MaxConnectionsPerIP){ socket.Send(System.Text.Encoding.ASCII.GetBytes("-ERR Maximum connections from your IP address is exceeded, try again later !\r\n")); socket.Shutdown(SocketShutdown.Both); socket.Close(); return; } } } }*/ string sessionID = Guid.NewGuid().ToString(); SocketEx socketEx = new SocketEx(socket); if(LogCommands){ //socketEx.Logger = new SocketLogger(socket,this.SessionLog); //socketEx.Logger.SessionID = sessionID; } HTTP_Session session = new HTTP_Session(sessionID,socketEx,bindInfo,this); } #endregion } } <file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/IO/SmartStream.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.IO { #region usings using System; using System.Diagnostics; using System.IO; using System.Text; using System.Threading; using System.Linq; #endregion /// <summary> /// This class is wrapper to normal stream, provides most needed stream methods which are missing from normal stream. /// </summary> public class SmartStream : Stream { #region Delegates private delegate void BufferCallback(Exception x); #endregion #region Members private readonly byte[] m_pReadBuffer; private readonly BufferReadAsyncOP m_pReadBufferOP; private Stream m_pStream; private int m_BufferSize = Workaround.Definitions.MaxStreamLineLength; private long m_BytesReaded; private long m_BytesWritten; private bool m_IsDisposed; private bool m_IsOwner; private DateTime m_LastActivity; private Encoding m_pEncoding = Encoding.Default; private int m_ReadBufferCount; private int m_ReadBufferOffset; #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="stream">Stream to wrap.</param> /// <param name="owner">Specifies if SmartStream is owner of <b>stream</b>.</param> /// <exception cref="ArgumentNullException">Is raised when <b>stream</b> is null.</exception> public SmartStream(Stream stream, bool owner) { if (stream == null) { throw new ArgumentNullException("stream"); } m_pStream = stream; m_pWriteStream = stream; m_IsOwner = owner; m_pReadBuffer = new byte[m_BufferSize]; m_pReadBufferOP = new BufferReadAsyncOP(this); m_LastActivity = DateTime.Now; } #endregion #region Properties /// <summary> /// Gets number of bytes in read buffer. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> public int BytesInReadBuffer { get { if (m_IsDisposed) { throw new ObjectDisposedException("SmartStream"); } return m_ReadBufferCount - m_ReadBufferOffset; } } /// <summary> /// Gets how many bytes are readed through this stream. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> public long BytesReaded { get { if (m_IsDisposed) { throw new ObjectDisposedException("SmartStream"); } return m_BytesReaded; } } /// <summary> /// Gets how many bytes are written through this stream. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> public long BytesWritten { get { if (m_IsDisposed) { throw new ObjectDisposedException("SmartStream"); } return m_BytesWritten; } } /// <summary> /// Gets a value indicating whether the current stream supports reading. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> public override bool CanRead { get { if (m_IsDisposed) { throw new ObjectDisposedException("SmartStream"); } return m_pStream.CanRead; } } /// <summary> /// Gets a value indicating whether the current stream supports seeking. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> public override bool CanSeek { get { if (m_IsDisposed) { throw new ObjectDisposedException("SmartStream"); } return m_pStream.CanSeek; } } /// <summary> /// Gets a value indicating whether the current stream supports writing. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> public override bool CanWrite { get { if (m_IsDisposed) { throw new ObjectDisposedException("SmartStream"); } return m_pStream.CanWrite; } } /// <summary> /// Gets or sets string related methods default encoding. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> /// <exception cref="ArgumentNullException">Is raised when null value is passed.</exception> public Encoding Encoding { get { if (m_IsDisposed) { throw new ObjectDisposedException("SmartStream"); } return m_pEncoding; } set { if (m_IsDisposed) { throw new ObjectDisposedException("SmartStream"); } if (value == null) { throw new ArgumentNullException(); } m_pEncoding = value; } } /// <summary> /// Gets if SmartStream is owner of source stream. This property affects like closing this stream will close SourceStream if IsOwner true. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> public bool IsOwner { get { if (m_IsDisposed) { throw new ObjectDisposedException("SmartStream"); } return m_IsOwner; } set { if (m_IsDisposed) { throw new ObjectDisposedException("SmartStream"); } m_IsOwner = value; } } /// <summary> /// Gets the last time when data was read or written. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> public DateTime LastActivity { get { if (m_IsDisposed) { throw new ObjectDisposedException("SmartStream"); } return m_LastActivity; } } /// <summary> /// Gets the length in bytes of the stream. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> public override long Length { get { if (m_IsDisposed) { throw new ObjectDisposedException("SmartStream"); } return m_pStream.Length; } } /// <summary> /// Gets or sets the position within the current stream. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> public override long Position { get { if (m_IsDisposed) { throw new ObjectDisposedException("SmartStream"); } return m_pStream.Position; } set { if (m_IsDisposed) { throw new ObjectDisposedException("SmartStream"); } m_pStream.Position = value; // Clear read buffer. m_ReadBufferOffset = 0; m_ReadBufferCount = 0; } } /// <summary> /// Gets this stream underlying stream. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> public Stream SourceStream { get { if (m_IsDisposed) { throw new ObjectDisposedException("SmartStream"); } return m_pStream; } } private bool _memoryBuffer = false; private Stream m_pWriteStream; public bool MemoryBuffer { get { return _memoryBuffer; } set { if (value != _memoryBuffer) { _memoryBuffer = value; if (_memoryBuffer) { m_pWriteStream = new MemoryStream(); } else { if (m_pWriteStream is MemoryStream) { //Copy all m_pWriteStream.Position = 0; Net_Utils.StreamCopy(m_pWriteStream, m_pStream, m_BufferSize); m_pWriteStream.Close(); m_pWriteStream.Dispose(); m_pStream.Flush(); } m_pWriteStream = m_pStream; } } } } #endregion #region Methods public override void Close() { Flush(); m_pStream.Close(); base.Close(); } /// <summary> /// Cleans up any resources being used. /// </summary> public new void Dispose() { if (m_IsDisposed) { return; } m_IsDisposed = true; if (m_IsOwner) { Close(); m_pStream.Dispose(); } } // TODO: // *) timeout support for sync versions // *) WriteHeader SmartStream buffers !!! we may not do this if stream wont support seeking. /// <summary> /// Begins an asynchronous line reading from the source stream. /// </summary> /// <param name="buffer">Buffer where to store readed line data.</param> /// <param name="offset">The location in <b>buffer</b> to begin storing the data.</param> /// <param name="maxCount">Maximum number of bytes to read.</param> /// <param name="exceededAction">Specifies how this method behaves when maximum line size exceeded.</param> /// <param name="callback">The AsyncCallback delegate that is executed when asynchronous operation completes.</param> /// <param name="state">An object that contains any additional user-defined data.</param> /// <returns>An IAsyncResult that represents the asynchronous call.</returns> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="ArgumentNullException">Is raised when <b>buffer</b> is null reference.</exception> /// <exception cref="ArgumentOutOfRangeException">is raised when any of the arguments has invalid value.</exception> public IAsyncResult BeginReadLine(byte[] buffer, int offset, int maxCount, SizeExceededAction exceededAction, AsyncCallback callback, object state) { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (buffer == null) { throw new ArgumentNullException("buffer"); } if (offset < 0) { throw new ArgumentOutOfRangeException("offset", "Argument 'offset' value must be >= 0."); } if (offset > buffer.Length) { throw new ArgumentOutOfRangeException("offset", "Argument 'offset' value must be < buffer.Length."); } if (maxCount < 0) { throw new ArgumentOutOfRangeException("maxCount", "Argument 'maxCount' value must be >= 0."); } if (offset + maxCount > buffer.Length) { throw new ArgumentOutOfRangeException("maxCount", "Argument 'maxCount' is bigger than than argument 'buffer' can store."); } return new ReadLineAsyncOperation(this, buffer, offset, maxCount, exceededAction, callback, state); } /// <summary> /// Handles the end of an asynchronous line reading. /// </summary> /// <param name="asyncResult">An IAsyncResult that represents an asynchronous call.</param> /// <returns>Returns number of bytes stored to <b>buffer</b>. Returns -1 if no more data, end of stream reached.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>asyncResult</b> is null reference.</exception> /// <exception cref="ArgumentException">Is raised when invalid <b>asyncResult</b> passed to this method.</exception> /// <exception cref="InvalidOperationException">Is raised when <b>EndReadLine</b> has already been called for specified <b>asyncResult</b>.</exception> /// <exception cref="LineSizeExceededException">Is raised when <b>maxCount</b> value is exceeded.</exception> public int EndReadLine(IAsyncResult asyncResult) { if (asyncResult == null) { throw new ArgumentNullException("asyncResult"); } if (!(asyncResult is ReadLineAsyncOperation)) { throw new ArgumentException( "Argument 'asyncResult' was not returned by a call to the BeginReadLine method."); } ReadLineAsyncOperation ar = (ReadLineAsyncOperation) asyncResult; if (ar.IsEndCalled) { throw new InvalidOperationException( "EndReadLine is already called for specified 'asyncResult'."); } ar.AsyncWaitHandle.WaitOne(); ar.IsEndCalled = true; if (ar.BytesReaded == 0) { return -1; } else { return ar.BytesStored; } } /// <summary> /// Begins line reading. /// </summary> /// <param name="op">Read line opeartion.</param> /// <param name="async">If true then this method can complete asynchronously. If false, this method completed always syncronously.</param> /// <returns>Returns true if read line completed synchronously, false if asynchronous operation pending.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>op</b> is null reference.</exception> public bool ReadLine(ReadLineAsyncOP op, bool async) { if (op == null) { throw new ArgumentNullException("op"); } if (!op.Start(async, this)) { /* REMOVE ME: if(!async){ // Wait while async operation completes. while(!op.IsCompleted){ Thread.Sleep(1); } return true; } else{ return false; }*/ return false; } // Completed synchronously. else { return true; } } /// <summary> /// Begins an asynchronous header reading from the source stream. /// </summary> /// <param name="storeStream">Stream where to store readed header.</param> /// <param name="maxCount">Maximum number of bytes to read. Value 0 means not limited.</param> /// <param name="exceededAction">Specifies action what is done if <b>maxCount</b> number of bytes has exceeded.</param> /// <param name="callback">The AsyncCallback delegate that is executed when asynchronous operation completes.</param> /// <param name="state">An object that contains any additional user-defined data.</param> /// <returns>An IAsyncResult that represents the asynchronous call.</returns> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="ArgumentNullException">Is raised when <b>storeStream</b> is null reference.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> public IAsyncResult BeginReadHeader(Stream storeStream, int maxCount, SizeExceededAction exceededAction, AsyncCallback callback, object state) { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (storeStream == null) { throw new ArgumentNullException("storeStream"); } if (maxCount < 0) { throw new ArgumentException("Argument 'maxCount' must be >= 0."); } return new ReadToTerminatorAsyncOperation(this, "", storeStream, maxCount, exceededAction, callback, state); } /// <summary> /// Handles the end of an asynchronous header reading. /// </summary> /// <param name="asyncResult">An IAsyncResult that represents an asynchronous call.</param> /// <returns>Returns number of bytes stored to <b>storeStream</b>.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>asyncResult</b> is null reference.</exception> /// <exception cref="ArgumentException">Is raised when invalid <b>asyncResult</b> passed to this method.</exception> /// <exception cref="InvalidOperationException">Is raised when <b>EndReadLine</b> has already been called for specified <b>asyncResult</b>.</exception> /// <exception cref="LineSizeExceededException">Is raised when source stream has too big line.</exception> /// <exception cref="DataSizeExceededException">Is raised when reading exceeds <b>maxCount</b> specified value.</exception> /// <exception cref="IncompleteDataException">Is raised when source stream closed before header-terminator reached.</exception> public int EndReadHeader(IAsyncResult asyncResult) { if (asyncResult == null) { throw new ArgumentNullException("asyncResult"); } if (!(asyncResult is ReadToTerminatorAsyncOperation)) { throw new ArgumentException( "Argument 'asyncResult' was not returned by a call to the BeginReadHeader method."); } ReadToTerminatorAsyncOperation ar = (ReadToTerminatorAsyncOperation) asyncResult; if (ar.IsEndCalled) { throw new InvalidOperationException( "EndReadHeader is already called for specified 'asyncResult'."); } ar.AsyncWaitHandle.WaitOne(); ar.IsEndCalled = true; if (ar.Exception != null) { throw ar.Exception; } return (int) ar.BytesStored; } /// <summary> /// Reads header from stream and stores to the specified <b>storeStream</b>. /// </summary> /// <param name="storeStream">Stream where to store readed header.</param> /// <param name="maxCount">Maximum number of bytes to read. Value 0 means not limited.</param> /// <param name="exceededAction">Specifies action what is done if <b>maxCount</b> number of bytes has exceeded.</param> /// <returns>Returns how many bytes readed from source stream.</returns> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="ArgumentNullException">Is raised when <b>storeStream</b> is null.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> /// <exception cref="LineSizeExceededException">Is raised when source stream has too big line.</exception> /// <exception cref="DataSizeExceededException">Is raised when reading exceeds <b>maxCount</b> specified value.</exception> /// <exception cref="IncompleteDataException">Is raised when source stream closed before header-terminator reached.</exception> public int ReadHeader(Stream storeStream, int maxCount, SizeExceededAction exceededAction) { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (storeStream == null) { throw new ArgumentNullException("storeStream"); } if (maxCount < 0) { throw new ArgumentException("Argument 'maxCount' must be >= 0."); } IAsyncResult ar = BeginReadHeader(storeStream, maxCount, exceededAction, null, null); return EndReadHeader(ar); } /// <summary> /// Begins period-terminated data reading. /// </summary> /// <param name="op">Read period terminated opeartion.</param> /// <param name="async">If true then this method can complete asynchronously. If false, this method completed always syncronously.</param> /// <returns>Returns true if read line completed synchronously, false if asynchronous operation pending.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>op</b> is null reference.</exception> public bool ReadPeriodTerminated(ReadPeriodTerminatedAsyncOP op, bool async) { if (op == null) { throw new ArgumentNullException("op"); } if (!op.Start(this)) { if (!async) { // Wait while async operation completes. while (!op.IsCompleted) { Thread.Sleep(1); } return true; } else { return false; } } // Completed synchronously. else { return true; } } /// <summary> /// Begins an asynchronous data reading from the source stream. /// </summary> /// <param name="storeStream">Stream where to store readed header.</param> /// <param name="count">Number of bytes to read.</param> /// <param name="callback">The AsyncCallback delegate that is executed when asynchronous operation completes.</param> /// <param name="state">An object that contains any additional user-defined data.</param> /// <returns>An IAsyncResult that represents the asynchronous call.</returns> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="ArgumentNullException">Is raised when <b>storeStream</b> is null reference.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> public IAsyncResult BeginReadFixedCount(Stream storeStream, long count, AsyncCallback callback, object state) { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (storeStream == null) { throw new ArgumentNullException("storeStream"); } if (count < 0) { throw new ArgumentException("Argument 'count' value must be >= 0."); } return new ReadToStreamAsyncOperation(this, storeStream, count, callback, state); } /// <summary> /// Handles the end of an asynchronous data reading. /// </summary> /// <param name="asyncResult">An IAsyncResult that represents an asynchronous call.</param> /// <exception cref="ArgumentNullException">Is raised when <b>asyncResult</b> is null reference.</exception> /// <exception cref="ArgumentException">Is raised when invalid <b>asyncResult</b> passed to this method.</exception> /// <exception cref="InvalidOperationException">Is raised when <b>EndReadToStream</b> has already been called for specified <b>asyncResult</b>.</exception> public void EndReadFixedCount(IAsyncResult asyncResult) { if (asyncResult == null) { throw new ArgumentNullException("asyncResult"); } if (!(asyncResult is ReadToStreamAsyncOperation)) { throw new ArgumentException( "Argument 'asyncResult' was not returned by a call to the BeginReadFixedCount method."); } ReadToStreamAsyncOperation ar = (ReadToStreamAsyncOperation) asyncResult; if (ar.IsEndCalled) { throw new InvalidOperationException( "EndReadFixedCount is already called for specified 'asyncResult'."); } ar.AsyncWaitHandle.WaitOne(); ar.IsEndCalled = true; if (ar.Exception != null) { throw ar.Exception; } } /// <summary> /// Reads specified number of bytes from source stream and writes to the specified stream. /// </summary> /// <param name="storeStream">Stream where to store readed data.</param> /// <param name="count">Number of bytes to read.</param> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="ArgumentNullException">Is raised when <b>storeStream</b> is null reference.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> public void ReadFixedCount(Stream storeStream, long count) { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (storeStream == null) { throw new ArgumentNullException("storeStream"); } if (count < 0) { throw new ArgumentException("Argument 'count' value must be >= 0."); } IAsyncResult ar = BeginReadFixedCount(storeStream, count, null, null); EndReadFixedCount(ar); } /// <summary> /// Reads specified number of bytes from source stream and converts it to string with current encoding. /// </summary> /// <param name="count">Number of bytes to read.</param> /// <returns>Returns readed data as string.</returns> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> public string ReadFixedCountString(int count) { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (count < 0) { throw new ArgumentException("Argument 'count' value must be >= 0."); } using (MemoryStream ms = new MemoryStream()) { ReadFixedCount(ms, count); return m_pEncoding.GetString(ms.ToArray()); } } /// <summary> /// Reads all data from source stream and stores to the specified stream. /// </summary> /// <param name="stream">Stream where to store readed data.</param> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="ArgumentNullException">Is raised when <b>stream</b> is null.</exception> public void ReadAll(Stream stream) { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (stream == null) { throw new ArgumentNullException("stream"); } byte[] buffer = new byte[Workaround.Definitions.MaxStreamLineLength]; while (true) { int readedCount = Read(buffer, 0, buffer.Length); // End of stream reached, we readed file sucessfully. if (readedCount == 0) { break; } else { stream.Write(buffer, 0, readedCount); } } } /// <summary> /// Returns the next available character but does not consume it. /// </summary> /// <returns>An integer representing the next character to be read, or -1 if no more characters are available.</returns> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> public int Peek() { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (BytesInReadBuffer == 0) { BufferRead(false, null); } // We are end of stream. if (BytesInReadBuffer == 0) { return -1; } else { return m_pReadBuffer[m_ReadBufferOffset]; } } public int Write(byte[] data) { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (data == null) { throw new ArgumentNullException("data"); } Write(data, 0, data.Length); return data.Length; } /// <summary> /// Writes specified string data to stream. /// </summary> /// <param name="data">Data to write.</param> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="ArgumentNullException">Is raised when <b>data</b> is null.</exception> public int Write(string data) { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (data == null) { throw new ArgumentNullException("data"); } byte[] dataBuff = Encoding.Default.GetBytes(data); return Write(dataBuff); } /// <summary> /// Writes specified line to stream. If CRLF is missing, it will be added automatically to line data. /// </summary> /// <param name="line">Line to send.</param> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="ArgumentNullException">Is raised when <b>line</b> is null.</exception> /// <returns>Returns number of raw bytes written.</returns> public int WriteLine(string line) { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (line == null) { throw new ArgumentNullException("line"); } if (!line.EndsWith("\r\n")) { line += "\r\n"; } return Write(line); } /// <summary> /// Writes all source <b>stream</b> data to stream. /// </summary> /// <param name="stream">Stream which data to write.</param> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="ArgumentNullException">Is raised when <b>stream</b> is null.</exception> public void WriteStream(Stream stream) { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (stream == null) { throw new ArgumentNullException("stream"); } byte[] buffer = new byte[m_BufferSize]; while (true) { int readed = stream.Read(buffer, 0, buffer.Length); // We readed all data. if (readed == 0) { break; } Write(buffer, 0, readed); } Flush(); } /// <summary> /// Writes specified number of bytes from source <b>stream</b> to stream. /// </summary> /// <param name="stream">Stream which data to write.</param> /// <param name="count">Number of bytes to write.</param> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="ArgumentNullException">Is raised when <b>stream</b> is null.</exception> /// <exception cref="ArgumentException">Is raised when <b>count</b> argument has invalid value.</exception> public void WriteStream(Stream stream, long count) { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (stream == null) { throw new ArgumentNullException("stream"); } if (count < 0) { throw new ArgumentException("Argument 'count' value must be >= 0."); } byte[] buffer = new byte[m_BufferSize]; long readedCount = 0; while (readedCount < count) { int readed = stream.Read(buffer, 0, (int) Math.Min(buffer.Length, count - readedCount)); readedCount += readed; Write(buffer, 0, readed); } Flush(); } /// <summary> /// Reads all data from the source <b>stream</b> and writes it to stream. Period handling and period terminator is added as required. /// </summary> /// <param name="stream">Source stream which data to write to stream.</param> /// <returns>Returns number of bytes written to source stream.</returns> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="ArgumentNullException">Is raised when <b>stream</b> is null.</exception> /// <exception cref="LineSizeExceededException">Is raised when <b>stream</b> has too big line.</exception> public long WritePeriodTerminated(Stream stream) { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (stream == null) { throw new ArgumentNullException("stream"); } // We need to read lines, do period handling and write them to stream. long totalWritten = 0; byte[] buffer = new byte[m_BufferSize]; ReadLineAsyncOP readLineOP = new ReadLineAsyncOP(buffer, SizeExceededAction.ThrowException); SmartStream reader = new SmartStream(stream, false); while (true) { reader.ReadLine(readLineOP, false); if (readLineOP.Error != null) { throw readLineOP.Error; } // We reached end of stream, no more data. if (readLineOP.BytesInBuffer == 0) { break; } // Period handling. If line starts with period(.), additional period is added. if (readLineOP.LineBytesInBuffer > 0 && buffer[0] == '.') { // Add additional period. Write(new[] {(byte) '.'}, 0, 1); totalWritten++; } // Write line to source stream. Write(buffer, 0, readLineOP.BytesInBuffer); totalWritten += readLineOP.BytesInBuffer; } // Write period terminator. WriteLine("."); Flush(); return totalWritten; } /// <summary> /// Reads header from source <b>stream</b> and writes it to stream. /// </summary> /// <param name="stream">Stream from where to read header.</param> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="ArgumentNullException">Is raised when <b>stream</b> is null.</exception> public void WriteHeader(Stream stream) { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (stream == null) { throw new ArgumentNullException("stream"); } SmartStream reader = new SmartStream(stream, false); reader.ReadHeader(this, -1, SizeExceededAction.ThrowException); } /// <summary> /// Clears all buffers for this stream and causes any buffered data to be written to the underlying device. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> public override void Flush() { if (m_IsDisposed) { throw new ObjectDisposedException("SmartStream"); } MemoryBuffer = false;//drop mem buffer m_pStream.Flush(); } /// <summary> /// Sets the position within the current stream. /// </summary> /// <param name="offset">A byte offset relative to the <b>origin</b> parameter.</param> /// <param name="origin">A value of type SeekOrigin indicating the reference point used to obtain the new position.</param> /// <returns>The new position within the current stream.</returns> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> public override long Seek(long offset, SeekOrigin origin) { if (m_IsDisposed) { throw new ObjectDisposedException("SmartStream"); } return m_pStream.Seek(offset, origin); } /// <summary> /// Sets the length of the current stream. /// </summary> /// <param name="value">The desired length of the current stream in bytes.</param> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> public override void SetLength(long value) { if (m_IsDisposed) { throw new ObjectDisposedException("SmartStream"); } m_pStream.SetLength(value); // Clear read buffer. m_ReadBufferOffset = 0; m_ReadBufferCount = 0; } /// <summary> /// Begins an asynchronous read operation. /// </summary> /// <param name="buffer">The buffer to read the data into.</param> /// <param name="offset">The byte offset in buffer at which to begin writing data read from the stream.</param> /// <param name="count">The maximum number of bytes to read.</param> /// <param name="callback">An optional asynchronous callback, to be called when the read is complete.</param> /// <param name="state">A user-provided object that distinguishes this particular asynchronous read request from other requests.</param> /// <returns>An IAsyncResult that represents the asynchronous read, which could still be pending.</returns> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="ArgumentNullException">Is raised when <b>buffer</b> is null reference.</exception> /// <exception cref="ArgumentOutOfRangeException">Is raised when any of the arguments has out of valid range.</exception> public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state) { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (buffer == null) { throw new ArgumentNullException("buffer"); } if (offset < 0) { throw new ArgumentOutOfRangeException("offset", "Argument 'offset' value must be >= 0."); } if (offset > buffer.Length) { throw new ArgumentOutOfRangeException("offset", "Argument 'offset' value must be < buffer.Length."); } if (count < 0) { throw new ArgumentOutOfRangeException("count", "Argument 'count' value must be >= 0."); } if (offset + count > buffer.Length) { throw new ArgumentOutOfRangeException("count", "Argument 'count' is bigger than than argument 'buffer' can store."); } return new ReadAsyncOperation(this, buffer, offset, count, callback, state); } /// <summary> /// Handles the end of an asynchronous data reading. /// </summary> /// <param name="asyncResult">The reference to the pending asynchronous request to finish.</param> /// <returns>The total number of bytes read into the <b>buffer</b>. This can be less than the number of bytes requested /// if that many bytes are not currently available, or zero (0) if the end of the stream has been reached.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>asyncResult</b> is null reference.</exception> public override int EndRead(IAsyncResult asyncResult) { if (asyncResult == null) { throw new ArgumentNullException("asyncResult"); } if (!(asyncResult is ReadAsyncOperation)) { throw new ArgumentException( "Argument 'asyncResult' was not returned by a call to the BeginRead method."); } ReadAsyncOperation ar = (ReadAsyncOperation) asyncResult; if (ar.IsEndCalled) { throw new InvalidOperationException("EndRead is already called for specified 'asyncResult'."); } ar.AsyncWaitHandle.WaitOne(); ar.IsEndCalled = true; return ar.BytesStored; } /// <summary> /// Reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read. /// </summary> /// <param name="buffer">An array of bytes. When this method returns, the buffer contains the specified byte array with the values between offset and (offset + count - 1) replaced by the bytes read from the current source.</param> /// <param name="offset">The zero-based byte offset in buffer at which to begin storing the data read from the current stream.</param> /// <param name="count">The maximum number of bytes to be read from the current stream.</param> /// <returns>The total number of bytes read into the buffer. This can be less than the number of bytes requested if that many bytes are not currently available, or zero (0) if the end of the stream has been reached.</returns> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="ArgumentNullException">Is raised when <b>buffer</b> is null reference.</exception> /// <exception cref="ArgumentOutOfRangeException">Is raised when any of the arguments has out of valid range.</exception> public override int Read(byte[] buffer, int offset, int count) { if (m_IsDisposed) { throw new ObjectDisposedException("SmartStream"); } if (buffer == null) { throw new ArgumentNullException("buffer"); } if (offset < 0) { throw new ArgumentOutOfRangeException("offset", "Argument 'offset' value must be >= 0."); } if (count < 0) { throw new ArgumentOutOfRangeException("count", "Argument 'count' value must be >= 0."); } if (offset + count > buffer.Length) { throw new ArgumentOutOfRangeException("count", "Argument 'count' is bigger than than argument 'buffer' can store."); } if (BytesInReadBuffer == 0) { BufferRead(false, null); } if (BytesInReadBuffer == 0) { return 0; } else { int countToCopy = Math.Min(count, BytesInReadBuffer); Array.Copy(m_pReadBuffer, m_ReadBufferOffset, buffer, offset, countToCopy); m_ReadBufferOffset += countToCopy; return countToCopy; } } /// <summary> /// Writes a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written. /// </summary> /// <param name="buffer">An array of bytes. This method copies count bytes from buffer to the current stream.</param> /// <param name="offset">The zero-based byte offset in buffer at which to begin copying bytes to the current stream.</param> /// <param name="count">The number of bytes to be written to the current stream.</param> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> public override void Write(byte[] buffer, int offset, int count) { if (m_IsDisposed) { throw new ObjectDisposedException("SmartStream"); } //Log dbg //Debug.Write(Encoding.UTF8.GetString(buffer, offset, count)); m_pWriteStream.Write(buffer, offset, count); m_LastActivity = DateTime.Now; m_BytesWritten += count; } #endregion #region Utility methods /// <summary> /// Begins buffering read-buffer. /// </summary> /// <param name="async">If true then this method can complete asynchronously. If false, this method completed always syncronously.</param> /// <param name="asyncCallback">The callback that is executed when asynchronous operation completes. /// If operation completes synchronously, no callback called.</param> /// <returns> /// Returns true if the I/O operation is pending. The BufferReadAsyncEventArgs.Completed event on the context parameter will be raised upon completion of the operation. /// Returns false if the I/O operation completed synchronously. The BufferReadAsyncEventArgs.Completed event on the context parameter will not be raised and the context object passed as a parameter may be examined immediately after the method call returns to retrieve the result of the operation. /// </returns> /// <exception cref="InvalidOperationException">Is raised when there is data in read buffer and this method is called.</exception> private bool BufferRead(bool async, BufferCallback asyncCallback) { if (BytesInReadBuffer != 0) { throw new InvalidOperationException("There is already data in read buffer."); } m_ReadBufferOffset = 0; m_ReadBufferCount = 0; m_pReadBufferOP.ReleaseEvents(); m_pReadBufferOP.Completed += delegate(object s, EventArgs<BufferReadAsyncOP> e) { if (e.Value.Error != null) { if (asyncCallback != null) { asyncCallback(e.Value.Error); } } else { m_ReadBufferOffset = 0; m_ReadBufferCount = e.Value.BytesInBuffer; m_BytesReaded += e.Value.BytesInBuffer; m_LastActivity = DateTime.Now; if (asyncCallback != null) { asyncCallback(null); } } }; if (async) { //Console.WriteLine(new StackTrace().ToString()); } if (!m_pReadBufferOP.Start(async, m_pReadBuffer, m_pReadBuffer.Length)) { return true; } else { if (m_pReadBufferOP.Error != null) { throw m_pReadBufferOP.Error; } else { m_ReadBufferOffset = 0; m_ReadBufferCount = m_pReadBufferOP.BytesInBuffer; m_BytesReaded += m_pReadBufferOP.BytesInBuffer; m_LastActivity = DateTime.Now; } return false; } /* REMOVE ME: if(!m_pReadBufferOP.Start(m_pReadBuffer,m_pReadBuffer.Length)){ if(async == false){ // Wait while async operation completes. while(!m_pReadBufferOP.IsCompleted){ Thread.Sleep(1); } return false; } else{ return true; } } else{ if(m_pReadBufferOP.Error != null){ throw m_pReadBufferOP.Error; } else{ m_ReadBufferOffset = 0; m_ReadBufferCount = m_pReadBufferOP.BytesInBuffer; m_BytesReaded += m_pReadBufferOP.BytesInBuffer; m_LastActivity = DateTime.Now; } return false; } */ } #endregion #region Nested type: BufferReadAsyncOP /// <summary> /// This class implements asynchronous read buffering. /// </summary> private class BufferReadAsyncOP : AsyncOP, IDisposable { #region Events /// <summary> /// Is raised when asynchronous operation has completed. /// </summary> public event EventHandler<EventArgs<BufferReadAsyncOP>> Completed = null; #endregion #region Members private int m_BytesInBuffer; private bool m_IsCompleted; private bool m_IsCompletedSync; private bool m_IsDisposed; private int m_MaxCount; private byte[] m_pBuffer; private Exception m_pException; private SmartStream m_pOwner; #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="owner">Owner stream.</param> /// <exception cref="ArgumentNullException">Is raised when <b>owner</b> is null reference.</exception> public BufferReadAsyncOP(SmartStream owner) { if (owner == null) { throw new ArgumentNullException("owner"); } m_pOwner = owner; } #endregion #region Properties /// <summary> /// Gets read buffer. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> public byte[] Buffer { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_pBuffer; } } /// <summary> /// Gets number of bytes stored in read buffer. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> public int BytesInBuffer { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_BytesInBuffer; } } /// <summary> /// Gets error occured during asynchronous operation. Value null means no error. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> public Exception Error { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_pException; } } /// <summary> /// Gets if asynchronous operation has completed. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> public override bool IsCompleted { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_IsCompleted; } } /// <summary> /// Gets if operation completed synchronously. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> public override bool IsCompletedSynchronously { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_IsCompletedSync; } } /// <summary> /// Gets if this object is disposed. /// </summary> public override bool IsDisposed { get { return m_IsDisposed; } } #endregion #region Methods /// <summary> /// Cleans up any resources being used. /// </summary> public void Dispose() { if (m_IsDisposed) { return; } m_IsDisposed = true; m_pOwner = null; m_pBuffer = null; Completed = null; } #endregion #region Overrides /// <summary> /// Destructor. /// </summary> ~BufferReadAsyncOP() { Dispose(); } #endregion #region Internal methods /// <summary> /// Starts asynchronous operation. /// </summary> /// <param name="async">If true then this method can complete asynchronously. If false, this method completed always syncronously.</param> /// <param name="buffer">Buffer where to store readed data.</param> /// <param name="count">Maximum number of bytes to read.</param> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="ArgumentNullException">Is raised when <b>buffer</b> is null reference.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> /// <returns>Returns true if operation completed synchronously, false if asynchronous operation pending.</returns> internal bool Start(bool async, byte[] buffer, int count) { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (buffer == null) { throw new ArgumentNullException("buffer"); } if (count < 0) { throw new ArgumentException("Argument 'count' value must be >= 0."); } if (count > buffer.Length) { throw new ArgumentException("Argumnet 'count' value must be <= buffer.Length."); } m_IsCompleted = false; m_pBuffer = buffer; m_MaxCount = count; m_BytesInBuffer = 0; m_pException = null; // Operation may complete asynchronously; if (async) { IAsyncResult ar = m_pOwner.m_pStream.BeginRead(buffer, 0, count, delegate(IAsyncResult r) { try { m_BytesInBuffer = m_pOwner.m_pStream.EndRead( r); } catch (Exception x) { m_pException = x; } if (!r.CompletedSynchronously) { OnCompleted(); } m_IsCompleted = true; }, null); m_IsCompletedSync = ar.CompletedSynchronously; } // Operation must complete synchronously. else { m_BytesInBuffer = m_pOwner.m_pStream.Read(buffer, 0, count); m_IsCompleted = true; m_IsCompletedSync = true; } return m_IsCompletedSync; } /// <summary> /// Releases all events attached to this class. /// </summary> internal void ReleaseEvents() { Completed = null; } #endregion #region Utility methods /// <summary> /// Raises <b>Completed</b> event. /// </summary> private void OnCompleted() { if (Completed != null) { Completed(this, new EventArgs<BufferReadAsyncOP>(this)); } } #endregion } #endregion #region Nested type: ReadAsyncOperation /// <summary> /// This class implements asynchronous data reader. /// </summary> private class ReadAsyncOperation : IAsyncResult { #region Members private readonly int m_MaxSize; private readonly int m_OffsetInBuffer; private readonly AsyncCallback m_pAsyncCallback; private readonly object m_pAsyncState; private readonly AutoResetEvent m_pAsyncWaitHandle; private readonly byte[] m_pBuffer; private readonly SmartStream m_pOwner; private int m_BytesStored; private bool m_CompletedSynchronously; private bool m_IsCompleted; private Exception m_pException; #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="owner">Owner stream.</param> /// <param name="buffer">Buffer where to store data.</param> /// <param name="offset">The location in <b>buffer</b> to begin storing the data.</param> /// <param name="maxSize">Maximum number of bytes to read.</param> /// <param name="callback">The AsyncCallback delegate that is executed when asynchronous operation completes.</param> /// <param name="asyncState">User-defined object that qualifies or contains information about an asynchronous operation.</param> public ReadAsyncOperation(SmartStream owner, byte[] buffer, int offset, int maxSize, AsyncCallback callback, object asyncState) { if (owner == null) { throw new ArgumentNullException("owner"); } if (buffer == null) { throw new ArgumentNullException("buffer"); } if (offset < 0) { throw new ArgumentOutOfRangeException("offset", "Argument 'offset' value must be >= 0."); } if (offset > buffer.Length) { throw new ArgumentOutOfRangeException("offset", "Argument 'offset' value must be < buffer.Length."); } if (maxSize < 0) { throw new ArgumentOutOfRangeException("maxSize", "Argument 'maxSize' value must be >= 0."); } if (offset + maxSize > buffer.Length) { throw new ArgumentOutOfRangeException("maxSize", "Argument 'maxSize' is bigger than than argument 'buffer' can store."); } m_pOwner = owner; m_pBuffer = buffer; m_OffsetInBuffer = offset; m_MaxSize = maxSize; m_pAsyncCallback = callback; m_pAsyncState = asyncState; m_pAsyncWaitHandle = new AutoResetEvent(false); DoRead(); } #endregion #region Properties /// <summary> /// Gets store buffer. /// </summary> internal byte[] Buffer { get { return m_pBuffer; } } /// <summary> /// Gets number of bytes stored in to <b>Buffer</b>. /// </summary> internal int BytesStored { get { return m_BytesStored; } } /// <summary> /// Gets or sets if <b>EndReadLine</b> method is called for this asynchronous operation. /// </summary> internal bool IsEndCalled { get; set; } #endregion #region Utility methods /// <summary> /// Is called when asynchronous read buffer buffering has completed. /// </summary> /// <param name="x">Exception that occured during async operation.</param> private void Buffering_Completed(Exception x) { if (x != null) { m_pException = x; Completed(); } // We reached end of stream, no more data. else if (m_pOwner.BytesInReadBuffer == 0) { Completed(); } // Continue data reading. else { DoRead(); } } /// <summary> /// Does asynchronous data reading. /// </summary> private void DoRead() { try { // Read buffer empty, buff next data block. if (m_pOwner.BytesInReadBuffer == 0) { // Buffering started asynchronously. if (m_pOwner.BufferRead(true, Buffering_Completed)) { return; } // Buffering completed synchronously, continue processing. else { // We reached end of stream, no more data. if (m_pOwner.BytesInReadBuffer == 0) { Completed(); return; } } } int readedCount = Math.Min(m_MaxSize, m_pOwner.BytesInReadBuffer); Array.Copy(m_pOwner.m_pReadBuffer, m_pOwner.m_ReadBufferOffset, m_pBuffer, m_OffsetInBuffer, readedCount); m_pOwner.m_ReadBufferOffset += readedCount; m_pOwner.m_LastActivity = DateTime.Now; m_BytesStored += readedCount; Completed(); } catch (Exception x) { m_pException = x; Completed(); } } /// <summary> /// This method must be called when asynchronous operation has completed. /// </summary> private void Completed() { m_IsCompleted = true; m_pAsyncWaitHandle.Set(); if (m_pAsyncCallback != null) { m_pAsyncCallback(this); } } #endregion #region IAsyncResult Members /// <summary> /// Gets a user-defined object that qualifies or contains information about an asynchronous operation. /// </summary> public object AsyncState { get { return m_pAsyncState; } } /// <summary> /// Gets a WaitHandle that is used to wait for an asynchronous operation to complete. /// </summary> public WaitHandle AsyncWaitHandle { get { return m_pAsyncWaitHandle; } } /// <summary> /// Gets an indication of whether the asynchronous operation completed synchronously. /// </summary> public bool CompletedSynchronously { get { return m_CompletedSynchronously; } } /// <summary> /// Gets an indication whether the asynchronous operation has completed. /// </summary> public bool IsCompleted { get { return m_IsCompleted; } } #endregion } #endregion #region Nested type: ReadLineAsyncOP /// <summary> /// This class implements read line operation. /// </summary> /// <remarks>This class can be reused on multiple calls of <see cref="SmartStream.ReadLine(ReadLineAsyncOP,bool)">SmartStream.ReadLine</see> method.</remarks> public class ReadLineAsyncOP : AsyncOP, IDisposable { #region Events /// <summary> /// Is raised when asynchronous operation has completed. /// </summary> public event EventHandler<EventArgs<ReadLineAsyncOP>> Completed = null; #endregion #region Members private readonly SizeExceededAction m_ExceededAction = SizeExceededAction.JunkAndThrowException; private int m_BytesInBuffer; private bool m_CRLFLinesOnly = true; private bool m_IsCompleted; private bool m_IsCompletedSync; private bool m_IsDisposed; private int m_LastByte = -1; private byte[] m_pBuffer; private Exception m_pException; private SmartStream m_pOwner; #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="buffer">Line buffer.</param> /// <param name="exceededAction">Specifies how line-reader behaves when maximum line size exceeded.</param> /// <exception cref="ArgumentNullException">Is raised when <b>buffer</b> is null reference.</exception> public ReadLineAsyncOP(byte[] buffer, SizeExceededAction exceededAction) { if (buffer == null) { throw new ArgumentNullException("buffer"); } m_pBuffer = buffer; m_ExceededAction = exceededAction; } #endregion #region Properties /// <summary> /// Gets line buffer. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> public byte[] Buffer { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_pBuffer; } } /// <summary> /// Gets number of bytes stored in the buffer. Ending line-feed characters included. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> public int BytesInBuffer { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_BytesInBuffer; } } /// <summary> /// Gets error occured during asynchronous operation. Value null means no error. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> public Exception Error { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_pException; } } /// <summary> /// Gets if asynchronous operation has completed. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> public override bool IsCompleted { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_IsCompleted; } } /// <summary> /// Gets if operation completed synchronously. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> public override bool IsCompletedSynchronously { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_IsCompletedSync; } } /// <summary> /// Gets if this object is disposed. /// </summary> public override bool IsDisposed { get { return m_IsDisposed; } } /// <summary> /// Gets line as ASCII string. Returns null if EOS(end of stream) reached. Ending line-feed characters not included. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> public string LineAscii { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (BytesInBuffer == 0) { return null; } else { return Encoding.ASCII.GetString(m_pBuffer, 0, LineBytesInBuffer); } } } /// <summary> /// Gets number of line data bytes stored in the buffer. Ending line-feed characters not included. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> public int LineBytesInBuffer { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } int retVal = m_BytesInBuffer; if (m_BytesInBuffer > 1) { if (m_pBuffer[m_BytesInBuffer - 1] == '\n') { retVal--; if (m_pBuffer[m_BytesInBuffer - 2] == '\r') { retVal--; } } } else if (m_BytesInBuffer > 0) { if (m_pBuffer[m_BytesInBuffer - 1] == '\n') { retVal--; } } return retVal; } } /// <summary> /// Gets line as UTF-32 string. Returns null if EOS(end of stream) reached. Ending line-feed characters not included. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> public string LineUtf32 { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (BytesInBuffer == 0) { return null; } else { return Encoding.UTF32.GetString(m_pBuffer, 0, LineBytesInBuffer); } } } /// <summary> /// Gets line as UTF-8 string. Returns null if EOS(end of stream) reached. Ending line-feed characters not included. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> public string LineUtf8 { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (BytesInBuffer == 0) { return null; } else { return Encoding.UTF8.GetString(m_pBuffer, 0, LineBytesInBuffer); } } } #endregion #region Methods /// <summary> /// Cleans up any resources being used. /// </summary> public void Dispose() { if (m_IsDisposed) { return; } m_IsDisposed = true; m_pOwner = null; m_pBuffer = null; m_pException = null; Completed = null; } #endregion #region Overrides /// <summary> /// Destructor. /// </summary> ~ReadLineAsyncOP() { Dispose(); } #endregion #region Internal methods /// <summary> /// Starts reading line. /// </summary> /// <param name="async">If true then this method can complete asynchronously. If false, this method completed always syncronously.</param> /// <param name="stream">Owner SmartStream.</param> /// <returns>Returns true if read line completed synchronously, false if asynchronous operation pending.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>stream</b> is null reference.</exception> internal bool Start(bool async, SmartStream stream) { if (stream == null) { throw new ArgumentNullException("stream"); } m_pOwner = stream; // Clear old data, if any. m_IsCompleted = false; m_BytesInBuffer = 0; m_LastByte = -1; m_pException = null; m_IsCompletedSync = DoLineReading(async); return m_IsCompletedSync; } #endregion #region Utility methods /// <summary> /// Is called when asynchronous read buffer buffering has completed. /// </summary> /// <param name="x">Exception that occured during async operation.</param> private void Buffering_Completed(Exception x) { if (x != null) { m_pException = x; OnCompleted(); } // We reached end of stream, no more data. else if (m_pOwner.BytesInReadBuffer == 0) { OnCompleted(); } // Continue line reading. else { if (DoLineReading(true)) { OnCompleted(); } } } /// <summary> /// Starts/continues line reading. /// </summary> /// <param name="async">If true then this method can complete asynchronously. If false, this method completed always syncronously.</param> /// <returns>Returns true if line reading completed.</returns> private bool DoLineReading(bool async) { try { while (true) { // Read buffer empty, buff next data block. if (m_pOwner.BytesInReadBuffer == 0) { // Buffering started asynchronously. if (m_pOwner.BufferRead(async, Buffering_Completed)) { return false; } // Buffering completed synchronously, continue processing. else { // We reached end of stream, no more data. if (m_pOwner.BytesInReadBuffer == 0) { return true; } } } byte b = m_pOwner.m_pReadBuffer[m_pOwner.m_ReadBufferOffset++]; // Line buffer full. if (m_BytesInBuffer >= m_pBuffer.Length) { m_pException = new LineSizeExceededException(); if (m_ExceededAction == SizeExceededAction.ThrowException) { return true; } } // Store byte. else { m_pBuffer[m_BytesInBuffer++] = b; } // We have LF line. if (b == '\n') { if (!m_CRLFLinesOnly || m_CRLFLinesOnly && m_LastByte == '\r') { return true; } } m_LastByte = b; } } catch (Exception x) { m_pException = x; } return true; } /// <summary> /// Raises <b>Completed</b> event. /// </summary> private void OnCompleted() { m_IsCompleted = true; if (Completed != null) { Completed(this, new EventArgs<ReadLineAsyncOP>(this)); } } #endregion } #endregion #region Nested type: ReadLineAsyncOperation /// <summary> /// This class implements asynchronous line reading. /// </summary> private class ReadLineAsyncOperation : IAsyncResult { #region Members private readonly int m_MaxCount; private readonly AsyncCallback m_pAsyncCallback; private readonly object m_pAsyncState; private readonly AutoResetEvent m_pAsyncWaitHandle; private readonly byte[] m_pBuffer; private readonly SmartStream m_pOwner; private readonly SizeExceededAction m_SizeExceededAction = SizeExceededAction.JunkAndThrowException; private int m_BytesReaded; private int m_BytesStored; private bool m_CompletedSynchronously; private bool m_IsCompleted; private int m_OffsetInBuffer; private Exception m_pException; #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="owner">Owner stream.</param> /// <param name="buffer">Buffer where to store data.</param> /// <param name="offset">The location in <b>buffer</b> to begin storing the data.</param> /// <param name="maxCount">Maximum number of bytes to read.</param> /// <param name="exceededAction">Specifies how this method behaves when maximum line size exceeded.</param> /// <param name="callback">The AsyncCallback delegate that is executed when asynchronous operation completes.</param> /// <param name="asyncState">User-defined object that qualifies or contains information about an asynchronous operation.</param> /// <exception cref="ArgumentNullException">Is raised when <b>owner</b>,<b>buffer</b> is null reference.</exception> /// <exception cref="ArgumentOutOfRangeException">Is raised when any of the arguments has out of valid range.</exception> public ReadLineAsyncOperation(SmartStream owner, byte[] buffer, int offset, int maxCount, SizeExceededAction exceededAction, AsyncCallback callback, object asyncState) { if (owner == null) { throw new ArgumentNullException("owner"); } if (buffer == null) { throw new ArgumentNullException("buffer"); } if (offset < 0) { throw new ArgumentOutOfRangeException("offset", "Argument 'offset' value must be >= 0."); } if (offset > buffer.Length) { throw new ArgumentOutOfRangeException("offset", "Argument 'offset' value must be < buffer.Length."); } if (maxCount < 0) { throw new ArgumentOutOfRangeException("maxCount", "Argument 'maxCount' value must be >= 0."); } if (offset + maxCount > buffer.Length) { throw new ArgumentOutOfRangeException("maxCount", "Argument 'maxCount' is bigger than than argument 'buffer' can store."); } m_pOwner = owner; m_pBuffer = buffer; m_OffsetInBuffer = offset; m_MaxCount = maxCount; m_SizeExceededAction = exceededAction; m_pAsyncCallback = callback; m_pAsyncState = asyncState; m_pAsyncWaitHandle = new AutoResetEvent(false); DoLineReading(); } #endregion #region Properties /// <summary> /// Gets store buffer. /// </summary> internal byte[] Buffer { get { return m_pBuffer; } } /// <summary> /// Gets number of bytes readed from source stream. /// </summary> internal int BytesReaded { get { return m_BytesReaded; } } /// <summary> /// Gets number of bytes stored in to <b>Buffer</b>. /// </summary> internal int BytesStored { get { return m_BytesStored; } } /// <summary> /// Gets or sets if <b>EndReadLine</b> method is called for this asynchronous operation. /// </summary> internal bool IsEndCalled { get; set; } #endregion #region Utility methods /// <summary> /// Is called when asynchronous read buffer buffering has completed. /// </summary> /// <param name="x">Exception that occured during async operation.</param> private void Buffering_Completed(Exception x) { if (x != null) { m_pException = x; Completed(); } // We reached end of stream, no more data. else if (m_pOwner.BytesInReadBuffer == 0) { Completed(); } // Continue line reading. else { DoLineReading(); } } /// <summary> /// Does line reading. /// </summary> private void DoLineReading() { try { while (true) { // Read buffer empty, buff next data block. if (m_pOwner.BytesInReadBuffer == 0) { // Buffering started asynchronously. if (m_pOwner.BufferRead(true, Buffering_Completed)) { return; } // Buffering completed synchronously, continue processing. else { // We reached end of stream, no more data. if (m_pOwner.BytesInReadBuffer == 0) { Completed(); return; } } } byte b = m_pOwner.m_pReadBuffer[m_pOwner.m_ReadBufferOffset++]; m_BytesReaded++; // We have LF line. if (b == '\n') { break; } // We have CRLF line. else if (b == '\r' && m_pOwner.Peek() == '\n') { // Consume LF char. m_pOwner.ReadByte(); m_BytesReaded++; break; } // We have CR line. else if (b == '\r') { break; } // We have normal line data char. else { // Line buffer full. if (m_BytesStored >= m_MaxCount) { if (m_SizeExceededAction == SizeExceededAction.ThrowException) { throw new LineSizeExceededException(); } // Just skip storing. else {} } else { m_pBuffer[m_OffsetInBuffer++] = b; m_BytesStored++; } } } } catch (Exception x) { m_pException = x; } Completed(); } /// <summary> /// This method must be called when asynchronous operation has completed. /// </summary> private void Completed() { m_IsCompleted = true; m_pAsyncWaitHandle.Set(); if (m_pAsyncCallback != null) { m_pAsyncCallback(this); } } #endregion #region IAsyncResult Members /// <summary> /// Gets a user-defined object that qualifies or contains information about an asynchronous operation. /// </summary> public object AsyncState { get { return m_pAsyncState; } } /// <summary> /// Gets a WaitHandle that is used to wait for an asynchronous operation to complete. /// </summary> public WaitHandle AsyncWaitHandle { get { return m_pAsyncWaitHandle; } } /// <summary> /// Gets an indication of whether the asynchronous operation completed synchronously. /// </summary> public bool CompletedSynchronously { get { return m_CompletedSynchronously; } } /// <summary> /// Gets an indication whether the asynchronous operation has completed. /// </summary> public bool IsCompleted { get { return m_IsCompleted; } } #endregion } #endregion #region Nested type: ReadPeriodTerminatedAsyncOP /// <summary> /// This class implements read period-terminated operation. /// </summary> public class ReadPeriodTerminatedAsyncOP : AsyncOP, IDisposable { #region Events /// <summary> /// Is raised when asynchronous operation has completed. /// </summary> public event EventHandler<EventArgs<ReadPeriodTerminatedAsyncOP>> Completed = null; #endregion #region Members private readonly long m_MaxCount; private long m_BytesStored; private SizeExceededAction m_ExceededAction = SizeExceededAction.JunkAndThrowException; private bool m_IsCompleted; private bool m_IsCompletedSync; private bool m_IsDisposed; private int m_LinesStored; private Exception m_pException; private SmartStream m_pOwner; private ReadLineAsyncOP m_pReadLineOP; private Stream m_pStream; #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="stream">Stream wehre to sore readed data.</param> /// <param name="maxCount">Maximum number of bytes to read. Value 0 means not limited.</param> /// <param name="exceededAction">Specifies how period-terminated reader behaves when <b>maxCount</b> exceeded.</param> /// <exception cref="ArgumentNullException">Is raised when <b>stream</b> is null reference.</exception> public ReadPeriodTerminatedAsyncOP(Stream stream, long maxCount, SizeExceededAction exceededAction) { if (stream == null) { throw new ArgumentNullException("stream"); } m_pStream = stream; m_MaxCount = maxCount; m_ExceededAction = exceededAction; m_pReadLineOP = new ReadLineAsyncOP(new byte[Workaround.Definitions.MaxStreamLineLength], exceededAction); m_pReadLineOP.Completed += m_pReadLineOP_Completed; } #endregion #region Properties /// <summary> /// Gets number of bytes stored to <see cref="Stream">Stream</see> stream. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> public long BytesStored { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_BytesStored; } } /// <summary> /// Gets error occured during asynchronous operation. Value null means no error. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> public Exception Error { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_pException; } } /// <summary> /// Gets if asynchronous operation has completed. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> public override bool IsCompleted { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_IsCompleted; } } /// <summary> /// Gets if operation completed synchronously. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> public override bool IsCompletedSynchronously { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_IsCompletedSync; } } /// <summary> /// Gets if this object is disposed. /// </summary> public override bool IsDisposed { get { return m_IsDisposed; } } /// <summary> /// Gets number of lines stored to <see cref="Stream">Stream</see> stream. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> public int LinesStored { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_LinesStored; } } /// <summary> /// Gets stream where period terminated data has stored. /// </summary> public Stream Stream { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_pStream; } } #endregion #region Methods /// <summary> /// Cleans up any resources being used. /// </summary> public void Dispose() { if (m_IsDisposed) { return; } m_IsDisposed = true; m_pOwner = null; m_pStream = null; m_pReadLineOP.Dispose(); m_pReadLineOP = null; m_pException = null; Completed = null; } #endregion #region Overrides /// <summary> /// Destructor. /// </summary> ~ReadPeriodTerminatedAsyncOP() { Dispose(); } #endregion #region Internal methods /// <summary> /// Starts period-terminated data reading. /// </summary> /// <param name="stream">Owner SmartStream.</param> /// <returns>Returns true if read line completed synchronously, false if asynchronous operation pending.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>stream</b> is null reference.</exception> internal bool Start(SmartStream stream) { if (stream == null) { throw new ArgumentNullException("stream"); } m_pOwner = stream; // Clear old data, if any. m_IsCompleted = false; m_BytesStored = 0; m_LinesStored = 0; m_pException = null; m_IsCompletedSync = DoRead(); return m_IsCompletedSync; } #endregion #region Utility methods /// <summary> /// Is called when asynchronous line reading has completed. /// </summary> /// <param name="sender">Sender.</param> /// <param name="e">Event data.</param> private void m_pReadLineOP_Completed(object sender, EventArgs<ReadLineAsyncOP> e) { if (ProcessReadedLine()) { OnCompleted(); } else { if (DoRead()) { OnCompleted(); } } } /// <summary> /// Continues period-terminated reading. /// </summary> /// <returns>Returns true if read line completed synchronously, false if asynchronous operation pending.</returns> private bool DoRead() { try { while (true) { if (m_pOwner.ReadLine(m_pReadLineOP, true)) { if (ProcessReadedLine()) { break; } } // Goto next while loop. else { return false; } } } catch (Exception x) { m_pException = x; } return true; } /// <summary> /// Processes readed line. /// </summary> /// <returns>Returns true if read period-terminated operation has completed.</returns> private bool ProcessReadedLine() { if (m_pReadLineOP.Error != null) { m_pException = m_pReadLineOP.Error; return true; } // We reached end of stream, no more data. else if (m_pReadLineOP.BytesInBuffer == 0) { m_pException = new IncompleteDataException("Data is not period-terminated."); return true; } // We have period terminator. else if (m_pReadLineOP.LineBytesInBuffer == 1 && m_pReadLineOP.Buffer[0] == '.') { return true; } // Normal line. else { if (m_MaxCount < 1 || m_BytesStored < m_MaxCount) { byte[] buf = m_pReadLineOP.Buffer; int bytesInBuffer = m_pReadLineOP.BytesInBuffer; if (m_pReadLineOP.LineBytesInBuffer > 2 && m_pReadLineOP.Buffer[0] == '.' && m_pReadLineOP.Buffer[1] == '.') { buf = m_pReadLineOP.Buffer.Skip(1).ToArray(); bytesInBuffer--; } m_pStream.Write(buf, 0, bytesInBuffer); m_BytesStored += bytesInBuffer; m_LinesStored++; } } return false; } /// <summary> /// Raises <b>Completed</b> event. /// </summary> private void OnCompleted() { m_IsCompleted = true; if (Completed != null) { Completed(this, new EventArgs<ReadPeriodTerminatedAsyncOP>(this)); } } #endregion } #endregion #region Nested type: ReadToStreamAsyncOperation /// <summary> /// This class implements asynchronous read to stream data reader. /// </summary> private class ReadToStreamAsyncOperation : IAsyncResult { #region Members private readonly long m_Count; private readonly AsyncCallback m_pAsyncCallback; private readonly object m_pAsyncState; private readonly AutoResetEvent m_pAsyncWaitHandle; private readonly SmartStream m_pOwner; private readonly Stream m_pStoreStream; private long m_BytesStored; private bool m_CompletedSynchronously; private bool m_IsCompleted; private Exception m_pException; #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="owner">Owner stream.</param> /// <param name="storeStream">Stream where to store readed data.</param> /// <param name="count">Number of bytes to read from source stream.</param> /// <param name="callback">The AsyncCallback delegate that is executed when asynchronous operation completes.</param> /// <param name="asyncState">User-defined object that qualifies or contains information about an asynchronous operation.</param> /// <exception cref="ArgumentNullException">Is raised when <b>owner</b> or <b>storeStream</b> is null reference.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> public ReadToStreamAsyncOperation(SmartStream owner, Stream storeStream, long count, AsyncCallback callback, object asyncState) { if (owner == null) { throw new ArgumentNullException("owner"); } if (storeStream == null) { throw new ArgumentNullException("storeStream"); } if (count < 0) { throw new ArgumentException("Argument 'count' must be >= 0."); } m_pOwner = owner; m_pStoreStream = storeStream; m_Count = count; m_pAsyncCallback = callback; m_pAsyncState = asyncState; m_pAsyncWaitHandle = new AutoResetEvent(false); if (m_Count == 0) { Completed(); } else { DoDataReading(); } } #endregion #region Properties /// <summary> /// Gets number of bytes stored in to <b>storeStream</b>. /// </summary> internal long BytesStored { get { return m_BytesStored; } } /// <summary> /// Gets exception happened on asynchronous operation. Returns null if operation was successfull. /// </summary> internal Exception Exception { get { return m_pException; } } /// <summary> /// Gets or sets if <b>EndReadLine</b> method is called for this asynchronous operation. /// </summary> internal bool IsEndCalled { get; set; } #endregion #region Utility methods /// <summary> /// Is called when asynchronous read buffer buffering has completed. /// </summary> /// <param name="x">Exception that occured during async operation.</param> private void Buffering_Completed(Exception x) { if (x != null) { m_pException = x; Completed(); } // We reached end of stream, no more data. else if (m_pOwner.BytesInReadBuffer == 0) { m_pException = new IncompleteDataException(); Completed(); } // Continue line reading. else { DoDataReading(); } } /// <summary> /// Does data reading. /// </summary> private void DoDataReading() { try { while (true) { // Read buffer empty, buff next data block. if (m_pOwner.BytesInReadBuffer == 0) { // Buffering started asynchronously. if (m_pOwner.BufferRead(true, Buffering_Completed)) { return; } // Buffering completed synchronously, continue processing. else { // We reached end of stream, no more data. if (m_pOwner.BytesInReadBuffer == 0) { throw new IncompleteDataException(); } } } int countToRead = (int) Math.Min(m_Count - m_BytesStored, m_pOwner.BytesInReadBuffer); m_pStoreStream.Write(m_pOwner.m_pReadBuffer, m_pOwner.m_ReadBufferOffset, countToRead); m_BytesStored += countToRead; m_pOwner.m_ReadBufferOffset += countToRead; // We have readed all data. if (m_Count == m_BytesStored) { Completed(); return; } } } catch (Exception x) { m_pException = x; Completed(); } } /// <summary> /// This method must be called when asynchronous operation has completed. /// </summary> private void Completed() { m_IsCompleted = true; m_pAsyncWaitHandle.Set(); if (m_pAsyncCallback != null) { m_pAsyncCallback(this); } } #endregion #region IAsyncResult Members /// <summary> /// Gets a user-defined object that qualifies or contains information about an asynchronous operation. /// </summary> public object AsyncState { get { return m_pAsyncState; } } /// <summary> /// Gets a WaitHandle that is used to wait for an asynchronous operation to complete. /// </summary> public WaitHandle AsyncWaitHandle { get { return m_pAsyncWaitHandle; } } /// <summary> /// Gets an indication of whether the asynchronous operation completed synchronously. /// </summary> public bool CompletedSynchronously { get { return m_CompletedSynchronously; } } /// <summary> /// Gets an indication whether the asynchronous operation has completed. /// </summary> public bool IsCompleted { get { return m_IsCompleted; } } #endregion } #endregion #region Nested type: ReadToTerminatorAsyncOperation /// <summary> /// This class implements asynchronous line-based terminated data reader, where terminator is on line itself. /// </summary> private class ReadToTerminatorAsyncOperation : IAsyncResult { #region Members private readonly long m_MaxCount; private readonly AsyncCallback m_pAsyncCallback; private readonly object m_pAsyncState; private readonly AutoResetEvent m_pAsyncWaitHandle; private readonly byte[] m_pLineBuffer; private readonly SmartStream m_pOwner; private readonly Stream m_pStoreStream; private readonly byte[] m_pTerminatorBytes; private readonly SizeExceededAction m_SizeExceededAction = SizeExceededAction.JunkAndThrowException; private readonly string m_Terminator = ""; private long m_BytesStored; private bool m_CompletedSynchronously; private bool m_IsCompleted; private Exception m_pException; #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="owner">Owner stream.</param> /// <param name="terminator">Data terminator.</param> /// <param name="storeStream">Stream where to store readed header.</param> /// <param name="maxCount">Maximum number of bytes to read. Value 0 means not limited.</param> /// <param name="exceededAction">Specifies how this method behaves when maximum line size exceeded.</param> /// <param name="callback">The AsyncCallback delegate that is executed when asynchronous operation completes.</param> /// <param name="asyncState">User-defined object that qualifies or contains information about an asynchronous operation.</param> /// <exception cref="ArgumentNullException">Is raised when <b>owner</b>,<b>terminator</b> or <b>storeStream</b> is null reference.</exception> public ReadToTerminatorAsyncOperation(SmartStream owner, string terminator, Stream storeStream, long maxCount, SizeExceededAction exceededAction, AsyncCallback callback, object asyncState) { if (owner == null) { throw new ArgumentNullException("owner"); } if (terminator == null) { throw new ArgumentNullException("terminator"); } if (storeStream == null) { throw new ArgumentNullException("storeStream"); } if (maxCount < 0) { throw new ArgumentException("Argument 'maxCount' must be >= 0."); } m_pOwner = owner; m_Terminator = terminator; m_pTerminatorBytes = Encoding.ASCII.GetBytes(terminator); m_pStoreStream = storeStream; m_MaxCount = maxCount; m_SizeExceededAction = exceededAction; m_pAsyncCallback = callback; m_pAsyncState = asyncState; m_pAsyncWaitHandle = new AutoResetEvent(false); m_pLineBuffer = new byte[Workaround.Definitions.MaxStreamLineLength]; // Start reading data. m_pOwner.BeginReadLine(m_pLineBuffer, 0, m_pLineBuffer.Length - 2, m_SizeExceededAction, ReadLine_Completed, null); } #endregion #region Properties /// <summary> /// Gets terminator. /// </summary> public string Terminator { get { return m_Terminator; } } /// <summary> /// Gets number of bytes stored in to <b>storeStream</b>. /// </summary> internal long BytesStored { get { return m_BytesStored; } } /// <summary> /// Gets exception happened on asynchronous operation. Returns null if operation was successfull. /// </summary> internal Exception Exception { get { return m_pException; } } /// <summary> /// Gets or sets if <b>EndReadLine</b> method is called for this asynchronous operation. /// </summary> internal bool IsEndCalled { get; set; } #endregion #region Utility methods /// <summary> /// This method is called when asyynchronous line reading has completed. /// </summary> /// <param name="asyncResult">An IAsyncResult that represents an asynchronous call.</param> private void ReadLine_Completed(IAsyncResult asyncResult) { try { int storedCount = 0; try { storedCount = m_pOwner.EndReadLine(asyncResult); } catch (LineSizeExceededException lx) { if (m_SizeExceededAction == SizeExceededAction.ThrowException) { throw lx; } m_pException = new LineSizeExceededException(); storedCount = Workaround.Definitions.MaxStreamLineLength - 2; } // Source stream closed berore we reached terminator. if (storedCount == -1) { throw new IncompleteDataException(); } // Check for terminator. if (Net_Utils.CompareArray(m_pTerminatorBytes, m_pLineBuffer, storedCount)) { Completed(); } else { // We have exceeded maximum allowed data count. if (m_MaxCount > 0 && (m_BytesStored + storedCount + 2) > m_MaxCount) { if (m_SizeExceededAction == SizeExceededAction.ThrowException) { throw new DataSizeExceededException(); } // Just skip storing. else { m_pException = new DataSizeExceededException(); } } else { // Store readed line. m_pLineBuffer[storedCount++] = (byte) '\r'; m_pLineBuffer[storedCount++] = (byte) '\n'; m_pStoreStream.Write(m_pLineBuffer, 0, storedCount); m_BytesStored += storedCount; } // Strart reading new line. m_pOwner.BeginReadLine(m_pLineBuffer, 0, m_pLineBuffer.Length - 2, m_SizeExceededAction, ReadLine_Completed, null); } } catch (Exception x) { m_pException = x; Completed(); } } /// <summary> /// This method must be called when asynchronous operation has completed. /// </summary> private void Completed() { m_IsCompleted = true; m_pAsyncWaitHandle.Set(); if (m_pAsyncCallback != null) { m_pAsyncCallback(this); } } #endregion #region IAsyncResult Members /// <summary> /// Gets a user-defined object that qualifies or contains information about an asynchronous operation. /// </summary> public object AsyncState { get { return m_pAsyncState; } } /// <summary> /// Gets a WaitHandle that is used to wait for an asynchronous operation to complete. /// </summary> public WaitHandle AsyncWaitHandle { get { return m_pAsyncWaitHandle; } } /// <summary> /// Gets an indication of whether the asynchronous operation completed synchronously. /// </summary> public bool CompletedSynchronously { get { return m_CompletedSynchronously; } } /// <summary> /// Gets an indication whether the asynchronous operation has completed. /// </summary> public bool IsCompleted { get { return m_IsCompleted; } } #endregion } #endregion } }<file_sep>/web/core/ASC.Web.Core/Users/UserPhotoThumbnailManager.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections.Generic; using System.Drawing; namespace ASC.Web.Core.Users { public class UserPhotoThumbnailManager { public static List<ThumbnailItem> SaveThumbnails(int x, int y, int width, int height, Guid userId) { return SaveThumbnails(new UserPhotoThumbnailSettings(x, y, width, height), userId); } public static List<ThumbnailItem> SaveThumbnails(Point point, Size size, Guid userId) { return SaveThumbnails(new UserPhotoThumbnailSettings(point, size), userId); } public static List<ThumbnailItem> SaveThumbnails(UserPhotoThumbnailSettings thumbnailSettings, Guid userId) { if (thumbnailSettings.Size.IsEmpty) return null; var thumbnailsData = new ThumbnailsData(userId); var resultBitmaps = new List<ThumbnailItem>(); var img = thumbnailsData.MainImgBitmap; if (img == null) return null; foreach (var thumbnail in thumbnailsData.ThumbnailList) { thumbnail.Bitmap = GetBitmap(img, thumbnail.Size, thumbnailSettings); resultBitmaps.Add(thumbnail); } thumbnailsData.Save(resultBitmaps); thumbnailSettings.SaveForUser(userId); return thumbnailsData.ThumbnailList; } public static Bitmap GetBitmap(Image mainImg, Size size, UserPhotoThumbnailSettings thumbnailSettings) { var thumbnailBitmap = new Bitmap(size.Width, size.Height); var scaleX = size.Width/(1.0*thumbnailSettings.Size.Width); var scaleY = size.Height/(1.0*thumbnailSettings.Size.Height); var rect = new Rectangle(-(int) (scaleX*(1.0*thumbnailSettings.Point.X)), -(int) (scaleY*(1.0*thumbnailSettings.Point.Y)), (int) (scaleX*mainImg.Width), (int) (scaleY*mainImg.Height)); using (var graphic = Graphics.FromImage(thumbnailBitmap)) { graphic.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; graphic.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality; graphic.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; graphic.DrawImage(mainImg, rect); using (var wrapMode = new System.Drawing.Imaging.ImageAttributes()) { wrapMode.SetWrapMode(System.Drawing.Drawing2D.WrapMode.TileFlipXY); graphic.DrawImage(mainImg, rect, 0, 0, mainImg.Width, mainImg.Height, GraphicsUnit.Pixel, wrapMode); } } return thumbnailBitmap; } } public class ThumbnailItem { public Size Size { get; set; } public string ImgUrl { get; set; } public Bitmap Bitmap { get; set; } } public class ThumbnailsData { private Guid UserId { get; set; } public ThumbnailsData(Guid userId) { UserId = userId; } public Bitmap MainImgBitmap { get { return UserPhotoManager.GetPhotoBitmap(UserId); } } public string MainImgUrl { get { return UserPhotoManager.GetPhotoAbsoluteWebPath(UserId); } } public List<ThumbnailItem> ThumbnailList { get { return new List<ThumbnailItem> { new ThumbnailItem { Size = UserPhotoManager.RetinaFotoSize, ImgUrl = UserPhotoManager.GetRetinaPhotoURL(UserId) }, new ThumbnailItem { Size = UserPhotoManager.MaxFotoSize, ImgUrl = UserPhotoManager.GetMaxPhotoURL(UserId) }, new ThumbnailItem { Size = UserPhotoManager.BigFotoSize, ImgUrl = UserPhotoManager.GetBigPhotoURL(UserId) }, new ThumbnailItem { Size = UserPhotoManager.MediumFotoSize, ImgUrl = UserPhotoManager.GetMediumPhotoURL(UserId) }, new ThumbnailItem { Size = UserPhotoManager.SmallFotoSize, ImgUrl = UserPhotoManager.GetSmallPhotoURL(UserId) } }; } } public void Save(List<ThumbnailItem> bitmaps) { foreach (var item in bitmaps) UserPhotoManager.SaveThumbnail(UserId, item.Bitmap, MainImgBitmap.RawFormat); } } }<file_sep>/web/studio/ASC.Web.Studio/ThirdParty/ImportContacts/Yahoo.aspx.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Xml.Linq; using ASC.FederatedLogin.Helpers; using ASC.FederatedLogin.LoginProviders; using ASC.Web.Core; using ASC.Web.Studio.Utility; using Newtonsoft.Json.Linq; namespace ASC.Web.Studio.ThirdParty.ImportContacts { public partial class Yahoo : BasePage { public static string Location { get { return CommonLinkUtility.ToAbsolute("~/ThirdParty/ImportContacts/Yahoo.aspx"); } } public static bool Enable { get { return YahooLoginProvider.Instance.IsEnabled; } } protected void Page_Load(object sender, EventArgs e) { try { var token = YahooLoginProvider.Instance.Auth(HttpContext.Current); var userGuid = RequestUserGuid(token.AccessToken); ImportContacts(userGuid, token.AccessToken); Master.SubmitContacts(); } catch (System.Threading.ThreadAbortException) { } catch (Exception ex) { Master.SubmitError(ex.Message); } } private void ImportContacts(string userGuid, string accessToken) { var responseString = RequestHelper.PerformRequest(string.Format(YahooLoginProvider.YahooUrlContactsFormat, userGuid), headers: new Dictionary<string, string> { { "Authorization", "Bearer " + accessToken } }); const string xmlns = "http://social.yahooapis.com/v1/schema.rng"; var contactsDocument = XDocument.Parse(responseString); var contacts = contactsDocument.Root.Elements(XName.Get("contact", xmlns)) .Select(entry => new { Name = entry.Elements(XName.Get("fields", xmlns)) .Where(field => field.Element(XName.Get("type", xmlns)).Value == "name") .Select(field => field.Element(XName.Get("value", xmlns)).Element(XName.Get("givenName", xmlns)).Value).FirstOrDefault(), LastName = entry.Elements(XName.Get("fields", xmlns)) .Where(field => field.Element(XName.Get("type", xmlns)).Value == "name") .Select(field => field.Element(XName.Get("value", xmlns)).Element(XName.Get("familyName", xmlns)).Value).FirstOrDefault(), Email = entry.Elements(XName.Get("fields", xmlns)) .Where(field => field.Element(XName.Get("type", xmlns)).Value == "email") .Select(field => field.Element(XName.Get("value", xmlns)).Value).FirstOrDefault(), }).ToList(); foreach (var contact in contacts) { if (String.IsNullOrEmpty(contact.Email)) { Master.AddContactInfo(contact.Name, contact.LastName, ""); } else { Master.AddContactInfo(contact.Name, contact.LastName, contact.Email); } } } public static string RequestUserGuid(string accessToken) { var responseString = RequestHelper.PerformRequest(YahooLoginProvider.YahooUrlUserGuid + "?format=json", headers: new Dictionary<string, string> { { "Authorization", "Bearer " + accessToken } }); var response = JObject.Parse(responseString); return response == null ? null : response["guid"].Value<string>("value"); } } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/TimerEx.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net { #region usings using System.Timers; #endregion /// <summary> /// Simple timer implementation. /// </summary> public class TimerEx : Timer { #region Constructor /// <summary> /// Default contructor. /// </summary> public TimerEx() {} /// <summary> /// Default contructor. /// </summary> /// <param name="interval">The time in milliseconds between events.</param> public TimerEx(double interval) : base(interval) {} /// <summary> /// Default contructor. /// </summary> /// <param name="interval">The time in milliseconds between events.</param> /// <param name="autoReset">Specifies if timer is auto reseted.</param> public TimerEx(double interval, bool autoReset) : base(interval) { AutoReset = autoReset; } #endregion // TODO: We need to do this class CF compatible. } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/SIP/Stack/SIP_ResponseReceivedEventArgs.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.SIP.Stack { #region usings using System; #endregion /// <summary> /// This class provides data for ResponseReceived events. /// </summary> public class SIP_ResponseReceivedEventArgs : EventArgs { #region Members private readonly SIP_Response m_pResponse; private readonly SIP_Stack m_pStack; private readonly SIP_ClientTransaction m_pTransaction; #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="stack">Reference to SIP stack.</param> /// <param name="transaction">Client transaction what response it is. This value can be null if no matching client response.</param> /// <param name="response">Received response.</param> internal SIP_ResponseReceivedEventArgs(SIP_Stack stack, SIP_ClientTransaction transaction, SIP_Response response) { m_pStack = stack; m_pResponse = response; m_pTransaction = transaction; } #endregion #region Properties /// <summary> /// Gets client transaction which response it is. This value is null if no matching client transaction. /// If this core is staless proxy then it's allowed, otherwise core MUST discard that response. /// </summary> public SIP_ClientTransaction ClientTransaction { get { return m_pTransaction; } } /// <summary> /// Gets SIP dialog where Response belongs to. Returns null if Response doesn't belong any dialog. /// </summary> public SIP_Dialog Dialog { get { return m_pStack.TransactionLayer.MatchDialog(m_pResponse); } } /// <summary> /// Gets response received by SIP stack. /// </summary> public SIP_Response Response { get { return m_pResponse; } } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/SIP/Message/SIP_t_ReferredBy.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.SIP.Message { #region usings using System; using System.Text; #endregion /// <summary> /// Implements SIP "Referred-By" value. Defined in RFC 3892. /// </summary> /// <remarks> /// <code> /// RFC 3892 Syntax: /// Referred-By = referrer-uri *( SEMI (referredby-id-param / generic-param) ) /// referrer-uri = ( name-addr / addr-spec ) /// referredby-id-param = "cid" EQUAL sip-clean-msg-id /// sip-clean-msg-id = LDQUOT dot-atom "@" (dot-atom / host) RDQUOT /// </code> /// </remarks> public class SIP_t_ReferredBy : SIP_t_ValueWithParams { #region Members private SIP_t_NameAddress m_pAddress; #endregion #region Properties /// <summary> /// Gets or sets address. /// </summary> /// <exception cref="ArgumentNullException">Is raised when null value is passed.</exception> public SIP_t_NameAddress Address { get { return m_pAddress; } set { if (value == null) { throw new ArgumentNullException("Address"); } m_pAddress = value; } } /// <summary> /// Gets or sets 'cid' parameter value. Value null means not specified. /// </summary> public string CID { get { SIP_Parameter parameter = Parameters["cid"]; if (parameter != null) { return parameter.Value; } else { return null; } } set { if (string.IsNullOrEmpty(value)) { Parameters.Remove("cid"); } else { Parameters.Set("cid", value); } } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="value">SIP 'Referred-By' value.</param> public SIP_t_ReferredBy(string value) { m_pAddress = new SIP_t_NameAddress(); Parse(value); } #endregion #region Methods /// <summary> /// Parses "Referred-By" from specified value. /// </summary> /// <param name="value">SIP "Referred-By" value.</param> /// <exception cref="ArgumentNullException">Raised when <b>value</b> is null.</exception> /// <exception cref="SIP_ParseException">Raised when invalid SIP message.</exception> public void Parse(string value) { if (value == null) { throw new ArgumentNullException("value"); } Parse(new StringReader(value)); } /// <summary> /// Parses "Referred-By" from specified reader. /// </summary> /// <param name="reader">Reader from where to parse.</param> /// <exception cref="ArgumentNullException">Raised when <b>reader</b> is null.</exception> /// <exception cref="SIP_ParseException">Raised when invalid SIP message.</exception> public override void Parse(StringReader reader) { /* Referred-By = referrer-uri *( SEMI (referredby-id-param / generic-param) ) referrer-uri = ( name-addr / addr-spec ) referredby-id-param = "cid" EQUAL sip-clean-msg-id sip-clean-msg-id = LDQUOT dot-atom "@" (dot-atom / host) RDQUOT */ if (reader == null) { throw new ArgumentNullException("reader"); } // referrer-uri m_pAddress.Parse(reader); // Parse parameters ParseParameters(reader); } /// <summary> /// Converts this to valid "Referred-By" value. /// </summary> /// <returns>Returns "Referred-By" value.</returns> public override string ToStringValue() { /* Referred-By = referrer-uri *( SEMI (referredby-id-param / generic-param) ) referrer-uri = ( name-addr / addr-spec ) referredby-id-param = "cid" EQUAL sip-clean-msg-id sip-clean-msg-id = LDQUOT dot-atom "@" (dot-atom / host) RDQUOT */ StringBuilder retVal = new StringBuilder(); // referrer-uri retVal.Append(m_pAddress.ToStringValue()); // Add parameters retVal.Append(ParametersToString()); return retVal.ToString(); } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/vCard/PhoneNumberType_enum.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.Mime.vCard { #region usings using System; #endregion /// <summary> /// vCal phone number type. Note this values may be flagged ! /// </summary> [Flags] public enum PhoneNumberType_enum { /// <summary> /// Phone number type not specified. /// </summary> NotSpecified = 0, /// <summary> /// Preferred phone number. /// </summary> Preferred = 1, /// <summary> /// Telephone number associated with a residence. /// </summary> Home = 2, /// <summary> /// Telephone number has voice messaging support. /// </summary> Msg = 4, /// <summary> /// Telephone number associated with a place of work. /// </summary> Work = 8, /// <summary> /// Voice telephone number. /// </summary> Voice = 16, /// <summary> /// Fax number. /// </summary> Fax = 32, /// <summary> /// Cellular phone number. /// </summary> Cellular = 64, /// <summary> /// Video conferencing telephone number. /// </summary> Video = 128, /// <summary> /// Paging device telephone number. /// </summary> Pager = 256, /// <summary> /// Bulletin board system telephone number. /// </summary> BBS = 512, /// <summary> /// Modem connected telephone number. /// </summary> Modem = 1024, /// <summary> /// Car-phone telephone number. /// </summary> Car = 2048, /// <summary> /// ISDN service telephone number. /// </summary> ISDN = 4096, /// <summary> /// Personal communication services telephone number. /// </summary> PCS = 8192, } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/SIP/Stack/SIP_ClientTransaction.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.SIP.Stack { #region usings using System; using System.Threading; using System.Timers; using Message; #endregion /// <summary> /// Implements SIP client transaction. Defined in rfc 3261 17.1. /// </summary> public class SIP_ClientTransaction : SIP_Transaction { #region Events /// <summary> /// Is raised when transaction received response from remote party. /// </summary> public event EventHandler<SIP_ResponseReceivedEventArgs> ResponseReceived = null; #endregion #region Members private bool m_IsCanceling; private TimerEx m_pTimerA; private TimerEx m_pTimerB; private TimerEx m_pTimerD; private TimerEx m_pTimerE; private TimerEx m_pTimerF; private TimerEx m_pTimerK; private int m_RSeq = -1; #endregion #region Properties /// <summary> /// Gets or sets RSeq value. Value -1 means no reliable provisional response received. /// </summary> internal int RSeq { get { return m_RSeq; } set { m_RSeq = value; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="stack">Owner SIP stack.</param> /// <param name="flow">SIP data flow which is used to send request.</param> /// <param name="request">SIP request that transaction will handle.</param> /// <exception cref="ArgumentNullException">Is raised when <b>stack</b>,<b>flow</b> or <b>request</b> is null reference.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> internal SIP_ClientTransaction(SIP_Stack stack, SIP_Flow flow, SIP_Request request) : base(stack, flow, request) { // Log if (Stack.Logger != null) { Stack.Logger.AddText(ID, "Transaction [branch='" + ID + "';method='" + Method + "';IsServer=false] created."); } SetState(SIP_TransactionState.WaitingToStart); } #endregion #region Methods /// <summary> /// Cleans up any resources being used. /// </summary> public override void Dispose() { lock (SyncRoot) { if (IsDisposed) { return; } // Log if (Stack.Logger != null) { Stack.Logger.AddText(ID, "Transaction [branch='" + ID + "';method='" + Method + "';IsServer=false] disposed."); } // Kill timers. if (m_pTimerA != null) { m_pTimerA.Dispose(); m_pTimerA = null; } if (m_pTimerB != null) { m_pTimerB.Dispose(); m_pTimerB = null; } if (m_pTimerD != null) { m_pTimerD.Dispose(); m_pTimerD = null; } if (m_pTimerE != null) { m_pTimerE.Dispose(); m_pTimerE = null; } if (m_pTimerF != null) { m_pTimerF.Dispose(); m_pTimerF = null; } if (m_pTimerK != null) { m_pTimerK.Dispose(); m_pTimerK = null; } ResponseReceived = null; base.Dispose(); } } /// <summary> /// Starts transaction processing. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this method is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when <b>Start</b> is called other state than 'WaitingToStart'.</exception> public void Start() { lock (SyncRoot) { if (State == SIP_TransactionState.Disposed) { throw new ObjectDisposedException(GetType().Name); } else if (State != SIP_TransactionState.WaitingToStart) { throw new InvalidOperationException( "Start method is valid only in 'WaitingToStart' state."); } // Move processing to thread pool. ThreadPool.QueueUserWorkItem(delegate { lock (SyncRoot) { #region INVITE if (Method == SIP_Methods.INVITE) { /* RFC 3261 17.1.1.2. The initial state, "calling", MUST be entered when the TU initiates a new client transaction with an INVITE request. The client transaction MUST pass the request to the transport layer for transmission (see Section 18). If an unreliable transport is being used, the client transaction MUST start timer A with a value of T1. If a reliable transport is being used, the client transaction SHOULD NOT start timer A (Timer A controls request retransmissions). For any transport, the client transaction MUST start timer B with a value of 64*T1 seconds (Timer B controls transaction timeouts). */ SetState(SIP_TransactionState.Calling); try { // Send initial request. Stack.TransportLayer.SendRequest(Flow, Request, this); } catch (Exception x) { OnTransportError(x); // NOTE: TransportError event handler could Dispose this transaction, so we need to check it. if (State != SIP_TransactionState.Disposed) { SetState(SIP_TransactionState.Terminated); } return; } // Start timer A for unreliable transports. if (!Flow.IsReliable) { m_pTimerA = new TimerEx( SIP_TimerConstants.T1, false); m_pTimerA.Elapsed += m_pTimerA_Elapsed; m_pTimerA.Enabled = true; // Log if (Stack.Logger != null) { Stack.Logger.AddText(ID, "Transaction [branch='" + ID + "';method='" + Method + "';IsServer=false] timer A(INVITE request retransmission) started, will triger after " + m_pTimerA.Interval + "."); } } // Start timer B. m_pTimerB = new TimerEx( 64*SIP_TimerConstants.T1, false); m_pTimerB.Elapsed += m_pTimerB_Elapsed; m_pTimerB.Enabled = true; // Log if (Stack.Logger != null) { Stack.Logger.AddText(ID, "Transaction [branch='" + ID + "';method='" + Method + "';IsServer=false] timer B(INVITE calling state timeout) started, will triger after " + m_pTimerB.Interval + "."); } } #endregion #region Non-INVITE else { /* RFC 3261 192.168.3.11. The "Trying" state is entered when the TU initiates a new client transaction with a request. When entering this state, the client transaction SHOULD set timer F to fire in 64*T1 seconds. The request MUST be passed to the transport layer for transmission. If an unreliable transport is in use, the client transaction MUST set timer E to fire in T1 seconds. */ SetState(SIP_TransactionState.Trying); // Start timer F. m_pTimerF = new TimerEx( 64*SIP_TimerConstants.T1, false); m_pTimerF.Elapsed += m_pTimerF_Elapsed; m_pTimerF.Enabled = true; // Log if (Stack.Logger != null) { Stack.Logger.AddText(ID, "Transaction [branch='" + ID + "';method='" + Method + "';IsServer=false] timer F(Non-INVITE trying,proceeding state timeout) started, will triger after " + m_pTimerF.Interval + "."); } try { // Send initial request. Stack.TransportLayer.SendRequest(Flow, Request, this); } catch (Exception x) { OnTransportError(x); // NOTE: TransportError event handler could Dispose this transaction, so we need to check it. if (State != SIP_TransactionState.Disposed) { SetState(SIP_TransactionState.Terminated); } return; } // Start timer E for unreliable transports. if (!Flow.IsReliable) { m_pTimerE = new TimerEx( SIP_TimerConstants.T1, false); m_pTimerE.Elapsed += m_pTimerE_Elapsed; m_pTimerE.Enabled = true; // Log if (Stack.Logger != null) { Stack.Logger.AddText(ID, "Transaction [branch='" + ID + "';method='" + Method + "';IsServer=false] timer E(Non-INVITE request retransmission) started, will triger after " + m_pTimerE.Interval + "."); } } } #endregion } }); } } /// <summary> /// Starts canceling transaction. /// </summary> /// <remarks>If client transaction has got final response, canel has no effect and will be ignored.</remarks> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this method is accessed.</exception> public override void Cancel() { lock (SyncRoot) { if (State == SIP_TransactionState.Disposed) { throw new ObjectDisposedException(GetType().Name); } else if (State == SIP_TransactionState.WaitingToStart) { SetState(SIP_TransactionState.Terminated); return; } else if (m_IsCanceling) { return; } else if (State == SIP_TransactionState.Terminated) { // RFC 3261 9.1. We got final response, nothing to cancel. return; } if (FinalResponse != null) { return; } m_IsCanceling = true; /* RFC 3261 9.1. If no provisional response has been received, the CANCEL request MUST NOT be sent; rather, the client MUST wait for the arrival of a provisional response before sending the request. */ if (Responses.Length == 0) { // We set canceling flag, so if provisional response arrives, we do cancel. } else { SendCancel(); } } } #endregion #region Event handlers /// <summary> /// Is raised when INVITE timer A triggered. /// </summary> /// <param name="sender">Sender.</param> /// <param name="e">Event data.</param> private void m_pTimerA_Elapsed(object sender, ElapsedEventArgs e) { /* RFC 3261 172.16.58.3. When timer A fires, the client transaction MUST retransmit the request by passing it to the transport layer, and MUST reset the timer with a value of 2*T1. The formal definition of retransmit within the context of the transaction layer is to take the message previously sent to the transport layer and pass it to the transport layer once more. When timer A fires 2*T1 seconds later, the request MUST be retransmitted again (assuming the client transaction is still in this state). This process MUST continue so that the request is retransmitted with intervals that double after each transmission. These retransmissions SHOULD only be done while the client transaction is in the "calling" state. */ lock (SyncRoot) { if (State == SIP_TransactionState.Calling) { // Log if (Stack.Logger != null) { Stack.Logger.AddText(ID, "Transaction [branch='" + ID + "';method='" + Method + "';IsServer=false] timer A(INVITE request retransmission) triggered."); } try { // Retransmit request. Stack.TransportLayer.SendRequest(Flow, Request, this); } catch (Exception x) { OnTransportError(x); SetState(SIP_TransactionState.Terminated); return; } // Update(double current) next transmit time. m_pTimerA.Interval *= 2; m_pTimerA.Enabled = true; // Log if (Stack.Logger != null) { Stack.Logger.AddText(ID, "Transaction [branch='" + ID + "';method='" + Method + "';IsServer=false] timer A(INVITE request retransmission) updated, will triger after " + m_pTimerA.Interval + "."); } } } } /// <summary> /// Is raised when INVITE timer B triggered. /// </summary> /// <param name="sender">Sender.</param> /// <param name="e">Event data.</param> private void m_pTimerB_Elapsed(object sender, ElapsedEventArgs e) { /* RFC 3261 172.16.58.3. If the client transaction is still in the "Calling" state when timer B fires, the client transaction SHOULD inform the TU that a timeout has occurred. The client transaction MUST NOT generate an ACK. The value of 64*T1 is equal to the amount of time required to send seven requests in the case of an unreliable transport. */ lock (SyncRoot) { if (State == SIP_TransactionState.Calling) { // Log if (Stack.Logger != null) { Stack.Logger.AddText(ID, "Transaction [branch='" + ID + "';method='" + Method + "';IsServer=false] timer B(INVITE calling state timeout) triggered."); } OnTimedOut(); SetState(SIP_TransactionState.Terminated); // Stop timers A,B. if (m_pTimerA != null) { m_pTimerA.Dispose(); m_pTimerA = null; } if (m_pTimerB != null) { m_pTimerB.Dispose(); m_pTimerB = null; } } } } /// <summary> /// Is raised when INVITE timer D triggered. /// </summary> /// <param name="sender">Sender.</param> /// <param name="e">Event data.</param> private void m_pTimerD_Elapsed(object sender, ElapsedEventArgs e) { /* RFC 3261 172.16.58.3. If timer D fires while the client transaction is in the "Completed" state, the client transaction MUST move to the terminated state. */ lock (SyncRoot) { if (State == SIP_TransactionState.Completed) { // Log if (Stack.Logger != null) { Stack.Logger.AddText(ID, "Transaction [branch='" + ID + "';method='" + Method + "';IsServer=false] timer D(INVITE 3xx - 6xx response retransmission wait) triggered."); } SetState(SIP_TransactionState.Terminated); } } } /// <summary> /// Is raised when Non-INVITE timer E triggered. /// </summary> /// <param name="sender">Sender.</param> /// <param name="e">Event data.</param> private void m_pTimerE_Elapsed(object sender, ElapsedEventArgs e) { /* RFC 3261 192.168.3.11. If timer E fires while in Trying state, the timer is reset, but this time with a value of MIN(2*T1, T2). When the timer fires again, it is reset to a MIN(4*T1, T2). This process continues so that retransmissions occur with an exponentially increasing interval that caps at T2. The default value of T2 is 4s, and it represents the amount of time a non-INVITE server transaction will take to respond to a request, if it does not respond immediately. For the default values of T1 and T2, this results in intervals of 500 ms, 1 s, 2 s, 4 s, 4 s, 4 s, etc. */ lock (SyncRoot) { if (State == SIP_TransactionState.Trying) { // Log if (Stack.Logger != null) { Stack.Logger.AddText(ID, "Transaction [branch='" + ID + "';method='" + Method + "';IsServer=false] timer E(-NonINVITE request retransmission) triggered."); } try { // Retransmit request. Stack.TransportLayer.SendRequest(Flow, Request, this); } catch (Exception x) { OnTransportError(x); SetState(SIP_TransactionState.Terminated); return; } // Update(double current) next transmit time. m_pTimerE.Interval = Math.Min(m_pTimerE.Interval*2, SIP_TimerConstants.T2); m_pTimerE.Enabled = true; // Log if (Stack.Logger != null) { Stack.Logger.AddText(ID, "Transaction [branch='" + ID + "';method='" + Method + "';IsServer=false] timer E(Non-INVITE request retransmission) updated, will triger after " + m_pTimerE.Interval + "."); } } } } /// <summary> /// Is raised when Non-INVITE timer F triggered. /// </summary> /// <param name="sender">Sender.</param> /// <param name="e">Event data.</param> private void m_pTimerF_Elapsed(object sender, ElapsedEventArgs e) { /* RFC 3261 1172.16.58.3. If Timer F fires while in the "Trying" state, the client transaction SHOULD inform the TU about the timeout, and then it SHOULD enter the "Terminated" state. If timer F fires while in the "Proceeding" state, the TU MUST be informed of a timeout, and the client transaction MUST transition to the terminated state. */ lock (SyncRoot) { if (State == SIP_TransactionState.Trying || State == SIP_TransactionState.Proceeding) { // Log if (Stack.Logger != null) { Stack.Logger.AddText(ID, "Transaction [branch='" + ID + "';method='" + Method + "';IsServer=false] timer F(Non-INVITE trying,proceeding state timeout) triggered."); } OnTimedOut(); SetState(SIP_TransactionState.Terminated); if (m_pTimerE != null) { m_pTimerE.Dispose(); m_pTimerE = null; } if (m_pTimerF != null) { m_pTimerF.Dispose(); m_pTimerF = null; } } } } /// <summary> /// Is raised when Non-INVITE timer K triggered. /// </summary> /// <param name="sender">Sender.</param> /// <param name="e">Event data.</param> private void m_pTimerK_Elapsed(object sender, ElapsedEventArgs e) { lock (SyncRoot) { if (State == SIP_TransactionState.Completed) { // Log if (Stack.Logger != null) { Stack.Logger.AddText(ID, "Transaction [branch='" + ID + "';method='" + Method + "';IsServer=false] timer K(Non-INVITE 3xx - 6xx response retransmission wait) triggered."); } SetState(SIP_TransactionState.Terminated); } } } #endregion #region Utility methods /// <summary> /// Creates and send CANCEL request to remote target. /// </summary> private void SendCancel() { /* RFC 3261 9.1. The following procedures are used to construct a CANCEL request. The Request-URI, Call-ID, To, the numeric part of CSeq, and From header fields in the CANCEL request MUST be identical to those in the request being cancelled, including tags. A CANCEL constructed by a client MUST have only a single Via header field value matching the top Via value in the request being cancelled. Using the same values for these header fields allows the CANCEL to be matched with the request it cancels (Section 9.2 indicates how such matching occurs). However, the method part of the CSeq header field MUST have a value of CANCEL. This allows it to be identified and processed as a transaction in its own right (See Section 17). If the request being cancelled contains a Route header field, the CANCEL request MUST include that Route header field's values. This is needed so that stateless proxies are able to route CANCEL requests properly. */ SIP_Request cancelRequest = new SIP_Request(SIP_Methods.CANCEL); cancelRequest.RequestLine.Uri = Request.RequestLine.Uri; cancelRequest.Via.Add(Request.Via.GetTopMostValue().ToStringValue()); cancelRequest.CallID = Request.CallID; cancelRequest.From = Request.From; cancelRequest.To = Request.To; cancelRequest.CSeq = new SIP_t_CSeq(Request.CSeq.SequenceNumber, SIP_Methods.CANCEL); foreach (SIP_t_AddressParam route in Request.Route.GetAllValues()) { cancelRequest.Route.Add(route.ToStringValue()); } cancelRequest.MaxForwards = 70; // We must use same data flow to send CANCEL what sent initial request. SIP_ClientTransaction transaction = Stack.TransactionLayer.CreateClientTransaction(Flow, cancelRequest, false); transaction.Start(); } /// <summary> /// Creates and sends ACK for final(3xx - 6xx) failure response. /// </summary> /// <param name="response">SIP response.</param> /// <exception cref="ArgumentNullException">Is raised when <b>response</b> is null.</exception> private void SendAck(SIP_Response response) { if (response == null) { throw new ArgumentNullException("resposne"); } /* RFC 3261 172.16.17.32 Construction of the ACK Request. The ACK request constructed by the client transaction MUST contain values for the Call-ID, From, and Request-URI that are equal to the values of those header fields in the request passed to the transport by the client transaction (call this the "original request"). The To header field in the ACK MUST equal the To header field in the response being acknowledged, and therefore will usually differ from the To header field in the original request by the addition of the tag parameter. The ACK MUST contain a single Via header field, and this MUST be equal to the top Via header field of the original request. The CSeq header field in the ACK MUST contain the same value for the sequence number as was present in the original request, but the method parameter MUST be equal to "ACK". If the INVITE request whose response is being acknowledged had Route header fields, those header fields MUST appear in the ACK. This is to ensure that the ACK can be routed properly through any downstream stateless proxies. */ SIP_Request ackRequest = new SIP_Request(SIP_Methods.ACK); ackRequest.RequestLine.Uri = Request.RequestLine.Uri; ackRequest.Via.AddToTop(Request.Via.GetTopMostValue().ToStringValue()); ackRequest.CallID = Request.CallID; ackRequest.From = Request.From; ackRequest.To = response.To; ackRequest.CSeq = new SIP_t_CSeq(Request.CSeq.SequenceNumber, "ACK"); foreach (SIP_HeaderField h in response.Header.Get("Route:")) { ackRequest.Header.Add("Route:", h.Value); } ackRequest.MaxForwards = 70; try { // Send request to target. Stack.TransportLayer.SendRequest(Flow, ackRequest, this); } catch (SIP_TransportException x) { OnTransportError(x); SetState(SIP_TransactionState.Terminated); } } // FIX ME: /// <summary> /// Raises ResponseReceived event. /// </summary> /// <param name="response">SIP response received.</param> private void OnResponseReceived(SIP_Response response) { if (ResponseReceived != null) { ResponseReceived(this, new SIP_ResponseReceivedEventArgs(Stack, this, response)); } } #endregion #region Internal methods /// <summary> /// Processes specified response through this transaction. /// </summary> /// <param name="flow">SIP data flow what received response.</param> /// <param name="response">SIP response to process.</param> /// <exception cref="ArgumentNullException">Is raised when <b>flow</b>,<b>response</b> is null reference.</exception> internal void ProcessResponse(SIP_Flow flow, SIP_Response response) { if (flow == null) { throw new ArgumentNullException("flow"); } if (response == null) { throw new ArgumentNullException("response"); } lock (SyncRoot) { if (State == SIP_TransactionState.Disposed) { return; } /* RFC 3261 9.1. CANCEL. *) If provisional response, send CANCEL, we should get '478 Request terminated'. *) If final response, skip canceling, nothing to cancel. */ else if (m_IsCanceling && response.StatusCodeType == SIP_StatusCodeType.Provisional) { SendCancel(); return; } // Log if (Stack.Logger != null) { byte[] responseData = response.ToByteData(); Stack.Logger.AddRead(Guid.NewGuid().ToString(), null, 0, "Response [transactionID='" + ID + "'; method='" + response.CSeq.RequestMethod + "'; cseq='" + response.CSeq.SequenceNumber + "'; " + "transport='" + flow.Transport + "'; size='" + responseData.Length + "'; statusCode='" + response.StatusCode + "'; " + "reason='" + response.ReasonPhrase + "'; received '" + flow.LocalEP + "' <- '" + flow.RemoteEP + "'.", flow.LocalEP, flow.RemoteEP, responseData); } #region INVITE /* RFC 3261 172.16.58.3. |INVITE from TU Timer A fires |INVITE sent Reset A, V Timer B fires INVITE sent +-----------+ or Transport Err. +---------| |---------------+inform TU | | Calling | | +-------->| |-------------->| +-----------+ 2xx | | | 2xx to TU | | |1xx | 300-699 +---------------+ |1xx to TU | ACK sent | | | resp. to TU | 1xx V | | 1xx to TU -----------+ | | +---------| | | | | |Proceeding |-------------->| | +-------->| | 2xx | | +-----------+ 2xx to TU | | 300-699 | | | ACK sent, | | | resp. to TU| | | | | NOTE: | 300-699 V | | ACK sent +-----------+Transport Err. | transitions | +---------| |Inform TU | labeled with | | | Completed |-------------->| the event | +-------->| | | over the action | +-----------+ | to take | ^ | | | | | Timer D fires | +--------------+ | - | | | V | +-----------+ | | | | | Terminated|<--------------+ | | +-----------+ */ if (Method == SIP_Methods.INVITE) { #region Calling if (State == SIP_TransactionState.Calling) { // Store response. AddResponse(response); // Stop timer A,B if (m_pTimerA != null) { m_pTimerA.Dispose(); m_pTimerA = null; // Log if (Stack.Logger != null) { Stack.Logger.AddText(ID, "Transaction [branch='" + ID + "';method='" + Method + "';IsServer=false] timer A(INVITE request retransmission) stoped."); } } if (m_pTimerB != null) { m_pTimerB.Dispose(); m_pTimerB = null; // Log if (Stack.Logger != null) { Stack.Logger.AddText(ID, "Transaction [branch='" + ID + "';method='" + Method + "';IsServer=false] timer B(INVITE calling state timeout) stoped."); } } // 1xx response. if (response.StatusCodeType == SIP_StatusCodeType.Provisional) { OnResponseReceived(response); SetState(SIP_TransactionState.Proceeding); } // 2xx response. else if (response.StatusCodeType == SIP_StatusCodeType.Success) { OnResponseReceived(response); SetState(SIP_TransactionState.Terminated); } // 3xx - 6xx response. else { SendAck(response); OnResponseReceived(response); SetState(SIP_TransactionState.Completed); /* RFC 3261 172.16.58.3. The client transaction SHOULD start timer D when it enters the "Completed" state, with a value of at least 32 seconds for unreliable transports, and a value of zero seconds for reliable transports. */ m_pTimerD = new TimerEx(Flow.IsReliable ? 0 : Workaround.Definitions.MaxStreamLineLength, false); m_pTimerD.Elapsed += m_pTimerD_Elapsed; // Log if (Stack.Logger != null) { Stack.Logger.AddText(ID, "Transaction [branch='" + ID + "';method='" + Method + "';IsServer=false] timer D(INVITE 3xx - 6xx response retransmission wait) started, will triger after " + m_pTimerD.Interval + "."); } m_pTimerD.Enabled = true; } } #endregion #region Proceeding else if (State == SIP_TransactionState.Proceeding) { // Store response. AddResponse(response); // 1xx response. if (response.StatusCodeType == SIP_StatusCodeType.Provisional) { OnResponseReceived(response); } // 2xx response. else if (response.StatusCodeType == SIP_StatusCodeType.Success) { OnResponseReceived(response); SetState(SIP_TransactionState.Terminated); } // 3xx - 6xx response. else { SendAck(response); OnResponseReceived(response); SetState(SIP_TransactionState.Completed); /* RFC 3261 172.16.58.3. The client transaction SHOULD start timer D when it enters the "Completed" state, with a value of at least 32 seconds for unreliable transports, and a value of zero seconds for reliable transports. */ m_pTimerD = new TimerEx(Flow.IsReliable ? 0 : Workaround.Definitions.MaxStreamLineLength, false); m_pTimerD.Elapsed += m_pTimerD_Elapsed; // Log if (Stack.Logger != null) { Stack.Logger.AddText(ID, "Transaction [branch='" + ID + "';method='" + Method + "';IsServer=false] timer D(INVITE 3xx - 6xx response retransmission wait) started, will triger after " + m_pTimerD.Interval + "."); } m_pTimerD.Enabled = true; } } #endregion #region Completed else if (State == SIP_TransactionState.Completed) { // 3xx - 6xx if (response.StatusCode >= 300) { SendAck(response); } } #endregion #region Terminated else if (State == SIP_TransactionState.Terminated) { // We should never reach here, but if so, do nothing. } #endregion } #endregion #region Non-INVITE /* RFC 3251 192.168.3.11 |Request from TU |send request Timer E V send request +-----------+ +---------| |-------------------+ | | Trying | Timer F | +-------->| | or Transport Err.| +-----------+ inform TU | 200-699 | | | resp. to TU | |1xx | +---------------+ |resp. to TU | | | | | Timer E V Timer F | | send req +-----------+ or Transport Err. | | +---------| | inform TU | | | |Proceeding |------------------>| | +-------->| |-----+ | | +-----------+ |1xx | | | ^ |resp to TU | | 200-699 | +--------+ | | resp. to TU | | | | | | V | | +-----------+ | | | | | | | Completed | | | | | | | +-----------+ | | ^ | | | | | Timer K | +--------------+ | - | | | V | NOTE: +-----------+ | | | | transitions | Terminated|<------------------+ labeled with | | the event +-----------+ over the action to take */ else { #region Trying if (State == SIP_TransactionState.Trying) { // Store response. AddResponse(response); // Stop timer E if (m_pTimerE != null) { m_pTimerE.Dispose(); m_pTimerE = null; // Log if (Stack.Logger != null) { Stack.Logger.AddText(ID, "Transaction [branch='" + ID + "';method='" + Method + "';IsServer=false] timer E(Non-INVITE request retransmission) stoped."); } } // 1xx response. if (response.StatusCodeType == SIP_StatusCodeType.Provisional) { OnResponseReceived(response); SetState(SIP_TransactionState.Proceeding); } // 2xx - 6xx response. else { // Stop timer F if (m_pTimerF != null) { m_pTimerF.Dispose(); m_pTimerF = null; // Log if (Stack.Logger != null) { Stack.Logger.AddText(ID, "Transaction [branch='" + ID + "';method='" + Method + "';IsServer=false] timer F(Non-INVITE trying,proceeding state timeout) stoped."); } } OnResponseReceived(response); SetState(SIP_TransactionState.Completed); /* RFC 3261 192.168.3.11. The client transaction enters the "Completed" state, it MUST set Timer K to fire in T4 seconds for unreliable transports, and zero seconds for reliable transports. */ m_pTimerK = new TimerEx(Flow.IsReliable ? 1 : SIP_TimerConstants.T4, false); m_pTimerK.Elapsed += m_pTimerK_Elapsed; // Log if (Stack.Logger != null) { Stack.Logger.AddText(ID, "Transaction [branch='" + ID + "';method='" + Method + "';IsServer=false] timer K(Non-INVITE 3xx - 6xx response retransmission wait) started, will triger after " + m_pTimerK.Interval + "."); } m_pTimerK.Enabled = true; } } #endregion #region Proceeding else if (State == SIP_TransactionState.Proceeding) { // Store response. AddResponse(response); // 1xx response. if (response.StatusCodeType == SIP_StatusCodeType.Provisional) { OnResponseReceived(response); } // 2xx - 6xx response. else { // Stop timer F if (m_pTimerF != null) { m_pTimerF.Dispose(); m_pTimerF = null; // Log if (Stack.Logger != null) { Stack.Logger.AddText(ID, "Transaction [branch='" + ID + "';method='" + Method + "';IsServer=false] timer F(Non-INVITE trying,proceeding state timeout) stoped."); } } OnResponseReceived(response); SetState(SIP_TransactionState.Completed); /* RFC 3261 192.168.3.11. The client transaction enters the "Completed" state, it MUST set Timer K to fire in T4 seconds for unreliable transports, and zero seconds for reliable transports. */ m_pTimerK = new TimerEx(Flow.IsReliable ? 0 : SIP_TimerConstants.T4, false); m_pTimerK.Elapsed += m_pTimerK_Elapsed; // Log if (Stack.Logger != null) { Stack.Logger.AddText(ID, "Transaction [branch='" + ID + "';method='" + Method + "';IsServer=false] timer K(Non-INVITE 3xx - 6xx response retransmission wait) started, will triger after " + m_pTimerK.Interval + "."); } m_pTimerK.Enabled = true; } } #endregion #region Completed else if (State == SIP_TransactionState.Completed) { // Eat retransmited response. } #endregion #region Terminated else if (State == SIP_TransactionState.Terminated) { // We should never reach here, but if so, do nothing. } #endregion } #endregion } } #endregion } }<file_sep>/web/studio/ASC.Web.Studio/UserControls/Management/StorageSettings/js/storagesettings.js /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ ASC.StorageSettings = (function () { function init() { var $storageSettingsTemplateBlock = jq("#storageSettingsBlockTemplate"); var storageBlock = { id: "storage", title: ASC.Resources.Master.Resource.StorageStorageTitle }; var cdnBlock = { id: "cdn", title: ASC.Resources.Master.Resource.StorageCdnTitle }; jq(".storageBlock") .append($storageSettingsTemplateBlock.tmpl(storageBlock)) .append($storageSettingsTemplateBlock.tmpl(cdnBlock)); Teamlab.getAllStorages({}, { success: onGet.bind(null, storageBlock.id, Teamlab.updateStorage, Teamlab.resetToDefaultStorage) }); Teamlab.getAllCdnStorages({}, { success: onGet.bind(null, cdnBlock.id, Teamlab.updateCdnStorage, Teamlab.resetToDefaultCdn) }); } function onGet(storageid, updateFunc, resetFunc, params, data) { var current = data.find(function (item) { return item.current; }) || data.find(function (item) { return item.isSet; }) || data[0]; var selected = current; var $storage = jq("#" + storageid); var $authService = $storage.find(".auth-service"); var $link = $authService.find(".link"); var $storageSettingsTemplate = jq("#storageSettingsTemplate"); var $storageBlock = $storage.find(".auth-data"); $link.advancedSelector( { itemsChoose: data, showSearch: false, onechosen: true, sortMethod: function() { return 0; } } ); $link.on("showList", function (event, item) { selected = data.find(function (dataItem) { return dataItem.id === item.id; }); $link.text(selected.title); $storageBlock.html($storageSettingsTemplate.tmpl(selected)); }); $link.advancedSelector("selectBeforeShow", current); $authService.removeClass("display-none"); var clickEvent = "click"; $storageBlock.on(clickEvent, "[id^='saveBtn']",function () { var $currentButton = jq(this); if ($currentButton.hasClass("disable")) return; $currentButton.addClass("disable"); var $item = $currentButton.parents(".storageItem"); var data = { module: selected.id, props: initProps($item.find("input")) }; updateFunc({}, data, { success: function () { location.reload(); }, error: function (params, data) { toastr.error(data); } }); }); $storageBlock.on(clickEvent, "[id^='setDefault']", function () { var $currentButton = jq(this); if ($currentButton.hasClass("disable")) return; $currentButton.addClass("disable"); resetFunc({}, { success: function () { location.reload(); }, error: function (params, data) { toastr.error(data); } }); }); } function initProps($inputs) { var result = []; for (var i = 0; i < $inputs.length; i++) { var $inputItem = jq($inputs[i]); result.push({ key: $inputItem.attr("id"), value: $inputItem.val() }); } return result; } return { init: init }; })(); jq(document).ready(function () { ASC.StorageSettings.init(); });<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/SMTP/SMTP_Notify.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.SMTP { /// <summary> /// This value implements SMTP Notify value. Defined in RFC 1891. /// </summary> public enum SMTP_Notify { /// <summary> /// Notify value not specified. /// </summary> /// <remarks> /// For compatibility with SMTP clients that do not use the NOTIFY /// facility, the absence of a NOTIFY parameter in a RCPT command may be /// interpreted as either NOTIFY=FAILURE or NOTIFY=FAILURE,DELAY. /// </remarks> NotSpecified = 0, /// <summary> /// DSN should not be returned to the sender under any conditions. /// </summary> Never = 0xFF, /// <summary> /// DSN should be sent on successful delivery. /// </summary> Success = 2, /// <summary> /// DSN should be sent on delivery failure. /// </summary> Failure = 4, /// <summary> /// This value indicates the sender's willingness to receive "delayed" DSNs. /// </summary> Delay = 8, } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/Data/LDB_DataType.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Data.lsDB { /// <summary> /// lsDB data types. /// </summary> public enum LDB_DataType { /// <summary> /// Unicode string. /// </summary> String = (int) 's', /// <summary> /// Long (64-bit integer). /// </summary> Long = (int) 'l', /// <summary> /// Integer (32-bit integer). /// </summary> Int = (int) 'i', /// <summary> /// Date time. /// </summary> DateTime = (int) 't', /// <summary> /// Boolean. /// </summary> Bool = (int) 'b', } }<file_sep>/module/ASC.Thrdparty/ASC.FederatedLogin/LoginProviders/OpenIdLoginProvider.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections.Generic; using System.Web; using ASC.FederatedLogin.Profile; using DotNetOpenAuth.Messaging; using DotNetOpenAuth.OpenId; using DotNetOpenAuth.OpenId.Extensions.AttributeExchange; using DotNetOpenAuth.OpenId.Extensions.SimpleRegistration; using DotNetOpenAuth.OpenId.RelyingParty; namespace ASC.FederatedLogin.LoginProviders { class OpenIdLoginProvider : ILoginProvider { private static readonly OpenIdRelyingParty Openid = new OpenIdRelyingParty(); public LoginProfile ProcessAuthoriztion(HttpContext context, IDictionary<string, string> @params) { var response = Openid.GetResponse(); if (response == null) { Identifier id; if (Identifier.TryParse(@params["oid"], out id)) { try { IAuthenticationRequest request; var realmUrlString = String.Empty; if (@params.ContainsKey("realmUrl")) realmUrlString = @params["realmUrl"]; if (!String.IsNullOrEmpty(realmUrlString)) request = Openid.CreateRequest(id, new Realm(realmUrlString)); else request = Openid.CreateRequest(id); request.AddExtension(new ClaimsRequest { Email = DemandLevel.Require, Nickname = DemandLevel.Require, Country = DemandLevel.Request, Gender = DemandLevel.Request, PostalCode = DemandLevel.Request, TimeZone = DemandLevel.Request, FullName = DemandLevel.Request, }); var fetch = new FetchRequest(); fetch.Attributes.AddRequired(WellKnownAttributes.Contact.Email); //Duplicating attributes fetch.Attributes.AddRequired("http://schema.openid.net/contact/email");//Add two more fetch.Attributes.AddRequired("http://openid.net/schema/contact/email"); fetch.Attributes.AddRequired(WellKnownAttributes.Name.Alias); fetch.Attributes.AddRequired(WellKnownAttributes.Name.First); fetch.Attributes.AddRequired(WellKnownAttributes.Media.Images.Default); fetch.Attributes.AddRequired(WellKnownAttributes.Name.Last); fetch.Attributes.AddRequired(WellKnownAttributes.Name.Middle); fetch.Attributes.AddRequired(WellKnownAttributes.Person.Gender); fetch.Attributes.AddRequired(WellKnownAttributes.BirthDate.WholeBirthDate); request.AddExtension(fetch); request.RedirectToProvider(); context.Response.End();//This will throw thread abort } catch (ProtocolException ex) { return LoginProfile.FromError(ex); } } else { return LoginProfile.FromError(new Exception("invalid OpenID identifier")); } } else { // Stage 3: OpenID Provider sending assertion response switch (response.Status) { case AuthenticationStatus.Authenticated: var spprofile = response.GetExtension<ClaimsResponse>(); var fetchprofile = response.GetExtension<FetchResponse>(); var realmUrlString = String.Empty; if (@params.ContainsKey("realmUrl")) realmUrlString = @params["realmUrl"]; var profile = ProfileFromOpenId(spprofile, fetchprofile, response.ClaimedIdentifier.ToString(), realmUrlString); return profile; case AuthenticationStatus.Canceled: return LoginProfile.FromError(new Exception("Canceled at provider")); case AuthenticationStatus.Failed: return LoginProfile.FromError(response.Exception); } } return null; } public LoginProfile GetLoginProfile(string accessToken) { throw new NotImplementedException(); } public string Scopes { get { return ""; } } public string CodeUrl { get { return ""; } } public string AccessTokenUrl { get { return ""; } } public string RedirectUri { get { return ""; } } public string ClientID { get { return ""; } } public string ClientSecret { get { return ""; } } public bool IsEnabled { get { return GoogleLoginProvider.Instance.IsEnabled; } } internal static LoginProfile ProfileFromOpenId(ClaimsResponse spprofile, FetchResponse fetchprofile, string claimedId, string realmUrlString) { var profile = new LoginProfile { Link = claimedId, Id = claimedId, Provider = ProviderConstants.OpenId, }; if (spprofile != null) { //Fill profile.BirthDay = spprofile.BirthDateRaw; profile.DisplayName = spprofile.FullName; profile.EMail = spprofile.Email; profile.Name = spprofile.Nickname; profile.Gender = spprofile.Gender.HasValue ? spprofile.Gender.Value.ToString() : ""; profile.TimeZone = spprofile.TimeZone; profile.Locale = spprofile.Language; } if (fetchprofile != null) { profile.Name = fetchprofile.GetAttributeValue(WellKnownAttributes.Name.Alias); profile.LastName = fetchprofile.GetAttributeValue(WellKnownAttributes.Name.Last); profile.FirstName = fetchprofile.GetAttributeValue(WellKnownAttributes.Name.First); profile.DisplayName = fetchprofile.GetAttributeValue(WellKnownAttributes.Name.FullName); profile.MiddleName = fetchprofile.GetAttributeValue(WellKnownAttributes.Name.Middle); profile.Salutation = fetchprofile.GetAttributeValue(WellKnownAttributes.Name.Prefix); profile.Avatar = fetchprofile.GetAttributeValue(WellKnownAttributes.Media.Images.Default); profile.EMail = fetchprofile.GetAttributeValue(WellKnownAttributes.Contact.Email); profile.Gender = fetchprofile.GetAttributeValue(WellKnownAttributes.Person.Gender); profile.BirthDay = fetchprofile.GetAttributeValue(WellKnownAttributes.BirthDate.WholeBirthDate); } profile.RealmUrl = realmUrlString; return profile; } } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/SIP/Stack/SIP_Dialog_Subscribe.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.SIP.Stack { #region usings using System; #endregion /// <summary> /// This class represent SUBSCRIBE dialog. Defined in RFC 3265. /// </summary> public class SIP_Dialog_Subscribe { #region Constructor /// <summary> /// Default constructor. /// </summary> internal SIP_Dialog_Subscribe() {} #endregion #region Methods /// <summary> /// Sends notify request to remote end point. /// </summary> /// <param name="notify">SIP NOTIFY request.</param> public void Notify(SIP_Request notify) { if (notify == null) { throw new ArgumentNullException("notify"); } // TODO: } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/FTP/Client/FTP_ClientException.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.FTP.Client { #region usings using System; #endregion /// <summary> /// FTP client exception. /// </summary> public class FTP_ClientException : Exception { #region Members private readonly string m_ResponseText = ""; private readonly int m_StatusCode = 500; #endregion #region Properties /// <summary> /// Gets FTP status code. /// </summary> public int StatusCode { get { return m_StatusCode; } } /// <summary> /// Gets FTP server response text after status code. /// </summary> public string ResponseText { get { return m_ResponseText; } } /// <summary> /// Gets if it is permanent FTP(5xx) error. /// </summary> public bool IsPermanentError { get { if (m_StatusCode >= 500 && m_StatusCode <= 599) { return true; } else { return false; } } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="responseLine">FTP server response line.</param> /// <exception cref="ArgumentNullException">Is raised when <b>responseLine</b> is null.</exception> public FTP_ClientException(string responseLine) : base(responseLine) { if (responseLine == null) { throw new ArgumentNullException("responseLine"); } string[] code_text = responseLine.Split(new[] {' '}, 2); try { m_StatusCode = Convert.ToInt32(code_text[0]); } catch {} if (code_text.Length == 2) { m_ResponseText = code_text[1]; } } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/FTP/FTP_ListItem.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.FTP { #region usings using System; #endregion /// <summary> /// This class holds single file or directory in the FTP server. /// </summary> public class FTP_ListItem { #region Members private readonly bool m_IsDir; private readonly DateTime m_Modified; private readonly string m_Name = ""; private readonly long m_Size; #endregion #region Properties /// <summary> /// Gets if current item is directory. /// </summary> public bool IsDir { get { return m_IsDir; } } /// <summary> /// Gets if current item is file. /// </summary> public bool IsFile { get { return !m_IsDir; } } /// <summary> /// Gets the name of the file or directory. /// </summary> public string Name { get { return m_Name; } } /// <summary> /// Gets file size in bytes. /// </summary> public long Size { get { return m_Size; } } /// <summary> /// Gets last time file or direcory was modified. /// </summary> public DateTime Modified { get { return m_Modified; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="name">Directory or file name.</param> /// <param name="size">File size in bytes, zero for directory.</param> /// <param name="modified">Directory or file last modification time.</param> /// <param name="isDir">Specifies if list item is directory or file.</param> /// <exception cref="ArgumentNullException">Is raised when <b>name</b> is null.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> public FTP_ListItem(string name, long size, DateTime modified, bool isDir) { if (name == null) { throw new ArgumentNullException("name"); } if (name == "") { throw new ArgumentException("Argument 'name' value must be specified."); } m_Name = name; m_Size = size; m_Modified = modified; m_IsDir = isDir; } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/MIME/MIME_b_SinglepartBase.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.MIME { #region usings using System; using System.IO; using System.Text; using IO; #endregion /// <summary> /// This class is base class for singlepart media bodies like: text,video,audio,image. /// </summary> public abstract class MIME_b_SinglepartBase : MIME_b, IDisposable { #region Members private readonly Stream m_pEncodedDataStream; private bool m_IsModified; private string m_MediaType = ""; #endregion #region Properties /// <summary> /// Gets if body has modified. /// </summary> public override bool IsModified { get { return m_IsModified; } } /// <summary> /// Gets encoded body data size in bytes. /// </summary> public int EncodedDataSize { get { return (int) m_pEncodedDataStream.Length; } } /// <summary> /// Gets body encoded data. /// </summary> /// <remarks>NOTE: Use this property with care, because body data may be very big and you may run out of memory. /// For bigger data use <see cref="GetEncodedDataStream"/> method instead.</remarks> public byte[] EncodedData { get { MemoryStream ms = new MemoryStream(); Net_Utils.StreamCopy(GetEncodedDataStream(), ms, Workaround.Definitions.MaxStreamLineLength); return ms.ToArray(); } } /// <summary> /// Gets body decoded data. /// </summary> /// <remarks>NOTE: Use this property with care, because body data may be very big and you may run out of memory. /// For bigger data use <see cref="GetDataStream"/> method instead.</remarks> /// <exception cref="NotSupportedException">Is raised when body contains not supported Content-Transfer-Encoding.</exception> /// fucking idiot! /// private byte[] _dataCached = null; public byte[] Data { get { if (_dataCached == null) { using (var ms = new MemoryStream()) { Net_Utils.StreamCopy(GetDataStream(), ms, Workaround.Definitions.MaxStreamLineLength); _dataCached = ms.ToArray(); } } return _dataCached; } } /// <summary> /// Gets encoded data stream. /// </summary> protected Stream EncodedStream { get { return m_pEncodedDataStream; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <exception cref="ArgumentNullException">Is raised when <b>mediaType</b> is null reference.</exception> public MIME_b_SinglepartBase(string mediaType) : base(new MIME_h_ContentType(mediaType)) { if (mediaType == null) { throw new ArgumentNullException("mediaType"); } m_MediaType = mediaType; /*m_pEncodedDataStream = new FileStream(Path.GetTempFileName(), FileMode.Create, FileAccess.ReadWrite, FileShare.None, Workaround.Definitions.MaxStreamLineLength, FileOptions.DeleteOnClose);*/ m_pEncodedDataStream = new MemoryStream(); } #endregion #region Methods /// <summary> /// Gets body encoded data stream. /// </summary> /// <returns>Returns body encoded data stream.</returns> public Stream GetEncodedDataStream() { m_pEncodedDataStream.Position = 0; return m_pEncodedDataStream; } /// <summary> /// Sets body encoded data from specified stream. /// </summary> /// <param name="contentTransferEncoding">Content-Transfer-Encoding in what encoding <b>stream</b> data is.</param> /// <param name="stream">Stream data to add.</param> /// <exception cref="ArgumentNullException">Is raised when <b>contentTransferEncoding</b> or <b>stream</b> is null reference.</exception> /// <exception cref="ArgumentException">Is raised when any of the argumennts has invalid value.</exception> public void SetEncodedData(string contentTransferEncoding, Stream stream) { if (contentTransferEncoding == null) { throw new ArgumentNullException("contentTransferEncoding"); } if (contentTransferEncoding == string.Empty) { throw new ArgumentException("Argument 'contentTransferEncoding' value must be specified."); } if (stream == null) { throw new ArgumentNullException("stream"); } m_pEncodedDataStream.SetLength(0); Net_Utils.StreamCopy(stream, m_pEncodedDataStream, Workaround.Definitions.MaxStreamLineLength); // If body won't end with CRLF, add CRLF. if (m_pEncodedDataStream.Length >= 2) { m_pEncodedDataStream.Position = m_pEncodedDataStream.Length - 2; } if (m_pEncodedDataStream.ReadByte() != '\r' && m_pEncodedDataStream.ReadByte() != '\n') { m_pEncodedDataStream.Write(new[] {(byte) '\r', (byte) '\n'}, 0, 2); } Entity.ContentTransferEncoding = contentTransferEncoding; m_IsModified = true; } /// <summary> /// Gets body decoded data stream. /// </summary> /// <returns>Returns body decoded data stream.</returns> /// <exception cref="NotSupportedException">Is raised when body contains not supported Content-Transfer-Encoding.</exception> /// <remarks>The returned stream should be clossed/disposed as soon as it's not needed any more.</remarks> public Stream GetDataStream() { /* RFC 2045 6.1. This is the default value -- that is, "Content-Transfer-Encoding: 7BIT" is assumed if the Content-Transfer-Encoding header field is not present. */ string transferEncoding = MIME_TransferEncodings.SevenBit; if (Entity.ContentTransferEncoding != null) { transferEncoding = Entity.ContentTransferEncoding.ToLowerInvariant(); } m_pEncodedDataStream.Position = 0; m_pEncodedDataStream.Seek(0, SeekOrigin.Begin); if (transferEncoding == MIME_TransferEncodings.QuotedPrintable) { return new QuotedPrintableStream(new SmartStream(m_pEncodedDataStream, false), FileAccess.Read); } else if (transferEncoding == MIME_TransferEncodings.Base64) { return new Base64Stream(m_pEncodedDataStream, false, true, FileAccess.Read); } else if (transferEncoding == MIME_TransferEncodings.Binary) { return new ReadWriteControlledStream(m_pEncodedDataStream, FileAccess.Read); } else if (transferEncoding == MIME_TransferEncodings.EightBit) { return new ReadWriteControlledStream(m_pEncodedDataStream, FileAccess.Read); } else if (transferEncoding == MIME_TransferEncodings.SevenBit) { return new ReadWriteControlledStream(m_pEncodedDataStream, FileAccess.Read); } else { throw new NotSupportedException("Not supported Content-Transfer-Encoding '" + Entity.ContentTransferEncoding + "'."); } } /// <summary> /// Sets body data from the specified stream. /// </summary> /// <param name="stream">Source stream.</param> /// <param name="transferEncoding">Specifies content-transfer-encoding to use to encode data.</param> /// <exception cref="ArgumentNullException">Is raised when <b>stream</b> or <b>transferEncoding</b> is null reference.</exception> public void SetData(Stream stream, string transferEncoding) { if (stream == null) { throw new ArgumentNullException("stream"); } if (transferEncoding == null) { throw new ArgumentNullException("transferEncoding"); } if (transferEncoding == MIME_TransferEncodings.QuotedPrintable) { using (MemoryStream mem_stream = new MemoryStream()) { QuotedPrintableStream encoder = new QuotedPrintableStream(new SmartStream(mem_stream, false), FileAccess.ReadWrite); Net_Utils.StreamCopy(stream, encoder, Workaround.Definitions.MaxStreamLineLength); encoder.Flush(); mem_stream.Position = 0; SetEncodedData(transferEncoding, mem_stream); } } else if (transferEncoding == MIME_TransferEncodings.Base64) { using (MemoryStream mem_stream = new MemoryStream()) { Base64Stream encoder = new Base64Stream(mem_stream, false, true, FileAccess.ReadWrite); Net_Utils.StreamCopy(stream, encoder, Workaround.Definitions.MaxStreamLineLength); encoder.Finish(); mem_stream.Position = 0; SetEncodedData(transferEncoding, mem_stream); } } else if (transferEncoding == MIME_TransferEncodings.Binary) { SetEncodedData(transferEncoding, stream); } else if (transferEncoding == MIME_TransferEncodings.EightBit) { SetEncodedData(transferEncoding, stream); } else if (transferEncoding == MIME_TransferEncodings.SevenBit) { SetEncodedData(transferEncoding, stream); } else { throw new NotSupportedException("Not supported Content-Transfer-Encoding '" + transferEncoding + "'."); } } /// <summary> /// Sets body data from the specified file. /// </summary> /// <param name="file">File name with optional path.</param> /// <param name="transferEncoding">Specifies content-transfer-encoding to use to encode data.</param> /// <exception cref="ArgumentNullException">Is raised when <b>file</b> is null reference.</exception> public void SetBodyDataFromFile(string file, string transferEncoding) { if (file == null) { throw new ArgumentNullException("file"); } using (FileStream fs = File.OpenRead(file)) { SetData(fs, transferEncoding); } } #endregion #region Overrides /// <summary> /// Stores MIME entity body to the specified stream. /// </summary> /// <param name="stream">Stream where to store body data.</param> /// <param name="headerWordEncoder">Header 8-bit words ecnoder. Value null means that words are not encoded.</param> /// <param name="headerParmetersCharset">Charset to use to encode 8-bit header parameters. Value null means parameters not encoded.</param> /// <exception cref="ArgumentNullException">Is raised when <b>stream</b> is null reference.</exception> protected internal override void ToStream(Stream stream, MIME_Encoding_EncodedWord headerWordEncoder, Encoding headerParmetersCharset) { if (stream == null) { throw new ArgumentNullException("stream"); } Net_Utils.StreamCopy(GetEncodedDataStream(), stream, Workaround.Definitions.MaxStreamLineLength); } #endregion public void Dispose() { if (m_pEncodedDataStream != null) { m_pEncodedDataStream.Dispose(); } } } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/_Obsolete/MIME/ContentDisposition_enum.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.Mime { #region usings using System; #endregion /// <summary> /// Rfc 2183 Content-Disposition. /// </summary> [Obsolete("See LumiSoft.Net.MIME or LumiSoft.Net.Mail namepaces for replacement.")] public enum ContentDisposition_enum { /// <summary> /// Content is attachment. /// </summary> Attachment = 0, /// <summary> /// Content is embbed resource. /// </summary> Inline = 1, /// <summary> /// Content-Disposition header field isn't available or isn't written to mime message. /// </summary> NotSpecified = 30, /// <summary> /// Content is unknown. /// </summary> Unknown = 40 } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/RTP/RTCP_Packet_Unknown.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.RTP { /// <summary> /// This class represents unknown RTCP packet. /// </summary> public class RTCP_Packet_Unknown { // private int m_Type = 0: // private byte[] m_pPacket = null; // TODO: #region Properties Implementation #endregion } }<file_sep>/web/studio/ASC.Web.Studio/HttpHandlers/InvoiceHandler.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Linq; using System.Web; using ASC.Common.Logging; using ASC.Common.Web; using ASC.Core; using ASC.Core.Users; using ASC.Web.Studio.Utility; using MimeMapping = System.Web.MimeMapping; namespace ASC.Web.Studio.HttpHandlers { public class InvoiceHandler : IHttpHandler { private static readonly ILog log = LogManager.GetLogger("ASC"); public bool IsReusable { get { return true; } } public void ProcessRequest(HttpContext context) { try { if (!SecurityContext.IsAuthenticated && !CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID).IsAdmin()) { throw new HttpException(403, "Access denied."); } var pid = context.Request.QueryString["pid"]; if (string.IsNullOrEmpty(pid)) { throw new HttpException(400, "Bad request."); } if (CoreContext.PaymentManager.GetTariffPayments(TenantProvider.CurrentTenantID).All(p => p.CartId != pid)) { throw new HttpException(403, "Access denied."); } var invoice = CoreContext.PaymentManager.GetPaymentInvoice(pid); if (invoice == null || string.IsNullOrEmpty(invoice.Sale)) { throw new HttpException(404, "Not found."); } var pdf = Convert.FromBase64String(invoice.Sale); context.Response.Clear(); context.Response.ContentType = MimeMapping.GetMimeMapping(".pdf"); context.Response.AddHeader("Content-Disposition", "inline; filename=\"" + pid + ".pdf\""); context.Response.AddHeader("Content-Length", pdf.Length.ToString()); for (int i = 0, count = 1024; i < pdf.Length; i += count) { context.Response.OutputStream.Write(pdf, i, Math.Min(count, pdf.Length - i)); } context.Response.Flush(); } catch (HttpException he) { context.Response.StatusCode = he.GetHttpCode(); context.Response.Write(HttpUtility.HtmlEncode(he.Message)); } catch (Exception error) { log.ErrorFormat("Url: {0} {1}", context.Request.Url, error); context.Response.StatusCode = 500; context.Response.Write(HttpUtility.HtmlEncode(error.Message)); } } } }<file_sep>/web/studio/ASC.Web.Studio/Products/People/js/peoplemanager.js /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ var PeopleManager = new function() { this.GroupHeader = ''; this.SelectedCount = ''; this.UserLimit = ''; }; // Google Analytics const var ga_Categories = { people: "people_list" }; var ga_Actions = { filterClick: "filter-click", createNew: "create-new", remove: "remove", edit: "edit", view: "view", changeStatus: "change-status", next: "next", userClick: "user-click", actionClick: "action-click", quickAction: "quick-action", bannerClick: "banner-click" }; // end Google Analytic <file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/Mail/Mail_t_AddressList.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.Mail { #region usings using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Linq; using MIME; #endregion /// <summary> /// This class represents <b>address-list</b>. Defined in RFC 5322 3.4. /// </summary> public class Mail_t_AddressList : IEnumerable { #region Members private readonly List<Mail_t_Address> m_pList; private bool m_IsModified; private static System.Text.RegularExpressions.Regex m_regParser = new System.Text.RegularExpressions.Regex(@"^[\w!#$%&'*+\-/=?\^_`{|}~]+(\.[\w!#$%&'*+\-/=?\^_`{|}~]+)*" + "@" + @"((([\-\w]+\.)+[a-zA-Z]{2,4})|(([0-9]{1,3}\.){3}[0-9]{1,3}))$");//"^([0-9a-zA-Z]([-.\\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\\w]*[0-9a-zA-Z]\\.)+[a-zA-Z]{2,9})$"); #endregion #region Properties /// <summary> /// Gets if list has modified since it was loaded. /// </summary> public bool IsModified { get { return m_IsModified; } } /// <summary> /// Gets number of items in the collection. /// </summary> public int Count { get { return m_pList.Count; } } /// <summary> /// Gets the element at the specified index. /// </summary> /// <param name="index">The zero-based index of the element to get.</param> /// <returns>Returns the element at the specified index.</returns> /// <exception cref="ArgumentOutOfRangeException">Is raised when <b>index</b> is out of range.</exception> public Mail_t_Address this[int index] { get { if (index < 0 || index >= m_pList.Count) { throw new ArgumentOutOfRangeException("index"); } return m_pList[index]; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> public Mail_t_AddressList() { m_pList = new List<Mail_t_Address>(); } #endregion #region Methods /// <summary> /// Inserts a address into the collection at the specified location. /// </summary> /// <param name="index">The location in the collection where you want to add the item.</param> /// <param name="value">Address to insert.</param> /// <exception cref="ArgumentOutOfRangeException">Is raised when <b>index</b> is out of range.</exception> /// <exception cref="ArgumentNullException">Is raised when <b>value</b> is null reference.</exception> public void Insert(int index, Mail_t_Address value) { if (index < 0 || index > m_pList.Count) { throw new ArgumentOutOfRangeException("index"); } if (value == null) { throw new ArgumentNullException("value"); } m_pList.Insert(index, value); m_IsModified = true; } /// <summary> /// Adds specified address to the end of the collection. /// </summary> /// <param name="value">Address to add.</param> /// <exception cref="ArgumentNullException">Is raised when <b>value</b> is null reference value.</exception> public void Add(Mail_t_Address value) { if (value == null) { throw new ArgumentNullException("value"); } m_pList.Add(value); m_IsModified = true; } /// <summary> /// Removes specified item from the collection. /// </summary> /// <param name="value">Address to remove.</param> /// <exception cref="ArgumentNullException">Is raised when <b>value</b> is null reference value.</exception> public void Remove(Mail_t_Address value) { if (value == null) { throw new ArgumentNullException("value"); } m_pList.Remove(value); } /// <summary> /// Removes all items from the collection. /// </summary> public void Clear() { m_pList.Clear(); m_IsModified = true; } /// <summary> /// Copies addresses to new array. /// </summary> /// <returns>Returns addresses array.</returns> public Mail_t_Address[] ToArray() { return m_pList.ToArray(); } /// <summary> /// Returns address-list as string. /// </summary> /// <returns>Returns address-list as string.</returns> public override string ToString() { StringBuilder retVal = new StringBuilder(); for (int i = 0; i < m_pList.Count; i++) { if (i == (m_pList.Count - 1)) { retVal.Append(m_pList[i].ToString()); } else { retVal.Append(m_pList[i] + ","); } } return retVal.ToString(); } /// <summary> /// Gets enumerator. /// </summary> /// <returns></returns> public IEnumerator GetEnumerator() { return m_pList.GetEnumerator(); } #endregion #region Internal methods /// <summary> /// Resets IsModified property to false. /// </summary> internal void AcceptChanges() { m_IsModified = false; } #endregion public static Mail_t_AddressList ParseAddressList(string value) { MIME_Reader r = new MIME_Reader(value); /* RFC 5322 3.4. address = mailbox / group mailbox = name-addr / addr-spec name-addr = [display-name] angle-addr angle-addr = [CFWS] "<" addr-spec ">" [CFWS] / obs-angle-addr group = display-name ":" [group-list] ";" [CFWS] display-name = phrase mailbox-list = (mailbox *("," mailbox)) / obs-mbox-list address-list = (address *("," address)) / obs-addr-list group-list = mailbox-list / CFWS / obs-group-list */ Mail_t_AddressList retVal = new Mail_t_AddressList(); while (true) { string word = r.QuotedReadToDelimiter(new[] { ',', '<', ':' }); // We processed all data. if (word == null && r.Available == 0) { if (retVal.Count == 0) { if (CheckEmail(value)) { retVal.Add(new Mail_t_Mailbox(null, value)); } } break; } // skip old group address format else if (r.Peek(true) == ':') { // Consume ':' r.Char(true); } // name-addr else if (r.Peek(true) == '<') { string address = r.ReadParenthesized(); if (CheckEmail(address)) { retVal.Add( new Mail_t_Mailbox( word != null ? MIME_Encoding_EncodedWord.DecodeS(TextUtils.UnQuoteString(word)) : null, address)); } } // addr-spec else { if (CheckEmail(word)) { retVal.Add(new Mail_t_Mailbox(null, word)); } } // We have more addresses. if (r.Peek(true) == ',') { r.Char(false); } } return retVal; } private static bool CheckEmail(string EmailAddress) { return !string.IsNullOrEmpty(EmailAddress) ? m_regParser.IsMatch(EmailAddress.Trim()) : false; } } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/_Obsolete/SIP_RequestSender.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections.Generic; using System.Text; namespace LumiSoft.Net.SIP.Stack { /// <summary> /// This class is responsible for sending <b>request</b> to one of the <b>hops</b>. /// Hops are tried one by one until a server is contacted. /// </summary> public class SIP_RequestSender { private bool m_IsStarted = false; private SIP_Stack m_pStack = null; private SIP_Request m_pRequest = null; private Queue<SIP_Hop> m_pHops = null; private int m_Timeout = 15; private SIP_ClientTransaction m_pTransaction = null; /// <summary> /// Default constructor. /// </summary> /// <param name="stack">SIP stack.</param> /// <param name="request">SIP request.</param> /// <param name="hops">Priority ordered "hops" where to send request.</param> /// <exception cref="ArgumentNullException">Is raised when <b>stack</b>,<b>request</b> or <b>hops</b> is null reference.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> public SIP_RequestSender(SIP_Stack stack,SIP_Request request,Queue<SIP_Hop> hops) { if(stack == null){ throw new ArgumentNullException("stack"); } if(request == null){ throw new ArgumentNullException("request"); } if(hops == null){ throw new ArgumentNullException("hops"); } if(hops.Count == 0){ throw new ArgumentException("There must be at least 1 hop in 'hops' queue."); } m_pStack = stack; m_pRequest = request; m_pHops = hops; } #region method Start /// <summary> /// Starts sending request. /// </summary> public void Start() { if(m_IsStarted){ throw new InvalidOperationException("Request sending is already started."); } m_IsStarted = true; // RFC 3261 8.1.2 and . 16.6. We need to create new client transaction for each attempt. } #endregion #region method Cancel /// <summary> /// Cancels request sending. /// </summary> public void Cancel() { } #endregion #region Properties implementation /// <summary> /// Gets SIP request what this sender is responsible for. /// </summary> public SIP_Request Request { get{ return m_pRequest; } } #endregion #region Events handling // public event EventHandler NewTransaction // public event EventHandler #endregion } } <file_sep>/redistributable/ShrapBox/Src/AppLimit.CloudComputing.SharpBox/UI/Presentation/Sandbox.cs using System; using System.Collections; using System.ComponentModel; using System.Windows.Forms; namespace AppLimit.CloudComputing.SharpBox.UI { /// <summary> /// Control that provide management of cloud folders /// </summary> public partial class Sandbox : UserControl { #region ATTRIBUTES private readonly WindowsFormsSynchronizationContext _syncContext; private CloudStorage _storage; private ListViewColumnSorter listViewFilesSorter; /// <summary> /// Event indicate that cloud folders have been loaded /// </summary> public event EventHandler SandboxLoadCompleted; /// <summary> /// Constructor of Sandbox control /// </summary> public Sandbox() { InitializeComponent(); _syncContext = AsyncOperationManager.SynchronizationContext as WindowsFormsSynchronizationContext; _storage = null; listViewFilesSorter = new ListViewColumnSorter(); lstFiles.ListViewItemSorter = listViewFilesSorter; lstFiles.Sort(); } #endregion /// <summary> /// Assign cloud storage /// </summary> /// <param name="storage">Cloud storage object</param> public void SetCloudStorage(CloudStorage storage) { _storage = storage; } /// <summary> /// Method to load cloud folders /// </summary> public void LoadSandBox() { if (!workerLoadFolders.IsBusy) { workerLoadFolders.RunWorkerAsync(); } } #region EVENTS private void OnSandboxLoadCompleted(object sender, EventArgs e) { EventHandler Current = (EventHandler)SandboxLoadCompleted; if (Current != null) { Current(this, new EventArgs()); } } private void viewFolders_AfterSelect(object sender, TreeViewEventArgs e) { if (!workerLoadFiles.IsBusy) { lstFiles.Items.Clear(); picLoading.Visible = true; workerLoadFiles.RunWorkerAsync(e.Node.Tag); } } private void lstFiles_ColumnClick(object sender, ColumnClickEventArgs e) { // check if the selected column is already sorted if (e.Column == listViewFilesSorter.SortColumn) { // Inverse sort order if (listViewFilesSorter.Order == SortOrder.Ascending) { listViewFilesSorter.Order = SortOrder.Descending; } else { listViewFilesSorter.Order = SortOrder.Ascending; } } else { // sort ascending on this column listViewFilesSorter.SortColumn = e.Column; listViewFilesSorter.Order = SortOrder.Ascending; } // Sort list lstFiles.Sort(); } #endregion #region METHODS private void ListCloudDirectoryEntry(ICloudDirectoryEntry cloudEntry) { foreach (var subCloudEntry in cloudEntry) { if (subCloudEntry is ICloudDirectoryEntry) { workerLoadFolders.ReportProgress(2, subCloudEntry); ListCloudDirectoryEntry((ICloudDirectoryEntry)subCloudEntry); } } } private void AddCloudDirectory(ICloudDirectoryEntry cloudEntry, TreeNode trParent) { TreeNode newNode = null; if (trParent == null) { newNode = viewFolders.Nodes.Add(cloudEntry.GetPropertyValue("path"), cloudEntry.Name); } else { newNode = trParent.Nodes.Add(cloudEntry.GetPropertyValue("path"), cloudEntry.Name); } newNode.Tag = cloudEntry; } #endregion #region WORKER FOLDERS private void workerLoadFolders_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e) { if (_storage == null) { throw new TypeInitializationException(typeof(CloudStorage).ToString(), null); } if (_storage.IsOpened == false) { throw new Exception("Storage is not opened"); } if (e.Argument == null) { // Clear workerLoadFolders.ReportProgress(0); // Load roots ICloudDirectoryEntry cloudEntries = _storage.GetRoot(); // List roots foreach (var cloudEntry in cloudEntries) { if (cloudEntry is ICloudDirectoryEntry) { workerLoadFolders.ReportProgress(1, cloudEntry); ListCloudDirectoryEntry((ICloudDirectoryEntry)cloudEntry); } } } } private void workerLoadFolders_ProgressChanged(object sender, ProgressChangedEventArgs e) { // For thread synchronization _syncContext.Post(workerLoadFolders_ProgressChanged_Callback, e); } private void workerLoadFolders_ProgressChanged_Callback(object ev) { ProgressChangedEventArgs e = (ProgressChangedEventArgs)ev; if (e.ProgressPercentage == 0) { // Clear tree view viewFolders.Nodes.Clear(); pbLoading.Visible = true; } else if (e.ProgressPercentage == 1) { ICloudDirectoryEntry cloudEntry = (ICloudDirectoryEntry)e.UserState; AddCloudDirectory(cloudEntry, null); } else if (e.ProgressPercentage == 2) { ICloudDirectoryEntry cloudEntry = (ICloudDirectoryEntry)e.UserState; // Find parent root TreeNode[] findedNodes = viewFolders.Nodes.Find(cloudEntry.Parent.GetPropertyValue("path"), true); if (findedNodes.Length == 1) { // add sub folders AddCloudDirectory(cloudEntry, findedNodes[0]); } } } private void workerLoadFolders_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { // For thread synchronization _syncContext.Post(workerLoadFolders_RunWorkerCompleted_Callback, e); } private void workerLoadFolders_RunWorkerCompleted_Callback(object ev) { RunWorkerCompletedEventArgs e = (RunWorkerCompletedEventArgs)ev; pbLoading.Visible = false; OnSandboxLoadCompleted(this, new EventArgs()); } #endregion #region WORKER FILES private void workerLoadFiles_DoWork(object sender, DoWorkEventArgs e) { ICloudDirectoryEntry cloudEntry = (ICloudDirectoryEntry)e.Argument; // Loop on each entries IEnumerator cloudEntries = cloudEntry.GetEnumerator(); while (cloudEntries.MoveNext()) { var entry = cloudEntries.Current; if (entry is ICloudDirectoryEntry) { // Nothing, it is a folder } else if (entry is ICloudFileSystemEntry) { ICloudFileSystemEntry fsEntry = (ICloudFileSystemEntry)entry; // Build new listviewitem object ListViewItem newEntry = new ListViewItem(fsEntry.Name); // Add size (add size to tag for sorting) ListViewItem.ListViewSubItem subItems = newEntry.SubItems.Add(FileSizeFormat.Format(fsEntry.Length)); subItems.Tag = fsEntry.Length; // Add modified date (add date to tag for sorting) subItems = newEntry.SubItems.Add(fsEntry.Modified.ToString()); subItems.Tag = fsEntry.Modified; // Add object to tag newEntry.Tag = fsEntry; // Report progress new entry to worker workerLoadFiles.ReportProgress(0, newEntry); } } } private void workerLoadFiles_ProgressChanged(object sender, ProgressChangedEventArgs e) { // For thread synchronization _syncContext.Post(workerLoadFiles_ProgressChanged_Callback, e); } private void workerLoadFiles_ProgressChanged_Callback(object ev) { ProgressChangedEventArgs e = (ProgressChangedEventArgs)ev; if (e.ProgressPercentage == 0) { if (e.UserState != null) { lstFiles.Items.Add((ListViewItem)e.UserState); } } } private void workerLoadFiles_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { // For thread synchronization _syncContext.Post(workerLoadFiles_RunWorkerCompleted_Callback, e); } private void workerLoadFiles_RunWorkerCompleted_Callback(object ev) { RunWorkerCompletedEventArgs e = (RunWorkerCompletedEventArgs)ev; picLoading.Visible = false; } #endregion } } <file_sep>/module/ASC.AuditTrail/AuditEventsRepository.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections.Generic; using ASC.AuditTrail.Mappers; using ASC.Common.Data; using ASC.Common.Data.Sql; using System.Linq; using ASC.Common.Data.Sql.Expressions; using ASC.Core.Tenants; using ASC.Core.Users; using ASC.MessagingSystem; using Newtonsoft.Json; namespace ASC.AuditTrail { public class AuditEventsRepository { private const string dbid = "core"; private static readonly string[] auditColumns = new[] { "id", "ip", "initiator", "browser", "platform", "date", "tenant_id", "user_id", "page", "action", "description", "target" }; public static IEnumerable<AuditEvent> GetLast(int tenant, int chunk) { return Get(tenant, null, null, chunk); } public static IEnumerable<AuditEvent> Get(int tenant, DateTime from, DateTime to) { return Get(tenant, from, to, null); } private static IEnumerable<AuditEvent> Get(int tenant, DateTime? from, DateTime? to, int? limit) { var q = new SqlQuery("audit_events a") .Select(auditColumns.Select(x => "a." + x).ToArray()) .LeftOuterJoin("core_user u", Exp.EqColumns("a.user_id", "u.id")) .Select("u.firstname", "u.lastname") .Where("a.tenant_id", tenant) .OrderBy("a.date", false); if (from.HasValue && to.HasValue) { q.Where(Exp.Between("a.date", from.Value, to.Value)); } if (limit.HasValue) { q.SetMaxResults(limit.Value); } using (var db = new DbManager(dbid)) { return db.ExecuteList(q) .Select(ToAuditEvent) .Where(x => x != null) .ToList(); } } public static int GetCount(int tenant, DateTime? from = null, DateTime? to = null) { var q = new SqlQuery("audit_events a") .SelectCount() .Where("a.tenant_id", tenant) .OrderBy("a.date", false); if (from.HasValue && to.HasValue) { q.Where(Exp.Between("a.date", from.Value, to.Value)); } using (var db = new DbManager(dbid)) { return db.ExecuteScalar<int>(q); } } private static AuditEvent ToAuditEvent(object[] row) { try { var evt = new AuditEvent { Id = Convert.ToInt32(row[0]), IP = Convert.ToString(row[1]), Initiator = Convert.ToString(row[2]), Browser = Convert.ToString(row[3]), Platform = Convert.ToString(row[4]), Date = TenantUtil.DateTimeFromUtc(Convert.ToDateTime(row[5])), TenantId = Convert.ToInt32(row[6]), UserId = Guid.Parse(Convert.ToString(row[7])), Page = Convert.ToString(row[8]), Action = Convert.ToInt32(row[9]) }; if (row[10] != null) { evt.Description = JsonConvert.DeserializeObject<IList<string>>( Convert.ToString(row[10]), new JsonSerializerSettings { DateTimeZoneHandling = DateTimeZoneHandling.Utc }); } evt.Target = MessageTarget.Parse(Convert.ToString(row[11])); evt.UserName = (row[12] != null && row[13] != null) ? UserFormatter.GetUserName(Convert.ToString(row[12]), Convert.ToString(row[13])) : evt.UserId == Core.Configuration.Constants.CoreSystem.ID ? AuditReportResource.SystemAccount : evt.UserId == Core.Configuration.Constants.Guest.ID ? AuditReportResource.GuestAccount : evt.Initiator ?? AuditReportResource.UnknownAccount; evt.ActionText = AuditActionMapper.GetActionText(evt); evt.ActionTypeText = AuditActionMapper.GetActionTypeText(evt); evt.Product = AuditActionMapper.GetProductText(evt); evt.Module = AuditActionMapper.GetModuleText(evt); return evt; } catch (Exception) { return null; } } } }<file_sep>/web/studio/ASC.Web.Studio/Products/Files/Controls/AnalyticsPersonalFirstVisit.js /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ try { if (window.ga) { window.ga('www.send', 'event', "account_registered"); } } catch (err) { } try { if ((typeof window.yaCounter23426227 !== 'undefined') && (yaCounter23426227!=null)) { yaCounter23426227.reachGoal('Account_Registered'); } } catch (e) { }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/SIP/Stack/SIP_TransportLayer.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.SIP.Stack { #region usings using System; using System.Collections.Generic; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; using System.Timers; using Dns.Client; using Message; using TCP; using UDP; #endregion /// <summary> /// Implements SIP transport layer. Defined in RFC 3261. /// </summary> public class SIP_TransportLayer { #region Members private readonly SIP_FlowManager m_pFlowManager; private readonly CircleCollection<IPAddress> m_pLocalIPv4; private readonly CircleCollection<IPAddress> m_pLocalIPv6; private readonly SIP_Stack m_pStack; private bool m_IsDisposed; private bool m_IsRunning; private IPBindInfo[] m_pBinds; private Random m_pRandom; private TCP_Server<TCP_ServerSession> m_pTcpServer; private UDP_Server m_pUdpServer; #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="stack">Owner SIP stack.</param> /// <exception cref="ArgumentNullException">Is raised when <b>stack</b> is null reference.</exception> internal SIP_TransportLayer(SIP_Stack stack) { if (stack == null) { throw new ArgumentNullException("stack"); } m_pStack = stack; m_pUdpServer = new UDP_Server(); m_pUdpServer.ProcessMode = UDP_ProcessMode.Parallel; m_pUdpServer.PacketReceived += m_pUdpServer_PacketReceived; m_pUdpServer.Error += m_pUdpServer_Error; m_pTcpServer = new TCP_Server<TCP_ServerSession>(); m_pTcpServer.SessionCreated += m_pTcpServer_SessionCreated; m_pFlowManager = new SIP_FlowManager(this); m_pBinds = new IPBindInfo[] {}; m_pRandom = new Random(); m_pLocalIPv4 = new CircleCollection<IPAddress>(); m_pLocalIPv6 = new CircleCollection<IPAddress>(); } #endregion #region Properties /// <summary> /// Gets or sets socket bind info. Use this property to specify on which protocol,IP,port server /// listnes and also if connections is SSL. /// </summary> public IPBindInfo[] BindInfo { get { return m_pBinds; } set { if (value == null) { throw new ArgumentNullException("BindInfo"); } //--- See binds has changed -------------- bool changed = false; if (m_pBinds.Length != value.Length) { changed = true; } else { for (int i = 0; i < m_pBinds.Length; i++) { if (!m_pBinds[i].Equals(value[i])) { changed = true; break; } } } if (changed) { m_pBinds = value; // Create listening points. List<IPEndPoint> udpListeningPoints = new List<IPEndPoint>(); List<IPBindInfo> tcpListeningPoints = new List<IPBindInfo>(); foreach (IPBindInfo bindInfo in m_pBinds) { if (bindInfo.Protocol == BindInfoProtocol.UDP) { udpListeningPoints.Add(new IPEndPoint(bindInfo.IP, bindInfo.Port)); } else { tcpListeningPoints.Add(bindInfo); } } m_pUdpServer.Bindings = udpListeningPoints.ToArray(); m_pTcpServer.Bindings = tcpListeningPoints.ToArray(); // Build possible local TCP/TLS IP addresses. foreach (IPEndPoint ep in m_pTcpServer.LocalEndPoints) { if (ep.AddressFamily == AddressFamily.InterNetwork) { m_pLocalIPv4.Add(ep.Address); } else if (ep.AddressFamily == AddressFamily.InterNetwork) { m_pLocalIPv6.Add(ep.Address); } } } } } /// <summary> /// Gets currently active flows. /// </summary> public SIP_Flow[] Flows { get { return m_pFlowManager.Flows; } } /// <summary> /// Gets if transport layer is running. /// </summary> public bool IsRunning { get { return m_IsRunning; } } /// <summary> /// Gets owner SIP stack. /// </summary> public SIP_Stack Stack { get { return m_pStack; } } /// <summary> /// Gets or sets STUN server name or IP address. This value must be filled if SIP stack is running behind a NAT. /// </summary> internal string StunServer { get; set; } /// <summary> /// Gets UDP server. /// </summary> internal UDP_Server UdpServer { get { return m_pUdpServer; } } #endregion #region Methods /// <summary> /// Gets existing flow or if flow doesn't exist, new one is created and returned. /// </summary> /// <param name="transport">SIP transport.</param> /// <param name="localEP">Local end point. Value null means system will allocate it.</param> /// <param name="remoteEP">Remote end point.</param> /// <returns>Returns data flow.</returns> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and and this method is accessed.</exception> /// <exception cref="ArgumentNullException">Is raised when <b>remoteEP</b>.</exception> public SIP_Flow GetOrCreateFlow(string transport, IPEndPoint localEP, IPEndPoint remoteEP) { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (remoteEP == null) { throw new ArgumentNullException("remoteEP"); } if (localEP == null) { if (transport == SIP_Transport.UDP) { // Get load-balanched local endpoint. localEP = m_pUdpServer.GetLocalEndPoint(remoteEP); } else if (transport == SIP_Transport.TCP) { // Get load-balanched local IP for TCP and create random port. if (remoteEP.AddressFamily == AddressFamily.InterNetwork) { localEP = new IPEndPoint(m_pLocalIPv4.Next(), m_pRandom.Next(10000, 65000)); } else { localEP = new IPEndPoint(m_pLocalIPv4.Next(), m_pRandom.Next(10000, 65000)); } } else if (transport == SIP_Transport.TLS) { // Get load-balanched local IP for TLS and create random port. if (remoteEP.AddressFamily == AddressFamily.InterNetwork) { localEP = new IPEndPoint(m_pLocalIPv4.Next(), m_pRandom.Next(10000, 65000)); } else { localEP = new IPEndPoint(m_pLocalIPv4.Next(), m_pRandom.Next(10000, 65000)); } } } return m_pFlowManager.GetOrCreateFlow(false, localEP, remoteEP, transport); } /// <summary> /// Returns specified flow or null if no such flow. /// </summary> /// <param name="flowID">Data flow ID.</param> /// <returns>Returns specified flow or null if no such flow.</returns> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and and this method is accessed.</exception> /// <exception cref="ArgumentNullException">Is raised when <b>flowID</b> is null reference.</exception> public SIP_Flow GetFlow(string flowID) { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (flowID == null) { throw new ArgumentNullException("flowID"); } return m_pFlowManager.GetFlow(flowID); } /// <summary> /// Sends request using methods as described in RFC 3261 [4](RFC 3263). /// </summary> /// <param name="request">SIP request to send.</param> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and and this method is accessed.</exception> /// <exception cref="ArgumentNullException">Is raised when <b>request</b> is null.</exception> /// <exception cref="SIP_TransportException">Is raised when transport error happens.</exception> public void SendRequest(SIP_Request request) { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (request == null) { throw new ArgumentNullException("request"); } SIP_Hop[] hops = m_pStack.GetHops((SIP_Uri) request.RequestLine.Uri, request.ToByteData().Length, false); if (hops.Length == 0) { throw new SIP_TransportException("No target hops for URI '" + request.RequestLine.Uri + "'."); } SIP_TransportException lastException = null; foreach (SIP_Hop hop in hops) { try { SendRequest(request, null, hop); return; } catch (SIP_TransportException x) { lastException = x; } } // If we reach so far, send failed, return last error. throw lastException; } /// <summary> /// Sends request to the specified hop. /// </summary> /// <param name="request">SIP request.</param> /// <param name="localEP">Local end point. Value null means system will allocate it.</param> /// <param name="hop">Target hop.</param> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and and this method is accessed.</exception> /// <exception cref="ArgumentNullException">Is raised when <b>request</b> or <b>hop</b> is null reference.</exception> public void SendRequest(SIP_Request request, IPEndPoint localEP, SIP_Hop hop) { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (request == null) { throw new ArgumentNullException("request"); } if (hop == null) { throw new ArgumentNullException("hop"); } SendRequest(GetOrCreateFlow(hop.Transport, localEP, hop.EndPoint), request); } /// <summary> /// Sends request to the specified flow. /// </summary> /// <param name="flow">Data flow.</param> /// <param name="request">SIP request.</param> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and and this method is accessed.</exception> /// <exception cref="ArgumentNullException">Is raised when <b>flow</b> or <b>request</b> is null reference.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments contains invalid value.</exception> public void SendRequest(SIP_Flow flow, SIP_Request request) { SendRequest(flow, request, null); } /// <summary> /// Sends specified response back to request maker using RFC 3261 18. rules. /// </summary> /// <param name="response">SIP response.</param> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and and this method is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when stack ahs not been started and this method is accessed.</exception> /// <exception cref="ArgumentNullException">Is raised when <b>response</b> is null reference.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> /// <exception cref="SIP_TransportException">Is raised when <b>response</b> sending has failed.</exception> /// <remarks>Use this method to send SIP responses from stateless SIP elements, like stateless proxy. /// Otherwise SIP_ServerTransaction.SendResponse method should be used.</remarks> public void SendResponse(SIP_Response response) { SendResponse(response, null); } /// <summary> /// Sends specified response back to request maker using RFC 3261 18. rules. /// </summary> /// <param name="response">SIP response.</param> /// <param name="localEP">Local IP end point to use for sending resposne. Value null means system will allocate it.</param> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and and this method is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when stack ahs not been started and this method is accessed.</exception> /// <exception cref="ArgumentNullException">Is raised when <b>response</b> is null reference.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> /// <exception cref="SIP_TransportException">Is raised when <b>response</b> sending has failed.</exception> /// <remarks>Use this method to send SIP responses from stateless SIP elements, like stateless proxy. /// Otherwise SIP_ServerTransaction.SendResponse method should be used.</remarks> public void SendResponse(SIP_Response response, IPEndPoint localEP) { // NOTE: all paramter / state validations are done in SendResponseInternal. SendResponseInternal(null, response, localEP); } #endregion #region Internal methods /// <summary> /// Cleans up any resources being used. /// </summary> internal void Dispose() { if (m_IsDisposed) { return; } m_IsDisposed = true; Stop(); m_IsRunning = false; m_pBinds = null; m_pRandom = null; m_pTcpServer.Dispose(); m_pTcpServer = null; m_pUdpServer.Dispose(); m_pUdpServer = null; } /// <summary> /// Starts listening incoming requests and responses. /// </summary> internal void Start() { if (m_IsRunning) { return; } // Set this flag before running thread, otherwise thead may exist before you set this flag. m_IsRunning = true; m_pUdpServer.Start(); m_pTcpServer.Start(); } /// <summary> /// Stops listening incoming requests and responses. /// </summary> internal void Stop() { if (!m_IsRunning) { return; } m_IsRunning = false; m_pUdpServer.Stop(); m_pTcpServer.Stop(); } /// <summary> /// Is called when specified SIP flow has got new SIP message. /// </summary> /// <param name="flow">SIP flow.</param> /// <param name="message">Received message.</param> /// <exception cref="ArgumentNullException">Is raised when <b>flow</b> or <b>message</b> is null reference.</exception> internal void OnMessageReceived(SIP_Flow flow, byte[] message) { if (flow == null) { throw new ArgumentNullException("flow"); } if (message == null) { throw new ArgumentNullException("message"); } // TODO: Log try { #region Ping / pong // We have "ping"(CRLFCRLF) request, response with "pong". if (message.Length == 4) { if (Stack.Logger != null) { Stack.Logger.AddRead("", null, 2, "Flow [id='" + flow.ID + "'] received \"ping\"", flow.LocalEP, flow.RemoteEP); } // Send "pong". flow.SendInternal(new[] {(byte) '\r', (byte) '\n'}); if (Stack.Logger != null) { Stack.Logger.AddWrite("", null, 2, "Flow [id='" + flow.ID + "'] sent \"pong\"", flow.LocalEP, flow.RemoteEP); } return; } // We have pong(CRLF), do nothing. else if (message.Length == 2) { if (Stack.Logger != null) { Stack.Logger.AddRead("", null, 2, "Flow [id='" + flow.ID + "'] received \"pong\"", flow.LocalEP, flow.RemoteEP); } return; } #endregion #region Response if (Encoding.UTF8.GetString(message, 0, 3).ToUpper().StartsWith("SIP")) { #region Parse and validate response SIP_Response response = null; try { response = SIP_Response.Parse(message); } catch (Exception x) { if (m_pStack.Logger != null) { m_pStack.Logger.AddText("Skipping message, parse error: " + x); } return; } try { response.Validate(); } catch (Exception x) { if (m_pStack.Logger != null) { m_pStack.Logger.AddText("Response validation failed: " + x); } return; } #endregion /* RFC 3261 18.1.2 Receiving Responses. When a response is received, the client transport examines the top Via header field value. If the value of the "sent-by" parameter in that header field value does not correspond to a value that the client transport is configured to insert into requests, the response MUST be silently discarded. If there are any client transactions in existence, the client transport uses the matching procedures of Section 17.1.3 to attempt to match the response to an existing transaction. If there is a match, the response MUST be passed to that transaction. Otherwise, the response MUST be passed to the core (whether it be stateless proxy, stateful proxy, or UA) for further processing. Handling of these "stray" responses is dependent on the core (a proxy will forward them, while a UA will discard, for example). */ SIP_ClientTransaction transaction = m_pStack.TransactionLayer.MatchClientTransaction(response); // Allow client transaction to process response. if (transaction != null) { transaction.ProcessResponse(flow, response); } else { // Pass response to dialog. SIP_Dialog dialog = m_pStack.TransactionLayer.MatchDialog(response); if (dialog != null) { dialog.ProcessResponse(response); } // Pass response to core. else { m_pStack.OnResponseReceived(new SIP_ResponseReceivedEventArgs(m_pStack, null, response)); } } } #endregion #region Request // SIP request. else { #region Parse and validate request SIP_Request request = null; try { request = SIP_Request.Parse(message); } catch (Exception x) { // Log if (m_pStack.Logger != null) { m_pStack.Logger.AddText("Skipping message, parse error: " + x.Message); } return; } try { request.Validate(); } catch (Exception x) { if (m_pStack.Logger != null) { m_pStack.Logger.AddText("Request validation failed: " + x); } // Bad request, send error to request maker. SendResponse( m_pStack.CreateResponse(SIP_ResponseCodes.x400_Bad_Request + ". " + x.Message, request)); return; } #endregion // TODO: Is that needed, core can reject message as it would like. SIP_ValidateRequestEventArgs eArgs = m_pStack.OnValidateRequest(request, flow.RemoteEP); // Request rejected, return response. if (eArgs.ResponseCode != null) { SendResponse(m_pStack.CreateResponse(eArgs.ResponseCode, request)); return; } request.Flow = flow; request.LocalEndPoint = flow.LocalEP; request.RemoteEndPoint = flow.RemoteEP; /* RFC 3261 18.2.1. When the server transport receives a request over any transport, it MUST examine the value of the "sent-by" parameter in the top Via header field value. If the host portion of the "sent-by" parameter contains a domain name, or if it contains an IP address that differs from the packet source address, the server MUST add a "received" parameter to that Via header field value. This parameter MUST contain the source address from which the packet was received. This is to assist the server transport layer in sending the response, since it must be sent to the source IP address from which the request came. Next, the server transport attempts to match the request to a server transaction. It does so using the matching rules described in Section 17.2.3. If a matching server transaction is found, the request is passed to that transaction for processing. If no match is found, the request is passed to the core, which may decide to construct a new server transaction for that request. Note that when a UAS core sends a 2xx response to INVITE, the server transaction is destroyed. This means that when the ACK arrives, there will be no matching server transaction, and based on this rule, the ACK is passed to the UAS core, where it is processed. */ /* RFC 3581 4. When a server compliant to this specification (which can be a proxy or UAS) receives a request, it examines the topmost Via header field value. If this Via header field value contains an "rport" parameter with no value, it MUST set the value of the parameter to the source port of the request. This is analogous to the way in which a server will insert the "received" parameter into the topmost Via header field value. In fact, the server MUST insert a "received" parameter containing the source IP address that the request came from, even if it is identical to the value of the "sent-by" component. Note that this processing takes place independent of the transport protocol. */ SIP_t_ViaParm via = request.Via.GetTopMostValue(); via.Received = flow.RemoteEP.Address; if (via.RPort == 0) { via.RPort = flow.RemoteEP.Port; } bool processed = false; SIP_ServerTransaction transaction = m_pStack.TransactionLayer.MatchServerTransaction(request); // Pass request to matched server transaction. if (transaction != null) { transaction.ProcessRequest(flow, request); processed = true; } else { SIP_Dialog dialog = m_pStack.TransactionLayer.MatchDialog(request); // Pass request to dialog. if (dialog != null) { processed = dialog.ProcessRequest(new SIP_RequestReceivedEventArgs(m_pStack, flow, request)); } } // Request not proecced by dialog or transaction, pass request to TU. if (!processed) { // Log if (m_pStack.Logger != null) { byte[] requestData = request.ToByteData(); m_pStack.Logger.AddRead(Guid.NewGuid().ToString(), null, 0, "Request [method='" + request.RequestLine.Method + "'; cseq='" + request.CSeq.SequenceNumber + "'; " + "transport='" + flow.Transport + "'; size='" + requestData.Length + "'; " + "received '" + flow.RemoteEP + "' -> '" + flow.LocalEP + "'.", flow.LocalEP, flow.RemoteEP, requestData); } m_pStack.OnRequestReceived(new SIP_RequestReceivedEventArgs(m_pStack, flow, request)); } } #endregion } catch (SocketException s) { // Skip all socket errors here string dummy = s.Message; } //catch(ArgumentException x){ // m_pStack.OnError(x); //} catch (Exception x) { m_pStack.OnError(x); } } /// <summary> /// Sends request to the specified flow. /// </summary> /// <param name="flow">Data flow.</param> /// <param name="request">SIP request.</param> /// <param name="transaction">Owner client transaction or null if stateless sending.</param> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and and this method is accessed.</exception> /// <exception cref="ArgumentNullException">Is raised when <b>flow</b> or <b>request</b> is null reference.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments contains invalid value.</exception> internal void SendRequest(SIP_Flow flow, SIP_Request request, SIP_ClientTransaction transaction) { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (flow == null) { throw new ArgumentNullException("flow"); } if (request == null) { throw new ArgumentNullException("request"); } if (request.Via.GetTopMostValue() == null) { throw new ArgumentException("Argument 'request' doesn't contain required Via: header field."); } // Set sent-by SIP_t_ViaParm via = request.Via.GetTopMostValue(); via.ProtocolTransport = flow.Transport; // Via sent-by is used only to send responses when request maker data flow is not active. // Normally this never used, so just report first local listening point as sent-by. HostEndPoint sentBy = null; foreach (IPBindInfo bind in BindInfo) { if (flow.Transport == SIP_Transport.UDP && bind.Protocol == BindInfoProtocol.UDP) { if (!string.IsNullOrEmpty(bind.HostName)) { sentBy = new HostEndPoint(bind.HostName, bind.Port); } else { sentBy = new HostEndPoint(flow.LocalEP.Address.ToString(), bind.Port); } break; } else if (flow.Transport == SIP_Transport.TLS && bind.Protocol == BindInfoProtocol.TCP && bind.SslMode == SslMode.SSL) { if (!string.IsNullOrEmpty(bind.HostName)) { sentBy = new HostEndPoint(bind.HostName, bind.Port); } else { sentBy = new HostEndPoint(flow.LocalEP.Address.ToString(), bind.Port); } break; } else if (flow.Transport == SIP_Transport.TCP && bind.Protocol == BindInfoProtocol.TCP) { if (!string.IsNullOrEmpty(bind.HostName)) { sentBy = new HostEndPoint(bind.HostName, bind.Port); } else { sentBy = new HostEndPoint(flow.LocalEP.Address.ToString(), bind.Port); } break; } } // No local end point for sent-by, just use flow local end point for it. if (sentBy == null) { via.SentBy = new HostEndPoint(flow.LocalEP); } else { via.SentBy = sentBy; } // Send request. flow.Send(request); // Log. if (m_pStack.Logger != null) { byte[] requestData = request.ToByteData(); m_pStack.Logger.AddWrite(Guid.NewGuid().ToString(), null, 0, "Request [" + (transaction == null ? "" : "transactionID='" + transaction.ID + "';") + "method='" + request.RequestLine.Method + "'; cseq='" + request.CSeq.SequenceNumber + "'; " + "transport='" + flow.Transport + "'; size='" + requestData.Length + "'; sent '" + flow.LocalEP + "' -> '" + flow.RemoteEP + "'.", flow.LocalEP, flow.RemoteEP, requestData); } } /// <summary> /// Sends specified response back to request maker using RFC 3261 18. rules. /// </summary> /// <param name="transaction">SIP server transaction which response to send.</param> /// <param name="response">SIP response.</param> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and and this method is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when stack ahs not been started and this method is accessed.</exception> /// <exception cref="ArgumentNullException">Is raised when <b>transaction</b> or <b>response</b> is null reference.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> /// <exception cref="SIP_TransportException">Is raised when <b>response</b> sending has failed.</exception> internal void SendResponse(SIP_ServerTransaction transaction, SIP_Response response) { if (transaction == null) { throw new ArgumentNullException("transaction"); } // NOTE: all other paramter / state validations are done in SendResponseInternal. SendResponseInternal(transaction, response, null); } /// <summary> /// Resolves data flow local NATed IP end point to public IP end point. /// </summary> /// <param name="flow">Data flow.</param> /// <returns>Returns public IP end point of local NATed IP end point.</returns> /// <exception cref="ArgumentNullException">Is raised <b>flow</b> is null reference.</exception> internal IPEndPoint Resolve(SIP_Flow flow) { if (flow == null) { throw new ArgumentNullException("flow"); } IPEndPoint resolvedEP = null; AutoResetEvent completionWaiter = new AutoResetEvent(false); // Create OPTIONS request SIP_Request optionsRequest = m_pStack.CreateRequest(SIP_Methods.OPTIONS, new SIP_t_NameAddress("sip:<EMAIL>"), new SIP_t_NameAddress("sip:<EMAIL>")); SIP_ClientTransaction optionsTransaction = m_pStack.TransactionLayer.CreateClientTransaction( flow, optionsRequest, true); optionsTransaction.ResponseReceived += delegate(object s, SIP_ResponseReceivedEventArgs e) { SIP_t_ViaParm via = e.Response.Via.GetTopMostValue(); resolvedEP = new IPEndPoint( via.Received == null ? flow.LocalEP.Address : via.Received, via.RPort > 0 ? via.RPort : flow.LocalEP.Port); completionWaiter.Set(); }; optionsTransaction.StateChanged += delegate { if (optionsTransaction.State == SIP_TransactionState.Terminated) { completionWaiter.Set(); } }; optionsTransaction.Start(); // Wait OPTIONS request to complete. completionWaiter.WaitOne(); if (resolvedEP != null) { return resolvedEP; } else { return flow.LocalEP; } } /// <summary> /// Gets contact URI <b>host</b> parameter suitable to the specified flow. /// </summary> /// <param name="flow">Data flow.</param> /// <returns>Returns contact URI <b>host</b> parameter suitable to the specified flow.</returns> internal HostEndPoint GetContactHost(SIP_Flow flow) { if (flow == null) { throw new ArgumentNullException("flow"); } HostEndPoint retVal = null; // Find suitable listening point for flow. foreach (IPBindInfo bind in BindInfo) { if (bind.Protocol == BindInfoProtocol.UDP && flow.Transport == SIP_Transport.UDP) { // For UDP flow localEP is also listeining EP, so use it. if (bind.IP.AddressFamily == flow.LocalEP.AddressFamily && bind.Port == flow.LocalEP.Port) { retVal = new HostEndPoint( (string.IsNullOrEmpty(bind.HostName) ? flow.LocalEP.Address.ToString() : bind.HostName), bind.Port); break; } } else if (bind.Protocol == BindInfoProtocol.TCP && bind.SslMode == SslMode.SSL && flow.Transport == SIP_Transport.TLS) { // Just use first matching listening point. // TODO: Probably we should imporve it with load-balanched local end point. if (bind.IP.AddressFamily == flow.LocalEP.AddressFamily) { if (bind.IP == IPAddress.Any || bind.IP == IPAddress.IPv6Any) { retVal = new HostEndPoint( (string.IsNullOrEmpty(bind.HostName) ? flow.LocalEP.Address.ToString() : bind.HostName), bind.Port); } else { retVal = new HostEndPoint( (string.IsNullOrEmpty(bind.HostName) ? bind.IP.ToString() : bind.HostName), bind.Port); } break; } } else if (bind.Protocol == BindInfoProtocol.TCP && flow.Transport == SIP_Transport.TCP) { // Just use first matching listening point. // TODO: Probably we should imporve it with load-balanched local end point. if (bind.IP.AddressFamily == flow.LocalEP.AddressFamily) { if (bind.IP.Equals(IPAddress.Any) || bind.IP.Equals(IPAddress.IPv6Any)) { retVal = new HostEndPoint( (string.IsNullOrEmpty(bind.HostName) ? flow.LocalEP.Address.ToString() : bind.HostName), bind.Port); } else { retVal = new HostEndPoint( (string.IsNullOrEmpty(bind.HostName) ? bind.IP.ToString() : bind.HostName), bind.Port); } break; } } } // We don't have suitable listening point for active flow. // RFC 3261 forces to have, but for TCP based protocls + NAT, server can't connect to use anyway, // so just ignore it and report flow local EP. if (retVal == null) { retVal = new HostEndPoint(flow.LocalEP); } // If flow remoteEP is public IP and our localEP is private IP, resolve localEP to public. if (retVal.IsIPAddress && Core.IsPrivateIP(IPAddress.Parse(retVal.Host)) && !Core.IsPrivateIP(flow.RemoteEP.Address)) { retVal = new HostEndPoint(Resolve(flow)); } return retVal; } /// <summary> /// Gets Record-Route for the specified transport. /// </summary> /// <param name="transport">SIP transport.</param> /// <returns>Returns Record-Route ro or null if no record route possible.</returns> internal string GetRecordRoute(string transport) { foreach (IPBindInfo bind in m_pBinds) { if (!string.IsNullOrEmpty(bind.HostName)) { if (bind.Protocol == BindInfoProtocol.TCP && bind.SslMode != SslMode.None && transport == SIP_Transport.TLS) { return "<sips:" + bind.HostName + ":" + bind.Port + ";lr>"; } else if (bind.Protocol == BindInfoProtocol.TCP && transport == SIP_Transport.TCP) { return "<sip:" + bind.HostName + ":" + bind.Port + ";lr>"; } else if (bind.Protocol == BindInfoProtocol.UDP && transport == SIP_Transport.UDP) { return "<sip:" + bind.HostName + ":" + bind.Port + ";lr>"; } } } return null; } #endregion #region Utility methods /// <summary> /// This method is called when new SIP UDP packet has received. /// </summary> /// <param name="e">Event data.</param> private void m_pUdpServer_PacketReceived(UDP_PacketEventArgs e) { try { SIP_Flow flow = m_pFlowManager.GetOrCreateFlow(true, e.LocalEndPoint, e.RemoteEndPoint, SIP_Transport.UDP); flow.OnUdpPacketReceived(e); } catch (Exception x) { m_pStack.OnError(x); } } /// <summary> /// This method is called when UDP server unknown error. /// </summary> /// <param name="sender">Sender.</param> /// <param name="e">Event data.</param> private void m_pUdpServer_Error(object sender, Error_EventArgs e) { m_pStack.OnError(e.Exception); } /// <summary> /// This method is called when SIP stack has got new incoming connection. /// </summary> /// <param name="sender">Sender.</param> /// <param name="e">Event data.</param> private void m_pTcpServer_SessionCreated(object sender, TCP_ServerSessionEventArgs<TCP_ServerSession> e) { m_pFlowManager.CreateFromSession(e.Session); } /// <summary> /// Sends response to request maker using RFC 3261 18. rules. /// </summary> /// <param name="transaction">Owner server transaction. Can be null if stateless response sending.</param> /// <param name="response">SIP response to send.</param> /// <param name="localEP">Local IP end point to use for sending resposne. Value null means system will allocate it.</param> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and and this method is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when stack ahs not been started and this method is accessed.</exception> /// <exception cref="ArgumentNullException">Is raised when <b>response</b> is null reference.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> /// <exception cref="SIP_TransportException">Is raised when <b>response</b> sending has failed.</exception> private void SendResponseInternal(SIP_ServerTransaction transaction, SIP_Response response, IPEndPoint localEP) { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (!m_IsRunning) { throw new InvalidOperationException("Stack has not been started."); } if (response == null) { throw new ArgumentNullException("response"); } /* RFC 3261 18.2.2. The server transport uses the value of the top Via header field in order to determine where to send a response. It MUST follow the following process: o If the "sent-protocol" is a reliable transport protocol such as TCP or SCTP, or TLS over those, the response MUST be sent using the existing connection to the source of the original request that created the transaction, if that connection is still open. This requires the server transport to maintain an association between server transactions and transport connections. If that connection is no longer open, the server SHOULD open a connection to the IP address in the "received" parameter, if present, using the port in the "sent-by" value, or the default port for that transport, if no port is specified. If that connection attempt fails, the server SHOULD use the procedures in [4] for servers in order to determine the IP address and port to open the connection and send the response to. o Otherwise, if the Via header field value contains a "maddr" parameter, the response MUST be forwarded to the address listed there, using the port indicated in "sent-by", or port 5060 if none is present. If the address is a multicast address, the response SHOULD be sent using the TTL indicated in the "ttl" parameter, or with a TTL of 1 if that parameter is not present. o Otherwise (for unreliable unicast transports), if the top Via has a "received" parameter, the response MUST be sent to the address in the "received" parameter, using the port indicated in the "sent-by" value, or using port 5060 if none is specified explicitly. If this fails, for example, elicits an ICMP "port unreachable" response, the procedures of Section 5 of [4] SHOULD be used to determine where to send the response. o Otherwise, if it is not receiver-tagged, the response MUST be sent to the address indicated by the "sent-by" value, using the procedures in Section 5 of [4]. */ /* RFC 3581 4. (Adds new processing between RFC 3261 18.2.2. bullet 2 and 3) When a server attempts to send a response, it examines the topmost Via header field value of that response. If the "sent-protocol" component indicates an unreliable unicast transport protocol, such as UDP, and there is no "maddr" parameter, but there is both a "received" parameter and an "rport" parameter, the response MUST be sent to the IP address listed in the "received" parameter, and the port in the "rport" parameter. The response MUST be sent from the same address and port that the corresponding request was received on. This effectively adds a new processing step between bullets two and three in Section 18.2.2 of SIP [1]. The response must be sent from the same address and port that the request was received on in order to traverse symmetric NATs. When a server is listening for requests on multiple ports or interfaces, it will need to remember the one on which the request was received. For a stateful proxy, storing this information for the duration of the transaction is not an issue. However, a stateless proxy does not store state between a request and its response, and therefore cannot remember the address and port on which a request was received. To properly implement this specification, a stateless proxy can encode the destination address and port of a request into the Via header field value that it inserts. When the response arrives, it can extract this information and use it to forward the response. */ SIP_t_ViaParm via = response.Via.GetTopMostValue(); if (via == null) { throw new ArgumentException("Argument 'response' does not contain required Via: header field."); } // TODO: If transport is not supported. //throw new SIP_TransportException("Not supported transport '" + via.ProtocolTransport + "'."); string logID = Guid.NewGuid().ToString(); string transactionID = transaction == null ? "" : transaction.ID; // Try to get local IP end point which we should use to send response back. if (transaction != null && transaction.Request.LocalEndPoint != null) { localEP = transaction.Request.LocalEndPoint; } // TODO: no "localEP" at moment // TODO: Stateless should use flowID instead. // Our stateless proxy add 'localEP' parameter to Via: if so normally we can get it from there. else if (via.Parameters["localEP"] != null) { localEP = Net_Utils.ParseIPEndPoint(via.Parameters["localEP"].Value); } byte[] responseData = response.ToByteData(); #region Try existing flow first /* First try active flow to send response, thats not 100% as RFC says, but works better in any case. RFC says that for TCP and TLS only, we do it for any transport. */ if (transaction != null) { try { SIP_Flow flow = transaction.Flow; flow.Send(response); if (m_pStack.Logger != null) { m_pStack.Logger.AddWrite(logID, null, 0, "Response [flowReuse=true; transactionID='" + transactionID + "'; method='" + response.CSeq.RequestMethod + "'; cseq='" + response.CSeq.SequenceNumber + "'; " + "transport='" + flow.Transport + "'; size='" + responseData.Length + "'; statusCode='" + response.StatusCode + "'; " + "reason='" + response.ReasonPhrase + "'; sent '" + flow.LocalEP + "' -> '" + flow.RemoteEP + "'.", localEP, flow.RemoteEP, responseData); } return; } catch { // Do nothing, processing will continue. } } #endregion #region Reliable TCP,TLS, ... if (SIP_Utils.IsReliableTransport(via.ProtocolTransport)) { // Get original request remote end point. IPEndPoint remoteEP = null; if (transaction != null && transaction.Request.RemoteEndPoint != null) { remoteEP = transaction.Request.RemoteEndPoint; } else if (via.Received != null) { remoteEP = new IPEndPoint(via.Received, via.SentBy.Port == -1 ? 5060 : via.SentBy.Port); } #region If original request connection alive, use it try { SIP_Flow flow = null; // Statefull if (transaction != null) { if (transaction.Request.Flow != null && !transaction.Request.Flow.IsDisposed) { flow = transaction.Request.Flow; } } // Stateless else { string flowID = via.Parameters["connectionID"].Value; if (flowID != null) { flow = m_pFlowManager[flowID]; } } if (flow != null) { flow.Send(response); if (m_pStack.Logger != null) { m_pStack.Logger.AddWrite(logID, null, 0, "Response [flowReuse=true; transactionID='" + transactionID + "'; method='" + response.CSeq.RequestMethod + "'; cseq='" + response.CSeq.SequenceNumber + "'; " + "transport='" + flow.Transport + "'; size='" + responseData.Length + "'; statusCode='" + response.StatusCode + "'; " + "reason='" + response.ReasonPhrase + "'; sent '" + flow.RemoteEP + "' -> '" + flow.LocalEP + "'.", localEP, remoteEP, responseData); } return; } } catch { // Do nothing, processing will continue. // Override RFC, if there is any existing connection and it gives error, try always RFC 3261 18.2.2(recieved) and 3265 5. } #endregion #region Send RFC 3261 18.2.2(recieved) if (remoteEP != null) { try { SendResponseToHost(logID, transactionID, null, remoteEP.Address.ToString(), remoteEP.Port, via.ProtocolTransport, response); } catch { // Do nothing, processing will continue -> "RFC 3265 5.". } } #endregion #region Send RFC 3265 5. SendResponse_RFC_3263_5(logID, transactionID, localEP, response); #endregion } #endregion #region UDP Via: maddr parameter else if (via.Maddr != null) { throw new SIP_TransportException( "Sending responses to multicast address(Via: 'maddr') is not supported."); } #endregion #region RFC 3581 4. UDP Via: received and rport parameters else if (via.Maddr == null && via.Received != null && via.RPort > 0) { SendResponseToHost(logID, transactionID, localEP, via.Received.ToString(), via.RPort, via.ProtocolTransport, response); } #endregion #region UDP Via: received parameter else if (via.Received != null) { SendResponseToHost(logID, transactionID, localEP, via.Received.ToString(), via.SentByPortWithDefault, via.ProtocolTransport, response); } #endregion #region UDP else { SendResponse_RFC_3263_5(logID, transactionID, localEP, response); } #endregion } /// <summary> /// Sends specified response back to request maker using RFC 3263 5. rules. /// </summary> /// <param name="logID">Log ID.</param> /// <param name="transactionID">Transaction ID. If null, then stateless response sending.</param> /// <param name="localEP">UDP local end point to use for sending. If null, system will use default.</param> /// <param name="response">SIP response.</param> /// <exception cref="SIP_TransportException">Is raised when <b>response</b> sending has failed.</exception> private void SendResponse_RFC_3263_5(string logID, string transactionID, IPEndPoint localEP, SIP_Response response) { /* RFC 3263 5. RFC 3261 [1] defines procedures for sending responses from a server back to the client. Typically, for unicast UDP requests, the response is sent back to the source IP address where the request came from, using the port contained in the Via header. For reliable transport protocols, the response is sent over the connection the request arrived on. However, it is important to provide failover support when the client element fails between sending the request and receiving the response. A server, according to RFC 3261 [1], will send a response on the connection it arrived on (in the case of reliable transport protocols), and for unreliable transport protocols, to the source address of the request, and the port in the Via header field. The procedures here are invoked when a server attempts to send to that location and that response fails (the specific conditions are detailed in RFC 3261). "Fails" is defined as any closure of the transport connection the request came in on before the response can be sent, or communication of a fatal error from the transport layer. In these cases, the server examines the value of the sent-by construction in the topmost Via header. If it contains a numeric IP address, the server attempts to send the response to that address, using the transport protocol from the Via header, and the port from sent-by, if present, else the default for that transport protocol. The transport protocol in the Via header can indicate "TLS", which refers to TLS over TCP. When this value is present, the server MUST use TLS over TCP to send the response. If, however, the sent-by field contained a domain name and a port number, the server queries for A or AAAA records with that name. It tries to send the response to each element on the resulting list of IP addresses, using the port from the Via, and the transport protocol from the Via (again, a value of TLS refers to TLS over TCP). As in the client processing, the next entry in the list is tried if the one before it results in a failure. If, however, the sent-by field contained a domain name and no port, the server queries for SRV records at that domain name using the service identifier "_sips" if the Via transport is "TLS", "_sip" otherwise, and the transport from the topmost Via header ("TLS" implies that the transport protocol in the SRV query is TCP). The resulting list is sorted as described in [2], and the response is sent to the topmost element on the new list described there. If that results in a failure, the next entry on the list is tried. */ SIP_t_ViaParm via = response.Via.GetTopMostValue(); #region Sent-By is IP address if (via.SentBy.IsIPAddress) { SendResponseToHost(logID, transactionID, localEP, via.SentBy.Host, via.SentByPortWithDefault, via.ProtocolTransport, response); } #endregion #region Sent-By is host name with port number else if (via.SentBy.Port != -1) { SendResponseToHost(logID, transactionID, localEP, via.SentBy.Host, via.SentByPortWithDefault, via.ProtocolTransport, response); } #endregion #region Sent-By is just host name else { try { // Query SRV records. string srvQuery = ""; if (via.ProtocolTransport == SIP_Transport.UDP) { srvQuery = "_sip._udp." + via.SentBy.Host; } else if (via.ProtocolTransport == SIP_Transport.TCP) { srvQuery = "_sip._tcp." + via.SentBy.Host; } else if (via.ProtocolTransport == SIP_Transport.UDP) { srvQuery = "_sips._tcp." + via.SentBy.Host; } DnsServerResponse dnsResponse = m_pStack.Dns.Query(srvQuery, QTYPE.SRV); if (dnsResponse.ResponseCode != RCODE.NO_ERROR) { throw new SIP_TransportException("Dns error: " + dnsResponse.ResponseCode); } DNS_rr_SRV[] srvRecords = dnsResponse.GetSRVRecords(); // Use SRV records. if (srvRecords.Length > 0) { for (int i = 0; i < srvRecords.Length; i++) { DNS_rr_SRV srv = srvRecords[i]; try { if (m_pStack.Logger != null) { m_pStack.Logger.AddText(logID, "Starts sending response to DNS SRV record '" + srv.Target + "'."); } SendResponseToHost(logID, transactionID, localEP, srv.Target, srv.Port, via.ProtocolTransport, response); } catch { // Generate error, all SRV records has failed. if (i == (srvRecords.Length - 1)) { if (m_pStack.Logger != null) { m_pStack.Logger.AddText(logID, "Failed to send response to DNS SRV record '" + srv.Target + "'."); } throw new SIP_TransportException("Host '" + via.SentBy.Host + "' is not accessible."); } // For loop will try next SRV record. else { if (m_pStack.Logger != null) { m_pStack.Logger.AddText(logID, "Failed to send response to DNS SRV record '" + srv.Target + "', will try next."); } } } } } // If no SRV, use A and AAAA records. (Thats not in 3263 5., but we need to todo it so.) else { if (m_pStack.Logger != null) { m_pStack.Logger.AddText(logID, "No DNS SRV records found, starts sending to Via: sent-by host '" + via.SentBy.Host + "'."); } SendResponseToHost(logID, transactionID, localEP, via.SentBy.Host, via.SentByPortWithDefault, via.ProtocolTransport, response); } } catch (DNS_ClientException dnsX) { throw new SIP_TransportException("Dns error: " + dnsX.ErrorCode); } } #endregion } /// <summary> /// Sends response to the specified host. /// </summary> /// <param name="logID">Log ID.</param> /// <param name="transactionID">Transaction ID. If null, then stateless response sending.</param> /// <param name="localEP">UDP local end point to use for sending. If null, system will use default.</param> /// <param name="host">Host name or IP address where to send response.</param> /// <param name="port">Target host port.</param> /// <param name="transport">SIP transport to use.</param> /// <param name="response">SIP response to send.</param> private void SendResponseToHost(string logID, string transactionID, IPEndPoint localEP, string host, int port, string transport, SIP_Response response) { try { IPAddress[] targets = null; if (Net_Utils.IsIPAddress(host)) { targets = new[] {IPAddress.Parse(host)}; } else { targets = m_pStack.Dns.GetHostAddresses(host); if (targets.Length == 0) { throw new SIP_TransportException("Invalid Via: Sent-By host name '" + host + "' could not be resolved."); } } byte[] responseData = response.ToByteData(); for (int i = 0; i < targets.Length; i++) { IPEndPoint remoteEP = new IPEndPoint(targets[i], port); try { SIP_Flow flow = GetOrCreateFlow(transport, localEP, remoteEP); flow.Send(response); // localEP = flow.LocalEP; if (m_pStack.Logger != null) { m_pStack.Logger.AddWrite(logID, null, 0, "Response [transactionID='" + transactionID + "'; method='" + response.CSeq.RequestMethod + "'; cseq='" + response.CSeq.SequenceNumber + "'; " + "transport='" + transport + "'; size='" + responseData.Length + "'; statusCode='" + response.StatusCode + "'; " + "reason='" + response.ReasonPhrase + "'; sent '" + localEP + "' -> '" + remoteEP + "'.", localEP, remoteEP, responseData); } // If we reach so far, send succeeded. return; } catch { // Generate error, all IP addresses has failed. if (i == (targets.Length - 1)) { if (m_pStack.Logger != null) { m_pStack.Logger.AddText(logID, "Failed to send response to host '" + host + "' IP end point '" + remoteEP + "'."); } throw new SIP_TransportException("Host '" + host + ":" + port + "' is not accessible."); } // For loop will try next IP address. else { if (m_pStack.Logger != null) { m_pStack.Logger.AddText(logID, "Failed to send response to host '" + host + "' IP end point '" + remoteEP + "', will try next A record."); } } } } } catch (DNS_ClientException dnsX) { throw new SIP_TransportException("Dns error: " + dnsX.ErrorCode); } } #endregion #region Nested type: SIP_FlowManager /// <summary> /// Implements SIP flow manager. /// </summary> private class SIP_FlowManager : IDisposable { #region Members private readonly object m_pLock = new object(); private int m_IdelTimeout = 60*5; private bool m_IsDisposed; private Dictionary<string, SIP_Flow> m_pFlows; private SIP_TransportLayer m_pOwner; private TimerEx m_pTimeoutTimer; #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="owner">Owner transport layer.</param> /// <exception cref="ArgumentNullException">Is raised when <b>owner</b> is null reference.</exception> internal SIP_FlowManager(SIP_TransportLayer owner) { if (owner == null) { throw new ArgumentNullException("owner"); } m_pOwner = owner; m_pFlows = new Dictionary<string, SIP_Flow>(); m_pTimeoutTimer = new TimerEx(15000); m_pTimeoutTimer.AutoReset = true; m_pTimeoutTimer.Elapsed += m_pTimeoutTimer_Elapsed; m_pTimeoutTimer.Enabled = true; } #endregion #region Properties /// <summary> /// Gets number of flows in the collection. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> public int Count { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_pFlows.Count; } } /// <summary> /// Gets active flows. /// </summary> public SIP_Flow[] Flows { get { lock (m_pLock) { SIP_Flow[] retVal = new SIP_Flow[m_pFlows.Count]; m_pFlows.Values.CopyTo(retVal, 0); return retVal; } } } /// <summary> /// Gets if this object is disposed. /// </summary> public bool IsDisposed { get { return m_IsDisposed; } } /// <summary> /// Gets a flow with the specified flow ID. /// </summary> /// <param name="flowID">SIP flow ID.</param> /// <returns>Returns flow with the specified flow ID or null if not found.</returns> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> /// <exception cref="ArgumentNullException">Is raised when <b>flowID</b> is null reference value.</exception> public SIP_Flow this[string flowID] { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (flowID == null) { throw new ArgumentNullException("flowID"); } if (m_pFlows.ContainsKey(flowID)) { return m_pFlows[flowID]; } else { return null; } } } /// <summary> /// Gets owner transpoprt layer. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> internal SIP_TransportLayer TransportLayer { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_pOwner; } } #endregion #region Methods /// <summary> /// Cleans up any resources being used. /// </summary> public void Dispose() { lock (m_pLock) { if (m_IsDisposed) { return; } m_IsDisposed = true; foreach (SIP_Flow flow in Flows) { flow.Dispose(); } m_pOwner = null; m_pFlows = null; m_pTimeoutTimer.Dispose(); m_pTimeoutTimer = null; } } /// <summary> /// Returns specified flow or null if no such flow. /// </summary> /// <param name="flowID">Data flow ID.</param> /// <returns>Returns specified flow or null if no such flow.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>flowID</b> is null reference.</exception> public SIP_Flow GetFlow(string flowID) { if (flowID == null) { throw new ArgumentNullException("flowID"); } lock (m_pFlows) { SIP_Flow retVal = null; m_pFlows.TryGetValue(flowID, out retVal); return retVal; } } #endregion #region Internal methods /// <summary> /// Returns existing flow if exists, otherwise new created flow. /// </summary> /// <param name="isServer">Specifies if created flow is server or client flow. This has effect only if flow is created.</param> /// <param name="localEP">Local end point.</param> /// <param name="remoteEP">Remote end point.</param> /// <param name="transport">SIP transport.</param> /// <returns>Returns existing flow if exists, otherwise new created flow.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>localEP</b>,<b>remoteEP</b> or <b>transport</b> is null reference.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> internal SIP_Flow GetOrCreateFlow(bool isServer, IPEndPoint localEP, IPEndPoint remoteEP, string transport) { if (localEP == null) { throw new ArgumentNullException("localEP"); } if (remoteEP == null) { throw new ArgumentNullException("remoteEP"); } if (transport == null) { throw new ArgumentNullException("transport"); } string flowID = localEP + "-" + remoteEP + "-" + transport; lock (m_pLock) { SIP_Flow flow = null; if (m_pFlows.TryGetValue(flowID, out flow)) { return flow; } else { flow = new SIP_Flow(m_pOwner.Stack, isServer, localEP, remoteEP, transport); m_pFlows.Add(flow.ID, flow); flow.IsDisposing += delegate { lock (m_pLock) { m_pFlows.Remove(flowID); } }; flow.Start(); return flow; } } } /// <summary> /// Creates new flow from TCP server session. /// </summary> /// <param name="session">TCP server session.</param> /// <returns>Returns created flow.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>session</b> is null reference.</exception> internal SIP_Flow CreateFromSession(TCP_ServerSession session) { if (session == null) { throw new ArgumentNullException("session"); } string flowID = session.LocalEndPoint + "-" + session.RemoteEndPoint + "-" + (session.IsSecureConnection ? SIP_Transport.TLS : SIP_Transport.TCP); lock (m_pLock) { SIP_Flow flow = new SIP_Flow(m_pOwner.Stack, session); m_pFlows.Add(flowID, flow); flow.IsDisposing += delegate { lock (m_pLock) { m_pFlows.Remove(flowID); } }; flow.Start(); return flow; } } #endregion #region Utility methods private void m_pTimeoutTimer_Elapsed(object sender, ElapsedEventArgs e) { lock (m_pLock) { if (m_IsDisposed) { return; } foreach (SIP_Flow flow in Flows) { try { if (flow.LastActivity.AddSeconds(m_IdelTimeout) < DateTime.Now) { flow.Dispose(); } } catch (ObjectDisposedException x) { string dummy = x.Message; } } } } #endregion } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/STUN/Message/STUN_MessageType.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.STUN.Message { /// <summary> /// This enum specifies STUN message type. /// </summary> public enum STUN_MessageType { /// <summary> /// STUN message is binding request. /// </summary> BindingRequest = 0x0001, /// <summary> /// STUN message is binding request response. /// </summary> BindingResponse = 0x0101, /// <summary> /// STUN message is binding requesr error response. /// </summary> BindingErrorResponse = 0x0111, /// <summary> /// STUN message is "shared secret" request. /// </summary> SharedSecretRequest = 0x0002, /// <summary> /// STUN message is "shared secret" request response. /// </summary> SharedSecretResponse = 0x0102, /// <summary> /// STUN message is "shared secret" request error response. /// </summary> SharedSecretErrorResponse = 0x0112, } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/IMAP/Client/IMAP_NamespacesInfo.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.IMAP.Client { #region usings using System.Collections.Generic; #endregion /// <summary> /// IMAP namespaces info. Defined in RFC 2342. /// </summary> public class IMAP_NamespacesInfo { #region Members private readonly IMAP_Namespace[] m_pOtherUsersNamespaces; private readonly IMAP_Namespace[] m_pPersonalNamespaces; private readonly IMAP_Namespace[] m_pSharedNamespaces; #endregion #region Properties /// <summary> /// Gets IMAP server "Personal Namespaces". Returns null if namespace not defined. /// </summary> public IMAP_Namespace[] PersonalNamespaces { get { return m_pPersonalNamespaces; } } /// <summary> /// Gets IMAP server "Other Users Namespaces". Returns null if namespace not defined. /// </summary> public IMAP_Namespace[] OtherUsersNamespaces { get { return m_pOtherUsersNamespaces; } } /// <summary> /// Gets IMAP server "Shared Namespaces". Returns null if namespace not defined. /// </summary> public IMAP_Namespace[] SharedNamespaces { get { return m_pSharedNamespaces; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="personalNamespaces">IMAP server "Personal Namespaces".</param> /// <param name="otherUsersNamespaces">IMAP server "Other Users Namespaces".</param> /// <param name="sharedNamespaces">IMAP server "Shared Namespaces".</param> public IMAP_NamespacesInfo(IMAP_Namespace[] personalNamespaces, IMAP_Namespace[] otherUsersNamespaces, IMAP_Namespace[] sharedNamespaces) { m_pPersonalNamespaces = personalNamespaces; m_pOtherUsersNamespaces = otherUsersNamespaces; m_pSharedNamespaces = sharedNamespaces; } #endregion #region Utility methods private static IMAP_Namespace[] ParseNamespaces(string val) { StringReader r = new StringReader(val); r.ReadToFirstChar(); List<IMAP_Namespace> namespaces = new List<IMAP_Namespace>(); while (r.StartsWith("(")) { namespaces.Add(ParseNamespace(r.ReadParenthesized())); } return namespaces.ToArray(); } private static IMAP_Namespace ParseNamespace(string val) { string[] parts = TextUtils.SplitQuotedString(val, ' ', true); string name = ""; if (parts.Length > 0) { name = parts[0]; } string delimiter = ""; if (parts.Length > 1) { delimiter = parts[1]; } // Remove delimiter from end, if it's there. if (name.EndsWith(delimiter)) { name = name.Substring(0, name.Length - delimiter.Length); } return new IMAP_Namespace(name, delimiter); } #endregion #region Internal methods /// <summary> /// Parses namespace info from IMAP NAMESPACE response string. /// </summary> /// <param name="namespaceString">IMAP NAMESPACE response string.</param> /// <returns></returns> internal static IMAP_NamespacesInfo Parse(string namespaceString) { StringReader r = new StringReader(namespaceString); // Skip NAMESPACE r.ReadWord(); IMAP_Namespace[] personalNamespaces = null; IMAP_Namespace[] otherUsersNamespaces = null; IMAP_Namespace[] sharedNamespaces = null; // Personal namespace r.ReadToFirstChar(); if (r.StartsWith("(")) { personalNamespaces = ParseNamespaces(r.ReadParenthesized()); } // NIL, skip it. else { r.ReadWord(); } // Users Shared namespace r.ReadToFirstChar(); if (r.StartsWith("(")) { otherUsersNamespaces = ParseNamespaces(r.ReadParenthesized()); } // NIL, skip it. else { r.ReadWord(); } // Shared namespace r.ReadToFirstChar(); if (r.StartsWith("(")) { sharedNamespaces = ParseNamespaces(r.ReadParenthesized()); } // NIL, skip it. else { r.ReadWord(); } return new IMAP_NamespacesInfo(personalNamespaces, otherUsersNamespaces, sharedNamespaces); } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/SMTP/Server/old/SmtpServerReply.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; namespace LumiSoft.Net.SMTP.Server { /// <summary> /// SMTP server reply info. This class specifies smtp reply what is returned to connected client. /// </summary> public class SmtpServerReply { private bool m_ErrorReply = false; private int m_SmtpReplyCode = -1; private string m_ReplyText = ""; /// <summary> /// Default consttuctor. /// </summary> public SmtpServerReply() { } #region method ToSmtpReply internal string ToSmtpReply(string defaultSmtpRelyCode,string defaultReplyText) { string replyText = ""; if(this.SmtpReplyCode == -1){ replyText = defaultSmtpRelyCode + " "; } else{ replyText = this.SmtpReplyCode.ToString() + " "; } if(this.ReplyText == ""){ replyText += defaultReplyText; } else{ replyText += this.ReplyText; } return replyText; } #endregion #region Properties Implementation /// <summary> /// Gets or sets if CustomReply is error or ok reply. /// </summary> public bool ErrorReply { get{ return m_ErrorReply; } set{ m_ErrorReply = value; } } /// <summary> /// Gets or sets SMTP reply code (250,500,500, ...). Value -1 means that SMTP reply code isn't specified and server uses it's defult error code. /// </summary> public int SmtpReplyCode { get{ return m_SmtpReplyCode; } set{ m_SmtpReplyCode = value; } } /// <summary> /// Gets or sets reply text what is shown to connected client. /// Note: Maximum lenth of reply text is 500 chars and text can contain only ASCII chars /// without CR or LF. /// </summary> public string ReplyText { get{ return m_ReplyText; } set{ if(!Core.IsAscii(value)){ throw new Exception("Reply text can contian only ASCII chars !"); } if(value.Length > 500){ value = value.Substring(0,500); } value = value.Replace("\r","").Replace("\n",""); m_ReplyText = value; } } #endregion } } <file_sep>/web/studio/ASC.Web.Studio/HttpHandlers/FCKEditorFileUploadHandler.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System.Text.RegularExpressions; using ASC.Common.Web; using ASC.Data.Storage; using ASC.Web.Core.Files; using ASC.Web.Studio.Core; using ASC.Web.Studio.Utility; using System; using System.Web; using Resources; namespace ASC.Web.Studio.HttpHandlers { public class FCKEditorFileUploadHandler : AbstractHttpAsyncHandler { public override void OnProcessRequest(HttpContext context) { if (string.IsNullOrEmpty(context.Request["newEditor"])) { OldProcessRequest(context); } else { NewProcessRequest(context); } } private static void OldProcessRequest(HttpContext context) { try { var storeDomain = context.Request["esid"]; var itemID = context.Request["iid"] ?? ""; var file = context.Request.Files["NewFile"]; if (file.ContentLength > SetupInfo.MaxImageUploadSize) { OldSendFileUploadResponse(context, 1, true, string.Empty, string.Empty, FileSizeComment.FileImageSizeExceptionString); return; } var filename = file.FileName.Replace("%", string.Empty); var ind = file.FileName.LastIndexOf("\\"); if (ind >= 0) { filename = file.FileName.Substring(ind + 1); } if (FileUtility.GetFileTypeByFileName(filename) != FileType.Image) { OldSendFileUploadResponse(context, 1, true, string.Empty, filename, Resource.ErrorUnknownFileImageType); return; } var folderID = CommonControlsConfigurer.FCKAddTempUploads(storeDomain, filename, itemID); var store = StorageFactory.GetStorage(TenantProvider.CurrentTenantID.ToString(), "fckuploaders"); var saveUri = store.Save(storeDomain, folderID + "/" + filename, file.InputStream).ToString(); OldSendFileUploadResponse(context, 0, true, saveUri, filename, string.Empty); } catch (Exception e) { OldSendFileUploadResponse(context, 1, true, string.Empty, string.Empty, e.Message.HtmlEncode()); } } private static void NewProcessRequest(HttpContext context) { try { var funcNum = context.Request["CKEditorFuncNum"]; var storeDomain = context.Request["esid"]; var itemID = context.Request["iid"] ?? ""; var file = context.Request.Files["upload"]; if (file.ContentLength > SetupInfo.MaxImageUploadSize) { NewSendFileUploadResponse(context, string.Empty, funcNum, FileSizeComment.FileImageSizeExceptionString); return; } var filename = file.FileName; var ind = filename.LastIndexOf("\\", StringComparison.Ordinal); if (ind >= 0) { filename = filename.Substring(ind + 1); } filename = new Regex("[\t*\\+:\"<>#%&?|\\\\/]").Replace(filename, "_"); if (FileUtility.GetFileTypeByFileName(filename) != FileType.Image) { NewSendFileUploadResponse(context, string.Empty, funcNum, Resource.ErrorUnknownFileImageType); return; } var folderID = CommonControlsConfigurer.FCKAddTempUploads(storeDomain, filename, itemID); var store = StorageFactory.GetStorage(TenantProvider.CurrentTenantID.ToString(), "fckuploaders"); var saveUri = store.Save(storeDomain, folderID + "/" + filename, file.InputStream).ToString(); NewSendFileUploadResponse(context, saveUri, funcNum, string.Empty); } catch (Exception e) { NewSendFileUploadResponse(context, string.Empty, string.Empty, e.Message.HtmlEncode()); } } private static void OldSendFileUploadResponse(HttpContext context, int errorNumber, bool isQuickUpload, string fileUrl, string fileName, string customMsg) { context.Response.Clear(); context.Response.Write("<script type=\"text/javascript\">"); // Minified version of the document.domain automatic fix script. // The original script can be found at _dev/domain_fix_template.js context.Response.Write(@"(function(){var d=document.domain; while (true){try{var A=window.top.opener.document.domain;break;}catch(e) {};d=d.replace(/.*?(?:\.|$)/g,'');if (d.length==0) break;try{document.domain=d;}catch (e){break;}}})();"); if (!string.IsNullOrEmpty(fileUrl)) { fileUrl = HttpUtility.UrlPathEncode(fileUrl).Replace("'", "\\'"); } if (!string.IsNullOrEmpty(fileName)) { fileName = HttpUtility.UrlEncode(fileName); } if (isQuickUpload) context.Response.Write("window.parent.OnUploadCompleted(" + errorNumber + ",'" + fileUrl.Replace("'", "\\'") + "','" + fileName.Replace("'", "\\'") + "','" + customMsg.Replace("'", "\\'") + "') ;"); else context.Response.Write("window.parent.frames['frmUpload'].OnUploadCompleted(" + errorNumber + ",'" + fileName.Replace("'", "\\'") + "') ;"); context.Response.Write("</script>"); } private static void NewSendFileUploadResponse(HttpContext context, string fileUrl, string funcNum, string errorMsg) { context.Response.Clear(); context.Response.Write("<script type=\"text/javascript\">"); if (string.IsNullOrEmpty(errorMsg)) { if (!string.IsNullOrEmpty(fileUrl)) { fileUrl = HttpUtility.UrlPathEncode(fileUrl).Replace("'", "\\'"); context.Response.Write("window.parent.CKEDITOR.tools.callFunction(" + funcNum + ",'" + fileUrl + "', '');"); } else { context.Response.Write("window.parent.CKEDITOR.tools.callFunction(" + funcNum + ",'', 'empty url');"); } } else { context.Response.Write("window.parent.CKEDITOR.tools.callFunction(" + funcNum + ",'', '" + errorMsg.Replace("'", "\\'") + "');"); } context.Response.Write("</script>"); } } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/RTP/RTP_Address.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.RTP { #region usings using System; using System.Net; #endregion /// <summary> /// This class implements RTP session address. /// </summary> public class RTP_Address { #region Members private readonly int m_ControlPort; private readonly int m_DataPort; private readonly IPAddress m_pIP; private readonly IPEndPoint m_pRtcpEP; private readonly IPEndPoint m_pRtpEP; private readonly int m_TTL; #endregion #region Properties /// <summary> /// Gets if this is multicast RTP address. /// </summary> public bool IsMulticast { get { return Net_Utils.IsMulticastAddress(m_pIP); } } /// <summary> /// Gets IP address. /// </summary> public IPAddress IP { get { return m_pIP; } } /// <summary> /// Gets RTP data port. /// </summary> public int DataPort { get { return m_DataPort; } } /// <summary> /// Gets RTCP control port. /// </summary> public int ControlPort { get { return m_ControlPort; } } /// <summary> /// Gets mulicast TTL(time to live) value. /// </summary> public int TTL { get { return m_TTL; } } /// <summary> /// Gets RTP end point. /// </summary> public IPEndPoint RtpEP { get { return m_pRtpEP; } } /// <summary> /// Gets RTPCP end point. /// </summary> public IPEndPoint RtcpEP { get { return m_pRtcpEP; } } #endregion #region Constructor /// <summary> /// Unicast constructor. /// </summary> /// <param name="ip">Unicast IP address.</param> /// <param name="dataPort">RTP data port.</param> /// <param name="controlPort">RTP control port. Usualy this is <b>dataPort</b> + 1.</param> /// <exception cref="ArgumentNullException">Is raised when <b>ip</b> is null reference.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid values.</exception> public RTP_Address(IPAddress ip, int dataPort, int controlPort) { if (ip == null) { throw new ArgumentNullException("ip"); } if (dataPort < IPEndPoint.MinPort || dataPort > IPEndPoint.MaxPort) { throw new ArgumentException("Argument 'dataPort' value must be between '" + IPEndPoint.MinPort + "' and '" + IPEndPoint.MaxPort + "'."); } if (controlPort < IPEndPoint.MinPort || controlPort > IPEndPoint.MaxPort) { throw new ArgumentException("Argument 'controlPort' value must be between '" + IPEndPoint.MinPort + "' and '" + IPEndPoint.MaxPort + "'."); } if (dataPort == controlPort) { throw new ArgumentException("Arguments 'dataPort' and 'controlPort' values must be different."); } m_pIP = ip; m_DataPort = dataPort; m_ControlPort = controlPort; m_pRtpEP = new IPEndPoint(ip, dataPort); m_pRtcpEP = new IPEndPoint(ip, controlPort); } /// <summary> /// Multicast constructor. /// </summary> /// <param name="ip">Multicast IP address.</param> /// <param name="dataPort">RTP data port.</param> /// <param name="controlPort">RTP control port. Usualy this is <b>dataPort</b> + 1.</param> /// <param name="ttl">RTP control port. Usualy this is <b>dataPort</b> + 1.</param> /// <exception cref="ArgumentNullException">Is raised when <b>ip</b> is null reference.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid values.</exception> public RTP_Address(IPAddress ip, int dataPort, int controlPort, int ttl) { if (ip == null) { throw new ArgumentNullException("ip"); } if (!Net_Utils.IsMulticastAddress(ip)) { throw new ArgumentException("Argument 'ip' is not multicast ip address."); } if (dataPort < IPEndPoint.MinPort || dataPort > IPEndPoint.MaxPort) { throw new ArgumentException("Argument 'dataPort' value must be between '" + IPEndPoint.MinPort + "' and '" + IPEndPoint.MaxPort + "'."); } if (controlPort < IPEndPoint.MinPort || controlPort > IPEndPoint.MaxPort) { throw new ArgumentException("Argument 'controlPort' value must be between '" + IPEndPoint.MinPort + "' and '" + IPEndPoint.MaxPort + "'."); } if (dataPort == controlPort) { throw new ArgumentException("Arguments 'dataPort' and 'controlPort' values must be different."); } if (ttl < 0 || ttl > 255) { throw new ArgumentException("Argument 'ttl' value must be between '0' and '255'."); } m_pIP = ip; m_DataPort = dataPort; m_ControlPort = controlPort; m_TTL = ttl; m_pRtpEP = new IPEndPoint(ip, dataPort); m_pRtcpEP = new IPEndPoint(ip, controlPort); } #endregion #region Methods /// <summary> /// Determines whether the specified Object is equal to the current Object. /// </summary> /// <param name="obj">The Object to compare with the current Object.</param> /// <returns>True if the specified Object is equal to the current Object; otherwise, false.</returns> public override bool Equals(object obj) { if (obj == null) { return false; } if (obj is RTP_Address) { RTP_Address a = (RTP_Address) obj; if (!a.IP.Equals(IP)) { return false; } if (a.DataPort != DataPort) { return false; } if (a.ControlPort != ControlPort) { return false; } } else { return false; } return true; } /// <summary> /// Gets this hash code. /// </summary> /// <returns></returns> public override int GetHashCode() { return base.GetHashCode(); } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/RTP/RTP_ReceiveStream.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.RTP { #region usings using System; #endregion /// <summary> /// Implements RTP session receive stream. /// </summary> public class RTP_ReceiveStream { #region Events /// <summary> /// Is raised when stream is closed by remote party (remote party sent BYE). /// </summary> public event EventHandler Closed = null; /// <summary> /// Is raised when new RTP packet received. /// </summary> public event EventHandler<RTP_PacketEventArgs> PacketReceived = null; /// <summary> /// Is raised when steam gets new sender report from remote party. /// </summary> public event EventHandler SenderReport = null; /// <summary> /// Is raised when receive stream has timed out by RTP session. /// </summary> /// <remarks>After <b>Timeout</b> event stream will be disposed and has no longer accessible.</remarks> public event EventHandler Timeout = null; #endregion #region Members private readonly RTP_Source m_pSSRC; private uint m_BaseSeq; private long m_BytesReceived; private long m_ExpectedPrior; private bool m_IsDisposed; private double m_Jitter; private uint m_LastBadSeqPlus1; private DateTime m_LastSRTime = DateTime.MinValue; private ushort m_MaxSeqNo; private long m_PacketsMisorder; private long m_PacketsReceived; private RTCP_Report_Sender m_pLastSR; private RTP_Participant_Remote m_pParticipant; private int m_Probation; private RTP_Session m_pSession; private long m_ReceivedPrior; private int m_SeqNoWrapCount; private int m_Transit; private int MAX_DROPOUT = 3000; private int MAX_MISORDER = 100; private int MIN_SEQUENTIAL = 2; private uint RTP_SEQ_MOD = (1 << 16); #endregion #region Properties /// <summary> /// Gets if this object is disposed. /// </summary> public bool IsDisposed { get { return m_IsDisposed; } } /// <summary> /// Gets stream owner RTP session. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public RTP_Session Session { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_pSession; } } /// <summary> /// Gets stream owner synchronization source. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public RTP_Source SSRC { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_pSSRC; } } /// <summary> /// Gets remote participant who is owner of this stream. Returns null if this stream is not yet received RTCP SDES. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public RTP_Participant_Remote Participant { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_pParticipant; } } /// <summary> /// Gets number of times <b>SeqNo</b> has wrapped around. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public int SeqNoWrapCount { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_SeqNoWrapCount; } } /// <summary> /// Gets first sequence number what this stream got. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public int FirstSeqNo { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return (int) m_BaseSeq; } } /// <summary> /// Gets maximum sequnce number that stream has got. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public int MaxSeqNo { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_MaxSeqNo; } } /// <summary> /// Gets how many RTP packets has received by this stream. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public long PacketsReceived { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_PacketsReceived; } } /// <summary> /// Gets how many RTP misorder packets has received by this stream. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public long PacketsMisorder { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_PacketsMisorder; } } /// <summary> /// Gets how many RTP packets has lost during transmission. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public long PacketsLost { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } // RFC 3550 A.3 Determining Number of Packets Expected and Lost. uint extHighestSeqNo = (uint) ((65536*m_SeqNoWrapCount) + m_MaxSeqNo); uint expected = extHighestSeqNo - m_BaseSeq + 1; long lost = expected - m_PacketsReceived; return lost; } } /// <summary> /// Gets how many RTP data has received by this stream. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public long BytesReceived { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_BytesReceived; } } /// <summary> /// Gets inter arrival jitter. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public double Jitter { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_Jitter; } } /// <summary> /// Gets delay between las SR(sender report) and now in milliseconds. Returns -1 if no SR received. /// </summary> public int DelaySinceLastSR { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return (int) (m_LastSRTime == DateTime.MinValue ? -1 : ((DateTime.Now - m_LastSRTime)).TotalMilliseconds); } } /// <summary> /// Gets time when last SR(sender report) was received. Returns <b>DateTime.MinValue</b> if no SR received. /// </summary> public DateTime LastSRTime { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_LastSRTime; } } /// <summary> /// Gets last received RTCP SR(sender report). Value null means no SR received. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public RTCP_Report_Sender LastSR { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_pLastSR; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="session">Owner RTP session.</param> /// <param name="ssrc">Onwer synchronization source.</param> /// <param name="packetSeqNo">RTP packet <b>SeqNo</b> value.</param> /// <exception cref="ArgumentNullException">Is riased when <b>session</b> or <b>ssrc</b> is null reference.</exception> internal RTP_ReceiveStream(RTP_Session session, RTP_Source ssrc, ushort packetSeqNo) { if (session == null) { throw new ArgumentNullException("session"); } if (ssrc == null) { throw new ArgumentNullException("ssrc"); } m_pSession = session; m_pSSRC = ssrc; // RFC 3550 A.1. InitSeq(packetSeqNo); m_MaxSeqNo = (ushort) (packetSeqNo - 1); m_Probation = MIN_SEQUENTIAL; } #endregion #region Utility methods /// <summary> /// Initializes new sequence number. /// </summary> /// <param name="seqNo">Sequence number.</param> private void InitSeq(ushort seqNo) { // For more info see RFC 3550 A.1. m_BaseSeq = seqNo; m_MaxSeqNo = seqNo; m_LastBadSeqPlus1 = RTP_SEQ_MOD + 1; /* so seq == bad_seq is false */ m_SeqNoWrapCount = 0; m_PacketsReceived = 0; m_ReceivedPrior = 0; m_ExpectedPrior = 0; } /// <summary> /// Updates sequence number. /// </summary> /// <param name="seqNo">RTP packet sequence number.</param> /// <returns>Returns true if sequence is valid, otherwise false.</returns> private bool UpdateSeq(ushort seqNo) { // For more info see RFC 3550 A.1. ushort udelta = (ushort) (seqNo - m_MaxSeqNo); /* * Source is not valid until MIN_SEQUENTIAL packets with * sequential sequence numbers have been received. */ // Stream not validated yet. if (m_Probation > 0) { // The seqNo is in sequence. if (seqNo == m_MaxSeqNo + 1) { m_Probation--; m_MaxSeqNo = seqNo; // The receive stream has validated ok. if (m_Probation == 0) { InitSeq(seqNo); m_PacketsReceived++; // Raise NewReceiveStream event. m_pSession.OnNewReceiveStream(this); return true; } } else { m_Probation = MIN_SEQUENTIAL - 1; m_MaxSeqNo = seqNo; } return false; } // The seqNo is order, with permissible gap. else if (udelta < MAX_DROPOUT) { // The seqNo has wrapped around. if (seqNo < m_MaxSeqNo) { m_SeqNoWrapCount++; } m_MaxSeqNo = seqNo; } // The seqNo made a very large jump. else if (udelta <= RTP_SEQ_MOD - MAX_MISORDER) { if (seqNo == m_LastBadSeqPlus1) { /* * Two sequential packets -- assume that the other side * restarted without telling us so just re-sync * (i.e., pretend this was the first packet). */ InitSeq(seqNo); } else { m_LastBadSeqPlus1 = (uint) ((seqNo + 1) & (RTP_SEQ_MOD - 1)); return false; } } else { /* duplicate or reordered packet */ m_PacketsMisorder++; } m_PacketsReceived++; return true; } /// <summary> /// Raises <b>Closed</b> event. /// </summary> private void OnClosed() { if (Closed != null) { Closed(this, new EventArgs()); } } /// <summary> /// Raises <b>SenderReport</b> event. /// </summary> private void OnSenderReport() { if (SenderReport != null) { SenderReport(this, new EventArgs()); } } /// <summary> /// Raises <b>PacketReceived</b> event. /// </summary> /// <param name="packet">RTP packet.</param> private void OnPacketReceived(RTP_Packet packet) { if (PacketReceived != null) { PacketReceived(this, new RTP_PacketEventArgs(packet)); } } #endregion #region Internal methods /// <summary> /// Cleans up any resources being used. /// </summary> internal void Dispose() { if (m_IsDisposed) { return; } m_IsDisposed = true; m_pSession = null; m_pParticipant = null; Closed = null; Timeout = null; SenderReport = null; PacketReceived = null; } /// <summary> /// Processes specified RTP packet thorugh this stream. /// </summary> /// <param name="packet">RTP packet.</param> /// <param name="size">RTP packet size in bytes.</param> /// <exception cref="ArgumentNullException">Is raised when <b>packet</b> is null reference.</exception> internal void Process(RTP_Packet packet, int size) { if (packet == null) { throw new ArgumentNullException("packet"); } m_BytesReceived += size; if (UpdateSeq(packet.SeqNo)) { OnPacketReceived(packet); /* RFC 3550 A.8 Estimating the Interarrival Jitter. The code fragments below implement the algorithm given in Section 6.4.1 for calculating an estimate of the statistical variance of the RTP data interarrival time to be inserted in the interarrival jitter field of reception reports. The inputs are r->ts, the timestamp from the incoming packet, and arrival, the current time in the same units. Here s points to state for the source; s->transit holds the relative transit time for the previous packet, and s->jitter holds the estimated jitter. The jitter field of the reception report is measured in timestamp units and expressed as an unsigned integer, but the jitter estimate is kept in a floating point. As each data packet arrives, the jitter estimate is updated: int transit = arrival - r->ts; int d = transit - s->transit; s->transit = transit; if (d < 0) d = -d; s->jitter += (1./16.) * ((double)d - s->jitter); When a reception report block (to which rr points) is generated for this member, the current jitter estimate is returned: rr->jitter = (u_int32) s->jitter; */ uint arrival = RTP_Utils.DateTimeToNTP32(DateTime.Now); int transit = (int) (arrival - packet.Timestamp); int d = transit - m_Transit; m_Transit = transit; if (d < 0) { d = -d; } m_Jitter += (1.0/16.0)*(d - m_Jitter); } // else Packet not valid, skip it. } /// <summary> /// Sets property <b>LastSR</b> value. /// </summary> /// <param name="report">Sender report.</param> /// <exception cref="ArgumentNullException">Is raised when <b>report</b> is null reference.</exception> internal void SetSR(RTCP_Report_Sender report) { if (report == null) { throw new ArgumentNullException("report"); } m_LastSRTime = DateTime.Now; m_pLastSR = report; OnSenderReport(); } /// <summary> /// Creates receiver report. /// </summary> /// <returns>Returns created receiver report.</returns> internal RTCP_Packet_ReportBlock CreateReceiverReport() { /* RFC 3550 A.3 Determining Number of Packets Expected and Lost. In order to compute packet loss rates, the number of RTP packets expected and actually received from each source needs to be known, using per-source state information defined in struct source referenced via pointer s in the code below. The number of packets received is simply the count of packets as they arrive, including any late or duplicate packets. The number of packets expected can be computed by the receiver as the difference between the highest sequence number received (s->max_seq) and the first sequence number received (s->base_seq). Since the sequence number is only 16 bits and will wrap around, it is necessary to extend the highest sequence number with the (shifted) count of sequence number wraparounds (s->cycles). Both the received packet count and the count of cycles are maintained the RTP header validity check routine in Appendix A.1. extended_max = s->cycles + s->max_seq; expected = extended_max - s->base_seq + 1; The number of packets lost is defined to be the number of packets expected less the number of packets actually received: lost = expected - s->received; Since this signed number is carried in 24 bits, it should be clamped at 0x7fffff for positive loss or 0x800000 for negative loss rather than wrapping around. The fraction of packets lost during the last reporting interval (since the previous SR or RR packet was sent) is calculated from differences in the expected and received packet counts across the interval, where expected_prior and received_prior are the values saved when the previous reception report was generated: expected_interval = expected - s->expected_prior; s->expected_prior = expected; received_interval = s->received - s->received_prior; s->received_prior = s->received; lost_interval = expected_interval - received_interval; if(expected_interval == 0 || lost_interval <= 0) fraction = 0; else fraction = (lost_interval << 8) / expected_interval; The resulting fraction is an 8-bit fixed point number with the binary point at the left edge. */ uint extHighestSeqNo = (uint) (m_SeqNoWrapCount << 16 + m_MaxSeqNo); uint expected = extHighestSeqNo - m_BaseSeq + 1; int expected_interval = (int) (expected - m_ExpectedPrior); m_ExpectedPrior = expected; int received_interval = (int) (m_PacketsReceived - m_ReceivedPrior); m_ReceivedPrior = m_PacketsReceived; int lost_interval = expected_interval - received_interval; int fraction = 0; if (expected_interval == 0 || lost_interval <= 0) { fraction = 0; } else { fraction = (lost_interval << 8)/expected_interval; } RTCP_Packet_ReportBlock rr = new RTCP_Packet_ReportBlock(SSRC.SSRC); rr.FractionLost = (uint) fraction; rr.CumulativePacketsLost = (uint) PacketsLost; rr.ExtendedHighestSeqNo = extHighestSeqNo; rr.Jitter = (uint) m_Jitter; rr.LastSR = (m_pLastSR == null ? 0 : ((uint) ((long) m_pLastSR.NtpTimestamp >> 8) & 0xFFFF)); rr.DelaySinceLastSR = (uint) Math.Max(0, DelaySinceLastSR/65.536); return rr; } /// <summary> /// Raised <b>Timeout</b> event. /// </summary> internal void OnTimeout() { if (Timeout != null) { Timeout(this, new EventArgs()); } } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/ServersCore/Error_EventArgs.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net { #region usings using System; using System.Diagnostics; #endregion /// <summary> /// Provides data for the SysError event for servers. /// </summary> public class Error_EventArgs { #region Members private readonly Exception m_pException; private readonly StackTrace m_pStackTrace; private string m_Text = ""; #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="x"></param> /// <param name="stackTrace"></param> public Error_EventArgs(Exception x, StackTrace stackTrace) { m_pException = x; m_pStackTrace = stackTrace; } #endregion #region Properties /// <summary> /// Occured error's exception. /// </summary> public Exception Exception { get { return m_pException; } } /// <summary> /// Occured error's stacktrace. /// </summary> public StackTrace StackTrace { get { return m_pStackTrace; } } /// <summary> /// Gets comment text. /// </summary> public string Text { get { return m_Text; } } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/SIP/Proxy/SIP_ProxyMode.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.SIP.Proxy { #region usings using System; #endregion /// <summary> /// Specifies SIP proxy mode. /// <example> /// All flags may be combined, except Stateless,Statefull,B2BUA. /// For example: (Stateless | Statefull) not allowed, but (Registrar | Presence | Statefull) is allowed. /// </example> /// </summary> [Flags] public enum SIP_ProxyMode { /// <summary> /// Proxy implements SIP registrar. /// </summary> Registrar = 1, /// <summary> /// Proxy implements SIP presence server. /// </summary> Presence = 2, /// <summary> /// Proxy runs in stateless mode. /// </summary> Stateless = 4, /// <summary> /// Proxy runs in statefull mode. /// </summary> Statefull = 8, /// <summary> /// Proxy runs in B2BUA(back to back user agent) mode. /// </summary> B2BUA = 16, } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/STUN/Client/STUN_Result.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.STUN.Client { #region usings using System.Net; #endregion /// <summary> /// This class holds STUN_Client.Query method return data. /// </summary> public class STUN_Result { #region Members private readonly STUN_NetType m_NetType = STUN_NetType.OpenInternet; private readonly IPEndPoint m_pPublicEndPoint; #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="netType">Specifies UDP network type.</param> /// <param name="publicEndPoint">Public IP end point.</param> public STUN_Result(STUN_NetType netType, IPEndPoint publicEndPoint) { m_NetType = netType; m_pPublicEndPoint = publicEndPoint; } #endregion #region Properties /// <summary> /// Gets UDP network type. /// </summary> public STUN_NetType NetType { get { return m_NetType; } } /// <summary> /// Gets public IP end point. This value is null if failed to get network type. /// </summary> public IPEndPoint PublicEndPoint { get { return m_pPublicEndPoint; } } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/ServersCore/ValidateIP_EventArgs.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net { #region usings using System.Net; #endregion /// <summary> /// Provides data for the ValidateIPAddress event for servers. /// </summary> public class ValidateIP_EventArgs { #region Members private readonly IPEndPoint m_pLocalEndPoint; private readonly IPEndPoint m_pRemoteEndPoint; private string m_ErrorText = ""; private bool m_Validated = true; #endregion #region Properties /// <summary> /// IP address of computer, which is sending mail to here. /// </summary> public string ConnectedIP { get { return m_pRemoteEndPoint.Address.ToString(); } } /// <summary> /// Gets local endpoint. /// </summary> public IPEndPoint LocalEndPoint { get { return m_pLocalEndPoint; } } /// <summary> /// Gets remote endpoint. /// </summary> public IPEndPoint RemoteEndPoint { get { return m_pRemoteEndPoint; } } /// <summary> /// Gets or sets if IP is allowed access. /// </summary> public bool Validated { get { return m_Validated; } set { m_Validated = value; } } /// <summary> /// Gets or sets user data what is stored to session.Tag property. /// </summary> public object SessionTag { get; set; } /// <summary> /// Gets or sets error text what is sent to connected socket. NOTE: This is only used if Validated = false. /// </summary> public string ErrorText { get { return m_ErrorText; } set { m_ErrorText = value; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="localEndPoint">Server IP.</param> /// <param name="remoteEndPoint">Connected client IP.</param> public ValidateIP_EventArgs(IPEndPoint localEndPoint, IPEndPoint remoteEndPoint) { m_pLocalEndPoint = localEndPoint; m_pRemoteEndPoint = remoteEndPoint; } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/SIP/Message/SIP_t_Join.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.SIP.Message { #region usings using System; using System.Text; #endregion /// <summary> /// Implements SIP "Join" value. Defined in RFC 3911. /// </summary> /// <remarks> /// <code> /// RFC 3911 Syntax: /// Join = callid *(SEMI join-param) /// join-param = to-tag / from-tag / generic-param /// to-tag = "to-tag" EQUAL token /// from-tag = "from-tag" EQUAL token /// </code> /// </remarks> public class SIP_t_Join : SIP_t_ValueWithParams { #region Members private SIP_t_CallID m_pCallID; #endregion #region Properties /// <summary> /// Gets or sets call ID value. /// </summary> /// <exception cref="ArgumentNullException">Is raised �when null value passed.</exception> public SIP_t_CallID CallID { get { return m_pCallID; } set { if (value == null) { throw new ArgumentNullException("CallID"); } m_pCallID = value; } } /// <summary> /// Gets or sets to-tag parameter value. This value is mandatory. /// </summary> /// <exception cref="ArgumentException">Is raised when invalid ToTag value is passed.</exception> public string ToTag { get { SIP_Parameter parameter = Parameters["to-tag"]; if (parameter != null) { return parameter.Value; } else { return null; } } set { if (string.IsNullOrEmpty(value)) { throw new ArgumentException("ToTag is mandatory and cant be null or empty !"); } else { Parameters.Set("to-tag", value); } } } /// <summary> /// Gets or sets from-tag parameter value. This value is mandatory. /// </summary> /// <exception cref="ArgumentException">Is raised when invalid FromTag value is passed.</exception> public string FromTag { get { SIP_Parameter parameter = Parameters["from-tag"]; if (parameter != null) { return parameter.Value; } else { return null; } } set { if (string.IsNullOrEmpty(value)) { throw new ArgumentException("FromTag is mandatory and cant be null or empty !"); } else { Parameters.Set("from-tag", value); } } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="value">Join value.</param> public SIP_t_Join(string value) { Parse(value); } #endregion #region Methods /// <summary> /// Parses "Join" from specified value. /// </summary> /// <param name="value">SIP "Join" value.</param> /// <exception cref="ArgumentNullException">Raised when <b>value</b> is null.</exception> /// <exception cref="SIP_ParseException">Raised when invalid SIP message.</exception> public void Parse(string value) { if (value == null) { throw new ArgumentNullException("value"); } Parse(new StringReader(value)); } /// <summary> /// Parses "Join" from specified reader. /// </summary> /// <param name="reader">Reader from where to parse.</param> /// <exception cref="ArgumentNullException">Raised when <b>reader</b> is null.</exception> /// <exception cref="SIP_ParseException">Raised when invalid SIP message.</exception> public override void Parse(StringReader reader) { /* Join = callid *(SEMI join-param) join-param = to-tag / from-tag / generic-param to-tag = "to-tag" EQUAL token from-tag = "from-tag" EQUAL token A Join header MUST contain exactly one to-tag and exactly one from- tag, as they are required for unique dialog matching. */ if (reader == null) { throw new ArgumentNullException("reader"); } // Parse address SIP_t_CallID callID = new SIP_t_CallID(); callID.Parse(reader); m_pCallID = callID; // Parse parameters ParseParameters(reader); // Check that to and from tags exist. if (Parameters["to-tag"] == null) { throw new SIP_ParseException("Join value mandatory to-tag value is missing !"); } if (Parameters["from-tag"] == null) { throw new SIP_ParseException("Join value mandatory from-tag value is missing !"); } } /// <summary> /// Converts this to valid "Join" value. /// </summary> /// <returns>Returns "Join" value.</returns> public override string ToStringValue() { /* Join = callid *(SEMI join-param) join-param = to-tag / from-tag / generic-param to-tag = "to-tag" EQUAL token from-tag = "from-tag" EQUAL token */ StringBuilder retVal = new StringBuilder(); // Add address retVal.Append(m_pCallID.ToStringValue()); // Add parameters retVal.Append(ParametersToString()); return retVal.ToString(); } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/SIP/UA/SIP_UA.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.SIP.UA { #region usings using System; using System.Collections.Generic; using System.Threading; using Stack; #endregion /// <summary> /// This class implements SIP UA. Defined in RFC 3261 8.1. /// </summary> public class SIP_UA : IDisposable { #region Events /// <summary> /// Is raised when new incoming call. /// </summary> public event EventHandler<SIP_UA_Call_EventArgs> IncomingCall = null; /// <summary> /// Is raised when user agent get new SIP request. /// </summary> public event EventHandler<SIP_RequestReceivedEventArgs> RequestReceived = null; #endregion #region Members private readonly List<SIP_UA_Call> m_pCalls; private readonly object m_pLock = new object(); private bool m_IsDisposed; private SIP_Stack m_pStack; #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> public SIP_UA() { m_pStack = new SIP_Stack(); m_pStack.RequestReceived += m_pStack_RequestReceived; m_pCalls = new List<SIP_UA_Call>(); } #endregion #region Properties /// <summary> /// Gets active calls. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and and this property is accessed.</exception> public SIP_UA_Call[] Calls { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_pCalls.ToArray(); } } /// <summary> /// Gets if this object is disposed. /// </summary> public bool IsDisposed { get { return m_IsDisposed; } } /// <summary> /// Gets SIP stack. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and and this property is accessed.</exception> public SIP_Stack Stack { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_pStack; } } #endregion #region Methods /// <summary> /// Cleans up any resources being used. /// </summary> public void Dispose() { lock (m_pLock) { if (m_IsDisposed) { return; } // Hang up all calls. foreach (SIP_UA_Call call in m_pCalls.ToArray()) { call.Terminate(); } // Wait till all registrations and calls disposed or wait timeout reached. DateTime start = DateTime.Now; while (m_pCalls.Count > 0) { Thread.Sleep(500); // Timeout, just kill all UA. if (((DateTime.Now - start)).Seconds > 15) { break; } } m_IsDisposed = true; RequestReceived = null; IncomingCall = null; m_pStack.Dispose(); m_pStack = null; } } /// <summary> /// Creates call to <b>invite</b> specified recipient. /// </summary> /// <param name="invite">INVITE request.</param> /// <returns>Returns created call.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>invite</b> is null reference.</exception> /// <exception cref="ArgumentException">Is raised when any of the argumnets has invalid value.</exception> public SIP_UA_Call CreateCall(SIP_Request invite) { if (invite == null) { throw new ArgumentNullException("invite"); } if (invite.RequestLine.Method != SIP_Methods.INVITE) { throw new ArgumentException("Argument 'invite' is not INVITE request."); } lock (m_pLock) { SIP_UA_Call call = new SIP_UA_Call(this, invite); call.StateChanged += Call_StateChanged; m_pCalls.Add(call); return call; } } #endregion #region Utility methods /// <summary> /// This method is called when SIP stack received new message. /// </summary> /// <param name="sender">Sender.</param> /// <param name="e">Event data.</param> private void m_pStack_RequestReceived(object sender, SIP_RequestReceivedEventArgs e) { // TODO: Performance: rise events on thread pool or see if this method called on pool aready, then we may not keep lock for events ? if (e.Request.RequestLine.Method == SIP_Methods.CANCEL) { /* RFC 3261 9.2. If the UAS did not find a matching transaction for the CANCEL according to the procedure above, it SHOULD respond to the CANCEL with a 481 (Call Leg/Transaction Does Not Exist). Regardless of the method of the original request, as long as the CANCEL matched an existing transaction, the UAS answers the CANCEL request itself with a 200 (OK) response. */ SIP_ServerTransaction trToCancel = m_pStack.TransactionLayer.MatchCancelToTransaction(e.Request); if (trToCancel != null) { trToCancel.Cancel(); e.ServerTransaction.SendResponse(m_pStack.CreateResponse(SIP_ResponseCodes.x200_Ok, e.Request)); } else { e.ServerTransaction.SendResponse( m_pStack.CreateResponse(SIP_ResponseCodes.x481_Call_Transaction_Does_Not_Exist, e.Request)); } } else if (e.Request.RequestLine.Method == SIP_Methods.BYE) { /* RFC 3261 15.1.2. If the BYE does not match an existing dialog, the UAS core SHOULD generate a 481 (Call/Transaction Does Not Exist) response and pass that to the server transaction. */ // TODO: SIP_Dialog dialog = m_pStack.TransactionLayer.MatchDialog(e.Request); if (dialog != null) { e.ServerTransaction.SendResponse(m_pStack.CreateResponse(SIP_ResponseCodes.x200_Ok, e.Request)); dialog.Terminate(); } else { e.ServerTransaction.SendResponse( m_pStack.CreateResponse(SIP_ResponseCodes.x481_Call_Transaction_Does_Not_Exist, e.Request)); } } else if (e.Request.RequestLine.Method == SIP_Methods.INVITE) { SIP_ServerTransaction transaction = e.ServerTransaction; transaction.SendResponse(m_pStack.CreateResponse(SIP_ResponseCodes.x180_Ringing, e.Request)); // TODO: See if we support SDP media. // Create call. SIP_UA_Call call = new SIP_UA_Call(this, transaction); call.StateChanged += Call_StateChanged; m_pCalls.Add(call); OnIncomingCall(call); } else { OnRequestReceived(e); } } /// <summary> /// Thsi method is called when call state has chnaged. /// </summary> /// <param name="sender">Sender.</param> /// <param name="e">Event data.</param> private void Call_StateChanged(object sender, EventArgs e) { SIP_UA_Call call = (SIP_UA_Call) sender; if (call.State == SIP_UA_CallState.Terminated) { m_pCalls.Remove(call); } } /// <summary> /// Raises event <b>IncomingCall</b>. /// </summary> /// <param name="call">Incoming call.</param> private void OnIncomingCall(SIP_UA_Call call) { if (IncomingCall != null) { IncomingCall(this, new SIP_UA_Call_EventArgs(call)); } } #endregion /// <summary> /// Raises <b>RequestReceived</b> event. /// </summary> /// <param name="request">SIP request.</param> protected void OnRequestReceived(SIP_RequestReceivedEventArgs request) { if (RequestReceived != null) { RequestReceived(this, request); } } } }<file_sep>/redistributable/BaseCampRestAPI-1.1.0/BasecampRestAPI/Interfaces/IWebRequestFactory.cs using System.Net; namespace BasecampRestAPI { public interface IWebRequestFactory { IWebRequest CreateWebRequest(string url); HttpWebRequest GetHttpWebRequest(string url); } }<file_sep>/build/install/rpm/Files/god/conf.d/mail.god God.watch do |w| w.name = "onlyofficeMailAggregator" w.group = "onlyoffice" w.grace = 15.seconds w.start = "systemctl start onlyofficeMailAggregator" w.stop = "systemctl stop onlyofficeMailAggregator" w.restart = "systemctl restart onlyofficeMailAggregator" w.pid_file = "/tmp/onlyofficeMailAggregator" w.behavior(:clean_pid_file) w.start_if do |start| start.condition(:process_running) do |c| c.interval = 10.seconds c.running = false end end w.restart_if do |restart| restart.condition(:memory_usage) do |c| c.above = 1000.megabytes c.times = 5 c.interval = 10.seconds end restart.condition(:cpu_usage) do |c| c.above = 90.percent c.times = 5 c.interval = 10.seconds end restart.condition(:lambda) do |c| c.interval = 10.seconds c.lambda = lambda{!File.exist?("/var/log/onlyoffice/mail.agg.log")} end restart.condition(:file_mtime) do |c| c.path = "/var/log/onlyoffice/mail.agg.log" c.max_age = 1.minutes c.interval = 10.seconds end end end <file_sep>/web/studio/ASC.Web.Studio/UserControls/Statistics/ProductQuotes/js/product_quotes.js /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ ASC.ProductQuotes = (function () { var $recalculateButton, $tabsHeaderItems, $tabCorner, $tabsContent, $statisticsItemListTmpl, disableClass = "disable", activeClass = "active", timeOut = 10000, teamlab; function init() { $recalculateButton = jq('.storeUsage .button.blue'); $tabsHeaderItems = jq(".tabs-header .tabs-header-item"); $tabCorner = jq(".tabs-header .tabs-header-corner"); $tabsContent = jq(".tabs-content"); $statisticsItemListTmpl = jq("#statisticsItemListTmpl"); teamlab = Teamlab; initClickEvents(); if ($recalculateButton.length) checkRecalculate(); if ($tabsHeaderItems.length) $tabsHeaderItems[0].click(); } function initClickEvents() { jq.switcherAction(".toggle-button", ".toggle-content"); jq(".tabs-header").on("click", ".tabs-header-item:not(.active)", setActiveTab); jq(".tabs-content").on("click", ".moreBox .link", showMore); $recalculateButton.click(function () { if ($recalculateButton.hasClass(disableClass)) return; teamlab.recalculateQuota({}, { success: onRecalculate }); }); } function onRecalculate() { $recalculateButton.addClass(disableClass); setTimeout(checkRecalculate, timeOut); } function checkRecalculate() { teamlab.checkRecalculateQuota({}, { success: onCheckRecalculate }); } function onCheckRecalculate(params, result) { if (!result) { $recalculateButton.removeClass(disableClass); return; } if (!$recalculateButton.hasClass(disableClass)) { $recalculateButton.addClass(disableClass); } setTimeout(checkRecalculate, timeOut); } function setActiveTab() { $tabsHeaderItems.removeClass(activeClass); var obj = jq(this).addClass(activeClass); if ($tabCorner.is(":visible")) $tabCorner.css("left", obj.position().left + (obj.width() / 2) - ($tabCorner.width() / 2)); var itemId = obj.attr("data-id"); var contentItem = jq("#tabsContent_" + itemId); var tabsContentItems = $tabsContent.find(".tabs-content-item"); if (contentItem.length) { tabsContentItems.removeClass(activeClass); contentItem.addClass(activeClass); return; } teamlab.getSpaceUsageStatistics({}, itemId, { success: function (params, result) { tabsContentItems.removeClass(activeClass); $tabsContent.append($statisticsItemListTmpl.tmpl({ id: itemId, items: result })); }, before: LoadingBanner.displayLoading, after: LoadingBanner.hideLoading, error: function (params, errors) { tabsContentItems.removeClass(activeClass); $tabsContent.append($statisticsItemListTmpl.tmpl({ id: itemId, items: [] })); if (errors && errors.length) toastr.error(errors[0]); } }); } function showMore() { var obj = jq(this); jq(obj.parent().prev()).find("tr").show(); obj.parent().hide(); } return { init: init }; })(); jq(document).ready(function () { ASC.ProductQuotes.init(); });<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Autoreply/AddressParsers/CommunityAddressParser.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System.Collections.Generic; using System.Text.RegularExpressions; using ASC.Core.Tenants; using ASC.Mail.Autoreply.ParameterResolvers; namespace ASC.Mail.Autoreply.AddressParsers { internal class CommunityAddressParser : AddressParser { protected override Regex GetRouteRegex() { return new Regex(@"^(?'type'blog|event)$", RegexOptions.Compiled); } protected override ApiRequest ParseRequestInfo(IDictionary<string,string> groups, Tenant t) { var callInfo = new ApiRequest("community/" + groups["type"]) { Parameters = new List<RequestParameter> { new RequestParameter("content", new HtmlContentResolver()), new RequestParameter("title", new TitleResolver(BlogTagsResolver.Pattern)), new RequestParameter("subscribeComments", true), new RequestParameter("type", 1), new RequestParameter("tags", new BlogTagsResolver()) } }; return callInfo; } } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/SMTP/Server/SMTP_e_RcptTo.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.SMTP.Server { #region usings using System; #endregion /// <summary> /// This class provided data for <b cref="SMTP_Session.RcptTo">SMTP_Session.RcptTo</b> event. /// </summary> public class SMTP_e_RcptTo : EventArgs { #region Members private readonly SMTP_RcptTo m_pRcptTo; private readonly SMTP_Session m_pSession; private SMTP_Reply m_pReply; #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="session">Owner SMTP server session.</param> /// <param name="to">RCPT TO: value.</param> /// <param name="reply">SMTP server reply.</param> /// <exception cref="ArgumentNullException">Is raised when <b>session</b>, <b>to</b> or <b>reply</b> is null reference.</exception> public SMTP_e_RcptTo(SMTP_Session session, SMTP_RcptTo to, SMTP_Reply reply) { if (session == null) { throw new ArgumentNullException("session"); } if (to == null) { throw new ArgumentNullException("from"); } if (reply == null) { throw new ArgumentNullException("reply"); } m_pSession = session; m_pRcptTo = to; m_pReply = reply; } #endregion #region Properties /// <summary> /// Gets RCPT TO: value. /// </summary> public SMTP_RcptTo RcptTo { get { return m_pRcptTo; } } /// <summary> /// Gets or sets SMTP server reply. /// </summary> /// <exception cref="ArgumentNullException">Is raised when null reference passed.</exception> public SMTP_Reply Reply { get { return m_pReply; } set { if (value == null) { throw new ArgumentNullException("Reply"); } m_pReply = value; } } /// <summary> /// Gets owner SMTP session. /// </summary> public SMTP_Session Session { get { return m_pSession; } } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/Data/_ldb_Utils.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Data.lsDB { /// <summary> ///LDB utility methods. /// </summary> internal class ldb_Utils { #region Methods /// <summary> /// Convert long value to byte[8]. /// </summary> /// <param name="val">Long value.</param> /// <returns></returns> public static byte[] LongToByte(long val) { byte[] retVal = new byte[8]; retVal[0] = (byte) ((val >> 56) & 0xFF); retVal[1] = (byte) ((val >> 48) & 0xFF); retVal[2] = (byte) ((val >> 40) & 0xFF); retVal[3] = (byte) ((val >> 32) & 0xFF); retVal[4] = (byte) ((val >> 24) & 0xFF); retVal[5] = (byte) ((val >> 16) & 0xFF); retVal[6] = (byte) ((val >> 8) & 0xFF); retVal[7] = (byte) ((val >> 0) & 0xFF); return retVal; } /// <summary> /// Converts 8 bytes to long value. Offset byte is included. /// </summary> /// <param name="array">Data array.</param> /// <param name="offset">Offset where 8 bytes long value starts. Offset byte is included.</param> /// <returns></returns> public static long ByteToLong(byte[] array, int offset) { long retVal = 0; retVal |= (long) array[offset + 0] << 56; retVal |= (long) array[offset + 1] << 48; retVal |= (long) array[offset + 2] << 40; retVal |= (long) array[offset + 3] << 32; retVal |= (long) array[offset + 4] << 24; retVal |= (long) array[offset + 5] << 16; retVal |= (long) array[offset + 6] << 8; retVal |= (long) array[offset + 7] << 0; return retVal; } /// <summary> /// Convert int value to byte[4]. /// </summary> /// <param name="val">Int value.</param> /// <returns></returns> public static byte[] IntToByte(int val) { byte[] retVal = new byte[4]; retVal[0] = (byte) ((val >> 24) & 0xFF); retVal[1] = (byte) ((val >> 16) & 0xFF); retVal[2] = (byte) ((val >> 8) & 0xFF); retVal[3] = (byte) ((val >> 0) & 0xFF); return retVal; } /// <summary> /// Converts 4 bytes to int value. Offset byte is included. /// </summary> /// <param name="array">Data array.</param> /// <param name="offset">Offset where 4 bytes int value starts. Offset byte is included.</param> /// <returns></returns> public static int ByteToInt(byte[] array, int offset) { int retVal = 0; retVal |= array[offset + 0] << 24; retVal |= array[offset + 1] << 16; retVal |= array[offset + 2] << 8; retVal |= array[offset + 3] << 0; return retVal; } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/IMAP/Server/IMAP_SearchKey.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.IMAP.Server { #region usings using System; using Mime; #endregion /// <summary> /// IMAP search key (RFC 3501 6.4.4 SEARCH Command). /// </summary> internal class SearchKey { #region Members private readonly string m_SearchKeyName = ""; private readonly object m_SearchKeyValue; #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> public SearchKey(string searchKeyName, object value) { m_SearchKeyName = searchKeyName; m_SearchKeyValue = value; } #endregion #region Methods /// <summary> /// Parses one search key from current position. Returns null if there isn't any search key left. /// </summary> /// <param name="reader"></param> public static SearchKey Parse(StringReader reader) { string searchKeyName = ""; object searchKeyValue = null; //Remove spaces from string start reader.ReadToFirstChar(); // Search keyname is always 1 word string word = reader.ReadWord(); if (word == null) { return null; } word = word.ToUpper().Trim(); //Remove spaces from string start reader.ReadToFirstChar(); #region ALL // ALL // All messages in the mailbox; the default initial key for ANDing. if (word == "ALL") { searchKeyName = "ALL"; } #endregion #region ANSWERED // ANSWERED // Messages with the \Answered flag set. else if (word == "ANSWERED") { // We internally use KEYWORD ANSWERED searchKeyName = "KEYWORD"; searchKeyValue = "ANSWERED"; } #endregion #region BCC // BCC <string> // Messages that contain the specified string in the envelope structure's BCC field. else if (word == "BCC") { // We internally use HEADER "BCC:" "value" searchKeyName = "HEADER"; // Read <string> string val = ReadString(reader); if (val != null) { searchKeyValue = new[] {"BCC:", TextUtils.UnQuoteString(val)}; } else { throw new Exception("BCC <string> value is missing !"); } } #endregion #region BEFORE // BEFORE <date> // Messages whose internal date (disregarding time and timezone) is earlier than the specified date. else if (word == "BEFORE") { searchKeyName = "BEFORE"; // Read <date> string val = reader.QuotedReadToDelimiter(' '); if (val != null) { // Parse date try { searchKeyValue = IMAP_Utils.ParseDate(TextUtils.UnQuoteString(val)); } // Invalid date catch { throw new Exception("Invalid BEFORE <date> value '" + val + "', valid date syntax: {dd-MMM-yyyy} !"); } } else { throw new Exception("BEFORE <date> value is missing !"); } } #endregion #region BODY // BODY <string> // Messages that contain the specified string in the body of the message. else if (word == "BODY") { searchKeyName = "BODY"; string val = ReadString(reader); if (val != null) { searchKeyValue = val; } else { throw new Exception("BODY <string> value is missing !"); } } #endregion #region CC // CC <string> // Messages that contain the specified string in the envelope structure's CC field. else if (word == "CC") { // We internally use HEADER "CC:" "value" searchKeyName = "HEADER"; // Read <string> string val = ReadString(reader); if (val != null) { searchKeyValue = new[] {"CC:", TextUtils.UnQuoteString(val)}; } else { throw new Exception("CC <string> value is missing !"); } } #endregion #region DELETED // DELETED // Messages with the \Deleted flag set. else if (word == "DELETED") { // We internally use KEYWORD DELETED searchKeyName = "KEYWORD"; searchKeyValue = "DELETED"; } #endregion #region DRAFT // DRAFT // Messages with the \Draft flag set. else if (word == "DRAFT") { // We internally use KEYWORD DRAFT searchKeyName = "KEYWORD"; searchKeyValue = "DRAFT"; } #endregion #region FLAGGED // FLAGGED // Messages with the \Flagged flag set. else if (word == "FLAGGED") { // We internally use KEYWORD FLAGGED searchKeyName = "KEYWORD"; searchKeyValue = "FLAGGED"; } #endregion #region FROM // FROM <string> // Messages that contain the specified string in the envelope structure's FROM field. else if (word == "FROM") { // We internally use HEADER "FROM:" "value" searchKeyName = "HEADER"; // Read <string> string val = ReadString(reader); if (val != null) { searchKeyValue = new[] {"FROM:", TextUtils.UnQuoteString(val)}; } else { throw new Exception("FROM <string> value is missing !"); } } #endregion #region HEADER // HEADER <field-name> <string> // Messages that have a header with the specified field-name (as // defined in [RFC-2822]) and that contains the specified string // in the text of the header (what comes after the colon). If the // string to search is zero-length, this matches all messages that // have a header line with the specified field-name regardless of // the contents. else if (word == "HEADER") { searchKeyName = "HEADER"; // Read <field-name> string fieldName = ReadString(reader); if (fieldName != null) { fieldName = TextUtils.UnQuoteString(fieldName); } else { throw new Exception("HEADER <field-name> value is missing !"); } // Read <string> string val = ReadString(reader); if (val != null) { searchKeyValue = new[] {fieldName, TextUtils.UnQuoteString(val)}; } else { throw new Exception("(HEADER <field-name>) <string> value is missing !"); } } #endregion #region KEYWORD // KEYWORD <flag> // Messages with the specified keyword flag set. else if (word == "KEYWORD") { searchKeyName = "KEYWORD"; // Read <flag> string val = reader.QuotedReadToDelimiter(' '); if (val != null) { searchKeyValue = TextUtils.UnQuoteString(val); } else { throw new Exception("KEYWORD <flag> value is missing !"); } } #endregion #region LARGER // LARGER <n> // Messages with an [RFC-2822] size larger than the specified number of octets. else if (word == "LARGER") { searchKeyName = "LARGER"; // Read <n> string val = reader.QuotedReadToDelimiter(' '); if (val != null) { // Parse <n> - must be integer value try { searchKeyValue = Convert.ToInt64(TextUtils.UnQuoteString(val)); } // Invalid <n> catch { throw new Exception("Invalid LARGER <n> value '" + val + "', it must be numeric value !"); } } else { throw new Exception("LARGER <n> value is missing !"); } } #endregion #region NEW // NEW // Messages that have the \Recent flag set but not the \Seen flag. // This is functionally equivalent to "(RECENT UNSEEN)". else if (word == "NEW") { // We internally use KEYWORD RECENT searchKeyName = "KEYWORD"; searchKeyValue = "RECENT"; } #endregion #region NOT // NOT <search-key> or (<search-key> <search-key> ...)(SearchGroup) // Messages that do not match the specified search key. else if (word == "NOT") { searchKeyName = "NOT"; object searchItem = SearchGroup.ParseSearchKey(reader); if (searchItem != null) { searchKeyValue = searchItem; } else { throw new Exception("Required NOT <search-key> isn't specified !"); } } #endregion #region OLD // OLD // Messages that do not have the \Recent flag set. This is // functionally equivalent to "NOT RECENT" (as opposed to "NOT NEW"). else if (word == "OLD") { // We internally use UNKEYWORD RECENT searchKeyName = "UNKEYWORD"; searchKeyValue = "RECENT"; } #endregion #region ON // ON <date> // Messages whose internal date (disregarding time and timezone) is within the specified date. else if (word == "ON") { searchKeyName = "ON"; // Read <date> string val = reader.QuotedReadToDelimiter(' '); if (val != null) { // Parse date try { searchKeyValue = IMAP_Utils.ParseDate(TextUtils.UnQuoteString(val)); } // Invalid date catch { throw new Exception("Invalid ON <date> value '" + val + "', valid date syntax: {dd-MMM-yyyy} !"); } } else { throw new Exception("ON <date> value is missing !"); } } #endregion #region OR // OR <search-key1> <search-key2> - SearckKey can be parenthesis list of keys ! // Messages that match either search key. else if (word == "OR") { searchKeyName = "OR"; //--- <search-key1> ----------------------------------------------------// object searchKey1 = SearchGroup.ParseSearchKey(reader); if (searchKey1 == null) { throw new Exception("Required OR <search-key1> isn't specified !"); } //----------------------------------------------------------------------// //--- <search-key2> ----------------------------------------------------// object searchKey2 = SearchGroup.ParseSearchKey(reader); if (searchKey2 == null) { throw new Exception("Required (OR <search-key1>) <search-key2> isn't specified !"); } //-----------------------------------------------------------------------// searchKeyValue = new[] {searchKey1, searchKey2}; } #endregion #region RECENT // RECENT // Messages that have the \Recent flag set. else if (word == "RECENT") { // We internally use KEYWORD RECENT searchKeyName = "KEYWORD"; searchKeyValue = "RECENT"; } #endregion #region SEEN // SEEN // Messages that have the \Seen flag set. else if (word == "SEEN") { // We internally use KEYWORD SEEN searchKeyName = "KEYWORD"; searchKeyValue = "SEEN"; } #endregion #region SENTBEFORE // SENTBEFORE <date> // Messages whose [RFC-2822] Date: header (disregarding time and // timezone) is earlier than the specified date. else if (word == "SENTBEFORE") { searchKeyName = "SENTBEFORE"; // Read <date> string val = reader.QuotedReadToDelimiter(' '); if (val != null) { // Parse date try { searchKeyValue = IMAP_Utils.ParseDate(TextUtils.UnQuoteString(val)); } // Invalid date catch { throw new Exception("Invalid SENTBEFORE <date> value '" + val + "', valid date syntax: {dd-MMM-yyyy} !"); } } else { throw new Exception("SENTBEFORE <date> value is missing !"); } } #endregion #region SENTON // SENTON <date> // Messages whose [RFC-2822] Date: header (disregarding time and // timezone) is within the specified date. else if (word == "SENTON") { searchKeyName = "SENTON"; // Read <date> string val = reader.QuotedReadToDelimiter(' '); if (val != null) { // Parse date try { searchKeyValue = IMAP_Utils.ParseDate(TextUtils.UnQuoteString(val)); } // Invalid date catch { throw new Exception("Invalid SENTON <date> value '" + val + "', valid date syntax: {dd-MMM-yyyy} !"); } } else { throw new Exception("SENTON <date> value is missing !"); } } #endregion #region SENTSINCE // SENTSINCE <date> // Messages whose [RFC-2822] Date: header (disregarding time and // timezone) is within or later than the specified date. else if (word == "SENTSINCE") { searchKeyName = "SENTSINCE"; // Read <date> string val = reader.QuotedReadToDelimiter(' '); if (val != null) { // Parse date try { searchKeyValue = IMAP_Utils.ParseDate(TextUtils.UnQuoteString(val)); } // Invalid date catch { throw new Exception("Invalid SENTSINCE <date> value '" + val + "', valid date syntax: {dd-MMM-yyyy} !"); } } else { throw new Exception("SENTSINCE <date> value is missing !"); } } #endregion #region SINCE // SINCE <date> // Messages whose internal date (disregarding time and timezone) // is within or later than the specified date. else if (word == "SINCE") { searchKeyName = "SINCE"; // Read <date> string val = reader.ReadWord(); if (val != null) { // Parse date try { searchKeyValue = IMAP_Utils.ParseDate(TextUtils.UnQuoteString(val)); } // Invalid date catch { throw new Exception("Invalid SINCE <date> value '" + val + "', valid date syntax: {dd-MMM-yyyy} !"); } } else { throw new Exception("SINCE <date> value is missing !"); } } #endregion #region SMALLER // SMALLER <n> // Messages with an [RFC-2822] size smaller than the specified number of octets. else if (word == "SMALLER") { searchKeyName = "SMALLER"; // Read <n> string val = reader.QuotedReadToDelimiter(' '); if (val != null) { val = TextUtils.UnQuoteString(val); // Parse <n> - must be integer value try { searchKeyValue = Convert.ToInt64(val); } // Invalid <n> catch { throw new Exception("Invalid SMALLER <n> value '" + val + "', it must be numeric value !"); } } else { throw new Exception("SMALLER <n> value is missing !"); } } #endregion #region SUBJECT // SUBJECT <string> // Messages that contain the specified string in the envelope structure's SUBJECT field. else if (word == "SUBJECT") { // We internally use HEADER "SUBJECT:" "value" searchKeyName = "HEADER"; // Read <string> string val = ReadString(reader); if (val != null) { searchKeyValue = new[] {"SUBJECT:", TextUtils.UnQuoteString(val)}; } else { throw new Exception("SUBJECT <string> value is missing !"); } } #endregion #region TEXT // TEXT <string> // Messages that contain the specified string in the header or body of the message. else if (word == "TEXT") { searchKeyName = "TEXT"; string val = ReadString(reader); if (val != null) { searchKeyValue = val; } else { throw new Exception("TEXT <string> value is missing !"); } } #endregion #region TO // TO <string> // Messages that contain the specified string in the envelope structure's TO field. else if (word == "TO") { // We internally use HEADER "TO:" "value" searchKeyName = "HEADER"; // Read <string> string val = ReadString(reader); if (val != null) { searchKeyValue = new[] {"TO:", TextUtils.UnQuoteString(val)}; } else { throw new Exception("TO <string> value is missing !"); } } #endregion #region UID // UID <sequence set> // Messages with unique identifiers corresponding to the specified // unique identifier set. Sequence set ranges are permitted. else if (word == "UID") { searchKeyName = "UID"; // Read <sequence set> string val = reader.QuotedReadToDelimiter(' '); if (val != null) { try { IMAP_SequenceSet sequenceSet = new IMAP_SequenceSet(); sequenceSet.Parse(TextUtils.UnQuoteString(val), long.MaxValue); searchKeyValue = sequenceSet; } catch { throw new Exception("Invalid UID <sequence-set> value '" + val + "' !"); } } else { throw new Exception("UID <sequence-set> value is missing !"); } } #endregion #region UNANSWERED // UNANSWERED // Messages that do not have the \Answered flag set. else if (word == "UNANSWERED") { // We internally use UNKEYWORD SEEN searchKeyName = "UNKEYWORD"; searchKeyValue = "ANSWERED"; } #endregion #region UNDELETED // UNDELETED // Messages that do not have the \Deleted flag set. else if (word == "UNDELETED") { // We internally use UNKEYWORD UNDELETED searchKeyName = "UNKEYWORD"; searchKeyValue = "DELETED"; } #endregion #region UNDRAFT // UNDRAFT // Messages that do not have the \Draft flag set. else if (word == "UNDRAFT") { // We internally use UNKEYWORD UNDRAFT searchKeyName = "UNKEYWORD"; searchKeyValue = "DRAFT"; } #endregion #region UNFLAGGED // UNFLAGGED // Messages that do not have the \Flagged flag set. else if (word == "UNFLAGGED") { // We internally use UNKEYWORD UNFLAGGED searchKeyName = "UNKEYWORD"; searchKeyValue = "FLAGGED"; } #endregion #region UNKEYWORD // UNKEYWORD <flag> // Messages that do not have the specified keyword flag set. else if (word == "UNKEYWORD") { searchKeyName = "UNKEYWORD"; // Read <flag> string val = reader.QuotedReadToDelimiter(' '); if (val != null) { searchKeyValue = TextUtils.UnQuoteString(val); } else { throw new Exception("UNKEYWORD <flag> value is missing !"); } } #endregion #region UNSEEN // UNSEEN // Messages that do not have the \Seen flag set. else if (word == "UNSEEN") { // We internally use UNKEYWORD UNSEEN searchKeyName = "UNKEYWORD"; searchKeyValue = "SEEN"; } #endregion #region Unknown or SEQUENCESET // Unkown keyword or <sequence set> else { // DUMMY palce(bad design) in IMAP. // Active keyword can be <sequence set> or bad keyword, there is now way to distinguish what is meant. // Why they don't key work SEQUENCESET <sequence set> ? // <sequence set> // Messages with message sequence numbers corresponding to the // specified message sequence number set. // Just try if it can be parsed as sequence-set try { IMAP_SequenceSet sequenceSet = new IMAP_SequenceSet(); sequenceSet.Parse(word, long.MaxValue); searchKeyName = "SEQUENCESET"; searchKeyValue = sequenceSet; } // This isn't vaild sequnce-set value catch { throw new Exception("Invalid search key or <sequnce-set> value '" + word + "' !"); } } #endregion // REMOVE ME: // Console.WriteLine(searchKeyName + " : " + Convert.ToString(searchKeyValue)); return new SearchKey(searchKeyName, searchKeyValue); } // TODO: We have envelope, see if Header is needed or can use envelope for it /// <summary> /// Gets if message Header is needed for matching. /// </summary> /// <returns></returns> public bool IsHeaderNeeded() { if (m_SearchKeyName == "HEADER") { return true; } else if (m_SearchKeyName == "NOT") { return SearchGroup.IsHeaderNeededForKey(m_SearchKeyValue); } else if (m_SearchKeyName == "OR") { object serachKey1 = ((object[]) m_SearchKeyValue)[0]; object serachKey2 = ((object[]) m_SearchKeyValue)[1]; if (SearchGroup.IsHeaderNeededForKey(serachKey1) || SearchGroup.IsHeaderNeededForKey(serachKey2)) { return true; } } else if (m_SearchKeyName == "SENTBEFORE") { return true; } else if (m_SearchKeyName == "SENTON") { return true; } else if (m_SearchKeyName == "SENTSINCE") { return true; } else if (m_SearchKeyName == "TEXT") { return true; } return false; } /// <summary> /// Gets if message body text is needed for matching. /// </summary> /// <returns></returns> public bool IsBodyTextNeeded() { if (m_SearchKeyName == "BODY") { return true; } else if (m_SearchKeyName == "NOT") { return SearchGroup.IsBodyTextNeededForKey(m_SearchKeyValue); } else if (m_SearchKeyName == "OR") { object serachKey1 = ((object[]) m_SearchKeyValue)[0]; object serachKey2 = ((object[]) m_SearchKeyValue)[1]; if (SearchGroup.IsBodyTextNeededForKey(serachKey1) || SearchGroup.IsBodyTextNeededForKey(serachKey2)) { return true; } } else if (m_SearchKeyName == "TEXT") { return true; } return false; } /// <summary> /// Gets if specified message matches with this class search-key. /// </summary> /// <param name="no">IMAP message sequence number.</param> /// <param name="uid">IMAP message UID.</param> /// <param name="size">IMAP message size in bytes.</param> /// <param name="internalDate">IMAP message INTERNALDATE (dateTime when server stored message).</param> /// <param name="flags">IMAP message flags.</param> /// <param name="mime">Mime message main header only.</param> /// <param name="bodyText">Message body text.</param> /// <returns></returns> public bool Match(long no, long uid, long size, DateTime internalDate, IMAP_MessageFlags flags, Mime mime, string bodyText) { #region ALL // ALL // All messages in the mailbox; the default initial key for ANDing. if (m_SearchKeyName == "ALL") { return true; } #endregion #region BEFORE // BEFORE <date> // Messages whose internal date (disregarding time and timezone) // is earlier than the specified date. else if (m_SearchKeyName == "BEFORE") { if (internalDate.Date < (DateTime) m_SearchKeyValue) { return true; } } #endregion #region BODY // BODY <string> // Messages that contain the specified string in the body of the message. // // NOTE: Compare must be done on decoded header and decoded body of message. // In all search keys that use strings, a message matches the key if // the string is a substring of the field. The matching is case-insensitive. else if (m_SearchKeyName == "BODY") { string val = bodyText; if (val != null && val.ToLower().IndexOf(((string) m_SearchKeyValue).ToLower()) > -1) { return true; } } #endregion #region HEADER // HEADER <field-name> <string> // Messages that have a header with the specified field-name (as // defined in [RFC-2822]) and that contains the specified string // in the text of the header (what comes after the colon). If the // string to search is zero-length, this matches all messages that // have a header line with the specified field-name regardless of // the contents. // // NOTE: Compare must be done on decoded header field value. // In all search keys that use strings, a message matches the key if // the string is a substring of the field. The matching is case-insensitive. else if (m_SearchKeyName == "HEADER") { string[] headerField_value = (string[]) m_SearchKeyValue; // If header field name won't end with :, add it if (!headerField_value[0].EndsWith(":")) { headerField_value[0] = headerField_value[0] + ":"; } if (mime.MainEntity.Header.Contains(headerField_value[0])) { if (headerField_value[1].Length == 0) { return true; } else if ( mime.MainEntity.Header.GetFirst(headerField_value[0]).Value.ToLower().IndexOf( headerField_value[1].ToLower()) > -1) { return true; } } } #endregion #region KEYWORD // KEYWORD <flag> // Messages with the specified keyword flag set. else if (m_SearchKeyName == "KEYWORD") { if ((flags & IMAP_Utils.ParseMessageFlags((string) m_SearchKeyValue)) != 0) { return true; } } #endregion #region LARGER // LARGER <n> // Messages with an [RFC-2822] size larger than the specified number of octets. else if (m_SearchKeyName == "LARGER") { if (size > (long) m_SearchKeyValue) { return true; } } #endregion #region NOT // NOT <search-key> or (<search-key> <search-key> ...)(SearchGroup) // Messages that do not match the specified search key. else if (m_SearchKeyName == "NOT") { return !SearchGroup.Match_Key_Value(m_SearchKeyValue, no, uid, size, internalDate, flags, mime, bodyText); } #endregion #region ON // ON <date> // Messages whose internal date (disregarding time and timezone) // is within the specified date. else if (m_SearchKeyName == "ON") { if (internalDate.Date == (DateTime) m_SearchKeyValue) { return true; } } #endregion #region OR // OR <search-key1> <search-key2> - SearckKey can be parenthesis list of keys ! // Messages that match either search key. else if (m_SearchKeyName == "OR") { object serachKey1 = ((object[]) m_SearchKeyValue)[0]; object serachKey2 = ((object[]) m_SearchKeyValue)[1]; if ( SearchGroup.Match_Key_Value(serachKey1, no, uid, size, internalDate, flags, mime, bodyText) || SearchGroup.Match_Key_Value(serachKey2, no, uid, size, internalDate, flags, mime, bodyText)) { return true; } } #endregion #region SENTBEFORE // SENTBEFORE <date> // Messages whose [RFC-2822] Date: header (disregarding time and // timezone) is earlier than the specified date. else if (m_SearchKeyName == "SENTBEFORE") { if (mime.MainEntity.Date.Date < (DateTime) m_SearchKeyValue) { return true; } } #endregion #region SENTON // SENTON <date> // Messages whose [RFC-2822] Date: header (disregarding time and // timezone) is within the specified date. else if (m_SearchKeyName == "SENTON") { if (mime.MainEntity.Date.Date == (DateTime) m_SearchKeyValue) { return true; } } #endregion #region SENTSINCE // SENTSINCE <date> // Messages whose [RFC-2822] Date: header (disregarding time and // timezone) is within or later than the specified date. else if (m_SearchKeyName == "SENTSINCE") { if (mime.MainEntity.Date.Date >= (DateTime) m_SearchKeyValue) { return true; } } #endregion #region SINCE // SINCE <date> // Messages whose internal date (disregarding time and timezone) // is within or later than the specified date. else if (m_SearchKeyName == "SINCE") { if (internalDate.Date >= (DateTime) m_SearchKeyValue) { return true; } } #endregion #region SMALLER // SMALLER <n> // Messages with an [RFC-2822] size smaller than the specified number of octets. else if (m_SearchKeyName == "SMALLER") { if (size < (long) m_SearchKeyValue) { return true; } } #endregion #region TEXT // TEXT <string> // Messages that contain the specified string in the header or body of the message. // // NOTE: Compare must be done on decoded header and decoded body of message. // In all search keys that use strings, a message matches the key if // the string is a substring of the field. The matching is case-insensitive. else if (m_SearchKeyName == "TEXT") { // See body first string val = bodyText; if (val != null && val.ToLower().IndexOf(((string) m_SearchKeyValue).ToLower()) > -1) { return true; } // If we reach so far, that means body won't contain specified text and we need to check header. foreach (HeaderField headerField in mime.MainEntity.Header) { if (headerField.Value.ToLower().IndexOf(((string) m_SearchKeyValue).ToLower()) > -1) { return true; } } } #endregion #region UID // UID <sequence set> // Messages with unique identifiers corresponding to the specified // unique identifier set. Sequence set ranges are permitted. else if (m_SearchKeyName == "UID") { return ((IMAP_SequenceSet) m_SearchKeyValue).Contains(uid); } #endregion #region UNKEYWORD // UNKEYWORD <flag> // Messages that do not have the specified keyword flag set. else if (m_SearchKeyName == "UNKEYWORD") { if ((flags & IMAP_Utils.ParseMessageFlags((string) m_SearchKeyValue)) == 0) { return true; } } #endregion #region SEQUENCESET // <sequence set> // Messages with message sequence numbers corresponding to the // specified message sequence number set. else if (m_SearchKeyName == "SEQUENCESET") { return ((IMAP_SequenceSet) m_SearchKeyValue).Contains(no); } #endregion return false; } #endregion #region Utility methods /// <summary> /// Reads search-key &lt;string&gt; value. /// </summary> /// <param name="reader"></param> /// <returns></returns> private static string ReadString(StringReader reader) { //Remove spaces from string start reader.ReadToFirstChar(); // We must support: // word // "text" // {string_length}data(string_length) // {string_length}data(string_length) if (reader.StartsWith("{")) { // Remove { reader.ReadSpecifiedLength("{".Length); int dataLength = Convert.ToInt32(reader.QuotedReadToDelimiter('}')); return reader.ReadSpecifiedLength(dataLength); } return TextUtils.UnQuoteString(reader.QuotedReadToDelimiter(' ')); } #endregion } }<file_sep>/redistributable/Twitterizer2/Twitterizer2/Core/TwitterImage.cs namespace Twitterizer { using System; using System.IO; /// <summary> /// The image type that is being uploaded. /// </summary> #if !SILVERLIGHT [Serializable] #endif public enum TwitterImageImageType { /// <summary> /// JPEG /// </summary> Jpeg, /// <summary> /// GIF /// </summary> Gif, /// <summary> /// PNG /// </summary> PNG } /// <summary> /// Represents an image for uploading. Used to upload new profile and background images. /// </summary> #if !SILVERLIGHT [Serializable] #endif public class TwitterImage { /// <summary> /// Gets or sets the filename. /// </summary> /// <value>The filename.</value> public string Filename { get; set; } /// <summary> /// Gets or sets the data. /// </summary> /// <value>The data.</value> public byte[] Data { get; set; } /// <summary> /// Gets or sets the type of the image. /// </summary> /// <value>The type of the image.</value> public TwitterImageImageType ImageType { get; set; } /// <summary> /// Gets the image's MIME type. /// </summary> /// <returns></returns> public string GetMimeType() { switch (this.ImageType) { case TwitterImageImageType.Jpeg: return "image/jpeg"; case TwitterImageImageType.Gif: return "image/gif"; case TwitterImageImageType.PNG: return "image/png"; default: throw new ArgumentOutOfRangeException(); } } /// <summary> /// Reads a file from the disk and returns a <see cref="TwitterImage"/> instance for uploading. /// </summary> /// <param name="filePath">The file path.</param> /// <returns></returns> public static TwitterImage ReadFromDisk(string filePath) { if (!File.Exists(filePath)) { throw new ArgumentException(string.Format("File does not be exist: {0}.", filePath)); } TwitterImage newImage = new TwitterImage(); newImage.Data = File.ReadAllBytes(filePath); FileInfo imageFileInfo = new FileInfo(filePath); newImage.Filename = imageFileInfo.Name; switch (imageFileInfo.Extension.ToLower()) { case ".jpg": case ".jpeg": newImage.ImageType = TwitterImageImageType.Jpeg; break; case ".gif": newImage.ImageType = TwitterImageImageType.Gif; break; case ".png": newImage.ImageType = TwitterImageImageType.PNG; break; default: throw new Exception("File is not a recognized type. Must be jpg, png, or gif."); } return newImage; } } } <file_sep>/module/ASC.Socket.IO/app/middleware/auth.js module.exports = function (socket, next) { const apiRequestManager = require('../apiRequestManager.js'); const req = socket.client.request; const authService = require('./authService.js')(); const co = require('co'); const session = socket.handshake.session; if (req.user) { next(); return; } if (!req.cookies || (!req.cookies['asc_auth_key'] && !req.cookies['authorization'])) { socket.disconnect('unauthorized'); next(new Error('Authentication error')); return; } if(session && session.user && session.portal && typeof(session.mailEnabled) !== "undefined") { req.user = session.user; req.portal = session.portal; req.mailEnabled = session.mailEnabled; next(); return; } if(req.cookies['authorization']){ if(!authService(req)){ next(new Error('Authentication error')); } else{ next(); } return; } co(function*(){ var batchRequest = apiRequestManager.batchFactory() .get("<EMAIL>.<EMAIL>?fields=id,userName,displayName") .get("portal.json?fields=tenantId,tenantDomain") .get("settings/security/2A923037-8B2D-487b-9A22-5AC0918ACF3F"); [session.user, session.portal, session.mailEnabled] = [req.user, req.portal, req.mailEnabled] = yield apiRequestManager.batch(batchRequest, req); session.save(); next(); }).catch((err) => { socket.disconnect('unauthorized'); next(new Error('Authentication error')); }); }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/SMTP/Server/SMTP_Server.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.SMTP.Server { #region usings using System; using System.Collections.Generic; using TCP; #endregion /// <summary> /// This class implements SMTP server. Defined RFC 5321. /// </summary> public class SMTP_Server : TCP_Server<SMTP_Session> { #region Members private readonly List<string> m_pServiceExtentions; private string m_GreetingText = ""; private int m_MaxBadCommands = 30; private int m_MaxMessageSize = 10000000; private int m_MaxRecipients = 100; private int m_MaxTransactions = 10; #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> public SMTP_Server() { m_pServiceExtentions = new List<string>(); m_pServiceExtentions.Add(SMTP_ServiceExtensions.PIPELINING); m_pServiceExtentions.Add(SMTP_ServiceExtensions.SIZE); m_pServiceExtentions.Add(SMTP_ServiceExtensions.STARTTLS); m_pServiceExtentions.Add(SMTP_ServiceExtensions._8BITMIME); m_pServiceExtentions.Add(SMTP_ServiceExtensions.BINARYMIME); m_pServiceExtentions.Add(SMTP_ServiceExtensions.CHUNKING); } #endregion #region Properties /// <summary> /// Gets or sets server greeting text. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> public string GreetingText { get { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_GreetingText; } set { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } m_GreetingText = value; } } /// <summary> /// Gets or sets how many bad commands session can have before it's terminated. Value 0 means unlimited. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> /// <exception cref="ArgumentException">Is raised when invalid value is passed.</exception> public int MaxBadCommands { get { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_MaxBadCommands; } set { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (value < 0) { throw new ArgumentException("Property 'MaxBadCommands' value must be >= 0."); } m_MaxBadCommands = value; } } /// <summary> /// Gets or sets maximum message size in bytes. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> /// <exception cref="ArgumentException">Is raised when invalid value is passed.</exception> public int MaxMessageSize { get { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_MaxMessageSize; } set { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (value < 500) { throw new ArgumentException("Property 'MaxMessageSize' value must be >= 500."); } m_MaxMessageSize = value; } } /// <summary> /// Gets or sets maximum allowed recipients per SMTP transaction. /// </summary> /// <remarks>According RFC 5321 this value SHOULD NOT be less than 100.</remarks> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> /// <exception cref="ArgumentException">Is raised when invalid value is passed.</exception> public int MaxRecipients { get { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_MaxRecipients; } set { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (value < 1) { throw new ArgumentException("Property 'MaxRecipients' value must be >= 1."); } m_MaxRecipients = value; } } /// <summary> /// Gets or sets maximum mail transactions per session. Value 0 means unlimited. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> /// <exception cref="ArgumentException">Is raised when invalid value is passed.</exception> public int MaxTransactions { get { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_MaxTransactions; } set { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (value < 0) { throw new ArgumentException("Property 'MaxTransactions' value must be >= 0."); } m_MaxTransactions = value; } } /// <summary> /// Gets or sets SMTP server supported service extentions. /// Supported values: PIPELINING,SIZE,STARTTLS,8BITMIME,BINARYMIME,CHUNKING,DSN. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> /// <exception cref="ArgumentNullException">Is raised when null reference passed.</exception> public string[] ServiceExtentions { get { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_pServiceExtentions.ToArray(); } set { if (value == null) { throw new ArgumentNullException("ServiceExtentions"); } m_pServiceExtentions.Clear(); foreach (string extention in value) { if (extention.ToUpper() == SMTP_ServiceExtensions.PIPELINING) { m_pServiceExtentions.Add(SMTP_ServiceExtensions.PIPELINING); } else if (extention.ToUpper() == SMTP_ServiceExtensions.SIZE) { m_pServiceExtentions.Add(SMTP_ServiceExtensions.SIZE); } else if (extention.ToUpper() == SMTP_ServiceExtensions.STARTTLS) { m_pServiceExtentions.Add(SMTP_ServiceExtensions.STARTTLS); } else if (extention.ToUpper() == SMTP_ServiceExtensions._8BITMIME) { m_pServiceExtentions.Add(SMTP_ServiceExtensions._8BITMIME); } else if (extention.ToUpper() == SMTP_ServiceExtensions.BINARYMIME) { m_pServiceExtentions.Add(SMTP_ServiceExtensions.BINARYMIME); } else if (extention.ToUpper() == SMTP_ServiceExtensions.CHUNKING) { m_pServiceExtentions.Add(SMTP_ServiceExtensions.CHUNKING); } else if (extention.ToUpper() == SMTP_ServiceExtensions.DSN) { m_pServiceExtentions.Add(SMTP_ServiceExtensions.DSN); } } } } /// <summary> /// Gets SMTP service extentions list. /// </summary> internal List<string> Extentions { get { return m_pServiceExtentions; } } #endregion // TODO: //public override Dispose #region Overrides /// <summary> /// Is called when new incoming session and server maximum allowed connections exceeded. /// </summary> /// <param name="session">Incoming session.</param> /// <remarks>This method allows inhereted classes to report error message to connected client. /// Session will be disconnected after this method completes. /// </remarks> protected override void OnMaxConnectionsExceeded(SMTP_Session session) { session.TcpStream.WriteLine( "421 Client host rejected: too many connections, please try again later."); } /// <summary> /// Is called when new incoming session and server maximum allowed connections per connected IP exceeded. /// </summary> /// <param name="session">Incoming session.</param> /// <remarks>This method allows inhereted classes to report error message to connected client. /// Session will be disconnected after this method completes. /// </remarks> protected override void OnMaxConnectionsPerIPExceeded(SMTP_Session session) { session.TcpStream.WriteLine("421 Client host rejected: too many connections from your IP(" + session.RemoteEndPoint.Address + "), please try again later."); } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/SIP/Message/SIP_t_AuthenticationInfo.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.SIP.Message { #region usings using System; using System.Text; #endregion /// <summary> /// Implements SIP "Authentication-Info" value. Defined in RFC 3261. /// According RFC 3261 authentication info can contain Digest authentication info only. /// </summary> public class SIP_t_AuthenticationInfo : SIP_t_Value { #region Members private string m_CNonce; private string m_NextNonce; private int m_NonceCount = -1; private string m_Qop; private string m_ResponseAuth; #endregion #region Properties /// <summary> /// Gets or sets server next predicted nonce value. Value null means that value not specified. /// </summary> public string NextNonce { get { return m_NextNonce; } set { m_NextNonce = value; } } /// <summary> /// Gets or sets QOP value. Value null means that value not specified. /// </summary> public string Qop { get { return m_Qop; } set { m_Qop = value; } } /// <summary> /// Gets or sets rspauth value. Value null means that value not specified. /// This can be only HEX value. /// </summary> public string ResponseAuth { get { return m_ResponseAuth; } set { // TODO: Check that value is hex value m_ResponseAuth = value; } } /// <summary> /// Gets or sets cnonce value. Value null means that value not specified. /// </summary> public string CNonce { get { return m_CNonce; } set { m_CNonce = value; } } /// <summary> /// Gets or sets nonce count. Value -1 means that value not specified. /// </summary> public int NonceCount { get { return m_NonceCount; } set { if (value < 0) { m_NonceCount = -1; } else { m_NonceCount = value; } } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="value">Authentication-Info valu value.</param> public SIP_t_AuthenticationInfo(string value) { Parse(new StringReader(value)); } #endregion #region Methods /// <summary> /// Parses "Authentication-Info" from specified value. /// </summary> /// <param name="value">SIP "Authentication-Info" value.</param> /// <exception cref="ArgumentNullException">Raised when <b>value</b> is null.</exception> /// <exception cref="SIP_ParseException">Raised when invalid SIP message.</exception> public void Parse(string value) { if (value == null) { throw new ArgumentNullException("value"); } Parse(new StringReader(value)); } /// <summary> /// Parses "Authentication-Info" from specified reader. /// </summary> /// <param name="reader">Reader what contains Authentication-Info value.</param> /// <exception cref="ArgumentNullException">Raised when <b>reader</b> is null.</exception> /// <exception cref="SIP_ParseException">Raised when invalid SIP message.</exception> public override void Parse(StringReader reader) { /* Authentication-Info = "Authentication-Info" HCOLON ainfo *(COMMA ainfo) ainfo = nextnonce / message-qop / response-auth / cnonce / nonce-count nextnonce = "nextnonce" EQUAL nonce-value response-auth = "rspauth" EQUAL response-digest response-digest = LDQUOT *LHEX RDQUOT nc-value = 8LHEX */ if (reader == null) { throw new ArgumentNullException("reader"); } while (reader.Available > 0) { string word = reader.QuotedReadToDelimiter(','); if (word != null && word.Length > 0) { string[] name_value = word.Split(new[] {'='}, 2); if (name_value[0].ToLower() == "nextnonce") { NextNonce = name_value[1]; } else if (name_value[0].ToLower() == "qop") { Qop = name_value[1]; } else if (name_value[0].ToLower() == "rspauth") { ResponseAuth = name_value[1]; } else if (name_value[0].ToLower() == "cnonce") { CNonce = name_value[1]; } else if (name_value[0].ToLower() == "nc") { NonceCount = Convert.ToInt32(name_value[1]); } else { throw new SIP_ParseException("Invalid Authentication-Info value !"); } } } } /// <summary> /// Converts SIP_t_AuthenticationInfo to valid Authentication-Info value. /// </summary> /// <returns></returns> public override string ToStringValue() { /* Authentication-Info = "Authentication-Info" HCOLON ainfo *(COMMA ainfo) ainfo = nextnonce / message-qop / response-auth / cnonce / nonce-count nextnonce = "nextnonce" EQUAL nonce-value response-auth = "rspauth" EQUAL response-digest response-digest = LDQUOT *LHEX RDQUOT nc-value = 8LHEX */ StringBuilder retVal = new StringBuilder(); if (m_NextNonce != null) { retVal.Append("nextnonce=" + m_NextNonce); } if (m_Qop != null) { if (retVal.Length > 0) { retVal.Append(','); } retVal.Append("qop=" + m_Qop); } if (m_ResponseAuth != null) { if (retVal.Length > 0) { retVal.Append(','); } retVal.Append("rspauth=" + TextUtils.QuoteString(m_ResponseAuth)); } if (m_CNonce != null) { if (retVal.Length > 0) { retVal.Append(','); } retVal.Append("cnonce=" + m_CNonce); } if (m_NonceCount != -1) { if (retVal.Length > 0) { retVal.Append(','); } retVal.Append("nc=" + m_NonceCount.ToString("X8")); } return retVal.ToString(); } #endregion } }<file_sep>/common/ASC.Common/Data/StreamExtension.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.IO; using ASC.Data.Storage; public static class StreamExtension { private const int BufferSize = 2048; //NOTE: set to 2048 to fit in minimum tcp window public static Stream GetBuffered(this Stream srcStream) { if (srcStream == null) throw new ArgumentNullException("srcStream"); if (!srcStream.CanSeek || srcStream.CanTimeout) { //Buffer it var memStream = TempStream.Create(); srcStream.StreamCopyTo(memStream); memStream.Position = 0; return memStream; } return srcStream; } public static byte[] GetCorrectBuffer(this Stream stream) { if (stream == null) { throw new ArgumentNullException("stream"); } using (var mem = stream.GetBuffered()) { var buffer = new byte[mem.Length]; mem.Position = 0; mem.Read(buffer, 0, buffer.Length); return buffer; } } public static void StreamCopyTo(this Stream srcStream, Stream dstStream) { if (srcStream == null) throw new ArgumentNullException("srcStream"); if (dstStream == null) throw new ArgumentNullException("dstStream"); var buffer = new byte[BufferSize]; int readed; while ((readed = srcStream.Read(buffer, 0, BufferSize)) > 0) { dstStream.Write(buffer, 0, readed); } } public static void StreamCopyTo(this Stream srcStream, Stream dstStream, int length) { if (srcStream == null) throw new ArgumentNullException("srcStream"); if (dstStream == null) throw new ArgumentNullException("dstStream"); var buffer = new byte[BufferSize]; int totalRead = 0; int readed; while ((readed = srcStream.Read(buffer, 0, length - totalRead > BufferSize ? BufferSize : length - totalRead)) > 0 && totalRead < length) { dstStream.Write(buffer, 0, readed); totalRead += readed; } } } <file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/TCP/TCP_SessionCollection.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System.Collections; namespace ASC.Mail.Net.TCP { #region usings using System; using System.Collections.Generic; #endregion /// <summary> /// This class implements TCP session collection. /// </summary> public class TCP_SessionCollection<T>:IEnumerable<T> where T : TCP_Session { #region Members private readonly Dictionary<string, T> m_pItems; #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> internal TCP_SessionCollection() { m_pItems = new Dictionary<string, T>(); } #endregion #region Properties /// <summary> /// Gets number of items in the collection. /// </summary> public int Count { get { return m_pItems.Count; } } /// <summary> /// Gets TCP session with the specified ID. /// </summary> /// <param name="id">Session ID.</param> /// <returns>Returns TCP session with the specified ID.</returns> public T this[string id] { get { return m_pItems[id]; } } #endregion #region Methods /// <summary> /// Copies all TCP server session to new array. This method is thread-safe. /// </summary> /// <returns>Returns TCP sessions array.</returns> public T[] ToArray() { lock (m_pItems) { T[] retVal = new T[m_pItems.Count]; m_pItems.Values.CopyTo(retVal, 0); return retVal; } } #endregion #region Internal methods /// <summary> /// Adds specified TCP session to the colletion. /// </summary> /// <param name="session">TCP server session to add.</param> /// <exception cref="ArgumentNullException">Is raised when <b>session</b> is null.</exception> internal void Add(T session) { if (session == null) { throw new ArgumentNullException("session"); } lock (m_pItems) { m_pItems.Add(session.ID, session); } } /// <summary> /// Removes specified TCP server session from the collection. /// </summary> /// <param name="session">TCP server session to remove.</param> /// <exception cref="ArgumentNullException">Is raised when <b>session</b> is null.</exception> internal void Remove(T session) { if (session == null) { throw new ArgumentNullException("session"); } lock (m_pItems) { m_pItems.Remove(session.ID); } } /// <summary> /// Removes all items from the collection. /// </summary> internal void Clear() { lock (m_pItems) { m_pItems.Clear(); } } #endregion public IEnumerator<T> GetEnumerator() { return m_pItems.Values.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } }<file_sep>/web/studio/ASC.Web.Studio/Products/Community/Modules/Bookmarking/Core/Common/BookmarkingBusinessFactory.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System.Web; namespace ASC.Bookmarking.Common { public static class BookmarkingBusinessFactory { public static T GetObjectFromSession<T>() where T : class, new() { T obj; var key = typeof(T).ToString(); if (HttpContext.Current.Session != null) { obj = (T) HttpContext.Current.Session[key]; if (obj == null) { obj = new T(); HttpContext.Current.Session[key] = obj; } } else { obj = (T)HttpContext.Current.Items[key]; if (obj == null) { obj = new T(); HttpContext.Current.Items[key] = obj; } } return obj; } public static void UpdateObjectInSession<T>(T obj) where T : class, new() { var key = typeof(T).ToString(); if (HttpContext.Current.Session != null) { HttpContext.Current.Session[key] = obj; } else { HttpContext.Current.Items[key] = obj; } } public static void UpdateDisplayMode(BookmarkDisplayMode mode) { var key = typeof (BookmarkDisplayMode).Name; if (HttpContext.Current != null && HttpContext.Current.Session != null) HttpContext.Current.Session.Add(key, mode); } public static BookmarkDisplayMode GetDisplayMode() { var key = typeof (BookmarkDisplayMode).Name; if (HttpContext.Current != null && HttpContext.Current.Session != null) return (BookmarkDisplayMode) HttpContext.Current.Session[key]; return BookmarkDisplayMode.AllBookmarks; } } } <file_sep>/common/ASC.Data.Storage.Encryption/EncryptionService.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using ASC.Common.Threading.Progress; namespace ASC.Data.Storage.Encryption { class EncryptionService : IEncryptionService { public void Start(EncryptionSettings encryptionSettings, string serverRootPath) { EncryptionWorker.Start(encryptionSettings, serverRootPath); } public double GetProgress() { var progress = (ProgressBase)EncryptionWorker.GetProgress(); return progress != null ? progress.Percentage : -1; } public void Stop() { EncryptionWorker.Stop(); } } } <file_sep>/module/ASC.Api/ASC.Employee/EmployeeWraperFull.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using ASC.Api.Impl; using ASC.Core; using ASC.Core.Users; using ASC.Specific; using ASC.Web.Core.Users; namespace ASC.Api.Employee { [DataContract(Name = "person", Namespace = "")] public class EmployeeWraperFull : EmployeeWraper { [DataMember(Order = 10)] public string FirstName { get; set; } [DataMember(Order = 10)] public string LastName { get; set; } [DataMember(Order = 2)] public string UserName { get; set; } [DataMember(Order = 10)] public string Email { get; set; } [DataMember(Order = 12, EmitDefaultValue = false)] protected List<Contact> Contacts { get; set; } [DataMember(Order = 10, EmitDefaultValue = false)] public ApiDateTime Birthday { get; set; } [DataMember(Order = 10, EmitDefaultValue = false)] public string Sex { get; set; } [DataMember(Order = 10)] public EmployeeStatus Status { get; set; } [DataMember(Order = 10)] public EmployeeActivationStatus ActivationStatus { get; set; } [DataMember(Order = 10)] public ApiDateTime Terminated { get; set; } [DataMember(Order = 10, EmitDefaultValue = false)] public string Department { get; set; } [DataMember(Order = 10, EmitDefaultValue = false)] public ApiDateTime WorkFrom { get; set; } [DataMember(Order = 20, EmitDefaultValue = false)] public List<GroupWrapperSummary> Groups { get; set; } [DataMember(Order = 10, EmitDefaultValue = false)] public string Location { get; set; } [DataMember(Order = 10, EmitDefaultValue = false)] public string Notes { get; set; } [DataMember(Order = 20)] public string AvatarMedium { get; set; } [DataMember(Order = 20)] public string Avatar { get; set; } [DataMember(Order = 20)] public bool IsAdmin { get; set; } [DataMember(Order = 20)] public bool IsLDAP { get; set; } [DataMember(Order = 20, EmitDefaultValue = false)] public List<string> ListAdminModules { get; set; } [DataMember(Order = 20)] public bool IsOwner { get; set; } [DataMember(Order = 2)] public bool IsVisitor { get; set; } [DataMember(Order = 20, EmitDefaultValue = false)] public string CultureName { get; set; } [DataMember(Order = 11, EmitDefaultValue = false)] protected String MobilePhone { get; set; } [DataMember(Order = 11, EmitDefaultValue = false)] protected MobilePhoneActivationStatus MobilePhoneActivationStatus { get; set; } [DataMember(Order = 20)] public bool IsSSO { get; set; } public EmployeeWraperFull() { } public EmployeeWraperFull(UserInfo userInfo) : this(userInfo, null) { } public EmployeeWraperFull(UserInfo userInfo, ApiContext context) : base(userInfo, context) { UserName = userInfo.UserName; IsVisitor = userInfo.IsVisitor(); FirstName = userInfo.FirstName; LastName = userInfo.LastName; Birthday = (ApiDateTime)userInfo.BirthDate; if (userInfo.Sex.HasValue) Sex = userInfo.Sex.Value ? "male" : "female"; Status = userInfo.Status; ActivationStatus = userInfo.ActivationStatus & ~EmployeeActivationStatus.AutoGenerated; Terminated = (ApiDateTime)userInfo.TerminatedDate; WorkFrom = (ApiDateTime)userInfo.WorkFromDate; Email = userInfo.Email; if (!string.IsNullOrEmpty(userInfo.Location)) { Location = userInfo.Location; } if (!string.IsNullOrEmpty(userInfo.Notes)) { Notes = userInfo.Notes; } if (!string.IsNullOrEmpty(userInfo.MobilePhone)) { MobilePhone = userInfo.MobilePhone; } MobilePhoneActivationStatus = userInfo.MobilePhoneActivationStatus; if (!string.IsNullOrEmpty(userInfo.CultureName)) { CultureName = userInfo.CultureName; } FillConacts(userInfo); if (CheckContext(context, "groups") || CheckContext(context, "department")) { var groups = CoreContext.UserManager.GetUserGroups(userInfo.ID).Select(x => new GroupWrapperSummary(x)).ToList(); if (groups.Any()) { Groups = groups; Department = string.Join(", ", Groups.Select(d => d.Name.HtmlEncode())); } else { Department = ""; } } if (CheckContext(context, "avatarMedium")) { AvatarMedium = UserPhotoManager.GetMediumPhotoURL(userInfo.ID) + "?_=" + userInfo.LastModified.GetHashCode(); } if (CheckContext(context, "avatar")) { Avatar = UserPhotoManager.GetBigPhotoURL(userInfo.ID) + "?_=" + userInfo.LastModified.GetHashCode(); } IsAdmin = userInfo.IsAdmin(); if (CheckContext(context, "listAdminModules")) { var listAdminModules = userInfo.GetListAdminModules(); if (listAdminModules.Any()) ListAdminModules = listAdminModules; } IsOwner = userInfo.IsOwner(); IsLDAP = userInfo.IsLDAP(); IsSSO = userInfo.IsSSO(); } private void FillConacts(UserInfo userInfo) { var contacts = new List<Contact>(); for (var i = 0; i < userInfo.Contacts.Count; i += 2) { if (i + 1 < userInfo.Contacts.Count) { contacts.Add(new Contact(userInfo.Contacts[i], userInfo.Contacts[i + 1])); } } if (contacts.Any()) { Contacts = contacts; } } public static bool CheckContext(ApiContext context, string field) { return context == null || context.Fields == null || (context.Fields != null && context.Fields.Contains(field)); } public static EmployeeWraperFull GetFull(Guid userId) { try { return GetFull(CoreContext.UserManager.GetUsers(userId)); } catch (Exception) { return GetFull(Core.Users.Constants.LostUser); } } public static EmployeeWraperFull GetFull(UserInfo userInfo) { return new EmployeeWraperFull(userInfo); } public new static EmployeeWraperFull GetSample() { return new EmployeeWraperFull { Avatar = "url to big avatar", AvatarSmall = "url to small avatar", Contacts = new List<Contact> { Contact.GetSample() }, Email = "<EMAIL>", FirstName = "Mike", Id = Guid.Empty, IsAdmin = false, ListAdminModules = new List<string> {"projects", "crm"}, UserName = "Mike.Zanyatski", LastName = "Zanyatski", Title = "Manager", Groups = new List<GroupWrapperSummary> { GroupWrapperSummary.GetSample() }, AvatarMedium = "url to medium avatar", Birthday = ApiDateTime.GetSample(), Department = "Marketing", Location = "Palo Alto", Notes = "Notes to worker", Sex = "male", Status = EmployeeStatus.Active, WorkFrom = ApiDateTime.GetSample(), //Terminated = ApiDateTime.GetSample(), CultureName = "en-EN", IsLDAP = false, IsSSO = false }; } } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/vCard/PhoneNumberCollection.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.Mime.vCard { #region usings using System.Collections; using System.Collections.Generic; #endregion /// <summary> /// vCard phone number collection implementation. /// </summary> public class PhoneNumberCollection : IEnumerable { #region Members private readonly List<PhoneNumber> m_pCollection; private readonly vCard m_pOwner; #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="owner">Owner vCard.</param> internal PhoneNumberCollection(vCard owner) { m_pOwner = owner; m_pCollection = new List<PhoneNumber>(); foreach (Item item in owner.Items.Get("TEL")) { m_pCollection.Add(PhoneNumber.Parse(item)); } } #endregion #region Properties /// <summary> /// Gets number of items in the collection. /// </summary> public int Count { get { return m_pCollection.Count; } } #endregion #region Methods /// <summary> /// Add new phone number to the collection. /// </summary> /// <param name="type">Phone number type. Note: This value can be flagged value !</param> /// <param name="number">Phone number.</param> public void Add(PhoneNumberType_enum type, string number) { Item item = m_pOwner.Items.Add("TEL", PhoneNumber.PhoneTypeToString(type), number); m_pCollection.Add(new PhoneNumber(item, type, number)); } /// <summary> /// Removes specified item from the collection. /// </summary> /// <param name="item">Item to remove.</param> public void Remove(PhoneNumber item) { m_pOwner.Items.Remove(item.Item); m_pCollection.Remove(item); } /// <summary> /// Removes all items from the collection. /// </summary> public void Clear() { foreach (PhoneNumber number in m_pCollection) { m_pOwner.Items.Remove(number.Item); } m_pCollection.Clear(); } /// <summary> /// Gets enumerator. /// </summary> /// <returns></returns> public IEnumerator GetEnumerator() { return m_pCollection.GetEnumerator(); } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/Data/LDB_Record.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Data.lsDB { #region usings using System; using System.Collections; using System.IO; using System.Text; #endregion /// <summary> /// lsDB database record. /// </summary> public class LDB_Record { #region Members private readonly DataPage m_pDataPage; private readonly DbFile m_pOwnerDb; private int[] m_ColumnValueSize; #endregion #region Properties /// <summary> /// Gets or set all data column values. /// </summary> public object[] Values { get { object[] retVal = new object[m_pOwnerDb.Columns.Count]; for (int i = 0; i < m_pOwnerDb.Columns.Count; i++) { retVal[i] = this[i]; } return retVal; } set { UpdateRecord(value); } } /// <summary> /// Gets or sets specified data column value. /// </summary> public object this[int columnIndex] { get { if (columnIndex < 0) { throw new Exception("The columnIndex can't be negative value !"); } if (columnIndex > m_pOwnerDb.Columns.Count) { throw new Exception("The columnIndex out of columns count !"); } return GetColumnData(columnIndex); } set { if (columnIndex < 0) { throw new Exception("The columnIndex can't be negative value !"); } if (columnIndex > m_pOwnerDb.Columns.Count) { throw new Exception("The columnIndex out of columns count !"); } // Get current row values object[] rowValues = Values; // Update specified column value rowValues[columnIndex] = value; // Update record UpdateRecord(rowValues); } } /// <summary> /// Gets or sets specified data column value. /// </summary> public object this[string columnName] { get { int index = m_pOwnerDb.Columns.IndexOf(columnName); if (index == -1) { throw new Exception("Table doesn't contain column '" + columnName + "' !"); } return this[index]; } set { int index = m_pOwnerDb.Columns.IndexOf(columnName); if (index == -1) { throw new Exception("Table doesn't contain column '" + columnName + "' !"); } this[index] = value; } } /// <summary> /// Gets or sets specified data column value. /// </summary> public object this[LDB_DataColumn column] { get { int index = m_pOwnerDb.Columns.IndexOf(column); if (index == -1) { throw new Exception("Table doesn't contain column '" + column.ColumnName + "' !"); } return this[index]; } set { int index = m_pOwnerDb.Columns.IndexOf(column); if (index == -1) { throw new Exception("Table doesn't contain column '" + column.ColumnName + "' !"); } this[index] = value; } } /// <summary> /// Gets data page on what row starts. /// </summary> internal DataPage DataPage { get { return m_pDataPage; } } /// <summary> /// Gets data pages held by this row. /// </summary> internal DataPage[] DataPages { get { ArrayList dataPages = new ArrayList(); DataPage page = m_pDataPage; dataPages.Add(page); while (page.NextDataPagePointer > 0) { page = new DataPage(m_pOwnerDb.DataPageDataAreaSize, m_pOwnerDb, page.NextDataPagePointer); dataPages.Add(page); } DataPage[] retVal = new DataPage[dataPages.Count]; dataPages.CopyTo(retVal); return retVal; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="ownerDb">Table that owns this row.</param> /// <param name="rowStartDataPage">Data page on what row starts.</param> internal LDB_Record(DbFile ownerDb, DataPage rowStartDataPage) { m_pOwnerDb = ownerDb; m_pDataPage = rowStartDataPage; ParseRowInfo(); } #endregion #region Utility methods /// <summary> /// Parse row info. /// </summary> private void ParseRowInfo() { /* RowInfo structure (4 bytes) * columnCount - holds column data data length xx bytes columns values */ m_ColumnValueSize = new int[m_pOwnerDb.Columns.Count]; byte[] columnValueSizes = m_pDataPage.ReadData(0, 4*m_pOwnerDb.Columns.Count); for (int i = 0; i < m_pOwnerDb.Columns.Count; i++) { m_ColumnValueSize[i] = ldb_Utils.ByteToInt(columnValueSizes, i*4); } } /// <summary> /// Gets specified column data. /// </summary> /// <param name="columnIndex">Column index.</param> /// <returns></returns> private object GetColumnData(int columnIndex) { // Get column data start offset int columnStartOffset = 4*m_pOwnerDb.Columns.Count; for (int i = 0; i < columnIndex; i++) { columnStartOffset += m_ColumnValueSize[i]; } int dataLength = m_ColumnValueSize[columnIndex]; int startDataPage = (int) Math.Floor(columnStartOffset/(double) m_pOwnerDb.DataPageDataAreaSize); int offsetInStartDataPage = columnStartOffset - (startDataPage*m_pOwnerDb.DataPageDataAreaSize); int dataOffset = 0; int currentDataPageIndex = 0; byte[] columnData = new byte[dataLength]; DataPage currentDataPage = DataPage; while (dataOffset < dataLength) { // We haven't reached to data page on what data starts, just go to next continuing data page if (currentDataPageIndex < startDataPage) { // Get next continuing data page currentDataPage = new DataPage(m_pOwnerDb.DataPageDataAreaSize, m_pOwnerDb, currentDataPage.NextDataPagePointer); currentDataPageIndex++; } // We need all this data page data + addtitional data pages data else if ((dataLength - dataOffset + offsetInStartDataPage) > currentDataPage.StoredDataLength) { currentDataPage.ReadData(columnData, dataOffset, m_pOwnerDb.DataPageDataAreaSize - offsetInStartDataPage, offsetInStartDataPage); dataOffset += m_pOwnerDb.DataPageDataAreaSize - offsetInStartDataPage; // Get next continuing data page currentDataPage = new DataPage(m_pOwnerDb.DataPageDataAreaSize, m_pOwnerDb, currentDataPage.NextDataPagePointer); currentDataPageIndex++; offsetInStartDataPage = 0; } // This data page has all data we need else { currentDataPage.ReadData(columnData, dataOffset, dataLength - dataOffset, offsetInStartDataPage); dataOffset += dataLength - dataOffset; offsetInStartDataPage = 0; } } // Convert to column data type return ConvertFromInternalData(m_pOwnerDb.Columns[columnIndex], columnData); } /// <summary> /// Updates this record values. /// </summary> /// <param name="rowValues">Row new values.</param> private void UpdateRecord(object[] rowValues) { bool unlock = true; // Table is already locked, don't lock it if (m_pOwnerDb.TableLocked) { unlock = false; } else { m_pOwnerDb.LockTable(15); } // Create new record byte[] rowData = CreateRecord(m_pOwnerDb, rowValues); DataPage[] dataPages = DataPages; // Clear old data ?? do we need that // for(int i=0;i<dataPages.Length;i++){ // dataPages[i].Data = new byte[1000]; // } // We haven't enough room to store row, get needed data pages if ((int) Math.Ceiling(rowData.Length/(double) m_pOwnerDb.DataPageDataAreaSize) > dataPages.Length) { int dataPagesNeeded = (int) Math.Ceiling(rowData.Length/(double) m_pOwnerDb.DataPageDataAreaSize) - dataPages.Length; DataPage[] additionalDataPages = m_pOwnerDb.GetDataPages(dataPages[dataPages.Length - 1].Pointer, dataPagesNeeded); // Append new data pages to existing data pages chain dataPages[dataPages.Length - 1].NextDataPagePointer = additionalDataPages[0].Pointer; DataPage[] newVal = new DataPage[dataPages.Length + additionalDataPages.Length]; Array.Copy(dataPages, 0, newVal, 0, dataPages.Length); Array.Copy(additionalDataPages, 0, newVal, dataPages.Length, additionalDataPages.Length); dataPages = newVal; } // Store new record DbFile.StoreDataToDataPages(m_pOwnerDb.DataPageDataAreaSize, rowData, dataPages); // Update row info ParseRowInfo(); if (unlock) { m_pOwnerDb.UnlockTable(); } } #endregion #region Internal methods /// <summary> /// Creates record. Contains record info + record values. /// </summary> /// <param name="ownerDb">Roecord owner table.</param> /// <param name="rowValues">Row values what to store to record.</param> /// <returns></returns> internal static byte[] CreateRecord(DbFile ownerDb, object[] rowValues) { if (ownerDb.Columns.Count != rowValues.Length) { throw new Exception("LDB_Record.CreateRecord m_pOwnerDb.Columns.Count != rowValues.Length !"); } // Convert values to internal store format ArrayList rowByteValues = new ArrayList(); for (int i = 0; i < rowValues.Length; i++) { rowByteValues.Add(ConvertToInternalData(ownerDb.Columns[i], rowValues[i])); } /* RowInfo structure (4 bytes) * columnCount - holds column data data length xx bytes columns values */ MemoryStream msRecord = new MemoryStream(); // Write values sizes for (int i = 0; i < rowByteValues.Count; i++) { msRecord.Write(ldb_Utils.IntToByte(((byte[]) rowByteValues[i]).Length), 0, 4); } // Write values for (int i = 0; i < rowByteValues.Count; i++) { byte[] val = (byte[]) rowByteValues[i]; msRecord.Write(val, 0, val.Length); } return msRecord.ToArray(); } /// <summary> /// Converts data to specied column internal store data. /// </summary> /// <param name="coulmn">Column where to store data.</param> /// <param name="val">Data to convert.</param> /// <returns></returns> internal static byte[] ConvertToInternalData(LDB_DataColumn coulmn, object val) { if (val == null) { throw new Exception("Null values aren't supported !"); } if (coulmn.DataType == LDB_DataType.Bool) { if (val.GetType() != typeof (bool)) { throw new Exception("Column '" + coulmn.ColumnName + "' requires datatype of bool, but value contains '" + val.GetType() + "' !"); } return new[] {Convert.ToByte((bool) val)}; } else if (coulmn.DataType == LDB_DataType.DateTime) { if (val.GetType() != typeof (DateTime)) { throw new Exception("Column '" + coulmn.ColumnName + "' requires datatype of DateTime, but value contains '" + val.GetType() + "' !"); } /* Data structure 1 byte day 1 byte month 4 byte year (int) 1 byte hour 1 byte minute 1 byte second */ DateTime d = (DateTime) val; byte[] dateBytes = new byte[13]; // day dateBytes[0] = (byte) d.Day; // month dateBytes[1] = (byte) d.Month; // year Array.Copy(ldb_Utils.IntToByte(d.Year), 0, dateBytes, 2, 4); // hour dateBytes[6] = (byte) d.Hour; // minute dateBytes[7] = (byte) d.Minute; // second dateBytes[8] = (byte) d.Second; return dateBytes; } else if (coulmn.DataType == LDB_DataType.Long) { if (val.GetType() != typeof (long)) { throw new Exception("Column '" + coulmn.ColumnName + "' requires datatype of Long, but value contains '" + val.GetType() + "' !"); } return ldb_Utils.LongToByte((long) val); } else if (coulmn.DataType == LDB_DataType.Int) { if (val.GetType() != typeof (int)) { throw new Exception("Column '" + coulmn.ColumnName + "' requires datatype of Int, but value contains '" + val.GetType() + "' !"); } return ldb_Utils.IntToByte((int) val); } else if (coulmn.DataType == LDB_DataType.String) { if (val.GetType() != typeof (string)) { throw new Exception("Column '" + coulmn.ColumnName + "' requires datatype of String, but value contains '" + val.GetType() + "' !"); } return Encoding.UTF8.GetBytes(val.ToString()); } else { throw new Exception("Invalid column data type, never must reach here !"); } } /// <summary> /// Converts internal data to .NET data type. /// </summary> /// <param name="coulmn">Column what data it is.</param> /// <param name="val">Internal data value.</param> /// <returns></returns> internal static object ConvertFromInternalData(LDB_DataColumn coulmn, byte[] val) { if (coulmn.DataType == LDB_DataType.Bool) { return Convert.ToBoolean(val[0]); } else if (coulmn.DataType == LDB_DataType.DateTime) { /* Data structure 1 byte day 1 byte month 4 byte year (int) 1 byte hour 1 byte minute 1 byte second */ byte[] dateBytes = new byte[13]; // day int day = val[0]; // month int month = val[1]; // year int year = ldb_Utils.ByteToInt(val, 2); // hour int hour = val[6]; // minute int minute = val[7]; // second int second = val[8]; return new DateTime(year, month, day, hour, minute, second); } else if (coulmn.DataType == LDB_DataType.Long) { return ldb_Utils.ByteToLong(val, 0); } else if (coulmn.DataType == LDB_DataType.Int) { return ldb_Utils.ByteToInt(val, 0); } else if (coulmn.DataType == LDB_DataType.String) { return Encoding.UTF8.GetString(val); } else { throw new Exception("Invalid column data type, never must reach here !"); } } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/TCP/TCP_Server.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.TCP { #region usings using System; using System.Collections.Generic; using System.Diagnostics; using System.Net; using System.Net.Sockets; using System.Threading; using System.Timers; using Log; #endregion /// <summary> /// This class implements generic TCP session based server. /// </summary> public class TCP_Server<T> : IDisposable where T : TCP_ServerSession, new() { #region Events /// <summary> /// This event is raised when TCP server has disposed. /// </summary> public event EventHandler Disposed = null; /// <summary> /// This event is raised when TCP server has unknown unhandled error. /// </summary> public event ErrorEventHandler Error = null; /// <summary> /// This event is raised when TCP server creates new session. /// </summary> public event EventHandler<TCP_ServerSessionEventArgs<T>> SessionCreated = null; /// <summary> /// This event is raised when TCP server has started. /// </summary> public event EventHandler Started = null; /// <summary> /// This event is raised when TCP server has stopped. /// </summary> public event EventHandler Stopped = null; #endregion #region Members private readonly List<ListeningPoint> m_pListeningPoints; private long m_ConnectionsProcessed; private bool m_IsDisposed; private bool m_IsRunning; private long m_MaxConnections; private long m_MaxConnectionsPerIP; private IPBindInfo[] m_pBindings = new IPBindInfo[0]; private Logger m_pLogger; private TCP_SessionCollection<T> m_pSessions; private TimerEx m_pTimer_IdleTimeout; private int m_SessionIdleTimeout = 100; private DateTime m_StartTime; #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> public TCP_Server() { m_pListeningPoints = new List<ListeningPoint>(); m_pSessions = new TCP_SessionCollection<T>(); } #endregion #region Properties /// <summary> /// Gets or sets TCP server IP bindings. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> public IPBindInfo[] Bindings { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_pBindings; } set { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (value == null) { value = new IPBindInfo[0]; } //--- See binds has changed -------------- bool changed = false; if (m_pBindings.Length != value.Length) { changed = true; } else { for (int i = 0; i < m_pBindings.Length; i++) { if (!m_pBindings[i].Equals(value[i])) { changed = true; break; } } } if (changed) { m_pBindings = value; if (m_IsRunning) { StartListen(); } } } } /// <summary> /// Gets how many connections this TCP server has processed. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when TCP server is not running and this property is accesed.</exception> public long ConnectionsProcessed { get { if (m_IsDisposed) { throw new ObjectDisposedException("TCP_Server"); } if (!m_IsRunning) { throw new InvalidOperationException("TCP server is not running."); } return m_ConnectionsProcessed; } } /// <summary> /// Gets if server is disposed. /// </summary> public bool IsDisposed { get { return m_IsDisposed; } } /// <summary> /// Gets if server is running. /// </summary> public bool IsRunning { get { return m_IsRunning; } } /// <summary> /// Gets local listening IP end points. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> public IPEndPoint[] LocalEndPoints { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } List<IPEndPoint> retVal = new List<IPEndPoint>(); foreach (IPBindInfo bind in Bindings) { if (bind.IP.Equals(IPAddress.Any)) { foreach (IPAddress ip in Dns.GetHostAddresses("")) { if (ip.AddressFamily == AddressFamily.InterNetwork && !retVal.Contains(new IPEndPoint(ip, bind.Port))) { retVal.Add(new IPEndPoint(ip, bind.Port)); } } } else if (bind.IP.Equals(IPAddress.IPv6Any)) { foreach (IPAddress ip in Dns.GetHostAddresses("")) { if (ip.AddressFamily == AddressFamily.InterNetworkV6 && !retVal.Contains(new IPEndPoint(ip, bind.Port))) { retVal.Add(new IPEndPoint(ip, bind.Port)); } } } else { if (!retVal.Contains(bind.EndPoint)) { retVal.Add(bind.EndPoint); } } } return retVal.ToArray(); } } /// <summary> /// Gets or sets logger. Value null means no logging. /// </summary> public Logger Logger { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_pLogger; } set { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } m_pLogger = value; } } /// <summary> /// Gets or sets maximum allowed concurent connections. Value 0 means unlimited. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> /// <exception cref="ArgumentException">Is raised when negative value is passed.</exception> public long MaxConnections { get { if (m_IsDisposed) { throw new ObjectDisposedException("TCP_Server"); } return m_MaxConnections; } set { if (m_IsDisposed) { throw new ObjectDisposedException("TCP_Server"); } if (value < 0) { throw new ArgumentException("Property 'MaxConnections' value must be >= 0."); } m_MaxConnections = value; } } /// <summary> /// Gets or sets maximum allowed connections for 1 IP address. Value 0 means unlimited. /// </summary> public long MaxConnectionsPerIP { get { if (m_IsDisposed) { throw new ObjectDisposedException("TCP_Server"); } return m_MaxConnectionsPerIP; } set { if (m_IsDisposed) { throw new ObjectDisposedException("TCP_Server"); } if (m_MaxConnectionsPerIP < 0) { throw new ArgumentException("Property 'MaxConnectionsPerIP' value must be >= 0."); } m_MaxConnectionsPerIP = value; } } /// <summary> /// Gets or sets maximum allowed session idle time in seconds, after what session will be terminated. Value 0 means unlimited, /// but this is strongly not recommened. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> /// <exception cref="ArgumentException">Is raised when negative value is passed.</exception> public int SessionIdleTimeout { get { if (m_IsDisposed) { throw new ObjectDisposedException("TCP_Server"); } return m_SessionIdleTimeout; } set { if (m_IsDisposed) { throw new ObjectDisposedException("TCP_Server"); } if (m_SessionIdleTimeout < 0) { throw new ArgumentException("Property 'SessionIdleTimeout' value must be >= 0."); } m_SessionIdleTimeout = value; } } /// <summary> /// Gets TCP server active sessions. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when TCP server is not running and this property is accesed.</exception> public TCP_SessionCollection<T> Sessions { get { if (m_IsDisposed) { throw new ObjectDisposedException("TCP_Server"); } if (!m_IsRunning) { throw new InvalidOperationException("TCP server is not running."); } return m_pSessions; } } /// <summary> /// Gets the time when server was started. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when TCP server is not running and this property is accesed.</exception> public DateTime StartTime { get { if (m_IsDisposed) { throw new ObjectDisposedException("TCP_Server"); } if (!m_IsRunning) { throw new InvalidOperationException("TCP server is not running."); } return m_StartTime; } } #endregion #region Methods /// <summary> /// Cleans up any resources being used. /// </summary> public void Dispose() { if (m_IsDisposed) { return; } if (m_IsRunning) { try { Stop(); } catch {} } m_IsDisposed = true; // We must call disposed event before we release events. try { OnDisposed(); } catch { // We never should get exception here, user should handle it, just skip it. } m_pSessions = null; // Release all events. Started = null; Stopped = null; Disposed = null; Error = null; } /// <summary> /// Starts TCP server. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> public void Start() { if (m_IsDisposed) { throw new ObjectDisposedException("TCP_Server"); } if (m_IsRunning) { return; } m_IsRunning = true; m_StartTime = DateTime.Now; m_ConnectionsProcessed = 0; ThreadPool.QueueUserWorkItem(delegate { StartListen(); }); m_pTimer_IdleTimeout = new TimerEx(30000, true); m_pTimer_IdleTimeout.Elapsed += m_pTimer_IdleTimeout_Elapsed; m_pTimer_IdleTimeout.Enabled = true; OnStarted(); } /// <summary> /// Stops TCP server, all active connections will be terminated. /// </summary> public void Stop() { if (!m_IsRunning) { return; } m_IsRunning = false; // Dispose all old binds. foreach (ListeningPoint listeningPoint in m_pListeningPoints.ToArray()) { try { listeningPoint.Socket.Close(); } catch (Exception x) { OnError(x); } } m_pListeningPoints.Clear(); m_pTimer_IdleTimeout.Dispose(); m_pTimer_IdleTimeout = null; OnStopped(); } /// <summary> /// Restarts TCP server. /// </summary> public void Restart() { Stop(); Start(); } #endregion #region Virtual methods /// <summary> /// Is called when new incoming session and server maximum allowed connections exceeded. /// </summary> /// <param name="session">Incoming session.</param> /// <remarks>This method allows inhereted classes to report error message to connected client. /// Session will be disconnected after this method completes. /// </remarks> protected virtual void OnMaxConnectionsExceeded(T session) {} /// <summary> /// Is called when new incoming session and server maximum allowed connections per connected IP exceeded. /// </summary> /// <param name="session">Incoming session.</param> /// <remarks>This method allows inhereted classes to report error message to connected client. /// Session will be disconnected after this method completes. /// </remarks> protected virtual void OnMaxConnectionsPerIPExceeded(T session) {} #endregion #region Utility methods /// <summary> /// Is called when session idle check timer triggered. /// </summary> /// <param name="sender">Sender.</param> /// <param name="e">Event data.</param> private void m_pTimer_IdleTimeout_Elapsed(object sender, ElapsedEventArgs e) { try { foreach (T session in Sessions.ToArray()) { try { if (DateTime.Now > session.TcpStream.LastActivity.AddSeconds(m_SessionIdleTimeout)) { session.OnTimeoutI(); // Session didn't dispose itself, so dispose it. if (!session.IsDisposed) { session.Disconnect(); session.Dispose(); } } } catch {} } } catch (Exception x) { OnError(x); } } /// <summary> /// Starts listening incoming connections. NOTE: All active listening points will be disposed. /// </summary> private void StartListen() { try { // Dispose all old binds. foreach (ListeningPoint listeningPoint in m_pListeningPoints.ToArray()) { try { listeningPoint.Socket.Close(); } catch (Exception x) { OnError(x); } } m_pListeningPoints.Clear(); // Create new listening points and start accepting connections. bool ioCompletion_asyncSockets = Net_Utils.IsIoCompletionPortsSupported(); foreach (IPBindInfo bind in m_pBindings) { try { Socket socket = null; if (bind.IP.AddressFamily == AddressFamily.InterNetwork) { socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); } else if (bind.IP.AddressFamily == AddressFamily.InterNetworkV6) { socket = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp); } else { // Invalid address family, just skip it. continue; } socket.Bind(new IPEndPoint(bind.IP, bind.Port)); socket.Listen(100); ListeningPoint listeningPoint = new ListeningPoint(socket, bind); m_pListeningPoints.Add(listeningPoint); // Begin accept. // We MUST use socket.AcceptAsync method, this consume all threading power in Windows paltform(IO completion ports). // For other platforms we need to use BeginAccept. #region IO completion ports if (ioCompletion_asyncSockets) { SocketAsyncEventArgs eArgs = new SocketAsyncEventArgs(); eArgs.Completed += delegate(object s, SocketAsyncEventArgs e) { if (e.SocketError == SocketError.Success) { ProcessConnection(e.AcceptSocket, bind); } // Start accepting new connection. IOCompletionBeginAccept(e, socket, bind); }; // Move processing to thread-pool, because IOCompletionBeginAccept keeps using calling thread as loang as there is work todo. ThreadPool.QueueUserWorkItem(delegate { // Start accepting new connection. IOCompletionBeginAccept(eArgs, socket, bind); }); } #endregion #region Async sockets else { // Begin accepting connection. socket.BeginAccept(new AsyncCallback(AsynSocketsAcceptCompleted), listeningPoint); } #endregion } catch (Exception x) { // The only exception what we should get there is if socket is in use. OnError(x); } } } catch (Exception x) { OnError(x); } } /// <summary> /// Starts accepting connection(s). /// </summary> /// <param name="socketArgs">AcceptAsync method data.</param> /// <param name="listeningSocket">Local listening socket.</param> /// <param name="bindInfo">Local listening socket bind info.</param> /// <exception cref="ArgumentNullException">Is raised when <b>socketArgs</b>,<b>listeningSocket</b> or <b>bindInfo</b> is null reference.</exception> private void IOCompletionBeginAccept(SocketAsyncEventArgs socketArgs, Socket listeningSocket, IPBindInfo bindInfo) { if (socketArgs == null) { throw new ArgumentNullException("socketArgs"); } if (listeningSocket == null) { throw new ArgumentNullException("listeningSocket"); } if (bindInfo == null) { throw new ArgumentNullException("bindInfo"); } try { // We need to clear it, before reuse. socketArgs.AcceptSocket = null; // Use active worker thread as long as AcceptAsync completes synchronously. // (With this approeach we don't have thread context switches while AcceptAsync completes synchronously) while (m_IsRunning && !listeningSocket.AcceptAsync(socketArgs)) { // Operation completed synchronously. if (socketArgs.SocketError == SocketError.Success) { ProcessConnection(socketArgs.AcceptSocket, bindInfo); } // We need to clear it, before reuse. socketArgs.AcceptSocket = null; } } catch (ObjectDisposedException x) { string dummy = x.Message; // Listening socket closed, so skip that error. } } /// <summary> /// This method is called when BeginAccept ha completed. /// </summary> /// <param name="ar">The result of the asynchronous operation.</param> private void AsynSocketsAcceptCompleted(IAsyncResult ar) { ListeningPoint lPoint = (ListeningPoint) ar.AsyncState; try { ProcessConnection(lPoint.Socket.EndAccept(ar), lPoint.BindInfo); } catch { // Skip accept errors. } // Begin accepting connection. lPoint.Socket.BeginAccept(new AsyncCallback(AsynSocketsAcceptCompleted), lPoint); } /// <summary> /// Processes specified connection. /// </summary> /// <param name="socket">Accpeted socket.</param> /// <param name="bindInfo">Local bind info what accpeted connection.</param> /// <exception cref="ArgumentNullException">Is raised when <b>socket</b> or <b>bindInfo</b> is null reference.</exception> private void ProcessConnection(Socket socket, IPBindInfo bindInfo) { if (socket == null) { throw new ArgumentNullException("socket"); } if (bindInfo == null) { throw new ArgumentNullException("bindInfo"); } m_ConnectionsProcessed++; try { T session = new T(); session.Init(this, socket, bindInfo.HostName, bindInfo.SslMode == SslMode.SSL, bindInfo.Certificate); // Maximum allowed connections exceeded, reject connection. if (m_MaxConnections != 0 && m_pSessions.Count > m_MaxConnections) { OnMaxConnectionsExceeded(session); session.Dispose(); } // Maximum allowed connections per IP exceeded, reject connection. else if (m_MaxConnectionsPerIP != 0) { OnMaxConnectionsPerIPExceeded(session); session.Dispose(); } // Start processing new session. else { session.Disonnected += delegate(object sender, EventArgs e) { m_pSessions.Remove((T)sender); }; m_pSessions.Add(session); OnSessionCreated(session); session.Start(); } } catch (Exception x) { OnError(x); } } /// <summary> /// Raises <b>SessionCreated</b> event. /// </summary> /// <param name="session">TCP server session that was created.</param> private void OnSessionCreated(T session) { if (SessionCreated != null) { SessionCreated(this, new TCP_ServerSessionEventArgs<T>(this, session)); } } /// <summary> /// Raises <b>Error</b> event. /// </summary> /// <param name="x">Exception happened.</param> protected void OnError(Exception x) { if (Error != null) { Error(this, new Error_EventArgs(x, new StackTrace())); } } #endregion /// <summary> /// Raises <b>Started</b> event. /// </summary> protected void OnStarted() { if (Started != null) { Started(this, new EventArgs()); } } /// <summary> /// Raises <b>Stopped</b> event. /// </summary> protected void OnStopped() { if (Stopped != null) { Stopped(this, new EventArgs()); } } /// <summary> /// Raises <b>Disposed</b> event. /// </summary> protected void OnDisposed() { if (Disposed != null) { Disposed(this, new EventArgs()); } } #region Nested type: ListeningPoint /// <summary> /// This class holds listening point info. /// </summary> private class ListeningPoint { #region Members private readonly IPBindInfo m_pBindInfo; private readonly Socket m_pSocket; #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="socket">Listening socket.</param> /// <param name="bind">Bind info what acceped socket.</param> public ListeningPoint(Socket socket, IPBindInfo bind) { m_pSocket = socket; m_pBindInfo = bind; } #endregion #region Properties /// <summary> /// Gets bind info. /// </summary> public IPBindInfo BindInfo { get { return m_pBindInfo; } } /// <summary> /// Gets socket. /// </summary> public Socket Socket { get { return m_pSocket; } } #endregion } #endregion } }<file_sep>/web/studio/ASC.Web.Studio/Core/Backup/BackupHelper.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Linq; using ASC.Core; using ASC.Core.Tenants; using ASC.Web.Studio.UserControls.Statistics; namespace ASC.Web.Studio.Core.Backup { public class BackupHelper { public const long AvailableZipSize = 10 * 1024 * 1024 * 1024L; private static readonly Guid mailStorageTag = new Guid("666ceac1-4532-4f8c-9cba-8f510eca2fd1"); public static BackupAvailableSize GetAvailableSize(int tenantId) { if (CoreContext.Configuration.Standalone) return BackupAvailableSize.Available; var size = CoreContext.TenantManager.FindTenantQuotaRows(new TenantQuotaRowQuery(tenantId)) .Where(r => !string.IsNullOrEmpty(r.Tag) && new Guid(r.Tag) != Guid.Empty && !new Guid(r.Tag).Equals(mailStorageTag)) .Sum(r => r.Counter); if (size > AvailableZipSize) { return BackupAvailableSize.NotAvailable; } size = TenantStatisticsProvider.GetUsedSize(tenantId); if (size > AvailableZipSize) { return BackupAvailableSize.WithoutMail; } return BackupAvailableSize.Available; } public static bool ExceedsMaxAvailableSize(int tenantId) { return GetAvailableSize(tenantId) != BackupAvailableSize.Available; } } public enum BackupAvailableSize { Available, WithoutMail, NotAvailable, } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/DNS/Client/DNS_rr_A.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.Dns.Client { #region usings using System; using System.Net; #endregion /// <summary> /// A record class. /// </summary> [Serializable] public class DNS_rr_A : DNS_rr_base { #region Members private readonly IPAddress m_IP; #endregion #region Properties /// <summary> /// Gets host IP address. /// </summary> public IPAddress IP { get { return m_IP; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="ip">IP address.</param> /// <param name="ttl">TTL value.</param> public DNS_rr_A(IPAddress ip, int ttl) : base(QTYPE.A, ttl) { m_IP = ip; } #endregion #region Methods /// <summary> /// Parses resource record from reply data. /// </summary> /// <param name="reply">DNS server reply data.</param> /// <param name="offset">Current offset in reply data.</param> /// <param name="rdLength">Resource record data length.</param> /// <param name="ttl">Time to live in seconds.</param> public static DNS_rr_A Parse(byte[] reply, ref int offset, int rdLength, int ttl) { // IPv4 = byte byte byte byte byte[] ip = new byte[rdLength]; Array.Copy(reply, offset, ip, 0, rdLength); offset += rdLength; return new DNS_rr_A(new IPAddress(ip), ttl); } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/IMAP/IMAP_Envelope.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.IMAP { #region usings using System; using System.Collections; using System.Text; using Mime; using MIME; #endregion /// <summary> /// IMAP ENVELOPE STRUCTURE (date, subject, from, sender, reply-to, to, cc, bcc, in-reply-to, and message-id). /// Defined in RFC 3501 7.4.2. /// </summary> public class IMAP_Envelope { #region Members private MailboxAddress[] m_Bcc; private MailboxAddress[] m_Cc; private DateTime m_Date = DateTime.MinValue; private MailboxAddress[] m_From; private string m_InReplyTo; private string m_MessageID; private MailboxAddress[] m_ReplyTo; private MailboxAddress m_Sender; private string m_Subject; private MailboxAddress[] m_To; #endregion #region Properties /// <summary> /// Gets header field "<b>Date:</b>" value. Returns DateTime.MinValue if no date or date parsing fails. /// </summary> public DateTime Date { get { return m_Date; } } /// <summary> /// Gets header field "<b>Subject:</b>" value. Returns null if value isn't set. /// </summary> public string Subject { get { return m_Subject; } } /// <summary> /// Gets header field "<b>From:</b>" value. Returns null if value isn't set. /// </summary> public MailboxAddress[] From { get { return m_From; } } /// <summary> /// Gets header field "<b>Sender:</b>" value. Returns null if value isn't set. /// </summary> public MailboxAddress Sender { get { return m_Sender; } } /// <summary> /// Gets header field "<b>Reply-To:</b>" value. Returns null if value isn't set. /// </summary> public MailboxAddress[] ReplyTo { get { return m_ReplyTo; } } /// <summary> /// Gets header field "<b>To:</b>" value. Returns null if value isn't set. /// </summary> public MailboxAddress[] To { get { return m_To; } } /// <summary> /// Gets header field "<b>Cc:</b>" value. Returns null if value isn't set. /// </summary> public MailboxAddress[] Cc { get { return m_Cc; } } /// <summary> /// Gets header field "<b>Bcc:</b>" value. Returns null if value isn't set. /// </summary> public MailboxAddress[] Bcc { get { return m_Bcc; } } /// <summary> /// Gets header field "<b>In-Reply-To:</b>" value. Returns null if value isn't set. /// </summary> public string InReplyTo { get { return m_InReplyTo; } } /// <summary> /// Gets header field "<b>Message-ID:</b>" value. Returns null if value isn't set. /// </summary> public string MessageID { get { return m_MessageID; } } #endregion #region Methods /// <summary> /// Construct secified mime entity ENVELOPE string. /// </summary> /// <param name="entity">Mime entity.</param> /// <returns></returns> public static string ConstructEnvelope(MimeEntity entity) { /* RFC 3501 7.4.2 ENVELOPE A parenthesized list that describes the envelope structure of a message. This is computed by the server by parsing the [RFC-2822] header into the component parts, defaulting various fields as necessary. The fields of the envelope structure are in the following order: date, subject, from, sender, reply-to, to, cc, bcc, in-reply-to, and message-id. The date, subject, in-reply-to, and message-id fields are strings. The from, sender, reply-to, to, cc, and bcc fields are parenthesized lists of address structures. An address structure is a parenthesized list that describes an electronic mail address. The fields of an address structure are in the following order: personal name, [SMTP] at-domain-list (source route), mailbox name, and host name. [RFC-2822] group syntax is indicated by a special form of address structure in which the host name field is NIL. If the mailbox name field is also NIL, this is an end of group marker (semi-colon in RFC 822 syntax). If the mailbox name field is non-NIL, this is a start of group marker, and the mailbox name field holds the group name phrase. If the Date, Subject, In-Reply-To, and Message-ID header lines are absent in the [RFC-2822] header, the corresponding member of the envelope is NIL; if these header lines are present but empty the corresponding member of the envelope is the empty string. Note: some servers may return a NIL envelope member in the "present but empty" case. Clients SHOULD treat NIL and empty string as identical. Note: [RFC-2822] requires that all messages have a valid Date header. Therefore, the date member in the envelope can not be NIL or the empty string. Note: [RFC-2822] requires that the In-Reply-To and Message-ID headers, if present, have non-empty content. Therefore, the in-reply-to and message-id members in the envelope can not be the empty string. If the From, To, cc, and bcc header lines are absent in the [RFC-2822] header, or are present but empty, the corresponding member of the envelope is NIL. If the Sender or Reply-To lines are absent in the [RFC-2822] header, or are present but empty, the server sets the corresponding member of the envelope to be the same value as the from member (the client is not expected to know to do this). Note: [RFC-2822] requires that all messages have a valid From header. Therefore, the from, sender, and reply-to members in the envelope can not be NIL. ENVELOPE ("date" "subject" from sender reply-to to cc bcc "in-reply-to" "messageID") */ // NOTE: all header fields and parameters must in ENCODED form !!! StringBuilder retVal = new StringBuilder(); retVal.Append("("); // date if (entity.Header.Contains("Date:")) { retVal.Append(TextUtils.QuoteString(MimeUtils.DateTimeToRfc2822(entity.Date))); } else { retVal.Append("NIL"); } // subject if (entity.Subject != null) { retVal.Append(" " + TextUtils.QuoteString(MimeUtils.EncodeHeaderField(entity.Subject))); } else { retVal.Append(" NIL"); } // from if (entity.From != null && entity.From.Count > 0) { retVal.Append(" " + ConstructAddresses(entity.From)); } else { retVal.Append(" NIL"); } // sender // NOTE: There is confusing part, according rfc 2822 Sender: is MailboxAddress and not AddressList. if (entity.Sender != null) { retVal.Append(" ("); retVal.Append(ConstructAddress(entity.Sender)); retVal.Append(")"); } else if (entity.From != null) { retVal.Append(" " + ConstructAddresses(entity.From)); } else { retVal.Append(" NIL"); } // reply-to if (entity.ReplyTo != null) { retVal.Append(" " + ConstructAddresses(entity.ReplyTo)); } else if (entity.From != null) { retVal.Append(" " + ConstructAddresses(entity.From)); } else { retVal.Append(" NIL"); } // to if (entity.To != null && entity.To.Count > 0) { retVal.Append(" " + ConstructAddresses(entity.To)); } else { retVal.Append(" NIL"); } // cc if (entity.Cc != null && entity.Cc.Count > 0) { retVal.Append(" " + ConstructAddresses(entity.Cc)); } else { retVal.Append(" NIL"); } // bcc if (entity.Bcc != null && entity.Bcc.Count > 0) { retVal.Append(" " + ConstructAddresses(entity.Bcc)); } else { retVal.Append(" NIL"); } // in-reply-to if (entity.InReplyTo != null) { retVal.Append(" " + TextUtils.QuoteString(MimeUtils.EncodeHeaderField(entity.InReplyTo))); } else { retVal.Append(" NIL"); } // message-id if (entity.MessageID != null) { retVal.Append(" " + TextUtils.QuoteString(MimeUtils.EncodeHeaderField(entity.MessageID))); } else { retVal.Append(" NIL"); } retVal.Append(")"); return retVal.ToString(); } /// <summary> /// Parses ENVELOPE from IMAP envelope string. /// </summary> /// <param name="envelopeString">Envelope string.</param> public void Parse(string envelopeString) { if (envelopeString.StartsWith("(")) { envelopeString = envelopeString.Substring(1); } if (envelopeString.EndsWith(")")) { envelopeString = envelopeString.Substring(0, envelopeString.Length - 1); } string word = ""; StringReader r = new StringReader(envelopeString); #region Date // Date word = r.ReadWord(); if (word == null) { throw new Exception("Invalid IMAP ENVELOPE structure !"); } if (word.ToUpper() == "NIL") { m_Date = DateTime.MinValue; } else { try { m_Date = MimeUtils.ParseDate(word); } catch { // Failed to parse date, return minimum. m_Date = DateTime.MinValue; } } #endregion #region Subject // Subject word = r.ReadWord(); if (word == null) { throw new Exception("Invalid IMAP ENVELOPE structure !"); } if (word.ToUpper() == "NIL") { m_Subject = null; } else { m_Subject = MIME_Encoding_EncodedWord.DecodeS(word); } #endregion #region From // From m_From = ParseAddresses(r); #endregion #region Sender // Sender // NOTE: There is confusing part, according rfc 2822 Sender: is MailboxAddress and not AddressList. MailboxAddress[] sender = ParseAddresses(r); if (sender != null && sender.Length > 0) { m_Sender = sender[0]; } else { m_Sender = null; } #endregion #region ReplyTo // ReplyTo m_ReplyTo = ParseAddresses(r); #endregion #region To // To m_To = ParseAddresses(r); #endregion #region Cc // Cc m_Cc = ParseAddresses(r); #endregion #region Bcc // Bcc m_Bcc = ParseAddresses(r); #endregion #region InReplyTo // InReplyTo r.ReadToFirstChar(); word = r.ReadWord(); if (word == null) { throw new Exception("Invalid IMAP ENVELOPE structure !"); } if (word.ToUpper() == "NIL") { m_InReplyTo = null; } else { m_InReplyTo = word; } #endregion #region MessageID // MessageID r.ReadToFirstChar(); word = r.ReadWord(); if (word == null) { throw new Exception("Invalid IMAP ENVELOPE structure !"); } if (word.ToUpper() == "NIL") { m_MessageID = null; } else { m_MessageID = word; } #endregion } #endregion #region Utility methods /// <summary> /// Constructs ENVELOPE addresses structure. /// </summary> /// <param name="addressList">Address list.</param> /// <returns></returns> private static string ConstructAddresses(AddressList addressList) { StringBuilder retVal = new StringBuilder(); retVal.Append("("); foreach (MailboxAddress address in addressList.Mailboxes) { retVal.Append(ConstructAddress(address)); } retVal.Append(")"); return retVal.ToString(); } /// <summary> /// Constructs ENVELOPE address structure. /// </summary> /// <param name="address">Mailbox address.</param> /// <returns></returns> private static string ConstructAddress(MailboxAddress address) { /* An address structure is a parenthesized list that describes an electronic mail address. The fields of an address structure are in the following order: personal name, [SMTP] at-domain-list (source route), mailbox name, and host name. */ // NOTE: all header fields and parameters must in ENCODED form !!! StringBuilder retVal = new StringBuilder(); retVal.Append("("); // personal name retVal.Append(TextUtils.QuoteString(MimeUtils.EncodeHeaderField(address.DisplayName))); // source route, always NIL (not used nowdays) retVal.Append(" NIL"); // mailbox name retVal.Append(" " + TextUtils.QuoteString(MimeUtils.EncodeHeaderField(address.LocalPart))); // host name retVal.Append(" " + TextUtils.QuoteString(MimeUtils.EncodeHeaderField(address.Domain))); retVal.Append(")"); return retVal.ToString(); } /// <summary> /// Parses addresses from IMAP ENVELOPE addresses structure. /// </summary> /// <param name="r"></param> /// <returns></returns> private MailboxAddress[] ParseAddresses(StringReader r) { r.ReadToFirstChar(); if (r.StartsWith("NIL", false)) { // Remove NIL r.ReadSpecifiedLength("NIL".Length); return null; } else { r.ReadToFirstChar(); // This must be ((address)[*(address)]) if (!r.StartsWith("(")) { throw new Exception("Invalid IMAP ENVELOPE structure !"); } else { // Read addresses string addressesString = r.ReadParenthesized(); ArrayList addresses = new ArrayList(); StringReader rAddresses = new StringReader(addressesString.Trim()); // Now we have (address)[*(address)], read addresses while (rAddresses.StartsWith("(")) { addresses.Add(ParseAddress(rAddresses.ReadParenthesized())); rAddresses.ReadToFirstChar(); } MailboxAddress[] retVal = new MailboxAddress[addresses.Count]; addresses.CopyTo(retVal); return retVal; } } } /// <summary> /// Parses address from IMAP ENVELOPE address structure. /// </summary> /// <param name="addressString">Address structure string.</param> /// <returns></returns> private MailboxAddress ParseAddress(string addressString) { /* RFC 3501 7.4.2 ENVELOPE An address structure is a parenthesized list that describes an electronic mail address. The fields of an address structure are in the following order: personal name, [SMTP] at-domain-list (source route), mailbox name, and host name. */ StringReader r = new StringReader(addressString.Trim()); string personalName = ""; string emailAddress = ""; // personal name if (r.StartsWith("NIL", false)) { // Remove NIL r.ReadSpecifiedLength("NIL".Length); } else { personalName = MIME_Encoding_EncodedWord.DecodeS(r.ReadWord()); } // source route, always NIL (not used nowdays) r.ReadWord(); // mailbox name if (r.StartsWith("NIL", false)) { // Remove NIL r.ReadSpecifiedLength("NIL".Length); } else { emailAddress = r.ReadWord() + "@"; } // host name if (r.StartsWith("NIL", false)) { // Remove NIL r.ReadSpecifiedLength("NIL".Length); } else { emailAddress += r.ReadWord(); } return new MailboxAddress(personalName, emailAddress); } #endregion } }<file_sep>/web/studio/ASC.Web.Studio/Products/Community/Modules/Wiki/WikiUC/fckeditor/editor/plugins/fck_wysiwyg/lang/ru.js FCKLang.Wikitext = "Вики"; FCKLang.wikiLoadingWikitext = "Загрузка вики. Пожалуйста подождите..."; //Link FCKLang.wikiLnkNoSearchAnchor = "якорь... поиск не производится"; FCKLang.wikiLnkNoSearchMail = "email... поиск не производится"; FCKLang.wikiLnkNoSearchExt = "внешняя ссылка... поиск не производится"; FCKLang.wikiLnkStartTyping = "начните печатать в поле наверху"; FCKLang.wikiLnkTooShort = "слишком мало... введите больше"; FCKLang.wikiLnkStopTyping = "прекратите печатать для начала поиска"; FCKLang.wikiLnkSearching = "поиск..."; FCKLang.wikiLnkSearchNothing = "ни одной страницы не найдено"; FCKLang.wikiLnkSearch1Found = "одна страница найдена"; FCKLang.wikiLnkSearchSeveral = "%1 страниц найдено"; FCKLang.wikiPageNameOrLnk = "Имя страницы или Ссылка:"; FCKLang.wikiLnkAutomatic = "Автоматический поиск результатов"; FCKLang.wikiLnkCaption = "Заголовок:" //Img FCKLang.wikiImgStartTyping = "начните печатать в поле наверху"; FCKLang.wikiImgTooShort = "слишком мало... введите больше"; FCKLang.wikiImgStopTyping = "прекратите печатать для начала поиска"; FCKLang.wikiImgSearchNothing = "ни одной картинки не найдено"; FCKLang.wikiImgSearch1Found = "одна картинка найдена"; FCKLang.wikiImgSearchSeveral = "%1 картинок найдено"; FCKLang.wikiImgFileName = "Имя файла картинки"; FCKLang.wikiFileName = "Имя файла"; FCKLang.wikiImgAutomatic = "Автоматический поиск результатов"; FCKLang.wikiImgCaption = "Заголовок"; FCKLang.wikiImgType = "Тип картинки"; FCKLang.wikiImgTypeThumb = "Миниатюра"; FCKLang.wikiImgTypeFrame = "Рамка"; FCKLang.DlgImgAlign = "Выравнивание"; FCKLang.DlgImgAlignRight = "Вправо"; FCKLang.DlgImgAlignLeftv = "Влево"; FCKLang.DlgImgWidth = "Ширина"; FCKLang.wikiFile = "Файл"; FCKLang.wikiDlgFileTitle = "Свойства файла"; FCKLang.wikiTOC = "Оглавление"; FCKLang.wikiTOCHereContent = "Оглавление";<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/SIP/Proxy/SIP_ProxyCore.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.SIP.Proxy { #region usings using System; using System.Collections.Generic; using System.Net; using AUTH; using Message; using Stack; #endregion #region Delegates /// <summary> /// Represents the method that will handle the SIP_ProxyCore.IsLocalUri event. /// </summary> /// <param name="uri">Request URI.</param> /// <returns>Returns true if server local URI, otherwise false.</returns> public delegate bool SIP_IsLocalUriEventHandler(string uri); /// <summary> /// Represents the method that will handle the SIP_ProxyCore.Authenticate event. /// </summary> public delegate void SIP_AuthenticateEventHandler(SIP_AuthenticateEventArgs e); /// <summary> /// Represents the method that will handle the SIP_ProxyCore.AddressExists event. /// </summary> /// <param name="address">SIP address to check.</param> /// <returns>Returns true if specified address exists, otherwise false.</returns> public delegate bool SIP_AddressExistsEventHandler(string address); /// <summary> /// Represents the method that will handle the SIP_ProxyCore.GetGateways event. /// </summary> /// <param name="e">Event data.</param> public delegate void SIP_GetGatewaysEventHandler(SIP_GatewayEventArgs e); #endregion /// <summary> /// Implements SIP registrar,statefull and stateless proxy. /// </summary> public class SIP_ProxyCore : IDisposable { #region Events /// <summary> /// This event is raised when SIP proxy needs to know if specified local server address exists. /// </summary> public event SIP_AddressExistsEventHandler AddressExists = null; /// <summary> /// This event is raised when SIP proxy or registrar server needs to authenticate user. /// </summary> public event SIP_AuthenticateEventHandler Authenticate = null; /// <summary> /// This event is raised when SIP proxy needs to get gateways for non-SIP URI. /// </summary> public event SIP_GetGatewaysEventHandler GetGateways = null; /// <summary> /// This event is raised when SIP proxy needs to know if specified request URI is local URI or remote URI. /// </summary> public event SIP_IsLocalUriEventHandler IsLocalUri = null; #endregion #region Members private readonly string m_Opaque = ""; private SIP_ForkingMode m_ForkingMode = SIP_ForkingMode.Parallel; private bool m_IsDisposed; private SIP_B2BUA m_pB2BUA; internal List<SIP_ProxyContext> m_pProxyContexts; private SIP_Registrar m_pRegistrar; private SIP_ProxyMode m_ProxyMode = SIP_ProxyMode.Registrar | SIP_ProxyMode.Statefull; private SIP_Stack m_pStack; #endregion #region Properties /// <summary> /// Gets if this object is disposed. /// </summary> public bool IsDisposed { get { return m_IsDisposed; } } /// <summary> /// Gets owner SIP stack. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and and this property is accessed.</exception> public SIP_Stack Stack { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_pStack; } } /// <summary> /// Gets or sets proxy mode. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and and this property is accessed.</exception> /// <exception cref="ArgumentException">Is raised when invalid combination modes passed.</exception> public SIP_ProxyMode ProxyMode { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_ProxyMode; } set { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } // Check for invalid mode () if ((value & SIP_ProxyMode.Statefull) != 0 && (value & SIP_ProxyMode.Stateless) != 0) { throw new ArgumentException("Proxy can't be at Statefull and Stateless at same time !"); } m_ProxyMode = value; } } /// <summary> /// Gets or sets how proxy handle forking. This property applies for statefull proxy only. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and and this property is accessed.</exception> public SIP_ForkingMode ForkingMode { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_ForkingMode; } set { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } m_ForkingMode = value; } } /// <summary> /// Gets SIP registrar server. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and and this property is accessed.</exception> public SIP_Registrar Registrar { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_pRegistrar; } } /// <summary> /// Gets SIP B2BUA server. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and and this property is accessed.</exception> public SIP_B2BUA B2BUA { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_pB2BUA; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="stack">Reference to SIP stack.</param> /// <exception cref="ArgumentNullException">Is raised when <b>sipStack</b> is null.</exception> public SIP_ProxyCore(SIP_Stack stack) { if (stack == null) { throw new ArgumentNullException("stack"); } m_pStack = stack; m_pStack.RequestReceived += m_pStack_RequestReceived; m_pStack.ResponseReceived += m_pStack_ResponseReceived; m_pRegistrar = new SIP_Registrar(this); m_pB2BUA = new SIP_B2BUA(this); m_Opaque = Auth_HttpDigest.CreateOpaque(); m_pProxyContexts = new List<SIP_ProxyContext>(); } #endregion #region Methods /// <summary> /// Cleans up any resources being used. /// </summary> public void Dispose() { if (m_IsDisposed) { return; } m_IsDisposed = true; if (m_pStack != null) { m_pStack.Dispose(); m_pStack = null; } m_pRegistrar = null; m_pB2BUA = null; m_pProxyContexts = null; } #endregion #region Event handlers /// <summary> /// This method is called when SIP stack receives new request. /// </summary> /// <param name="sender">Sender.</param> /// <param name="e">Event data.</param> private void m_pStack_RequestReceived(object sender, SIP_RequestReceivedEventArgs e) { OnRequestReceived(e); } /// <summary> /// This method is called when SIP stack receives new response. /// </summary> /// <param name="sender">Sender.</param> /// <param name="e">Event data.</param> private void m_pStack_ResponseReceived(object sender, SIP_ResponseReceivedEventArgs e) { OnResponseReceived(e); } #endregion #region Utility methods /// <summary> /// This method is called when new request is received. /// </summary> /// <param name="e">Request event arguments.</param> private void OnRequestReceived(SIP_RequestReceivedEventArgs e) { /* RFC 3261 16.12. ????????? Forward does all thse steps. 1. The proxy will inspect the Request-URI. If it indicates a resource owned by this proxy, the proxy will replace it with the results of running a location service. Otherwise, the proxy will not change the Request-URI. 2. The proxy will inspect the URI in the topmost Route header field value. If it indicates this proxy, the proxy removes it from the Route header field (this route node has been reached). 3. The proxy will forward the request to the resource indicated by the URI in the topmost Route header field value or in the Request-URI if no Route header field is present. The proxy determines the address, port and transport to use when forwarding the request by applying the procedures in [4] to that URI. */ SIP_Request request = e.Request; try { #region Registrar // Registrar if ((m_ProxyMode & SIP_ProxyMode.Registrar) != 0 && request.RequestLine.Method == SIP_Methods.REGISTER) { m_pRegistrar.Register(e); } #endregion #region Presence /* // Presence else if((m_ProxyMode & SIP_ProxyMode.Presence) != 0 && (request.Method == "SUBSCRIBE" || request.Method == "NOTIFY")){ } */ #endregion #region Statefull // Statefull else if ((m_ProxyMode & SIP_ProxyMode.Statefull) != 0) { // Statefull proxy is transaction statefull proxy only, // what don't create dialogs and keep dialog state. /* RFC 3261 16.10. StateFull proxy: If a matching response context is found, the element MUST immediately return a 200 (OK) response to the CANCEL request. If a response context is not found, the element does not have any knowledge of the request to apply the CANCEL to. It MUST statelessly forward the CANCEL request (it may have statelessly forwarded the associated request previously). */ if (e.Request.RequestLine.Method == SIP_Methods.CANCEL) { // Don't do server transaction before we get CANCEL matching transaction. SIP_ServerTransaction trToCancel = m_pStack.TransactionLayer.MatchCancelToTransaction(e.Request); if (trToCancel != null) { trToCancel.Cancel(); e.ServerTransaction.SendResponse(m_pStack.CreateResponse( SIP_ResponseCodes.x200_Ok, request)); } else { ForwardRequest(false, e); } } // ACK never creates transaction, it's always passed directly to transport layer. else if (e.Request.RequestLine.Method == SIP_Methods.ACK) { ForwardRequest(false, e); } else { ForwardRequest(true, e); } } #endregion #region B2BUA // B2BUA else if ((m_ProxyMode & SIP_ProxyMode.B2BUA) != 0) { m_pB2BUA.OnRequestReceived(e); } #endregion #region Stateless // Stateless else if ((m_ProxyMode & SIP_ProxyMode.Stateless) != 0) { // Stateless proxy don't do transaction, just forwards all. ForwardRequest(false, e); } #endregion #region Proxy won't accept command else { e.ServerTransaction.SendResponse( m_pStack.CreateResponse(SIP_ResponseCodes.x501_Not_Implemented, request)); } #endregion } catch (Exception x) { try { m_pStack.TransportLayer.SendResponse( m_pStack.CreateResponse( SIP_ResponseCodes.x500_Server_Internal_Error + ": " + x.Message, e.Request)); } catch { // Skip transport layer exception if send fails. } // Don't raise OnError for transport errors. if (!(x is SIP_TransportException)) { m_pStack.OnError(x); } } } /// <summary> /// This method is called when new response is received. /// </summary> /// <param name="e">Response event arguments.</param> private void OnResponseReceived(SIP_ResponseReceivedEventArgs e) { if ((m_ProxyMode & SIP_ProxyMode.B2BUA) != 0) { m_pB2BUA.OnResponseReceived(e); } else { /* This method is called when stateless proxy gets response or statefull proxy has no matching server transaction. */ /* RFC 3261 16.11. When a response arrives at a stateless proxy, the proxy MUST inspect the sent-by value in the first (topmost) Via header field value. If that address matches the proxy, (it equals a value this proxy has inserted into previous requests) the proxy MUST remove that header field value from the response and forward the result to the location indicated in the next Via header field value. */ // Just remove topmost Via:, sent-by check is done in transport layer. e.Response.Via.RemoveTopMostValue(); if ((m_ProxyMode & SIP_ProxyMode.Statefull) != 0) { // We should not reach here. This happens when no matching client transaction found. // RFC 3161 18.1.2 orders to forward them statelessly. m_pStack.TransportLayer.SendResponse(e.Response); } else if ((m_ProxyMode & SIP_ProxyMode.Stateless) != 0) { m_pStack.TransportLayer.SendResponse(e.Response); } } } /// <summary> /// Forwards specified request to destination recipient. /// </summary> /// <param name="statefull">Specifies if request is sent statefully or statelessly.</param> /// <param name="e">Request event arguments.</param> private void ForwardRequest(bool statefull, SIP_RequestReceivedEventArgs e) { ForwardRequest(statefull, e, e.Request, true); } #endregion #region Internal methods /// <summary> /// Forwards specified request to target recipient. /// </summary> /// <param name="statefull">Specifies if request is sent statefully or statelessly.</param> /// <param name="e">Request event arguments.</param> /// <param name="request">SIP request to forward.</param> /// <param name="addRecordRoute">Specifies if Record-Route header filed is added.</param> internal void ForwardRequest(bool statefull, SIP_RequestReceivedEventArgs e, SIP_Request request, bool addRecordRoute) { List<SIP_ProxyTarget> targetSet = new List<SIP_ProxyTarget>(); List<NetworkCredential> credentials = new List<NetworkCredential>(); SIP_Uri route = null; /* RFC 3261 16. 1. Validate the request (Section 16.3) 1. Reasonable Syntax 2. URI scheme 3. Max-Forwards 4. (Optional) Loop Detection 5. Proxy-Require 6. Proxy-Authorization 2. Preprocess routing information (Section 16.4) 3. Determine target(s) for the request (Section 16.5) 4. Forward the request (Section 16.6) */ #region 1. Validate the request (Section 16.3) // 1.1 Reasonable Syntax. // SIP_Message will do it. // 1.2 URI scheme check. if (!SIP_Utils.IsSipOrSipsUri(request.RequestLine.Uri.ToString())) { // TODO: SIP_GatewayEventArgs eArgs = OnGetGateways("uriScheme", "userName"); // No suitable gateway or authenticated user has no access. if (eArgs.Gateways.Count == 0) { e.ServerTransaction.SendResponse( m_pStack.CreateResponse(SIP_ResponseCodes.x416_Unsupported_URI_Scheme, e.Request)); return; } } // 1.3 Max-Forwards. if (request.MaxForwards <= 0) { e.ServerTransaction.SendResponse(m_pStack.CreateResponse( SIP_ResponseCodes.x483_Too_Many_Hops, request)); return; } // 1.4 (Optional) Loop Detection. // Skip. // 1.5 Proxy-Require. // TODO: // 1.6 Proxy-Authorization. // We need to auth all foreign calls. if (!SIP_Utils.IsSipOrSipsUri(request.RequestLine.Uri.ToString()) || !OnIsLocalUri(((SIP_Uri) request.RequestLine.Uri).Host)) { // We need to pass-through ACK. if (request.RequestLine.Method == SIP_Methods.ACK) {} else if (!AuthenticateRequest(e)) { return; } } #endregion #region 2. Preprocess routing information (Section 16.4). /* The proxy MUST inspect the Request-URI of the request. If the Request-URI of the request contains a value this proxy previously placed into a Record-Route header field (see Section 16.6 item 4), the proxy MUST replace the Request-URI in the request with the last value from the Route header field, and remove that value from the Route header field. The proxy MUST then proceed as if it received this modified request. If the first value in the Route header field indicates this proxy, the proxy MUST remove that value from the request. */ // Strict route. if (SIP_Utils.IsSipOrSipsUri(request.RequestLine.Uri.ToString()) && IsLocalRoute(((SIP_Uri) request.RequestLine.Uri))) { request.RequestLine.Uri = request.Route.GetAllValues()[request.Route.GetAllValues().Length - 1].Address.Uri; SIP_t_AddressParam[] routes = request.Route.GetAllValues(); route = (SIP_Uri) routes[routes.Length - 1].Address.Uri; request.Route.RemoveLastValue(); } // Loose route. else if (request.Route.GetAllValues().Length > 0 && IsLocalRoute(SIP_Uri.Parse(request.Route.GetTopMostValue().Address.Uri.ToString()))) { route = (SIP_Uri) request.Route.GetTopMostValue().Address.Uri; request.Route.RemoveTopMostValue(); } #endregion #region 3. Determine target(s) for the request (Section 16.5) /* 3. Determine target(s) for the request (Section 16.5) Next, the proxy calculates the target(s) of the request. The set of targets will either be predetermined by the contents of the request or will be obtained from an abstract location service. Each target in the set is represented as a URI. If the domain of the Request-URI indicates a domain this element is not responsible for, the Request-URI MUST be placed into the target set as the only target, and the element MUST proceed to the task of Request Forwarding (Section 16.6). If the target set for the request has not been predetermined as described above, this implies that the element is responsible for the domain in the Request-URI, and the element MAY use whatever mechanism it desires to determine where to send the request. Any of these mechanisms can be modeled as accessing an abstract Location Service. This may consist of obtaining information from a location service created by a SIP Registrar, reading a database, consulting a presence server, utilizing other protocols, or simply performing an algorithmic substitution on the Request-URI. When accessing the location service constructed by a registrar, the Request-URI MUST first be canonicalized as described in Section 10.3 before being used as an index. The output of these mechanisms is used to construct the target set. */ // Non-SIP // Foreign SIP // Local SIP // FIX ME: we may have tel: here SIP_Uri requestUri = (SIP_Uri) e.Request.RequestLine.Uri; // Proxy is not responsible for the domain in the Request-URI. if (!OnIsLocalUri(requestUri.Host)) { /* NAT traversal. When we do record routing, store request sender flow info and request target flow info. Now the tricky part, how proxy later which flow is target (because both sides can send requests). Sender-flow will store from-tag to flow and target-flow will store flowID only (Because we don't know to-tag). Later if request to-tag matches(incoming request), use that flow, otherwise(outgoing request) other flow. flowInfo: sender-flow "/" target-flow sender-flow = from-tag ":" flowID target-flow = flowID */ SIP_Flow targetFlow = null; string flowInfo = (route != null && route.Parameters["flowInfo"] != null) ? route.Parameters["flowInfo"].Value : null; if (flowInfo != null && request.To.Tag != null) { string flow1Tag = flowInfo.Substring(0, flowInfo.IndexOf(':')); string flow1ID = flowInfo.Substring(flowInfo.IndexOf(':') + 1, flowInfo.IndexOf('/') - flowInfo.IndexOf(':') - 1); string flow2ID = flowInfo.Substring(flowInfo.IndexOf('/') + 1); if (flow1Tag == request.To.Tag) { targetFlow = m_pStack.TransportLayer.GetFlow(flow1ID); } else { ; targetFlow = m_pStack.TransportLayer.GetFlow(flow2ID); } } targetSet.Add(new SIP_ProxyTarget(requestUri, targetFlow)); } // Proxy is responsible for the domain in the Request-URI. else { // TODO: tel: //SIP_Uri requestUri = SIP_Uri.Parse(e.Request.Uri); // Try to get AOR from registrar. SIP_Registration registration = m_pRegistrar.GetRegistration(requestUri.Address); // We have AOR specified in request-URI in registrar server. if (registration != null) { // Add all AOR SIP contacts to target set. foreach (SIP_RegistrationBinding binding in registration.Bindings) { if (binding.ContactURI is SIP_Uri && binding.TTL > 0) { targetSet.Add(new SIP_ProxyTarget((SIP_Uri) binding.ContactURI, binding.Flow)); } } } // We don't have AOR specified in request-URI in registrar server. else { // If the Request-URI indicates a resource at this proxy that does not // exist, the proxy MUST return a 404 (Not Found) response. if (!OnAddressExists(requestUri.Address)) { e.ServerTransaction.SendResponse( m_pStack.CreateResponse(SIP_ResponseCodes.x404_Not_Found, e.Request)); return; } } } // If the target set remains empty after applying all of the above, the proxy MUST return an error response, // which SHOULD be the 480 (Temporarily Unavailable) response. if (targetSet.Count == 0) { e.ServerTransaction.SendResponse( m_pStack.CreateResponse(SIP_ResponseCodes.x480_Temporarily_Unavailable, e.Request)); return; } #endregion #region 4. Forward the request (Section 16.6) #region Statefull if (statefull) { // Create proxy context that will be responsible for forwarding request. SIP_ProxyContext proxyContext = new SIP_ProxyContext(this, e.ServerTransaction, request, addRecordRoute, m_ForkingMode, (ProxyMode & SIP_ProxyMode.B2BUA) != 0, false, false, targetSet.ToArray(), credentials.ToArray()); m_pProxyContexts.Add(proxyContext); proxyContext.Start(); } #endregion #region Stateless else { /* RFC 3261 16.6 Request Forwarding. For each target, the proxy forwards the request following these steps: 1. Make a copy of the received request 2. Update the Request-URI 3. Update the Max-Forwards header field 4. Optionally add a Record-route header field value 5. Optionally add additional header fields 6. Postprocess routing information 7. Determine the next-hop address, port, and transport 8. Add a Via header field value 9. Add a Content-Length header field if necessary 10. Forward the new request */ /* RFC 3261 16.11 Stateless Proxy. o A stateless proxy MUST choose one and only one target from the target set. This choice MUST only rely on fields in the message and time-invariant properties of the server. In particular, a retransmitted request MUST be forwarded to the same destination each time it is processed. Furthermore, CANCEL and non-Routed ACK requests MUST generate the same choice as their associated INVITE. However, a stateless proxy cannot simply use a random number generator to compute the first component of the branch ID, as described in Section 16.6 bullet 8. This is because retransmissions of a request need to have the same value, and a stateless proxy cannot tell a retransmission from the original request. We just use: "z9hG4bK-" + md5(topmost branch) */ bool isStrictRoute = false; SIP_Hop[] hops = null; #region 1. Make a copy of the received request SIP_Request forwardRequest = request.Copy(); #endregion #region 2. Update the Request-URI forwardRequest.RequestLine.Uri = targetSet[0].TargetUri; #endregion #region 3. Update the Max-Forwards header field forwardRequest.MaxForwards--; #endregion #region 4. Optionally add a Record-route header field value #endregion #region 5. Optionally add additional header fields #endregion #region 6. Postprocess routing information /* 6. Postprocess routing information. If the copy contains a Route header field, the proxy MUST inspect the URI in its first value. If that URI does not contain an lr parameter, the proxy MUST modify the copy as follows: - The proxy MUST place the Request-URI into the Route header field as the last value. - The proxy MUST then place the first Route header field value into the Request-URI and remove that value from the Route header field. */ if (forwardRequest.Route.GetAllValues().Length > 0 && !forwardRequest.Route.GetTopMostValue().Parameters.Contains("lr")) { forwardRequest.Route.Add(forwardRequest.RequestLine.Uri.ToString()); forwardRequest.RequestLine.Uri = SIP_Utils.UriToRequestUri(forwardRequest.Route.GetTopMostValue().Address.Uri); forwardRequest.Route.RemoveTopMostValue(); isStrictRoute = true; } #endregion #region 7. Determine the next-hop address, port, and transport /* 7. Determine the next-hop address, port, and transport. The proxy MAY have a local policy to send the request to a specific IP address, port, and transport, independent of the values of the Route and Request-URI. Such a policy MUST NOT be used if the proxy is not certain that the IP address, port, and transport correspond to a server that is a loose router. However, this mechanism for sending the request through a specific next hop is NOT RECOMMENDED; instead a Route header field should be used for that purpose as described above. In the absence of such an overriding mechanism, the proxy applies the procedures listed in [4] as follows to determine where to send the request. If the proxy has reformatted the request to send to a strict-routing element as described in step 6 above, the proxy MUST apply those procedures to the Request-URI of the request. Otherwise, the proxy MUST apply the procedures to the first value in the Route header field, if present, else the Request-URI. The procedures will produce an ordered set of (address, port, transport) tuples. Independently of which URI is being used as input to the procedures of [4], if the Request-URI specifies a SIPS resource, the proxy MUST follow the procedures of [4] as if the input URI were a SIPS URI. As described in [4], the proxy MUST attempt to deliver the message to the first tuple in that set, and proceed through the set in order until the delivery attempt succeeds. For each tuple attempted, the proxy MUST format the message as appropriate for the tuple and send the request using a new client transaction as detailed in steps 8 through 10. Since each attempt uses a new client transaction, it represents a new branch. Thus, the branch parameter provided with the Via header field inserted in step 8 MUST be different for each attempt. If the client transaction reports failure to send the request or a timeout from its state machine, the proxy continues to the next address in that ordered set. If the ordered set is exhausted, the request cannot be forwarded to this element in the target set. The proxy does not need to place anything in the response context, but otherwise acts as if this element of the target set returned a 408 (Request Timeout) final response. */ SIP_Uri uri = null; if (isStrictRoute) { uri = (SIP_Uri) forwardRequest.RequestLine.Uri; } else if (forwardRequest.Route.GetTopMostValue() != null) { uri = (SIP_Uri) forwardRequest.Route.GetTopMostValue().Address.Uri; } else { uri = (SIP_Uri) forwardRequest.RequestLine.Uri; } hops = m_pStack.GetHops(uri, forwardRequest.ToByteData().Length, ((SIP_Uri) forwardRequest.RequestLine.Uri).IsSecure); if (hops.Length == 0) { if (forwardRequest.RequestLine.Method != SIP_Methods.ACK) { e.ServerTransaction.SendResponse( m_pStack.CreateResponse( SIP_ResponseCodes.x503_Service_Unavailable + ": No hop(s) for target.", forwardRequest)); } return; } #endregion #region 8. Add a Via header field value forwardRequest.Via.AddToTop( "SIP/2.0/transport-tl-addign sentBy-tl-assign-it;branch=z9hG4bK-" + Core.ComputeMd5(request.Via.GetTopMostValue().Branch, true)); // Add 'flowID' what received request, you should use the same flow to send response back. // For more info see RFC 3261 18.2.2. forwardRequest.Via.GetTopMostValue().Parameters.Add("flowID", request.Flow.ID); #endregion #region 9. Add a Content-Length header field if necessary // Skip, our SIP_Message class is smart and do it when ever it's needed. #endregion #region 10. Forward the new request try { try { if (targetSet[0].Flow != null) { m_pStack.TransportLayer.SendRequest(targetSet[0].Flow, request); return; } } catch { m_pStack.TransportLayer.SendRequest(request, null, hops[0]); } } catch (SIP_TransportException x) { string dummy = x.Message; if (forwardRequest.RequestLine.Method != SIP_Methods.ACK) { /* RFC 3261 16.9 Handling Transport Errors If the transport layer notifies a proxy of an error when it tries to forward a request (see Section 18.4), the proxy MUST behave as if the forwarded request received a 503 (Service Unavailable) response. */ e.ServerTransaction.SendResponse( m_pStack.CreateResponse( SIP_ResponseCodes.x503_Service_Unavailable + ": Transport error.", forwardRequest)); } } #endregion } #endregion #endregion } /// <summary> /// Authenticates SIP request. This method also sends all needed replys to request sender. /// </summary> /// <param name="e">Request event arguments.</param> /// <returns>Returns true if request was authenticated.</returns> internal bool AuthenticateRequest(SIP_RequestReceivedEventArgs e) { string userName = null; return AuthenticateRequest(e, out userName); } /// <summary> /// Authenticates SIP request. This method also sends all needed replys to request sender. /// </summary> /// <param name="e">Request event arguments.</param> /// <param name="userName">If authentication sucessful, then authenticated user name is stored to this variable.</param> /// <returns>Returns true if request was authenticated.</returns> internal bool AuthenticateRequest(SIP_RequestReceivedEventArgs e, out string userName) { userName = null; SIP_t_Credentials credentials = SIP_Utils.GetCredentials(e.Request, m_pStack.Realm); // No credentials for our realm. if (credentials == null) { SIP_Response notAuthenticatedResponse = m_pStack.CreateResponse(SIP_ResponseCodes.x407_Proxy_Authentication_Required, e.Request); notAuthenticatedResponse.ProxyAuthenticate.Add( new Auth_HttpDigest(m_pStack.Realm, m_pStack.DigestNonceManager.CreateNonce(), m_Opaque). ToChallange()); e.ServerTransaction.SendResponse(notAuthenticatedResponse); return false; } Auth_HttpDigest auth = new Auth_HttpDigest(credentials.AuthData, e.Request.RequestLine.Method); // Check opaque validity. if (auth.Opaque != m_Opaque) { SIP_Response notAuthenticatedResponse = m_pStack.CreateResponse( SIP_ResponseCodes.x407_Proxy_Authentication_Required + ": Opaque value won't match !", e.Request); notAuthenticatedResponse.ProxyAuthenticate.Add( new Auth_HttpDigest(m_pStack.Realm, m_pStack.DigestNonceManager.CreateNonce(), m_Opaque). ToChallange()); // Send response e.ServerTransaction.SendResponse(notAuthenticatedResponse); return false; } // Check nonce validity. if (!m_pStack.DigestNonceManager.NonceExists(auth.Nonce)) { SIP_Response notAuthenticatedResponse = m_pStack.CreateResponse( SIP_ResponseCodes.x407_Proxy_Authentication_Required + ": Invalid nonce value !", e.Request); notAuthenticatedResponse.ProxyAuthenticate.Add( new Auth_HttpDigest(m_pStack.Realm, m_pStack.DigestNonceManager.CreateNonce(), m_Opaque). ToChallange()); // Send response e.ServerTransaction.SendResponse(notAuthenticatedResponse); return false; } // Valid nonce, consume it so that nonce can't be used any more. else { m_pStack.DigestNonceManager.RemoveNonce(auth.Nonce); } SIP_AuthenticateEventArgs eArgs = OnAuthenticate(auth); // Authenticate failed. if (!eArgs.Authenticated) { SIP_Response notAuthenticatedResponse = m_pStack.CreateResponse( SIP_ResponseCodes.x407_Proxy_Authentication_Required + ": Authentication failed.", e.Request); notAuthenticatedResponse.ProxyAuthenticate.Add( new Auth_HttpDigest(m_pStack.Realm, m_pStack.DigestNonceManager.CreateNonce(), m_Opaque). ToChallange()); // Send response e.ServerTransaction.SendResponse(notAuthenticatedResponse); return false; } userName = auth.UserName; return true; } /// <summary> /// Gets if this proxy server is responsible for specified route. /// </summary> /// <param name="uri">Route value to check.</param> /// <returns>Returns trues if server route, otherwise false.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>uri</b> is null reference.</exception> internal bool IsLocalRoute(SIP_Uri uri) { if (uri == null) { throw new ArgumentNullException("uri"); } // Not a route. if (uri.User != null) { return false; } // Consider any IP address as local route, because if server behind NAT we can't do IP check. if (Net_Utils.IsIPAddress(uri.Host)) { return true; } else { foreach (IPBindInfo bind in m_pStack.BindInfo) { if (uri.Host.ToLower() == bind.HostName.ToLower()) { return true; } } } return false; } // REMOVE ME: /* /// <summary> /// Creates new Contact header field for b2bua forward request. /// </summary> /// <param name="address">Address.</param> /// <returns>Returns new Contact value.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>address</b> is null.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> internal SIP_t_NameAddress CreateContactX(SIP_t_NameAddress address) { if(address == null){ throw new ArgumentNullException("address"); } if(address.IsSipOrSipsUri){ SIP_Uri uri = SIP_Uri.Parse(address.Uri.ToString()); uri.Host = m_pStack.TransportLayer.GetEndPoint(address.Uri); uri.Port = -1; SIP_t_NameAddress contact = new SIP_t_NameAddress(); contact.Uri = uri; return contact; } else{ throw new ArgumentException("Not SIP URI !"); } }*/ /// <summary> /// Raises 'IsLocalUri' event. /// </summary> /// <param name="uri">Request URI.</param> /// <returns>Returns true if server local URI, otherwise false.</returns> internal bool OnIsLocalUri(string uri) { if (IsLocalUri != null) { return IsLocalUri(uri); } return true; } /// <summary> /// Is called by SIP proxy or registrar server when it needs to authenticate user. /// </summary> /// <param name="auth">Authentication context.</param> /// <returns></returns> internal SIP_AuthenticateEventArgs OnAuthenticate(Auth_HttpDigest auth) { SIP_AuthenticateEventArgs eArgs = new SIP_AuthenticateEventArgs(auth); if (Authenticate != null) { Authenticate(eArgs); } return eArgs; } /// <summary> /// Is called by SIP proxy if it needs to check if specified address exists. /// </summary> /// <param name="address">SIP address to check.</param> /// <returns>Returns true if specified address exists, otherwise false.</returns> internal bool OnAddressExists(string address) { if (AddressExists != null) { return AddressExists(address); } return false; } #endregion /// <summary> /// Is called by SIP proxy when SIP proxy needs to get gateways for non-SIP URI. /// </summary> /// <param name="uriScheme">Non-SIP URI scheme which gateways to get.</param> /// <param name="userName">Authenticated user name.</param> /// <returns>Returns event data.</returns> protected SIP_GatewayEventArgs OnGetGateways(string uriScheme, string userName) { SIP_GatewayEventArgs e = new SIP_GatewayEventArgs(uriScheme, userName); if (GetGateways != null) { GetGateways(e); } return e; } } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/Net_Utils.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net { #region usings using System; using System.IO; using System.Net; using System.Net.Sockets; using System.Text; #endregion /// <summary> /// Common utility methods. /// </summary> public class Net_Utils { #region Methods /// <summary> /// Gets local host name or argument <b>hostName</b> value if it's specified. /// </summary> /// <param name="hostName">Host name or null.</param> /// <returns>Returns local host name or argument <b>hostName</b> value if it's specified.</returns> public static string GetLocalHostName(string hostName) { if (string.IsNullOrEmpty(hostName)) { return System.Net.Dns.GetHostName(); } else { return hostName; } } /// <summary> /// Compares if specified array itmes equals. /// </summary> /// <param name="array1">Array 1.</param> /// <param name="array2">Array 2</param> /// <returns>Returns true if both arrays are equal.</returns> public static bool CompareArray(Array array1, Array array2) { return CompareArray(array1, array2, array2.Length); } /// <summary> /// Compares if specified array itmes equals. /// </summary> /// <param name="array1">Array 1.</param> /// <param name="array2">Array 2</param> /// <param name="array2Count">Number of bytes in array 2 used for compare.</param> /// <returns>Returns true if both arrays are equal.</returns> public static bool CompareArray(Array array1, Array array2, int array2Count) { if (array1 == null && array2 == null) { return true; } if (array1 == null && array2 != null) { return false; } if (array1 != null && array2 == null) { return false; } if (array1.Length != array2Count) { return false; } else { for (int i = 0; i < array1.Length; i++) { if (!array1.GetValue(i).Equals(array2.GetValue(i))) { return false; } } } return true; } /// <summary> /// Copies <b>source</b> stream data to <b>target</b> stream. /// </summary> /// <param name="source">Source stream. Reading starts from stream current position.</param> /// <param name="target">Target stream. Writing starts from stream current position.</param> /// <param name="blockSize">Specifies transfer block size in bytes.</param> /// <returns>Returns number of bytes copied.</returns> public static long StreamCopy(Stream source, Stream target, int blockSize) { if (source == null) { throw new ArgumentNullException("source"); } if (target == null) { throw new ArgumentNullException("target"); } if (blockSize < 1024) { throw new ArgumentException("Argument 'blockSize' value must be >= 1024."); } byte[] buffer = new byte[blockSize]; long totalReaded = 0; while (true) { int readedCount = source.Read(buffer, 0, buffer.Length); // We reached end of stream, we readed all data sucessfully. if (readedCount == 0) { return totalReaded; } else { target.Write(buffer, 0, readedCount); totalReaded += readedCount; } } } /// <summary> /// Gets if the specified string value is IP address. /// </summary> /// <param name="value">Value to check.</param> /// <returns>Returns true if specified value is IP address.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>value</b> is null reference.</exception> public static bool IsIPAddress(string value) { if (value == null) { throw new ArgumentNullException("value"); } IPAddress ip = null; return IPAddress.TryParse(value, out ip); } /// <summary> /// Gets if the specified IP address is multicast address. /// </summary> /// <param name="ip">IP address.</param> /// <returns>Returns true if <b>ip</b> is muticast address, otherwise false.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>ip</b> s null reference.</exception> public static bool IsMulticastAddress(IPAddress ip) { if (ip == null) { throw new ArgumentNullException("ip"); } // IPv4 multicast 172.16.17.32 to 172.16.58.3 if (ip.IsIPv6Multicast) { return true; } else if (ip.AddressFamily == AddressFamily.InterNetwork) { byte[] bytes = ip.GetAddressBytes(); if (bytes[0] >= 224 && bytes[0] <= 239) { return true; } } return false; } /// <summary> /// Parses IPEndPoint from the specified string value. /// </summary> /// <param name="value">IPEndPoint string value.</param> /// <returns>Returns parsed IPEndPoint.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>value</b> is null reference.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> public static IPEndPoint ParseIPEndPoint(string value) { if (value == null) { throw new ArgumentNullException("value"); } try { string[] ip_port = value.Split(':'); return new IPEndPoint(IPAddress.Parse(ip_port[0]), Convert.ToInt32(ip_port[1])); } catch (Exception x) { throw new ArgumentException("Invalid IPEndPoint value.", "value", x); } } /// <summary> /// Gets if IO completion ports supported by OS. /// </summary> /// <returns></returns> public static bool IsIoCompletionPortsSupported() { Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); try { SocketAsyncEventArgs e = new SocketAsyncEventArgs(); e.SetBuffer(new byte[0], 0, 0); e.RemoteEndPoint = new IPEndPoint(IPAddress.Loopback, 111); s.SendToAsync(e); return true; } catch (NotSupportedException nX) { string dummy = nX.Message; return false; } finally { s.Close(); } } /// <summary> /// Converts specified string to HEX string. /// </summary> /// <param name="text">String to convert.</param> /// <returns>Returns hex string.</returns> public static string Hex(string text) { return BitConverter.ToString(Encoding.Default.GetBytes(text)).ToLower().Replace("-", ""); } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/SIP/Message/SIP_t_ReferSub.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.SIP.Message { #region usings using System; using System.Text; #endregion /// <summary> /// Implements SIP "refer-sub" value. Defined in RFC 4488. /// </summary> /// <remarks> /// <code> /// RFC 4488 Syntax: /// Refer-Sub = refer-sub-value *(SEMI exten) /// refer-sub-value = "true" / "false" /// exten = generic-param /// </code> /// </remarks> public class SIP_t_ReferSub : SIP_t_ValueWithParams { #region Members private bool m_Value; #endregion #region Properties /// <summary> /// Gets or sets refer-sub-value value. /// </summary> public bool Value { get { return m_Value; } set { m_Value = value; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> public SIP_t_ReferSub() {} /// <summary> /// Default constructor. /// </summary> /// <param name="value">Refer-Sub value.</param> public SIP_t_ReferSub(string value) { Parse(value); } #endregion #region Methods /// <summary> /// Parses "Refer-Sub" from specified value. /// </summary> /// <param name="value">SIP "Refer-Sub" value.</param> /// <exception cref="ArgumentNullException">Raised when <b>value</b> is null.</exception> /// <exception cref="SIP_ParseException">Raised when invalid SIP message.</exception> public void Parse(string value) { if (value == null) { throw new ArgumentNullException("value"); } Parse(new StringReader(value)); } /// <summary> /// Parses "Refer-Sub" from specified reader. /// </summary> /// <param name="reader">Reader from where to parse.</param> /// <exception cref="ArgumentNullException">Raised when <b>reader</b> is null.</exception> /// <exception cref="SIP_ParseException">Raised when invalid SIP message.</exception> public override void Parse(StringReader reader) { /* Refer-Sub = refer-sub-value *(SEMI exten) refer-sub-value = "true" / "false" exten = generic-param */ if (reader == null) { throw new ArgumentNullException("reader"); } // refer-sub-value string word = reader.ReadWord(); if (word == null) { throw new SIP_ParseException("Refer-Sub refer-sub-value value is missing !"); } try { m_Value = Convert.ToBoolean(word); } catch { throw new SIP_ParseException("Invalid Refer-Sub refer-sub-value value !"); } // Parse parameters ParseParameters(reader); } /// <summary> /// Converts this to valid "contact-param" value. /// </summary> /// <returns>Returns "contact-param" value.</returns> public override string ToStringValue() { /* Refer-Sub = refer-sub-value *(SEMI exten) refer-sub-value = "true" / "false" exten = generic-param */ StringBuilder retVal = new StringBuilder(); // refer-sub-value retVal.Append(m_Value.ToString()); // Add parameters retVal.Append(ParametersToString()); return retVal.ToString(); } #endregion } }<file_sep>/redistributable/SelectelSharp/Models/File/GetFileResult.cs #region Import using SelectelSharp.Headers; using System.Collections.Specialized; using System.IO; #endregion namespace SelectelSharp.Models.File { public class GetFileResult : FileInfo { public Stream ResponseStream { get; set; } public GetFileResult(Stream responseStream, string name, NameValueCollection headers) { HeaderParsers.ParseHeaders(this, headers); this.ResponseStream = responseStream; this.Name = name; } } } <file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/SMTP/Server/SMTP_RcptTo.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.SMTP.Server { #region usings using System; #endregion /// <summary> /// This class holds RCPT TO: command value. /// </summary> public class SMTP_RcptTo { #region Members private readonly string m_Mailbox = ""; private readonly SMTP_Notify m_Notify = SMTP_Notify.NotSpecified; private readonly string m_ORCPT = ""; #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="mailbox">Mailbox value.</param> /// <param name="notify">DSN NOTIFY parameter value.</param> /// <param name="orcpt">DSN ORCPT parameter value.</param> /// <exception cref="ArgumentNullException">Is raised when <b>mailbox</b> is null reference.</exception> public SMTP_RcptTo(string mailbox, SMTP_Notify notify, string orcpt) { if (mailbox == null) { throw new ArgumentNullException("mailbox"); } m_Mailbox = mailbox; m_Notify = notify; m_ORCPT = orcpt; } #endregion #region Properties /// <summary> /// Gets SMTP "mailbox" value. Actually this is just email address. /// </summary> public string Mailbox { get { return m_Mailbox; } } /// <summary> /// Gets DSN NOTIFY parameter value. /// This value specified when SMTP server should send delivery status notification. /// Defined in RFC 1891. /// </summary> public SMTP_Notify Notify { get { return m_Notify; } } /// <summary> /// Gets DSN ORCPT parameter value. Value null means not specified. /// This value specifies "original" recipient address where message is sent (has point only when message forwarded). /// Defined in RFC 1891. /// </summary> public string ORCPT { get { return m_ORCPT; } } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/SIP/Stack/SIP_Dialog_Invite.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.SIP.Stack { #region usings using System; using System.Collections.Generic; using System.Timers; using Message; using SDP; #endregion /// <summary> /// This class represent INVITE dialog. Defined in RFC 3261. /// </summary> public class SIP_Dialog_Invite : SIP_Dialog { #region Nested type: UacInvite2xxRetransmissionWaiter /// <summary> /// This class waits INVITE 2xx response retransmissions and answers with ACK request to them. /// For more info see RFC 3261 172.16.58.3. /// </summary> private class UacInvite2xxRetransmissionWaiter { #region Members private bool m_IsDisposed; private SIP_Dialog_Invite m_pDialog; private SIP_Request m_pInvite; private object m_pLock = ""; private TimerEx m_pTimer; #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="dialog">Owner INVITE dialog.</param> /// <param name="invite">INVITE request which 2xx retransmission to wait.</param> /// <exception cref="ArgumentNullException">Is raised when <b>dialog</b> or <b>invite</b> is null reference.</exception> public UacInvite2xxRetransmissionWaiter(SIP_Dialog_Invite dialog, SIP_Request invite) { if (dialog == null) { throw new ArgumentNullException("dialog"); } if (invite == null) { throw new ArgumentNullException("invite"); } m_pDialog = dialog; m_pInvite = invite; /* RFC 3261 13.2.2.4. The UAC core considers the INVITE transaction completed 64*T1 seconds after the reception of the first 2xx response. */ m_pTimer = new TimerEx(64*SIP_TimerConstants.T1, false); m_pTimer.Elapsed += m_pTimer_Elapsed; m_pTimer.Enabled = true; } #endregion #region Methods /// <summary> /// Cleans up any resources being used. /// </summary> public void Dispose() { lock (m_pLock) { if (m_IsDisposed) { return; } m_IsDisposed = true; m_pDialog.m_pUacInvite2xxRetransmitWaits.Remove(this); m_pDialog = null; m_pInvite = null; if (m_pTimer != null) { m_pTimer.Dispose(); m_pTimer = null; } } } /// <summary> /// Checks if specified response matches this 2xx response retransmission wait entry. /// </summary> /// <param name="response">INVITE 2xx response.</param> /// <returns>Returns true if response matches, othwerwise false.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>response</b> is null reference value.</exception> public bool Match(SIP_Response response) { if (response == null) { throw new ArgumentNullException("response"); } if (m_pInvite.CSeq.RequestMethod == response.CSeq.RequestMethod && m_pInvite.CSeq.SequenceNumber == response.CSeq.SequenceNumber) { return true; } else { return false; } } /// <summary> /// Processes retransmited INVITE 2xx response. /// </summary> /// <param name="response">INVITE 2xx response.</param> /// <exception cref="ArgumentNullException">Is raised when <b>response</b> is null reference.</exception> public void Process(SIP_Response response) { if (response == null) { throw new ArgumentNullException("response"); } lock (m_pLock) { SIP_Request ack = CreateAck(); try { // Try existing flow. m_pDialog.Flow.Send(ack); // Log if (m_pDialog.Stack.Logger != null) { byte[] ackBytes = ack.ToByteData(); m_pDialog.Stack.Logger.AddWrite(m_pDialog.ID, null, ackBytes.Length, "Dialog [id='" + m_pDialog.ID + "] ACK sent for 2xx response.", m_pDialog.Flow.LocalEP, m_pDialog.Flow.RemoteEP, ackBytes); } } catch { /* RFC 3261 13.2.2.4. Once the ACK has been constructed, the procedures of [4] are used to determine the destination address, port and transport. However, the request is passed to the transport layer directly for transmission, rather than a client transaction. */ try { m_pDialog.Stack.TransportLayer.SendRequest(ack); } catch (Exception x) { // Log if (m_pDialog.Stack.Logger != null) { m_pDialog.Stack.Logger.AddText("Dialog [id='" + m_pDialog.ID + "'] ACK send for 2xx response failed: " + x.Message + "."); } } } } } #endregion #region Event handlers /// <summary> /// Is raised when INVITE 2xx retrasmission wait time expired. /// </summary> /// <param name="sender">Sender.</param> /// <param name="e">Event data.</param> private void m_pTimer_Elapsed(object sender, ElapsedEventArgs e) { Dispose(); } #endregion #region Utility methods /// <summary> /// Creates ACK request for pending INVITE. /// </summary> /// <returns>Returns created ACK request.</returns> private SIP_Request CreateAck() { /* RFC 3261 172.16.58.3. The header fields of the ACK are constructed in the same way as for any request sent within a dialog (see Section 12) with the exception of the CSeq and the header fields related to authentication. The sequence number of the CSeq header field MUST be the same as the INVITE being acknowledged, but the CSeq method MUST be ACK. The ACK MUST contain the same credentials as the INVITE. ACK must have same branch. */ SIP_Request ackRequest = m_pDialog.CreateRequest(SIP_Methods.ACK); ackRequest.Via.AddToTop(m_pInvite.Via.GetTopMostValue().ToStringValue()); ackRequest.CSeq = new SIP_t_CSeq(m_pInvite.CSeq.SequenceNumber, SIP_Methods.ACK); // Authorization foreach (SIP_HeaderField h in m_pInvite.Authorization.HeaderFields) { ackRequest.Authorization.Add(h.Value); } // Proxy-Authorization foreach (SIP_HeaderField h in m_pInvite.ProxyAuthorization.HeaderFields) { ackRequest.Authorization.Add(h.Value); } return ackRequest; } #endregion } #endregion #region Nested type: UasInvite2xxRetransmit /// <summary> /// This class is responsible for retransmitting INVITE 2xx response while ACK is received form target UAC. /// For more info see RFC 3261 192.168.3.11. /// </summary> private class UasInvite2xxRetransmit { #region Members private bool m_IsDisposed; private SIP_Dialog_Invite m_pDialog; private object m_pLock = ""; private SIP_Response m_pResponse; private TimerEx m_pTimer; private DateTime m_StartTime = DateTime.Now; #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="dialog">Owner INVITE dialog.</param> /// <param name="response">INVITE 2xx response.</param> /// <exception cref="ArgumentNullException">Is raised when <b>dialog</b> or <b>response</b> is null reference.</exception> public UasInvite2xxRetransmit(SIP_Dialog_Invite dialog, SIP_Response response) { if (dialog == null) { throw new ArgumentNullException("dialog"); } if (response == null) { throw new ArgumentNullException("response"); } m_pDialog = dialog; m_pResponse = response; /* RFC 3261 192.168.3.11. Once the response has been constructed, it is passed to the INVITE server transaction. Note, however, that the INVITE server transaction will be destroyed as soon as it receives this final response and passes it to the transport. Therefore, it is necessary to periodically pass the response directly to the transport until the ACK arrives. The 2xx response is passed to the transport with an interval that starts at T1 seconds and doubles for each retransmission until it reaches T2 seconds (T1 and T2 are defined in Section 17). Response retransmissions cease when an ACK request for the response is received. This is independent of whatever transport protocols are used to send the response. Since 2xx is retransmitted end-to-end, there may be hops between UAS and UAC that are UDP. To ensure reliable delivery across these hops, the response is retransmitted periodically even if the transport at the UAS is reliable. */ m_pTimer = new TimerEx(SIP_TimerConstants.T1, false); m_pTimer.Elapsed += m_pTimer_Elapsed; m_pTimer.Enabled = true; } #endregion #region Methods /// <summary> /// Cleans up any resources being used. /// </summary> public void Dispose() { lock (m_pLock) { if (m_IsDisposed) { return; } m_IsDisposed = true; m_pDialog.m_pUasInvite2xxRetransmits.Remove(this); if (m_pTimer != null) { m_pTimer.Dispose(); m_pTimer = null; } m_pDialog = null; m_pResponse = null; } } /// <summary> /// Checks if specified ACK request matches this 2xx response retransmission. /// </summary> /// <param name="ackRequest">ACK request.</param> /// <returns>Returns true if ACK matches, othwerwise false.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>ackRequest</b> is null reference value.</exception> public bool MatchAck(SIP_Request ackRequest) { if (ackRequest == null) { throw new ArgumentNullException("ackRequest"); } if (ackRequest.CSeq.SequenceNumber == m_pResponse.CSeq.SequenceNumber) { return true; } else { return false; } } #endregion #region Event handlers /// <summary> /// This method is called when INVITE 2xx retransmit timer triggered. /// </summary> /// <param name="sender">Sender.</param> /// <param name="e">Event data.</param> private void m_pTimer_Elapsed(object sender, ElapsedEventArgs e) { /* RFC 3261 192.168.3.11. Once the response has been constructed, it is passed to the INVITE server transaction. Note, however, that the INVITE server transaction will be destroyed as soon as it receives this final response and passes it to the transport. Therefore, it is necessary to periodically pass the response directly to the transport until the ACK arrives. The 2xx response is passed to the transport with an interval that starts at T1 seconds and doubles for each retransmission until it reaches T2 seconds (T1 and T2 are defined in Section 17). Response retransmissions cease when an ACK request for the response is received. This is independent of whatever transport protocols are used to send the response. Since 2xx is retransmitted end-to-end, there may be hops between UAS and UAC that are UDP. To ensure reliable delivery across these hops, the response is retransmitted periodically even if the transport at the UAS is reliable. If the server retransmits the 2xx response for 64*T1 seconds without receiving an ACK, the dialog is confirmed, but the session SHOULD be terminated. This is accomplished with a BYE, as described in Section 15. */ lock (m_pLock) { if (m_StartTime.AddMilliseconds(64*SIP_TimerConstants.T1) < DateTime.Now) { // Log if (m_pDialog.Stack.Logger != null) { m_pDialog.Stack.Logger.AddText("Dialog [id='" + m_pDialog.ID + "'] ACK was not received for (re-)INVITE, terminating INVITE session."); } m_pDialog.Terminate("Dialog Error: ACK was not received for (re-)INVITE.", true); Dispose(); } else { // Retransmit response. try { m_pDialog.Flow.Send(m_pResponse); // Log if (m_pDialog.Stack.Logger != null) { m_pDialog.Stack.Logger.AddText("Dialog [id='" + m_pDialog.ID + "';statusCode=" + m_pResponse.StatusCode + "] UAS 2xx response retransmited"); } } catch (Exception x) { // Log if (m_pDialog.Stack.Logger != null) { m_pDialog.Stack.Logger.AddText("Dialog [id='" + m_pDialog.ID + "'] UAS 2xx response retransmission failed: " + x.Message); } } m_pTimer.Interval = Math.Min(m_pTimer.Interval*2, SIP_TimerConstants.T2); m_pTimer.Enabled = true; } } } #endregion } #endregion #region Events /// <summary> /// Is raised when re-INVITE is received. /// </summary> /// <remarks>INVITE dialog consumer always should respond to this event(accept or decline it).</remarks> public event EventHandler Reinvite = null; #endregion #region Members private SIP_Transaction m_pActiveInvite; private List<UacInvite2xxRetransmissionWaiter> m_pUacInvite2xxRetransmitWaits; private List<UasInvite2xxRetransmit> m_pUasInvite2xxRetransmits; #endregion #region Properties /// <summary> /// Gets if dialog has pending INVITE transaction. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public bool HasPendingInvite { get { if (State == SIP_DialogState.Disposed) { throw new ObjectDisposedException(GetType().Name); } if (m_pActiveInvite != null) { return true; } else { return false; } } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> internal SIP_Dialog_Invite() { m_pUasInvite2xxRetransmits = new List<UasInvite2xxRetransmit>(); m_pUacInvite2xxRetransmitWaits = new List<UacInvite2xxRetransmissionWaiter>(); } #endregion #region Methods /// <summary> /// Cleans up any resources being used. /// </summary> public override void Dispose() { lock (SyncRoot) { if (State == SIP_DialogState.Disposed) { return; } foreach (UasInvite2xxRetransmit t in m_pUasInvite2xxRetransmits.ToArray()) { t.Dispose(); } m_pUasInvite2xxRetransmits = null; foreach (UacInvite2xxRetransmissionWaiter w in m_pUacInvite2xxRetransmitWaits.ToArray()) { w.Dispose(); } m_pUacInvite2xxRetransmitWaits = null; m_pActiveInvite = null; base.Dispose(); } } /// <summary> /// Starts terminating dialog. /// </summary> /// <param name="reason">Termination reason. This value may be null.</param> /// <param name="sendBye">If true BYE is sent to remote party.</param> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this method is accessed.</exception> public override void Terminate(string reason, bool sendBye) { lock (SyncRoot) { if (State == SIP_DialogState.Disposed) { throw new ObjectDisposedException(GetType().Name); } if (State == SIP_DialogState.Terminating || State == SIP_DialogState.Terminated) { return; } /* RFC 3261 15. The caller's UA MAY send a BYE for either confirmed or early dialogs, and the callee's UA MAY send a BYE on confirmed dialogs, but MUST NOT send a BYE on early dialogs. RFC 3261 15.1. Once the BYE is constructed, the UAC core creates a new non-INVITE client transaction, and passes it the BYE request. The UAC MUST consider the session terminated (and therefore stop sending or listening for media) as soon as the BYE request is passed to the client transaction. If the response for the BYE is a 481 (Call/Transaction Does Not Exist) or a 408 (Request Timeout) or no response at all is received for the BYE (that is, a timeout is returned by the client transaction), the UAC MUST consider the session and the dialog terminated. */ if (sendBye) { if ((State == SIP_DialogState.Early && m_pActiveInvite is SIP_ClientTransaction) || State == SIP_DialogState.Confirmed) { SetState(SIP_DialogState.Terminating, true); SIP_Request bye = CreateRequest(SIP_Methods.BYE); if (!string.IsNullOrEmpty(reason)) { SIP_t_ReasonValue r = new SIP_t_ReasonValue(); r.Protocol = "SIP"; r.Text = reason; bye.Reason.Add(r.ToStringValue()); } // Send BYE, just wait BYE to complete, we don't care about response code. SIP_RequestSender sender = CreateRequestSender(bye); sender.Completed += delegate { SetState(SIP_DialogState.Terminated, true); }; sender.Start(); } else { /* We are "early" UAS dialog, we need todo follwoing: *) If we havent sent final response, send '408 Request terminated' and we are done. *) We have sen't final response, we need to wait ACK to arrive or timeout. If will ACK arrives or timeout, send BYE. */ if (m_pActiveInvite != null && m_pActiveInvite.FinalResponse == null) { Stack.CreateResponse(SIP_ResponseCodes.x408_Request_Timeout, m_pActiveInvite.Request); SetState(SIP_DialogState.Terminated, true); } else { // Wait ACK to arrive or timeout. SetState(SIP_DialogState.Terminating, true); } } } else { SetState(SIP_DialogState.Terminated, true); } } } /// <summary> /// Re-invites remote party. /// </summary> /// <param name="contact">New contact value. Value null means current contact value used.</param> /// <param name="sdp">SDP media offer.</param> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this method is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when there is pending invite and this method is called or dialog is in invalid state.</exception> /// <exception cref="ArgumentNullException">Is raised when <b>sdp</b> is null reference.</exception> public void ReInvite(SIP_Uri contact, SDP_Message sdp) { if (State == SIP_DialogState.Disposed) { throw new ObjectDisposedException(GetType().Name); } if (HasPendingInvite) { throw new InvalidOperationException("There is pending INVITE."); } if (State != SIP_DialogState.Confirmed) { throw new InvalidOperationException("ReInvite is only available in Confirmed state."); } if (sdp == null) { throw new ArgumentNullException("sdp"); } lock (SyncRoot) { // TODO: SIP_Request reinvite = CreateRequest(SIP_Methods.INVITE); if (contact != null) { reinvite.Contact.RemoveAll(); reinvite.Contact.Add(contact.ToString()); } reinvite.ContentType = "application/sdp"; // reinvite.Data = sdp.ToStringData(); // TODO: Create request sender // TODO: Try to reuse existing data flow //SIP_RequestSender sender = this.Stack.CreateRequestSender(reinvite); //sender.Start(); } } #endregion #region Overrides /// <summary> /// Initializes dialog. /// </summary> /// <param name="stack">Owner stack.</param> /// <param name="transaction">Owner transaction.</param> /// <param name="response">SIP response what caused dialog creation.</param> /// <exception cref="ArgumentNullException">Is raised when <b>stack</b>,<b>transaction</b> or <b>response</b>.</exception> protected internal override void Init(SIP_Stack stack, SIP_Transaction transaction, SIP_Response response) { if (stack == null) { throw new ArgumentNullException("stack"); } if (transaction == null) { throw new ArgumentNullException("transaction"); } if (response == null) { throw new ArgumentNullException("response"); } base.Init(stack, transaction, response); if (transaction is SIP_ServerTransaction) { if (response.StatusCodeType == SIP_StatusCodeType.Success) { SetState(SIP_DialogState.Early, false); // We need to retransmit 2xx response while we get ACK or timeout. (RFC 3261 192.168.3.11.) m_pUasInvite2xxRetransmits.Add(new UasInvite2xxRetransmit(this, response)); } else if (response.StatusCodeType == SIP_StatusCodeType.Provisional) { SetState(SIP_DialogState.Early, false); m_pActiveInvite = transaction; m_pActiveInvite.StateChanged += delegate { if (m_pActiveInvite != null && m_pActiveInvite.State == SIP_TransactionState.Terminated) { m_pActiveInvite = null; } }; // Once we send 2xx response, we need to retransmit it while get ACK or timeout. (RFC 3261 192.168.3.11.) ((SIP_ServerTransaction) m_pActiveInvite).ResponseSent += delegate(object s, SIP_ResponseSentEventArgs a) { if (a.Response.StatusCodeType == SIP_StatusCodeType.Success) { m_pUasInvite2xxRetransmits.Add(new UasInvite2xxRetransmit(this, a.Response)); } }; } else { throw new ArgumentException( "Argument 'response' has invalid status code, 1xx - 2xx is only allowed."); } } else { if (response.StatusCodeType == SIP_StatusCodeType.Success) { SetState(SIP_DialogState.Confirmed, false); // Wait for retransmited 2xx responses. (RFC 3261 172.16.58.3.) m_pUacInvite2xxRetransmitWaits.Add(new UacInvite2xxRetransmissionWaiter(this, transaction. Request)); } else if (response.StatusCodeType == SIP_StatusCodeType.Provisional) { SetState(SIP_DialogState.Early, false); m_pActiveInvite = transaction; m_pActiveInvite.StateChanged += delegate { if (m_pActiveInvite != null && m_pActiveInvite.State == SIP_TransactionState.Terminated) { m_pActiveInvite = null; } }; // Once we receive 2xx response, we need to wait for retransmitted 2xx responses. (RFC 3261 172.16.58.3) ((SIP_ClientTransaction) m_pActiveInvite).ResponseReceived += delegate(object s, SIP_ResponseReceivedEventArgs a) { if (a.Response.StatusCodeType == SIP_StatusCodeType.Success) { UacInvite2xxRetransmissionWaiter waiter = new UacInvite2xxRetransmissionWaiter(this, m_pActiveInvite.Request); m_pUacInvite2xxRetransmitWaits.Add(waiter); // Force to send initial ACK to 2xx response. waiter.Process(a.Response); SetState(SIP_DialogState.Confirmed, true); } }; } else { throw new ArgumentException( "Argument 'response' has invalid status code, 1xx - 2xx is only allowed."); } } } /// <summary> /// Processes specified request through this dialog. /// </summary> /// <param name="e">Method arguments.</param> /// <returns>Returns true if this dialog processed specified request, otherwise false.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>e</b> is null reference.</exception> protected internal override bool ProcessRequest(SIP_RequestReceivedEventArgs e) { if (e == null) { throw new ArgumentNullException("e"); } if (base.ProcessRequest(e)) { return true; } // We must support: INVITE(re-invite),UPDATE,ACK, [BYE will be handled by base class] #region INVITE if (e.Request.RequestLine.Method == SIP_Methods.INVITE) { /* RFC 3261 14.2. A UAS that receives a second INVITE before it sends the final response to a first INVITE with a lower CSeq sequence number on the same dialog MUST return a 500 (Server Internal Error) response to the second INVITE and MUST include a Retry-After header field with a randomly chosen value of between 0 and 10 seconds. A UAS that receives an INVITE on a dialog while an INVITE it had sent on that dialog is in progress MUST return a 491 (Request Pending) response to the received INVITE. */ if (m_pActiveInvite != null && m_pActiveInvite is SIP_ServerTransaction && (m_pActiveInvite).Request.CSeq.SequenceNumber < e.Request.CSeq.SequenceNumber) { SIP_Response response = Stack.CreateResponse( SIP_ResponseCodes.x500_Server_Internal_Error + ": INVITE with a lower CSeq is pending(RFC 3261 14.2).", e.Request); response.RetryAfter = new SIP_t_RetryAfter("10"); e.ServerTransaction.SendResponse(response); return true; } if (m_pActiveInvite != null && m_pActiveInvite is SIP_ClientTransaction) { e.ServerTransaction.SendResponse( Stack.CreateResponse(SIP_ResponseCodes.x491_Request_Pending, e.Request)); return true; } // Force server transaction creation and set it as active INVITE transaction. m_pActiveInvite = e.ServerTransaction; m_pActiveInvite.StateChanged += delegate { if (m_pActiveInvite.State == SIP_TransactionState.Terminated) { m_pActiveInvite = null; } }; // Once we send 2xx response, we need to retransmit it while get ACK or timeout. (RFC 3261 192.168.3.11.) ((SIP_ServerTransaction) m_pActiveInvite).ResponseSent += delegate(object s, SIP_ResponseSentEventArgs a) { if (a.Response.StatusCodeType == SIP_StatusCodeType.Success) { m_pUasInvite2xxRetransmits.Add(new UasInvite2xxRetransmit(this, a.Response)); } }; OnReinvite(((SIP_ServerTransaction) m_pActiveInvite)); return true; } #endregion #region ACK else if (e.Request.RequestLine.Method == SIP_Methods.ACK) { // Search corresponding INVITE 2xx retransmit entry and dispose it. foreach (UasInvite2xxRetransmit t in m_pUasInvite2xxRetransmits) { if (t.MatchAck(e.Request)) { t.Dispose(); if (State == SIP_DialogState.Early) { SetState(SIP_DialogState.Confirmed, true); // TODO: If Terminating } return true; } } return false; } #endregion #region UPDATE //else if(request.RequestLine.Method == SIP_Methods.UPDATE){ // TODO: //} #endregion // RFC 5057 5.6. Refusing New Usages. Decline(603 Decline) new dialog usages. else if (SIP_Utils.MethodCanEstablishDialog(e.Request.RequestLine.Method)) { e.ServerTransaction.SendResponse( Stack.CreateResponse( SIP_ResponseCodes.x603_Decline + " : New dialog usages not allowed (RFC 5057).", e.Request)); return true; } else { return false; } } /// <summary> /// Processes specified response through this dialog. /// </summary> /// <param name="response">SIP response to process.</param> /// <returns>Returns true if this dialog processed specified response, otherwise false.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>response</b> is null.</exception> protected internal override bool ProcessResponse(SIP_Response response) { if (response == null) { throw new ArgumentNullException("response"); } if (response.StatusCodeType == SIP_StatusCodeType.Success) { // Search pending INVITE 2xx response retransmission waite entry. foreach (UacInvite2xxRetransmissionWaiter w in m_pUacInvite2xxRetransmitWaits) { if (w.Match(response)) { w.Process(response); return true; } } } return false; } #endregion #region Utility methods /// <summary> /// Raises <b>Reinvite</b> event. /// </summary> /// <param name="reinvite">Re-INVITE server transaction.</param> private void OnReinvite(SIP_ServerTransaction reinvite) { if (Reinvite != null) { Reinvite(this, new EventArgs()); } } #endregion } }<file_sep>/module/ASC.Api/ASC.Api.Mail/MailApi.Images.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections.Generic; using ASC.Api.Attributes; namespace ASC.Api.Mail { public partial class MailApi { /// <summary> /// Returns list of all trusted addresses for image displaying. /// </summary> /// <returns>Addresses list. Email adresses represented as string name@domain.</returns> /// <short>Get trusted addresses</short> /// <category>Images</category> [Read(@"display_images/addresses")] public IEnumerable<string> GetDisplayImagesAddresses() { return MailEngineFactory.DisplayImagesAddressEngine.Get(); } /// <summary> /// Add the address to trusted addresses. /// </summary> /// <param name="address">Address for adding. </param> /// <returns>Added address</returns> /// <short>Add trusted address</short> /// <exception cref="ArgumentException">Exception happens when in parameters is invalid. Text description contains parameter name and text description.</exception> /// <category>Images</category> [Create(@"display_images/address")] public string AddDisplayImagesAddress(string address) { MailEngineFactory.DisplayImagesAddressEngine.Add(address); return address; } /// <summary> /// Remove the address from trusted addresses. /// </summary> /// <param name="address">Address for removing</param> /// <returns>Removed address</returns> /// <short>Remove from trusted addresses</short> /// <exception cref="ArgumentException">Exception happens when in parameters is invalid. Text description contains parameter name and text description.</exception> /// <category>Images</category> [Delete(@"display_images/address")] public string RemovevDisplayImagesAddress(string address) { MailEngineFactory.DisplayImagesAddressEngine.Remove(address); return address; } } } <file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/_Obsolete/SmtpClientEx.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.SMTP.Client { #region usings using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Net; using System.Net.Sockets; using System.Security.Cryptography; using System.Text; using System.Threading; using Dns.Client; using Mime; #endregion /// <summary> /// Is called when asynchronous command had completed. /// </summary> public delegate void CommadCompleted(SocketCallBackResult result, Exception exception); /// <summary> /// SMTP client. /// </summary> [Obsolete("Use SMTP_Client instead !")] public class SmtpClientEx : IDisposable { #region Nested type: Auth_state_data /// <summary> /// Provides state date for BeginAuthenticate method. /// </summary> private class Auth_state_data { #region Members private readonly string m_Password = ""; private readonly CommadCompleted m_pCallback; private readonly string m_UserName = ""; #endregion #region Properties /// <summary> /// Gets user name. /// </summary> public string UserName { get { return m_UserName; } } /// <summary> /// Gets user password. /// </summary> public string Password { get { return m_Password; } } /// <summary> /// Gets callback what must be called when aynchrounous execution completes. /// </summary> public CommadCompleted Callback { get { return m_pCallback; } } /// <summary> /// Gets or sets user data. /// </summary> public object Tag { get; set; } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="userName">User name.</param> /// <param name="password"><PASSWORD>.</param> /// <param name="callback">Callback what must be called when aynchrounous execution completes.</param> public Auth_state_data(string userName, string password, CommadCompleted callback) { m_UserName = userName; m_Password = <PASSWORD>; m_pCallback = callback; } #endregion } #endregion #region Events /// <summary> /// Occurs when SMTP session has finished and session log is available. /// </summary> public event LogEventHandler SessionLog = null; #endregion #region Members private bool m_Authenticated; private bool m_Connected; private string[] m_pDnsServers; private SocketLogger m_pLogger; private SocketEx m_pSocket; private bool m_Supports_Bdat; private bool m_Supports_CramMd5; private bool m_Supports_Login; private bool m_Supports_Size; #endregion #region Properties /// <summary> /// Gets local endpoint. Returns null if smtp client isn't connected. /// </summary> public EndPoint LocalEndpoint { get { if (m_pSocket != null) { return m_pSocket.LocalEndPoint; } else { return null; } } } /// <summary> /// Gets remote endpoint. Returns null if smtp client isn't connected. /// </summary> public EndPoint RemoteEndPoint { get { if (m_pSocket != null) { return m_pSocket.RemoteEndPoint; } else { return null; } } } /// <summary> /// Gets or sets dns servers. /// </summary> public string[] DnsServers { get { return m_pDnsServers; } set { m_pDnsServers = value; } } /// <summary> /// Gets if smtp client is connected. /// </summary> public bool Connected { get { return m_Connected; } } /// <summary> /// Gets if pop3 client is authenticated. /// </summary> public bool Authenticated { get { return m_Authenticated; } } /// <summary> /// Gets when was last activity. /// </summary> public DateTime LastDataTime { get { return m_pSocket.LastActivity; } } /// <summary> /// Gets log entries that are currently in log buffer. Returns null if socket not connected or no logging enabled. /// </summary> public SocketLogger SessionActiveLog { get { if (m_pSocket == null) { return null; } else { return m_pSocket.Logger; } } } /// <summary> /// Gets how many bytes are readed through smtp client. /// </summary> public long ReadedCount { get { if (!m_Connected) { throw new Exception("You must connect first"); } return m_pSocket.ReadedCount; } } /// <summary> /// Gets how many bytes are written through smtp client. /// </summary> public long WrittenCount { get { if (!m_Connected) { throw new Exception("You must connect first"); } return m_pSocket.WrittenCount; } } /// <summary> /// Gets if the connection is an SSL connection. /// </summary> public bool IsSecureConnection { get { if (!m_Connected) { throw new Exception("You must connect first"); } return m_pSocket.SSL; } } #endregion #region Methods /// <summary> /// Sends specified message to specified smart host. /// </summary> /// <param name="smartHost">Smarthost name or IP.</param> /// <param name="port">SMTP port number. Normally this is 25.</param> /// <param name="hostName">Host name reported to SMTP server.</param> /// <param name="message">Mime message to send.</param> public static void QuickSendSmartHost(string smartHost, int port, string hostName, Mime message) { QuickSendSmartHost(smartHost, port, hostName, "", "", message); } /// <summary> /// Sends specified message to specified smart host. /// </summary> /// <param name="smartHost">Smarthost name or IP.</param> /// <param name="port">SMTP port number. Normally this is 25.</param> /// <param name="hostName">Host name reported to SMTP server.</param> /// <param name="userName">SMTP user name. Note: Pass empty string if no authentication wanted.</param> /// <param name="password">SMTP password.</param> /// <param name="message">Mime message to send.</param> public static void QuickSendSmartHost(string smartHost, int port, string hostName, string userName, string password, Mime message) { QuickSendSmartHost(smartHost, port, false, hostName, userName, password, message); } /// <summary> /// Sends specified message to specified smart host. /// </summary> /// <param name="smartHost">Smarthost name or IP.</param> /// <param name="port">SMTP port number. Default SMTP port is 25 and SSL port is 465.</param> /// <param name="ssl">Specifies if to connected via SSL.</param> /// <param name="hostName">Host name reported to SMTP server.</param> /// <param name="userName">SMTP user name. Note: Pass empty string if no authentication wanted.</param> /// <param name="password">SMTP password.</param> /// <param name="message">Mime message to send.</param> public static void QuickSendSmartHost(string smartHost, int port, bool ssl, string hostName, string userName, string password, Mime message) { string from = ""; if (message.MainEntity.From != null) { MailboxAddress[] addresses = message.MainEntity.From.Mailboxes; if (addresses.Length > 0) { from = addresses[0].EmailAddress; } } ArrayList recipients = new ArrayList(); if (message.MainEntity.To != null) { MailboxAddress[] addresses = message.MainEntity.To.Mailboxes; foreach (MailboxAddress address in addresses) { recipients.Add(address.EmailAddress); } } if (message.MainEntity.Cc != null) { MailboxAddress[] addresses = message.MainEntity.Cc.Mailboxes; foreach (MailboxAddress address in addresses) { recipients.Add(address.EmailAddress); } } if (message.MainEntity.Bcc != null) { MailboxAddress[] addresses = message.MainEntity.Bcc.Mailboxes; foreach (MailboxAddress address in addresses) { recipients.Add(address.EmailAddress); } } string[] to = new string[recipients.Count]; recipients.CopyTo(to); MemoryStream messageStream = new MemoryStream(); message.ToStream(messageStream); messageStream.Position = 0; // messageStream QuickSendSmartHost(smartHost, port, ssl, hostName, userName, password, from, to, messageStream); } /// <summary> /// Sends specified message to specified smart host. NOTE: Message sending starts from message stream current posision. /// </summary> /// <param name="smartHost">Smarthost name or IP.</param> /// <param name="port">SMTP port number. Normally this is 25.</param> /// <param name="hostName">Host name reported to SMTP server.</param> /// <param name="from">From address reported to SMTP server.</param> /// <param name="to">Message recipients.</param> /// <param name="messageStream">Message stream. NOTE: Message sending starts from message stream current posision.</param> public static void QuickSendSmartHost(string smartHost, int port, string hostName, string from, string[] to, Stream messageStream) { QuickSendSmartHost(smartHost, port, false, hostName, "", "", from, to, messageStream); } /// <summary> /// Sends specified message to specified smart host. NOTE: Message sending starts from message stream current posision. /// </summary> /// <param name="smartHost">Smarthost name or IP.</param> /// <param name="port">SMTP port number. Normally this is 25.</param> /// <param name="hostName">Host name reported to SMTP server.</param> /// <param name="userName">SMTP user name. Note: Pass empty string if no authentication wanted.</param> /// <param name="password">SMTP password.</param> /// <param name="from">From address reported to SMTP server.</param> /// <param name="to">Message recipients.</param> /// <param name="messageStream">Message stream. NOTE: Message sending starts from message stream current posision.</param> public static void QuickSendSmartHost(string smartHost, int port, string hostName, string userName, string password, string from, string[] to, Stream messageStream) { QuickSendSmartHost(smartHost, port, false, hostName, userName, password, from, to, messageStream); } /// <summary> /// Sends specified message to specified smart host. NOTE: Message sending starts from message stream current posision. /// </summary> /// <param name="smartHost">Smarthost name or IP.</param> /// <param name="port">SMTP port number. Default SMTP port is 25 and SSL port is 465.</param> /// <param name="ssl">Specifies if to connected via SSL.</param> /// <param name="hostName">Host name reported to SMTP server.</param> /// <param name="userName">SMTP user name. Note: Pass empty string if no authentication wanted.</param> /// <param name="password">SMTP password.</param> /// <param name="from">From address reported to SMTP server.</param> /// <param name="to">Message recipients.</param> /// <param name="messageStream">Message stream. NOTE: Message sending starts from message stream current posision.</param> public static void QuickSendSmartHost(string smartHost, int port, bool ssl, string hostName, string userName, string password, string from, string[] to, Stream messageStream) { using (SmtpClientEx smtp = new SmtpClientEx()) { smtp.Connect(smartHost, port, ssl); smtp.Ehlo(hostName); if (userName.Length > 0) { smtp.Authenticate(userName, password); } smtp.SetSender(MailboxAddress.Parse(from).EmailAddress, messageStream.Length - messageStream.Position); foreach (string t in to) { smtp.AddRecipient(MailboxAddress.Parse(t).EmailAddress); } smtp.SendMessage(messageStream); } } /// <summary> /// Cleasns up resources and disconnect smtp client if open. /// </summary> public void Dispose() { try { Disconnect(); } catch {} } /// <summary> /// Connects to sepcified host. /// </summary> /// <param name="host">Host name or IP address.</param> /// <param name="port">Port where to connect.</param> public void Connect(string host, int port) { Connect(null, host, port, false); } /// <summary> /// Connects to sepcified host. /// </summary> /// <param name="host">Host name or IP address.</param> /// <param name="port">Port where to connect. Default SMTP port is 25 and SSL port is 465.</param> /// <param name="ssl">Specifies if to connected via SSL.</param> public void Connect(string host, int port, bool ssl) { Connect(null, host, port, ssl); } /// <summary> /// Connects to sepcified host. /// </summary> /// <param name="localEndpoint">Sets local endpoint. Pass null, to use default.</param> /// <param name="host">Host name or IP address.</param> /// <param name="port">Port where to connect.</param> public void Connect(IPEndPoint localEndpoint, string host, int port) { Connect(localEndpoint, host, port, false); } /// <summary> /// Connects to sepcified host. /// </summary> /// <param name="localEndpoint">Sets local endpoint. Pass null, to use default.</param> /// <param name="host">Host name or IP address.</param> /// <param name="port">Port where to connect.</param> /// <param name="ssl">Specifies if to connected via SSL. Default SMTP port is 25 and SSL port is 465.</param> public void Connect(IPEndPoint localEndpoint, string host, int port, bool ssl) { m_pSocket = new SocketEx(); if (localEndpoint != null) { m_pSocket.Bind(localEndpoint); } // Create logger if (SessionLog != null) { m_pLogger = new SocketLogger(m_pSocket.RawSocket, SessionLog); m_pLogger.SessionID = Guid.NewGuid().ToString(); m_pSocket.Logger = m_pLogger; } if (host.IndexOf("@") == -1) { m_pSocket.Connect(host, port, ssl); } else { //---- Parse e-domain -------------------------------// string domain = host; // eg. Ivx <<EMAIL>> if (domain.IndexOf("<") > -1 && domain.IndexOf(">") > -1) { domain = domain.Substring(domain.IndexOf("<") + 1, domain.IndexOf(">") - domain.IndexOf("<") - 1); } if (domain.IndexOf("@") > -1) { domain = domain.Substring(domain.LastIndexOf("@") + 1); } if (domain.Trim().Length == 0) { if (m_pLogger != null) { m_pLogger.AddTextEntry("Destination address '" + host + "' is invalid, aborting !"); } throw new Exception("Destination address '" + host + "' is invalid, aborting !"); } //--- Get MX record -------------------------------------------// Dns_Client dns = new Dns_Client(); Dns_Client.DnsServers = m_pDnsServers; DnsServerResponse dnsResponse = dns.Query(domain, QTYPE.MX); bool connected = false; switch (dnsResponse.ResponseCode) { case RCODE.NO_ERROR: DNS_rr_MX[] mxRecords = dnsResponse.GetMXRecords(); // Try all available hosts by MX preference order, if can't connect specified host. foreach (DNS_rr_MX mx in mxRecords) { try { if (m_pLogger != null) { m_pLogger.AddTextEntry("Connecting with mx record to: " + mx.Host); } m_pSocket.Connect(mx.Host, port, ssl); connected = true; break; } catch (Exception x) { // Just skip and let for to try next host. if (m_pLogger != null) { m_pLogger.AddTextEntry("Failed connect to: " + mx.Host + " error:" + x.Message); } } } // None of MX didn't connect if (mxRecords.Length > 0 && !connected) { throw new Exception("Destination email server is down"); } /* Rfc 2821 5 If no MX records are found, but an A RR is found, the A RR is treated as if it was associated with an implicit MX RR, with a preference of 0, pointing to that host. */ if (!connected) { // Try to connect with A record IPAddress[] ipEntry = null; try { if (m_pLogger != null) { m_pLogger.AddTextEntry("No mx record, trying to get A record for: " + domain); } ipEntry = Dns_Client.Resolve(domain); } catch { if (m_pLogger != null) { m_pLogger.AddTextEntry("Invalid domain,no MX or A record: " + domain); } throw new Exception("Invalid domain,no MX or A record: " + domain); } try { if (m_pLogger != null) { m_pLogger.AddTextEntry("Connecting with A record to:" + domain); } m_pSocket.Connect(domain, port, ssl); } catch { if (m_pLogger != null) { m_pLogger.AddTextEntry("Failed connect to:" + domain); } throw new Exception("Destination email server is down"); } } break; case RCODE.NAME_ERROR: if (m_pLogger != null) { m_pLogger.AddTextEntry("Invalid domain,no MX or A record: " + domain); } throw new Exception("Invalid domain,no MX or A record: " + domain); case RCODE.SERVER_FAILURE: if (m_pLogger != null) { m_pLogger.AddTextEntry("Dns server unvailable."); } throw new Exception("Dns server unvailable."); } } /* * Notes: Greeting may be single or multiline response. * * Examples: * 220<SP>SMTP server ready<CRLF> * * 220-SMTP server ready<CRLF> * 220-Addtitional text<CRLF> * 220<SP>final row<CRLF> * */ // Read server response string responseLine = m_pSocket.ReadLine(1000); while (!responseLine.StartsWith("220 ")) { // If lisne won't start with 220, then its error response if (!responseLine.StartsWith("220")) { throw new Exception(responseLine); } responseLine = m_pSocket.ReadLine(1000); } m_Connected = true; } /// <summary> /// Starts connection to specified host. /// </summary> /// <param name="host">Host name or IP address.</param> /// <param name="port">Port where to connect.</param> /// <param name="callback">Callback to be called if connect ends.</param> public void BeginConnect(string host, int port, CommadCompleted callback) { BeginConnect(null, host, port, false, callback); } /// <summary> /// Starts connection to specified host. /// </summary> /// <param name="host">Host name or IP address.</param> /// <param name="port">Port where to connect.</param> /// <param name="ssl">Specifies if to connected via SSL.</param> /// <param name="callback">Callback to be called if connect ends.</param> public void BeginConnect(string host, int port, bool ssl, CommadCompleted callback) { BeginConnect(null, host, port, ssl, callback); } /// <summary> /// Starts connection to specified host. /// </summary> /// <param name="localEndpoint">Sets local endpoint. Pass null, to use default.</param> /// <param name="host">Host name or IP address.</param> /// <param name="port">Port where to connect.</param> /// <param name="callback">Callback to be called if connect ends.</param> public void BeginConnect(IPEndPoint localEndpoint, string host, int port, CommadCompleted callback) { BeginConnect(localEndpoint, host, port, false, callback); } /// <summary> /// Starts connection to specified host. /// </summary> /// <param name="localEndpoint">Sets local endpoint. Pass null, to use default.</param> /// <param name="host">Host name or IP address.</param> /// <param name="port">Port where to connect.</param> /// <param name="ssl">Specifies if to connected via SSL.</param> /// <param name="callback">Callback to be called if connect ends.</param> public void BeginConnect(IPEndPoint localEndpoint, string host, int port, bool ssl, CommadCompleted callback) { ThreadPool.QueueUserWorkItem(BeginConnect_workerThread, new object[] {localEndpoint, host, port, ssl, callback}); } /* /// <summary> /// Starts disconnecting SMTP client. /// </summary> public void BeginDisconnect() { if(!m_Connected){ throw new Exception("You must connect first"); } }*/ /// <summary> /// Disconnects smtp client from server. /// </summary> public void Disconnect() { try { if (m_pSocket != null && m_pSocket.Connected) { m_pSocket.WriteLine("QUIT"); m_pSocket.Shutdown(SocketShutdown.Both); } } catch {} m_pSocket = null; m_Connected = false; m_Supports_Size = false; m_Supports_Bdat = false; m_Supports_Login = false; m_Supports_CramMd5 = false; if (m_pLogger != null) { m_pLogger.Flush(); m_pLogger = null; } } /// <summary> /// Switches SMTP connection to SSL. /// </summary> public void StartTLS() { /* RFC 2487 STARTTLS 5. STARTTLS Command. STARTTLS with no parameters. After the client gives the STARTTLS command, the server responds with one of the following reply codes: 220 Ready to start TLS 501 Syntax error (no parameters allowed) 454 TLS not available due to temporary reason */ if (!m_Connected) { throw new Exception("You must connect first !"); } if (m_Authenticated) { throw new Exception("The STLS command is only valid in non-authenticated state !"); } if (m_pSocket.SSL) { throw new Exception("Connection is already secure !"); } m_pSocket.WriteLine("STARTTLS"); string reply = m_pSocket.ReadLine(); if (!reply.ToUpper().StartsWith("220")) { throw new Exception("Server returned:" + reply); } m_pSocket.SwitchToSSL_AsClient(); } /// <summary> /// Start TLS(SSL) negotiation asynchronously. /// </summary> /// <param name="callback">The method to be called when the asynchronous StartTLS operation is completed.</param> public void BeginStartTLS(CommadCompleted callback) { ThreadPool.QueueUserWorkItem(BeginStartTLS_workerThread, callback); } /// <summary> /// Does EHLO command. If server don't support EHLO, tries HELO. /// </summary> /// <param name="hostName">Host name which is reported to SMTP server.</param> public void Ehlo(string hostName) { if (!m_Connected) { throw new Exception("You must connect first"); } /* Rfc 2821 172.16.58.3 EHLO * Syntax: "EHLO" SP Domain CRLF */ if (hostName.Length == 0) { hostName = Dns.GetHostName(); } // Send EHLO command to server m_pSocket.WriteLine("EHLO " + hostName); string responseLine = m_pSocket.ReadLine(); // Response line must start with 250 or otherwise it's error response, // try HELO if (!responseLine.StartsWith("250")) { // Send HELO command to server m_pSocket.WriteLine("HELO " + hostName); responseLine = m_pSocket.ReadLine(); // HELO failed, return error if (!responseLine.StartsWith("250")) { throw new Exception(responseLine); } } /* RFC 2821 4.1.1.1 EHLO * Examples: * 250-domain<SP>free_text<CRLF> * 250-EHLO_keyword<CRLF> * 250<SP>EHLO_keyword<CRLF> * * 250<SP> specifies that last EHLO response line. */ while (!responseLine.StartsWith("250 ")) { //---- Store supported ESMTP features --------------------// if (responseLine.ToLower().IndexOf("size") > -1) { m_Supports_Size = true; } else if (responseLine.ToLower().IndexOf("chunking") > -1) { m_Supports_Bdat = true; } else if (responseLine.ToLower().IndexOf("cram-md5") > -1) { m_Supports_CramMd5 = true; } else if (responseLine.ToLower().IndexOf("login") > -1) { m_Supports_Login = true; } //--------------------------------------------------------// // Read next EHLO response line responseLine = m_pSocket.ReadLine(); } } /// <summary> /// Begins EHLO command. /// </summary> /// <param name="hostName">Host name which is reported to SMTP server.</param> /// <param name="callback">Callback to be called if command ends.</param> public void BeginEhlo(string hostName, CommadCompleted callback) { if (!m_Connected) { throw new Exception("You must connect first"); } /* Rfc 2821 4.1.1.1 EHLO * Syntax: "EHLO" SP Domain CRLF */ if (hostName.Length == 0) { hostName = Dns.GetHostName(); } // Start sending EHLO command to server m_pSocket.BeginWriteLine("EHLO " + hostName, new object[] {hostName, callback}, OnEhloSendFinished); } /// <summary> /// Does AUTH command. /// </summary> /// <param name="userName">Uesr name.</param> /// <param name="password"><PASSWORD>.</param> public void Authenticate(string userName, string password) { if (!m_Connected) { throw new Exception("You must connect first !"); } if (!(m_Supports_CramMd5 || m_Supports_Login)) { throw new Exception("Authentication isn't supported."); } /* LOGIN * Example: * C: AUTH<SP>LOGIN<CRLF> * S: 334<SP>base64(USERNAME)<CRLF> // USERNAME is string constant * C: base64(username)<CRLF> * S: 334<SP>base64(PASSWORD)<CRLF> // PASSWORD is string constant * C: base64(password)<CRLF> * S: 235 Ok<CRLF> */ /* Cram-M5 Example: C: AUTH<SP>CRAM-MD5<CRLF> S: 334<SP>base64(md5_calculation_hash)<CRLF> C: base64(username<SP>password_hash)<CRLF> S: 235 Ok<CRLF> */ if (m_Supports_CramMd5) { m_pSocket.WriteLine("AUTH CRAM-MD5"); string responseLine = m_pSocket.ReadLine(); // Response line must start with 334 or otherwise it's error response if (!responseLine.StartsWith("334")) { throw new Exception(responseLine); } string md5HashKey = Encoding.ASCII.GetString(Convert.FromBase64String(responseLine.Split(' ')[1])); HMACMD5 kMd5 = new HMACMD5(Encoding.ASCII.GetBytes(password)); byte[] md5HashByte = kMd5.ComputeHash(Encoding.ASCII.GetBytes(md5HashKey)); string hashedPwd = BitConverter.ToString(md5HashByte).ToLower().Replace("-", ""); m_pSocket.WriteLine(Convert.ToBase64String(Encoding.ASCII.GetBytes(userName + " " + hashedPwd))); responseLine = m_pSocket.ReadLine(); // Response line must start with 235 or otherwise it's error response if (!responseLine.StartsWith("235")) { throw new Exception(responseLine); } m_Authenticated = true; } else if (m_Supports_Login) { m_pSocket.WriteLine("AUTH LOGIN"); string responseLine = m_pSocket.ReadLine(); // Response line must start with 334 or otherwise it's error response if (!responseLine.StartsWith("334")) { throw new Exception(responseLine); } // Send user name to server m_pSocket.WriteLine(Convert.ToBase64String(Encoding.ASCII.GetBytes(userName))); responseLine = m_pSocket.ReadLine(); // Response line must start with 334 or otherwise it's error response if (!responseLine.StartsWith("334")) { throw new Exception(responseLine); } // Send password to server m_pSocket.WriteLine(Convert.ToBase64String(Encoding.ASCII.GetBytes(password))); responseLine = m_pSocket.ReadLine(); // Response line must start with 235 or otherwise it's error response if (!responseLine.StartsWith("235")) { throw new Exception(responseLine); } m_Authenticated = true; } if (m_Authenticated && m_pSocket.Logger != null) { m_pSocket.Logger.UserName = userName; } } /// <summary> /// Begins authenticate. /// </summary> /// <param name="userName">Uesr name.</param> /// <param name="password">Password.</param> /// <param name="callback">Callback to be called if command ends.</param> public void BeginAuthenticate(string userName, string password, CommadCompleted callback) { if (!m_Connected) { throw new Exception("You must connect first !"); } if (!(m_Supports_CramMd5 || m_Supports_Login)) { throw new Exception("Authentication isn't supported."); } /* LOGIN * Example: * C: AUTH<SP>LOGIN<CRLF> * S: 334<SP>base64(USERNAME)<CRLF> // USERNAME is string constant * C: base64(username)<CRLF> * S: 334<SP>base64(PASSWORD)<CRLF> // PASSWORD is string constant * C: base64(password)<CRLF> * S: 235 Ok<CRLF> */ /* Cram-M5 Example: C: AUTH<SP>CRAM-MD5<CRLF> S: 334<SP>base64(md5_calculation_hash)<CRLF> C: base64(username<SP>password_hash)<CRLF> S: 235 Ok<CRLF> */ if (m_Supports_CramMd5) { m_pSocket.BeginWriteLine("AUTH CRAM-MD5", new Auth_state_data(userName, password, callback), OnAuthCramMd5SendFinished); } else if (m_Supports_Login) { m_pSocket.BeginWriteLine("AUTH LOGIN", new Auth_state_data(userName, password, callback), OnAuthLoginSendFinished); } } /// <summary> /// Does MAIL FROM: command. /// </summary> /// <param name="senderEmail">Sender email address what is reported to smtp server</param> /// <param name="messageSize">Message size in bytes or -1 if message size isn't known.</param> public void SetSender(string senderEmail, long messageSize) { if (!m_Connected) { throw new Exception("You must connect first"); } /* RFC 2821 4.1.1.2 MAIL * Examples: * MAIL FROM:<<EMAIL>> * * RFC 1870 adds optional SIZE keyword support. * SIZE keyword may only be used if it's reported in EHLO command response. * Examples: * MAIL FROM:<<EMAIL>> SIZE=1000 */ if (m_Supports_Size && messageSize > -1) { m_pSocket.WriteLine("MAIL FROM:<" + senderEmail + "> SIZE=" + messageSize); } else { m_pSocket.WriteLine("MAIL FROM:<" + senderEmail + ">"); } string responseLine = m_pSocket.ReadLine(); // Response line must start with 250 or otherwise it's error response if (!responseLine.StartsWith("250")) { throw new Exception(responseLine); } } /// <summary> /// Begin setting sender. /// </summary> /// <param name="senderEmail">Sender email address what is reported to smtp server.</param> /// <param name="messageSize">Message size in bytes or -1 if message size isn't known.</param> /// <param name="callback">Callback to be called if command ends.</param> public void BeginSetSender(string senderEmail, long messageSize, CommadCompleted callback) { if (!m_Connected) { throw new Exception("You must connect first"); } /* RFC 2821 4.1.1.2 MAIL * Examples: * MAIL FROM:<<EMAIL>> * * RFC 1870 adds optional SIZE keyword support. * SIZE keyword may only be used if it's reported in EHLO command response. * Examples: * MAIL FROM:<<EMAIL>> SIZE=1000 */ if (m_Supports_Size && messageSize > -1) { m_pSocket.BeginWriteLine("MAIL FROM:<" + senderEmail + "> SIZE=" + messageSize, callback, OnMailSendFinished); } else { m_pSocket.BeginWriteLine("MAIL FROM:<" + senderEmail + ">", callback, OnMailSendFinished); } } /// <summary> /// Does RCPT TO: command. /// </summary> /// <param name="recipientEmail">Recipient email address.</param> public void AddRecipient(string recipientEmail) { if (!m_Connected) { throw new Exception("You must connect first"); } /* RFC 2821 4.1.1.2 RCPT * Examples: * RCPT TO:<<EMAIL>> */ m_pSocket.WriteLine("RCPT TO:<" + recipientEmail + ">"); string responseLine = m_pSocket.ReadLine(); // Response line must start with 250 or otherwise it's error response if (!responseLine.StartsWith("250")) { throw new Exception(responseLine); } } /// <summary> /// Begin adding recipient. /// </summary> /// <param name="recipientEmail">Recipient email address.</param> /// <param name="callback">Callback to be called if command ends.</param> public void BeginAddRecipient(string recipientEmail, CommadCompleted callback) { if (!m_Connected) { throw new Exception("You must connect first"); } /* RFC 2821 4.1.1.2 RCPT * Examples: * RCPT TO:<<EMAIL>> */ m_pSocket.BeginWriteLine("RCPT TO:<" + recipientEmail + ">", callback, OnRcptSendFinished); } /// <summary> /// Sends message to server. NOTE: Message sending starts from message stream current posision. /// </summary> /// <param name="message">Message what will be sent to server. NOTE: Message sending starts from message stream current posision.</param> public void SendMessage(Stream message) { if (!m_Connected) { throw new Exception("You must connect first"); } /* RFC 2821 4.1.1.4 DATA * Notes: * Message must be period handled for DATA command. This meas if message line starts with ., * additional .(period) must be added. * Message send is ended with <CRLF>.<CRLF>. * Examples: * C: DATA<CRLF> * S: 354 Start sending message, end with <crlf>.<crlf><CRLF> * C: send_message * C: <CRLF>.<CRLF> */ /* RFC 3030 BDAT * Syntax:BDAT<SP>message_size_in_bytes<SP>LAST<CRLF> * * Exapmle: * C: BDAT 1000 LAST<CRLF> * C: send_1000_byte_message * S: 250 OK<CRLF> * */ if (m_Supports_Bdat) { m_pSocket.WriteLine("BDAT " + (message.Length - message.Position) + " LAST"); m_pSocket.Write(message); string responseLine = m_pSocket.ReadLine(); // Response line must start with 250 or otherwise it's error response if (!responseLine.StartsWith("250")) { throw new Exception(responseLine); } } else { m_pSocket.WriteLine("DATA"); string responseLine = m_pSocket.ReadLine(); // Response line must start with 334 or otherwise it's error response if (!responseLine.StartsWith("354")) { throw new Exception(responseLine); } m_pSocket.WritePeriodTerminated(message); responseLine = m_pSocket.ReadLine(); // Response line must start with 250 or otherwise it's error response if (!responseLine.StartsWith("250")) { throw new Exception(responseLine); } } } /// <summary> /// Starts sending message. /// </summary> /// <param name="message">Message what will be sent to server. NOTE: Message sending starts from message stream current posision.</param> /// <param name="callback">Callback to be called if command ends.</param> public void BeginSendMessage(Stream message, CommadCompleted callback) { if (!m_Connected) { throw new Exception("You must connect first"); } /* RFC 2821 4.1.1.4 DATA * Notes: * Message must be period handled for DATA command. This meas if message line starts with ., * additional .(period) must be added. * Message send is ended with <CRLF>.<CRLF>. * Examples: * C: DATA<CRLF> * S: 354 Start sending message, end with <crlf>.<crlf><CRLF> * C: send_message * C: <CRLF>.<CRLF> */ /* RFC 3030 BDAT * Syntax:BDAT<SP>message_size_in_bytes<SP>LAST<CRLF> * * Exapmle: * C: BDAT 1000 LAST<CRLF> * C: send_1000_byte_message * S: 250 OK<CRLF> * */ if (m_Supports_Bdat) { m_pSocket.BeginWriteLine("BDAT " + (message.Length - message.Position) + " LAST", new object[] {message, callback}, OnBdatSendFinished); } else { m_pSocket.BeginWriteLine("DATA", new object[] {message, callback}, OnDataSendFinished); } } /// <summary> /// Send RSET command to SMTP server, resets SMTP session. /// </summary> public void Reset() { if (!m_Connected) { throw new Exception("You must connect first"); } m_pSocket.WriteLine("RSET"); string responseLine = m_pSocket.ReadLine(); if (!responseLine.StartsWith("250")) { throw new Exception(responseLine); } } /// <summary> /// Gets specified email domain possible connect points. Values are in priority descending order. /// </summary> /// <param name="domain">Email address or domain name.</param> /// <returns>Returns possible email server connection points.</returns> public IPAddress[] GetDestinations(string domain) { /* 1) Add MX records 2) Add A records */ // We have email address, just get domain from it. if (domain.IndexOf('@') > -1) { domain = domain.Substring(domain.IndexOf('@') + 1); } List<IPAddress> retVal = new List<IPAddress>(); Dns_Client dns = new Dns_Client(); Dns_Client.DnsServers = DnsServers; DnsServerResponse response = dns.Query(domain, QTYPE.MX); // Add MX foreach (DNS_rr_MX mx in response.GetMXRecords()) { try { IPAddress[] ips = Dns.GetHostAddresses(mx.Host); foreach (IPAddress ip in ips) { if (!retVal.Contains(ip)) { retVal.Add(ip); } } } catch { // Probably wrong MX record, no A reocrd for it, so we don't get IP. Just skip it. } } // Add A records only if no MX records. if (retVal.Count == 0) { response = dns.Query(domain, QTYPE.A); foreach (DNS_rr_A a in response.GetARecords()) { IPAddress ip = a.IP; if (!retVal.Contains(ip)) { retVal.Add(ip); } } } return retVal.ToArray(); } #endregion #region Utility methods /// <summary> /// Is called from ThreadPool Thread. This method just call synchrounous Connect. /// </summary> /// <param name="tag"></param> private void BeginConnect_workerThread(object tag) { CommadCompleted callback = (CommadCompleted) ((object[]) tag)[4]; try { IPEndPoint localEndpoint = (IPEndPoint) ((object[]) tag)[0]; string host = (string) ((object[]) tag)[1]; int port = (int) ((object[]) tag)[2]; bool ssl = (bool) ((object[]) tag)[3]; Connect(localEndpoint, host, port, ssl); // Connect completed susscessfully, call callback method. callback(SocketCallBackResult.Ok, null); } catch (Exception x) { // Pass exception to callback method callback(SocketCallBackResult.Exception, x); } } /// <summary> /// Is called from ThreadPool Thread. This method just call synchrounous StartTLS. /// </summary> /// <param name="tag">User data.</param> private void BeginStartTLS_workerThread(object tag) { CommadCompleted callback = (CommadCompleted) tag; try { StartTLS(); // Connect completed susscessfully, call callback method. callback(SocketCallBackResult.Ok, null); } catch (Exception x) { // Pass exception to callback method callback(SocketCallBackResult.Exception, x); } } /// <summary> /// Is called when smtp client has finished EHLO command sending. /// </summary> /// <param name="result"></param> /// <param name="count"></param> /// <param name="exception"></param> /// <param name="tag"></param> private void OnEhloSendFinished(SocketCallBackResult result, long count, Exception exception, object tag) { CommadCompleted callback = (CommadCompleted) (((object[]) tag)[1]); try { if (result == SocketCallBackResult.Ok) { // Begin reading server EHLO command response MemoryStream ms = new MemoryStream(); m_pSocket.BeginReadLine(ms, 1000, new[] {((object[]) tag)[0], callback, ms}, OnEhloReadServerResponseFinished); } else { HandleSocketError(result, exception); } } catch (Exception x) { // Pass exception to callback method callback(SocketCallBackResult.Exception, x); } } /// <summary> /// Is called when smtp client has finished reading EHLO command server response line. /// </summary> /// <param name="result"></param> /// <param name="count"></param> /// <param name="exception"></param> /// <param name="tag"></param> private void OnEhloReadServerResponseFinished(SocketCallBackResult result, long count, Exception exception, object tag) { CommadCompleted callback = (CommadCompleted) (((object[]) tag)[1]); try { if (result == SocketCallBackResult.Ok) { string responseLine = Encoding.ASCII.GetString(((MemoryStream) (((object[]) tag)[2])).ToArray()); /* RFC 2821 172.16.58.3 EHLO * Examples: * 250-domain<SP>free_text<CRLF> * 250-EHLO_keyword<CRLF> * 250<SP>EHLO_keyword<CRLF> * * 250<SP> specifies that last EHLO response line. */ // Response line must start with 250 or otherwise it's error response if (!responseLine.StartsWith("250")) { // Server isn't required to support EHLO, try HELO string hostName = (string) (((object[]) tag)[0]); m_pSocket.BeginWriteLine("HELO " + hostName, callback, OnHeloSendFinished); } else { //---- Store supported ESMTP features --------------------// if (responseLine.ToLower().IndexOf("size") > -1) { m_Supports_Size = true; } else if (responseLine.ToLower().IndexOf("chunking") > -1) { m_Supports_Bdat = true; } else if (responseLine.ToLower().IndexOf("cram-md5") > -1) { m_Supports_CramMd5 = true; } else if (responseLine.ToLower().IndexOf("login") > -1) { m_Supports_Login = true; } //--------------------------------------------------------// // This isn't last EHLO response line if (!responseLine.StartsWith("250 ")) { MemoryStream ms = new MemoryStream(); m_pSocket.BeginReadLine(ms, 1000, new[] {(((object[]) tag)[0]), callback, ms}, OnEhloReadServerResponseFinished); } else { // EHLO completed susscessfully, call callback method. callback(SocketCallBackResult.Ok, null); } } } else { HandleSocketError(result, exception); } } catch (Exception x) { // Pass exception to callback method callback(SocketCallBackResult.Exception, x); } } /// <summary> /// Is called when smtp client has finished HELO command sending. /// </summary> /// <param name="result"></param> /// <param name="count"></param> /// <param name="exception"></param> /// <param name="tag"></param> private void OnHeloSendFinished(SocketCallBackResult result, long count, Exception exception, object tag) { CommadCompleted callback = (CommadCompleted) tag; try { if (result == SocketCallBackResult.Ok) { // Begin reading server HELO command response MemoryStream ms = new MemoryStream(); m_pSocket.BeginReadLine(ms, 1000, new object[] {callback, ms}, OnHeloReadServerResponseFinished); } else { HandleSocketError(result, exception); } } catch (Exception x) { // Pass exception to callback method callback(SocketCallBackResult.Exception, x); } } /// <summary> /// Is called when smtp client has finished reading EHLO command server response line. /// </summary> /// <param name="result"></param> /// <param name="count"></param> /// <param name="exception"></param> /// <param name="tag"></param> private void OnHeloReadServerResponseFinished(SocketCallBackResult result, long count, Exception exception, object tag) { CommadCompleted callback = (CommadCompleted) (((object[]) tag)[0]); try { if (result == SocketCallBackResult.Ok) { string responseLine = Encoding.ASCII.GetString(((MemoryStream) (((object[]) tag)[1])).ToArray()); /* RFC 2821 172.16.58.3 HELO * Examples: * 250<SP>domain<SP>free_text<CRLF> * */ // Response line must start with 250 or otherwise it's error response if (!responseLine.StartsWith("250")) { throw new Exception(responseLine); } else { // EHLO completed susscessfully, call callback method. callback(SocketCallBackResult.Ok, null); } } else { HandleSocketError(result, exception); } } catch (Exception x) { // Pass exception to callback method callback(SocketCallBackResult.Exception, x); } } /// <summary> /// Is called when smtp client has finished AUTH CRAM-MD5 command sending. /// </summary> /// <param name="result"></param> /// <param name="count"></param> /// <param name="exception"></param> /// <param name="tag"></param> private void OnAuthCramMd5SendFinished(SocketCallBackResult result, long count, Exception exception, object tag) { Auth_state_data stateData = (Auth_state_data) tag; try { if (result == SocketCallBackResult.Ok) { MemoryStream ms = new MemoryStream(); stateData.Tag = ms; m_pSocket.BeginReadLine(ms, 1000, stateData, OnAuthCramMd5ReadServerResponseFinished); } else { HandleSocketError(result, exception); } } catch (Exception x) { // Pass exception to callback method stateData.Callback(SocketCallBackResult.Exception, x); } } /// <summary> /// Is called when smtp client has finished reading AUTH CRAM-MD% server response line. /// </summary> /// <param name="result"></param> /// <param name="count"></param> /// <param name="exception"></param> /// <param name="tag"></param> private void OnAuthCramMd5ReadServerResponseFinished(SocketCallBackResult result, long count, Exception exception, object tag) { Auth_state_data stateData = (Auth_state_data) tag; try { if (result == SocketCallBackResult.Ok) { string responseLine = Encoding.ASCII.GetString(((MemoryStream) stateData.Tag).ToArray()); // Response line must start with 334 or otherwise it's error response if (!responseLine.StartsWith("334")) { throw new Exception(responseLine); } else { string md5HashKey = Encoding.ASCII.GetString(Convert.FromBase64String(responseLine.Split(' ')[1])); HMACMD5 kMd5 = new HMACMD5(Encoding.ASCII.GetBytes(stateData.Password)); byte[] md5HashByte = kMd5.ComputeHash(Encoding.ASCII.GetBytes(md5HashKey)); string hashedPwd = BitConverter.ToString(md5HashByte).ToLower().Replace("-", ""); // Start sending user name to server m_pSocket.BeginWriteLine( Convert.ToBase64String( Encoding.ASCII.GetBytes(stateData.UserName + " " + hashedPwd)), stateData, OnAuthCramMd5UserPwdSendFinished); } } else { HandleSocketError(result, exception); } } catch (Exception x) { // Pass exception to callback method stateData.Callback(SocketCallBackResult.Exception, x); } } /// <summary> /// Is called when smtp client has finished sending username and password to smtp server. /// </summary> /// <param name="result"></param> /// <param name="count"></param> /// <param name="exception"></param> /// <param name="tag"></param> private void OnAuthCramMd5UserPwdSendFinished(SocketCallBackResult result, long count, Exception exception, object tag) { Auth_state_data stateData = (Auth_state_data) tag; try { if (result == SocketCallBackResult.Ok) { MemoryStream ms = new MemoryStream(); stateData.Tag = ms; m_pSocket.BeginReadLine(ms, 1000, stateData, OnAuthCramMd5UserPwdReadServerResponseFinished); } else { HandleSocketError(result, exception); } } catch (Exception x) { // Pass exception to callback method stateData.Callback(SocketCallBackResult.Exception, x); } } /// <summary> /// Is called when smtp client has finished reading user name and password send server response line. /// </summary> /// <param name="result"></param> /// <param name="count"></param> /// <param name="exception"></param> /// <param name="tag"></param> private void OnAuthCramMd5UserPwdReadServerResponseFinished(SocketCallBackResult result, long count, Exception exception, object tag) { Auth_state_data stateData = (Auth_state_data) tag; try { if (result == SocketCallBackResult.Ok) { string responseLine = Encoding.ASCII.GetString(((MemoryStream) stateData.Tag).ToArray()); // Response line must start with 235 or otherwise it's error response if (!responseLine.StartsWith("235")) { throw new Exception(responseLine); } else { m_Authenticated = true; if (m_Authenticated && m_pSocket.Logger != null) { m_pSocket.Logger.UserName = stateData.UserName; } // AUTH CRAM-MD5 completed susscessfully, call callback method. stateData.Callback(SocketCallBackResult.Ok, null); } } else { HandleSocketError(result, exception); } } catch (Exception x) { // Pass exception to callback method stateData.Callback(SocketCallBackResult.Exception, x); } } /// <summary> /// Is called when smtp client has finished AUTH LOGIN command sending. /// </summary> /// <param name="result"></param> /// <param name="count"></param> /// <param name="exception"></param> /// <param name="tag"></param> private void OnAuthLoginSendFinished(SocketCallBackResult result, long count, Exception exception, object tag) { Auth_state_data stateData = (Auth_state_data) tag; try { if (result == SocketCallBackResult.Ok) { MemoryStream ms = new MemoryStream(); stateData.Tag = ms; m_pSocket.BeginReadLine(ms, 1000, stateData, OnAuthLoginReadServerResponseFinished); } else { HandleSocketError(result, exception); } } catch (Exception x) { // Pass exception to callback method stateData.Callback(SocketCallBackResult.Exception, x); } } /// <summary> /// Is called when smtp client has finished reading MAIL FROM: command server response line. /// </summary> /// <param name="result"></param> /// <param name="count"></param> /// <param name="exception"></param> /// <param name="tag"></param> private void OnAuthLoginReadServerResponseFinished(SocketCallBackResult result, long count, Exception exception, object tag) { Auth_state_data stateData = (Auth_state_data) tag; try { if (result == SocketCallBackResult.Ok) { string responseLine = Encoding.ASCII.GetString(((MemoryStream) (stateData.Tag)).ToArray()); // Response line must start with 334 or otherwise it's error response if (!responseLine.StartsWith("334")) { throw new Exception(responseLine); } else { // Start sending user name to server m_pSocket.BeginWriteLine( Convert.ToBase64String(Encoding.ASCII.GetBytes(stateData.UserName)), stateData, OnAuthLoginUserSendFinished); } } else { HandleSocketError(result, exception); } } catch (Exception x) { // Pass exception to callback method stateData.Callback(SocketCallBackResult.Exception, x); } } /// <summary> /// Is called when smtp client has finished sending user name to SMTP server. /// </summary> /// <param name="result"></param> /// <param name="count"></param> /// <param name="exception"></param> /// <param name="tag"></param> private void OnAuthLoginUserSendFinished(SocketCallBackResult result, long count, Exception exception, object tag) { Auth_state_data stateData = (Auth_state_data) tag; try { if (result == SocketCallBackResult.Ok) { MemoryStream ms = new MemoryStream(); stateData.Tag = ms; m_pSocket.BeginReadLine(ms, 1000, stateData, OnAuthLoginUserReadServerResponseFinished); } else { HandleSocketError(result, exception); } } catch (Exception x) { // Pass exception to callback method stateData.Callback(SocketCallBackResult.Exception, x); } } /// <summary> /// Is called when smtp client has finished reading AUTH LOGIN user send server response line. /// </summary> /// <param name="result"></param> /// <param name="count"></param> /// <param name="exception"></param> /// <param name="tag"></param> private void OnAuthLoginUserReadServerResponseFinished(SocketCallBackResult result, long count, Exception exception, object tag) { Auth_state_data stateData = (Auth_state_data) tag; try { if (result == SocketCallBackResult.Ok) { string responseLine = Encoding.ASCII.GetString(((MemoryStream) stateData.Tag).ToArray()); // Response line must start with 334 or otherwise it's error response if (!responseLine.StartsWith("334")) { throw new Exception(responseLine); } else { // Start sending password to server m_pSocket.BeginWriteLine( Convert.ToBase64String(Encoding.ASCII.GetBytes(stateData.Password)), stateData, OnAuthLoginPasswordSendFinished); } } else { HandleSocketError(result, exception); } } catch (Exception x) { // Pass exception to callback method stateData.Callback(SocketCallBackResult.Exception, x); } } /// <summary> /// Is called when smtp client has finished sending password to SMTP server. /// </summary> /// <param name="result"></param> /// <param name="count"></param> /// <param name="exception"></param> /// <param name="tag"></param> private void OnAuthLoginPasswordSendFinished(SocketCallBackResult result, long count, Exception exception, object tag) { Auth_state_data stateData = (Auth_state_data) tag; try { if (result == SocketCallBackResult.Ok) { MemoryStream ms = new MemoryStream(); stateData.Tag = ms; m_pSocket.BeginReadLine(ms, 1000, stateData, OnAuthLoginPwdReadServerResponseFinished); } else { HandleSocketError(result, exception); } } catch (Exception x) { // Pass exception to callback method stateData.Callback(SocketCallBackResult.Exception, x); } } /// <summary> /// Is called when smtp client has finished reading AUTH LOGIN password send server response line. /// </summary> /// <param name="result"></param> /// <param name="count"></param> /// <param name="exception"></param> /// <param name="tag"></param> private void OnAuthLoginPwdReadServerResponseFinished(SocketCallBackResult result, long count, Exception exception, object tag) { Auth_state_data stateData = (Auth_state_data) tag; try { if (result == SocketCallBackResult.Ok) { string responseLine = Encoding.ASCII.GetString(((MemoryStream) stateData.Tag).ToArray()); // Response line must start with 235 or otherwise it's error response if (!responseLine.StartsWith("235")) { throw new Exception(responseLine); } else { m_Authenticated = true; if (m_Authenticated && m_pSocket.Logger != null) { m_pSocket.Logger.UserName = stateData.UserName; } // AUTH LOGIN completed susscessfully, call callback method. stateData.Callback(SocketCallBackResult.Ok, null); } } else { HandleSocketError(result, exception); } } catch (Exception x) { // Pass exception to callback method stateData.Callback(SocketCallBackResult.Exception, x); } } /// <summary> /// Is called when smtp client has finished MAIL FROM: command sending. /// </summary> /// <param name="result"></param> /// <param name="count"></param> /// <param name="exception"></param> /// <param name="tag"></param> private void OnMailSendFinished(SocketCallBackResult result, long count, Exception exception, object tag) { CommadCompleted callback = (CommadCompleted) tag; try { if (result == SocketCallBackResult.Ok) { MemoryStream ms = new MemoryStream(); m_pSocket.BeginReadLine(ms, 1000, new object[] {callback, ms}, OnMailReadServerResponseFinished); } else { HandleSocketError(result, exception); } } catch (Exception x) { // Pass exception to callback method callback(SocketCallBackResult.Exception, x); } } /// <summary> /// Is called when smtp client has finished reading MAIL FROM: command server response line. /// </summary> /// <param name="result"></param> /// <param name="count"></param> /// <param name="exception"></param> /// <param name="tag"></param> private void OnMailReadServerResponseFinished(SocketCallBackResult result, long count, Exception exception, object tag) { CommadCompleted callback = (CommadCompleted) (((object[]) tag)[0]); try { if (result == SocketCallBackResult.Ok) { string responseLine = Encoding.ASCII.GetString(((MemoryStream) (((object[]) tag)[1])).ToArray()); // Response line must start with 250 or otherwise it's error response if (!responseLine.StartsWith("250")) { throw new Exception(responseLine); } else { // MAIL FROM: completed susscessfully, call callback method. callback(SocketCallBackResult.Ok, null); } } else { HandleSocketError(result, exception); } } catch (Exception x) { // Pass exception to callback method callback(SocketCallBackResult.Exception, x); } } /// <summary> /// Is called when smtp client has finished RCPT TO: command sending. /// </summary> /// <param name="result"></param> /// <param name="count"></param> /// <param name="exception"></param> /// <param name="tag"></param> private void OnRcptSendFinished(SocketCallBackResult result, long count, Exception exception, object tag) { CommadCompleted callback = (CommadCompleted) tag; try { if (result == SocketCallBackResult.Ok) { MemoryStream ms = new MemoryStream(); m_pSocket.BeginReadLine(ms, 1000, new object[] {callback, ms}, OnRcptReadServerResponseFinished); } else { HandleSocketError(result, exception); } } catch (Exception x) { // Pass exception to callback method callback(SocketCallBackResult.Exception, x); } } /// <summary> /// Is called when smtp client has finished reading RCPT TO: command server response line. /// </summary> /// <param name="result"></param> /// <param name="count"></param> /// <param name="exception"></param> /// <param name="tag"></param> private void OnRcptReadServerResponseFinished(SocketCallBackResult result, long count, Exception exception, object tag) { CommadCompleted callback = (CommadCompleted) (((object[]) tag)[0]); try { if (result == SocketCallBackResult.Ok) { string responseLine = Encoding.ASCII.GetString(((MemoryStream) (((object[]) tag)[1])).ToArray()); // Response line must start with 250 or otherwise it's error response if (!responseLine.StartsWith("250")) { throw new Exception(responseLine); } else { // RCPT TO: completed susscessfully, call callback method. callback(SocketCallBackResult.Ok, null); } } else { HandleSocketError(result, exception); } } catch (Exception x) { // Pass exception to callback method callback(SocketCallBackResult.Exception, x); } } /// <summary> /// Is called when smtp client has finished BDAT command sending. /// </summary> /// <param name="result"></param> /// <param name="count"></param> /// <param name="exception"></param> /// <param name="tag"></param> private void OnBdatSendFinished(SocketCallBackResult result, long count, Exception exception, object tag) { CommadCompleted callback = (CommadCompleted) (((object[]) tag)[1]); try { if (result == SocketCallBackResult.Ok) { // BDAT command successfully sent to SMTP server, start sending DATA. m_pSocket.BeginWrite((Stream) (((object[]) tag)[0]), callback, OnBdatDataSendFinished); } else { HandleSocketError(result, exception); } } catch (Exception x) { // Pass exception to callback method callback(SocketCallBackResult.Exception, x); } } /// <summary> /// Is called when smtp client has finished sending BDAT message data to smtp server. /// </summary> /// <param name="result"></param> /// <param name="count"></param> /// <param name="exception"></param> /// <param name="tag"></param> private void OnBdatDataSendFinished(SocketCallBackResult result, long count, Exception exception, object tag) { CommadCompleted callback = (CommadCompleted) tag; try { if (result == SocketCallBackResult.Ok) { // BDAT message data successfully sent to SMTP server, start reading server response MemoryStream ms = new MemoryStream(); m_pSocket.BeginReadLine(ms, 1000, new object[] {callback, ms}, OnBdatReadServerResponseFinished); } else { HandleSocketError(result, exception); } } catch (Exception x) { // Pass exception to callback method callback(SocketCallBackResult.Exception, x); } } /// <summary> /// Is called when smtp client has finished reading BDAT: command server response line. /// </summary> /// <param name="result"></param> /// <param name="count"></param> /// <param name="exception"></param> /// <param name="tag"></param> private void OnBdatReadServerResponseFinished(SocketCallBackResult result, long count, Exception exception, object tag) { CommadCompleted callback = (CommadCompleted) (((object[]) tag)[0]); try { if (result == SocketCallBackResult.Ok) { string responseLine = Encoding.ASCII.GetString(((MemoryStream) (((object[]) tag)[1])).ToArray()); // Response line must start with 250 or otherwise it's error response if (!responseLine.StartsWith("250")) { throw new Exception(responseLine); } else { // BDAT: completed susscessfully, call callback method. callback(SocketCallBackResult.Ok, null); } } else { HandleSocketError(result, exception); } } catch (Exception x) { // Pass exception to callback method callback(SocketCallBackResult.Exception, x); } } /// <summary> /// Is called when smtp client has finished DATA command sending. /// </summary> /// <param name="result"></param> /// <param name="count"></param> /// <param name="exception"></param> /// <param name="tag"></param> private void OnDataSendFinished(SocketCallBackResult result, long count, Exception exception, object tag) { CommadCompleted callback = (CommadCompleted) (((object[]) tag)[1]); try { if (result == SocketCallBackResult.Ok) { // DATA command has sent to SMTP server, start reading server response. MemoryStream ms = new MemoryStream(); m_pSocket.BeginReadLine(ms, 1000, new object[] {(((object[]) tag)[0]), callback, ms}, OnDataReadServerResponseFinished); } else { HandleSocketError(result, exception); } } catch (Exception x) { // Pass exception to callback method callback(SocketCallBackResult.Exception, x); } } /// <summary> /// Is called when smtp client has finished reading DATA command server response line. /// </summary> /// <param name="result"></param> /// <param name="count"></param> /// <param name="exception"></param> /// <param name="tag"></param> private void OnDataReadServerResponseFinished(SocketCallBackResult result, long count, Exception exception, object tag) { CommadCompleted callback = (CommadCompleted) (((object[]) tag)[1]); try { if (result == SocketCallBackResult.Ok) { string responseLine = Encoding.ASCII.GetString(((MemoryStream) (((object[]) tag)[2])).ToArray()); // Response line must start with 334 or otherwise it's error response if (!responseLine.StartsWith("354")) { throw new Exception(responseLine); } else { Stream message = (Stream) (((object[]) tag)[0]); // Start sending message to smtp server m_pSocket.BeginWritePeriodTerminated(message, callback, OnDataMessageSendFinished); } } else { HandleSocketError(result, exception); } } catch (Exception x) { // Pass exception to callback method callback(SocketCallBackResult.Exception, x); } } /// <summary> /// Is called when smtp client has sending MESSAGE to smtp server. /// </summary> /// <param name="result"></param> /// <param name="count"></param> /// <param name="exception"></param> /// <param name="tag"></param> private void OnDataMessageSendFinished(SocketCallBackResult result, long count, Exception exception, object tag) { CommadCompleted callback = (CommadCompleted) tag; try { if (result == SocketCallBackResult.Ok) { // Message has successfully sent to smtp server, start reading server response MemoryStream ms = new MemoryStream(); m_pSocket.BeginReadLine(ms, 1000, new object[] {callback, ms}, OnDataMessageSendReadServerResponseFinished); } else { HandleSocketError(result, exception); } } catch (Exception x) { // Pass exception to callback method callback(SocketCallBackResult.Exception, x); } } /// <summary> /// Is called when smtp client has finished reading MESSAGE send smtp server response line. /// </summary> /// <param name="result"></param> /// <param name="count"></param> /// <param name="exception"></param> /// <param name="tag"></param> private void OnDataMessageSendReadServerResponseFinished(SocketCallBackResult result, long count, Exception exception, object tag) { CommadCompleted callback = (CommadCompleted) (((object[]) tag)[0]); try { // TODO: some servers close connection after DATA command, hanndle Socket closed. if (result == SocketCallBackResult.Ok) { string responseLine = Encoding.ASCII.GetString(((MemoryStream) (((object[]) tag)[1])).ToArray()); // Response line must start with 250 or otherwise it's error response if (!responseLine.StartsWith("250")) { throw new Exception(responseLine); } else { // DATA: completed susscessfully, call callback method. callback(SocketCallBackResult.Ok, null); } } else { HandleSocketError(result, exception); } } catch (Exception x) { // Pass exception to callback method callback(SocketCallBackResult.Exception, x); } } /// <summary> /// Handles socket errors. /// </summary> /// <param name="result"></param> /// <param name="x"></param> private void HandleSocketError(SocketCallBackResult result, Exception x) { // Log socket errors to log if (m_pSocket.Logger != null) { if (result == SocketCallBackResult.SocketClosed) { m_pSocket.Logger.AddTextEntry("Server closed socket !"); } else if (x != null && x is SocketException) { SocketException socketException = (SocketException) x; // Server disconnected or aborted connection if (socketException.ErrorCode == 10054 || socketException.ErrorCode == 10053) { m_pSocket.Logger.AddTextEntry("Server closed socket or aborted connection !"); } } else { m_pSocket.Logger.AddTextEntry("Unknown error !"); } } if (result == SocketCallBackResult.Exception) { throw x; } else { throw new Exception(result.ToString()); } } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/SIP/Message/SIP_t_ContactParam.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.SIP.Message { #region usings using System; using System.Globalization; using System.Text; #endregion /// <summary> /// Implements SIP "contact-param" value. Defined in RFC 3261. /// </summary> /// <remarks> /// <code> /// RFC 3261 Syntax: /// contact-param = (name-addr / addr-spec) *(SEMI contact-params) /// contact-params = c-p-q / c-p-expires / contact-extension /// c-p-q = "q" EQUAL qvalue /// c-p-expires = "expires" EQUAL delta-seconds /// contact-extension = generic-param /// delta-seconds = 1*DIGIT /// </code> /// </remarks> public class SIP_t_ContactParam : SIP_t_ValueWithParams { #region Members private SIP_t_NameAddress m_pAddress; #endregion #region Properties /// <summary> /// Gets is this SIP contact is special STAR contact. /// </summary> public bool IsStarContact { get { if (m_pAddress.Uri.Value.StartsWith("*")) { return true; } else { return false; } } } /// <summary> /// Gets contact address. /// </summary> public SIP_t_NameAddress Address { get { return m_pAddress; } } /// <summary> /// Gets or sets qvalue parameter. Targets are processed from highest qvalue to lowest. /// This value must be between 0.0 and 1.0. Value -1 means that value not specified. /// </summary> public double QValue { get { if (!Parameters.Contains("qvalue")) { return -1; } else { return double.Parse(Parameters["qvalue"].Value, NumberStyles.Any); } } set { if (value < 0 || value > 1) { throw new ArgumentException("Property QValue value must be between 0.0 and 1.0 !"); } if (value < 0) { Parameters.Remove("qvalue"); } else { Parameters.Set("qvalue", value.ToString()); } } } /// <summary> /// Gets or sets expire parameter (time in seconds when contact expires). Value -1 means not specified. /// </summary> public int Expires { get { SIP_Parameter parameter = Parameters["expires"]; if (parameter != null) { return Convert.ToInt32(parameter.Value); } else { return -1; } } set { if (value < 0) { Parameters.Remove("expires"); } else { Parameters.Set("expires", value.ToString()); } } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> public SIP_t_ContactParam() { m_pAddress = new SIP_t_NameAddress(); } #endregion #region Methods /// <summary> /// Parses "contact-param" from specified value. /// </summary> /// <param name="value">SIP "contact-param" value.</param> /// <exception cref="ArgumentNullException">Raised when <b>value</b> is null.</exception> /// <exception cref="SIP_ParseException">Raised when invalid SIP message.</exception> public void Parse(string value) { if (value == null) { throw new ArgumentNullException("value"); } Parse(new StringReader(value)); } /// <summary> /// Parses "contact-param" from specified reader. /// </summary> /// <param name="reader">Reader from where to parse.</param> /// <exception cref="ArgumentNullException">Raised when <b>reader</b> is null.</exception> /// <exception cref="SIP_ParseException">Raised when invalid SIP message.</exception> public override void Parse(StringReader reader) { /* Contact = ("Contact" / "m" ) HCOLON ( STAR / (contact-param *(COMMA contact-param))) contact-param = (name-addr / addr-spec) *(SEMI contact-params) name-addr = [ display-name ] LAQUOT addr-spec RAQUOT addr-spec = SIP-URI / SIPS-URI / absoluteURI display-name = *(token LWS)/ quoted-string contact-params = c-p-q / c-p-expires / contact-extension c-p-q = "q" EQUAL qvalue c-p-expires = "expires" EQUAL delta-seconds contact-extension = generic-param delta-seconds = 1*DIGIT When the header field value contains a display name, the URI including all URI parameters is enclosed in "<" and ">". If no "<" and ">" are present, all parameters after the URI are header parameters, not URI parameters. Even if the "display-name" is empty, the "name-addr" form MUST be used if the "addr-spec" contains a comma, semicolon, or question mark. There may or may not be LWS between the display-name and the "<". */ if (reader == null) { throw new ArgumentNullException("reader"); } // Parse address SIP_t_NameAddress address = new SIP_t_NameAddress(); address.Parse(reader); m_pAddress = address; // Parse parameters ParseParameters(reader); } /// <summary> /// Converts this to valid "contact-param" value. /// </summary> /// <returns>Returns "contact-param" value.</returns> public override string ToStringValue() { /* Contact = ("Contact" / "m" ) HCOLON ( STAR / (contact-param *(COMMA contact-param))) contact-param = (name-addr / addr-spec) *(SEMI contact-params) name-addr = [ display-name ] LAQUOT addr-spec RAQUOT addr-spec = SIP-URI / SIPS-URI / absoluteURI display-name = *(token LWS)/ quoted-string contact-params = c-p-q / c-p-expires / contact-extension c-p-q = "q" EQUAL qvalue c-p-expires = "expires" EQUAL delta-seconds contact-extension = generic-param delta-seconds = 1*DIGIT */ StringBuilder retVal = new StringBuilder(); // Add address retVal.Append(m_pAddress.ToStringValue()); // Add parameters retVal.Append(ParametersToString()); return retVal.ToString(); } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/SMTP/Relay/Relay_Queue.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.SMTP.Relay { #region usings using System; using System.Collections.Generic; using System.IO; #endregion /// <summary> /// This class implements SMTP relay queue. /// </summary> public class Relay_Queue : IDisposable { #region Members private readonly string m_Name = ""; private readonly Queue<Relay_QueueItem> m_pQueue; #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="name">Relay queue name.</param> /// <exception cref="ArgumentNullException">Is raised when <b>name</b> is null.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> public Relay_Queue(string name) { if (name == null) { throw new ArgumentNullException("name"); } if (name == "") { throw new ArgumentException("Argument 'name' value may not be empty."); } m_Name = name; m_pQueue = new Queue<Relay_QueueItem>(); } #endregion #region Properties /// <summary> /// Gets number of queued items in queue. /// </summary> public int Count { get { return m_pQueue.Count; } } /// <summary> /// Gets queue name. /// </summary> public string Name { get { return m_Name; } } #endregion #region Methods /// <summary> /// Cleans up any resources being used. /// </summary> public void Dispose() {} /// <summary> /// Queues message for relay. /// </summary> /// <param name="from">Sender address.</param> /// <param name="to">Target recipient address.</param> /// <param name="messageID">Message ID.</param> /// <param name="message">Raw mime message. Message reading starts from current position.</param> /// <param name="tag">User data.</param> /// <exception cref="ArgumentNullException">Is raised when <b>to</b>,<b>to</b>,<b>messageID</b> or <b>message</b> is null.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> public void QueueMessage(string from, string to, string messageID, Stream message, object tag) { if (messageID == null) { throw new ArgumentNullException("messageID"); } if (messageID == "") { throw new ArgumentException("Argument 'messageID' value must be specified."); } if (message == null) { throw new ArgumentNullException("message"); } lock (m_pQueue) { m_pQueue.Enqueue(new Relay_QueueItem(this, from, to, messageID, message, tag)); } } /// <summary> /// Dequeues message from queue. If there are no messages, this method returns null. /// </summary> /// <returns>Returns queued relay message or null if no messages.</returns> public Relay_QueueItem DequeueMessage() { lock (m_pQueue) { if (m_pQueue.Count > 0) { return m_pQueue.Dequeue(); } else { return null; } } } #endregion } }<file_sep>/redistributable/BaseCampRestAPI-1.1.0/BasecampRestAPI/ProductionWebRequestFactory.cs using System.Net; namespace BasecampRestAPI { class ProductionWebRequestFactory : IWebRequestFactory { public static ProductionWebRequestFactory GetInstance() { return new ProductionWebRequestFactory(); } private ProductionWebRequestFactory() { } #region Implementation of IWebRequestFactory public IWebRequest CreateWebRequest(string url) { return ProductionWebRequest.GetInstance(url); } public HttpWebRequest GetHttpWebRequest(string url) { return ProductionWebRequest.GetInstance(url).HttpWebRequest; } #endregion } } <file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/SMTP/Server/old/GetMessageStoreStream_eArgs.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections.Generic; using System.Text; using System.IO; namespace LumiSoft.Net.SMTP.Server { /// <summary> /// This class provides data for the GetMessageStoreStream event. /// </summary> public class GetMessageStoreStream_eArgs { private SMTP_Session m_pSession = null; private Stream m_pStoreStream = null; /// <summary> /// Default constructor. /// </summary> /// <param name="session">Reference to calling SMTP sesssion.</param> public GetMessageStoreStream_eArgs(SMTP_Session session) { m_pSession = session; m_pStoreStream = new MemoryStream(); } #region Properties Implementation /// <summary> /// Gets reference to smtp session. /// </summary> public SMTP_Session Session { get{ return m_pSession; } } /// <summary> /// Gets or sets Stream where to store incoming message. Storing starts from stream current position. /// </summary> public Stream StoreStream { get{ return m_pStoreStream; } set{ if(value == null){ throw new ArgumentNullException("Property StoreStream value can't be null !"); } m_pStoreStream = value; } } #endregion } } <file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/MIME/MIME_Encoding_EncodedWord.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System.Text.RegularExpressions; namespace ASC.Mail.Net.MIME { #region usings using System; using System.IO; using System.Text; #endregion /// <summary> /// Implements 'encoded-word' encoding. Defined in RFC 2047. /// </summary> public class MIME_Encoding_EncodedWord { #region Members private readonly MIME_EncodedWordEncoding m_Encoding; private readonly Encoding m_pCharset; #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="encoding">Encoding to use to encode text.</param> /// <param name="charset">Charset to use for encoding. If not sure UTF-8 is strongly recommended.</param> /// <exception cref="ArgumentNullException">Is raised when <b>charset</b> is null reference.</exception> public MIME_Encoding_EncodedWord(MIME_EncodedWordEncoding encoding, Encoding charset) { if (charset == null) { throw new ArgumentNullException("charset"); } m_Encoding = encoding; m_pCharset = charset; } #endregion #region Methods /// <summary> /// Checks if specified text must be encoded. /// </summary> /// <param name="text">Text to encode.</param> /// <returns>Returns true if specified text must be encoded, otherwise false.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>text</b> is null reference.</exception> public static bool MustEncode(string text) { if (text == null) { throw new ArgumentNullException("text"); } // Encoding is needed only for non-ASCII chars. foreach (char c in text) { if (c > 127) { return true; } } return false; } /// <summary> /// Encodes specified text if it contains 8-bit chars, otherwise text won't be encoded. /// </summary> /// <param name="encoding">Encoding to use to encode text.</param> /// <param name="charset">Charset to use for encoding. If not sure UTF-8 is strongly recommended.</param> /// <param name="text">Text to encode.</param> /// <returns>Returns encoded text.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>charset</b> or <b>text</b> is null reference.</exception> public static string EncodeS(MIME_EncodedWordEncoding encoding, Encoding charset, string text) { if (charset == null) { throw new ArgumentNullException("charset"); } if (text == null) { throw new ArgumentNullException("text"); } /* RFC 2047 2. encoded-word = "=?" charset "?" encoding "?" encoded-text "?=" An 'encoded-word' may not be more than 75 characters long, including 'charset', 'encoding', 'encoded-text', and delimiters. If it is desirable to encode more text than will fit in an 'encoded-word' of 75 characters, multiple 'encoded-word's (separated by CRLF SPACE) may be used. RFC 2231 (updates syntax) encoded-word := "=?" charset ["*" language] "?" encoded-text "?=" */ if (MustEncode(text)) { StringBuilder retVal = new StringBuilder(); byte[] data = charset.GetBytes(text); int maxEncodedTextSize = 75 - (("=?" + charset.WebName + "?" + encoding + "?" + "?=")).Length; #region B encode if (encoding == MIME_EncodedWordEncoding.B) { retVal.Append("=?" + charset.WebName + "?B?"); int stored = 0; string base64 = Convert.ToBase64String(data); for (int i = 0; i < base64.Length; i += 4) { // Encoding buffer full, create new encoded-word. if (stored + 4 > maxEncodedTextSize) { retVal.Append("?=\r\n =?" + charset.WebName + "?B?"); stored = 0; } retVal.Append(base64, i, 4); stored += 4; } retVal.Append("?="); } #endregion #region Q encode else { retVal.Append("=?" + charset.WebName + "?Q?"); int stored = 0; foreach (byte b in data) { string val = null; // We need to encode byte. Defined in RFC 2047 4.2. if (b > 127 || b == '=' || b == '?' || b == '_' || b == ' ') { val = "=" + b.ToString("X2"); } else { val = ((char)b).ToString(); } // Encoding buffer full, create new encoded-word. if (stored + val.Length > maxEncodedTextSize) { retVal.Append("?=\r\n =?" + charset.WebName + "?Q?"); stored = 0; } retVal.Append(val); stored += val.Length; } retVal.Append("?="); } #endregion return retVal.ToString(); } else { return text; } } public static string DecodeSubject(string text) { if (string.IsNullOrEmpty(text)) { return text; } if (ParseRegex.IsMatch(text)) { //Kill spaces text = Regex.Replace(text,@"(\s+|\t+)",""); string[] separator = { @"?==?" }; string[] splitStr = text.Split(separator, StringSplitOptions.None); for (int i = 1; i < splitStr.Length; i++) { if (splitStr[i - 1][splitStr[i - 1].Length - 1] != '=') splitStr[i] = Regex.Replace(splitStr[i], @"(?<charset>.*?)\?(?<encoding>[qQbB])\?", ""); else splitStr[i] = @"?==?" + splitStr[i]; } if(splitStr.Length >1) text = string.Join("", splitStr); } return ParseRegex.Replace(text, new MatchEvaluator(Evalute)); } private static readonly Regex ParseRegex = new Regex(@"=\?(?<charset>.*?)\?(?<encoding>[qQbB])\?(?<value>.*?)\?=", RegexOptions.Multiline|RegexOptions.Compiled); public static string DecodeAll(string text) { if (string.IsNullOrEmpty(text)) { return text; } return ParseRegex.Replace(text, new MatchEvaluator(Evalute)); //StringBuilder builder = new StringBuilder(); //StringBuilder notDecoded = new StringBuilder(); //builder.Append(text); ////Try decode as single //var fullWordParts = text.Split('?'); //try //{ // if (fullWordParts.Length == 5) // { // if (fullWordParts[2].Equals("B", StringComparison.OrdinalIgnoreCase)) // { // //do processing // using (var ms = new MemoryStream()) // { // byte[] bytes = Convert.FromBase64String(fullWordParts[3]); // ms.Write(bytes, 0, bytes.Length); // notDecoded.Append( // Encoding.GetEncoding(fullWordParts[1].Split('*')[0]).GetString(ms.ToArray())); // builder = notDecoded; // } // } // else // { // notDecoded.Append(DecodeS(builder.ToString())); // builder = notDecoded; // } // } // else // { // var words = text.Split(' ', '\t'); // //Get encoded word start // int decodedWordIndex = 0; // while (decodedWordIndex < words.Length) // { // string[] wordparts = words[decodedWordIndex].Split('?'); // if (wordparts.Length == 5) // { // if (wordparts[2].Equals("B", StringComparison.OrdinalIgnoreCase)) // { // //do processing // using (MemoryStream ms = new MemoryStream()) // { // for (int i = decodedWordIndex; i < words.Length; i++) // { // string[] parts = words[i].Split('?'); // // Not encoded-word. // if (parts.Length == 5) // { // byte[] bytes = Convert.FromBase64String(parts[3]); // ms.Write(bytes, 0, bytes.Length); // } // } // notDecoded.Append( // Encoding.GetEncoding(wordparts[1].Split('*')[0]).GetString(ms.ToArray())); // builder = notDecoded; // break; // } // } // else // { // //Found decoded // //encoded // builder = new StringBuilder(); // //Get the first part // builder.Append(words[decodedWordIndex].Substring(0, // words[decodedWordIndex]. // LastIndexOf('?'))); // //extract data from others // for (int i = decodedWordIndex + 1; i < words.Length; i++) // { // string[] parts = words[i].Split('?'); // // Not encoded-word. // if (parts.Length == 5) // { // builder.Append(parts[3]); // } // } // builder.Append("?="); // notDecoded.Append(DecodeS(builder.ToString())); // builder = notDecoded; // break; // } // } // else // { // notDecoded.Append(words[decodedWordIndex] + " "); // decodedWordIndex++; // } // } // } //} //catch //{ // return text; //} //return builder.ToString(); } private static string Evalute(Match match) { try { if (match.Success) { string charSet = match.Groups["charset"].Value; string encoding = match.Groups["encoding"].Value.ToUpper(); string value = match.Groups["value"].Value; Encoding enc = EncodingTools.GetEncodingByCodepageName(charSet) ?? ("utf-8".Equals(encoding,StringComparison.OrdinalIgnoreCase) ? Encoding.UTF8 : Encoding.Default); if (encoding.ToLower().Equals("b")) return enc.GetString(Convert.FromBase64String(value)); return Core.QDecode(enc, value); } } catch (Exception) { } return match.Value; } /// <summary> /// Decodes non-ascii word with MIME <b>encoded-word</b> method. Defined in RFC 2047 2. /// </summary> /// <param name="word">MIME encoded-word value.</param> /// <returns>Returns decoded word.</returns> /// <remarks>If <b>word</b> is not encoded-word or has invalid syntax, <b>word</b> is leaved as is.</remarks> /// <exception cref="ArgumentNullException">Is raised when <b>word</b> is null reference.</exception> public static string DecodeS(string word) { if (word == null) { throw new ArgumentNullException("word"); } /* RFC 2047 2. encoded-word = "=?" charset "?" encoding "?" encoded-text "?=" RFC 2231. encoded-word := "=?" charset ["*" language] "?" encoded-text "?=" */ try { return ParseRegex.Replace(word, new MatchEvaluator(Evalute)); } catch { // Failed to parse encoded-word, leave it as is. RFC 2047 6.3. return word; } } /// <summary> /// Encodes specified text if it contains 8-bit chars, otherwise text won't be encoded. /// </summary> /// <param name="text">Text to encode.</param> /// <returns>Returns encoded text.</returns> public string Encode(string text) { if (MustEncode(text)) { return EncodeS(m_Encoding, m_pCharset, text); } else { return text; } } /// <summary> /// Decodes specified encoded-word. /// </summary> /// <param name="text">Encoded-word value.</param> /// <returns>Returns decoded text.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>text</b> is null reference.</exception> public string Decode(string text) { if (text == null) { throw new ArgumentNullException("text"); } return DecodeS(text); } #endregion } }<file_sep>/redistributable/Twitterizer2/Twitterizer2/Methods/Trends/TwitterTrend.cs //----------------------------------------------------------------------- // <copyright file="TwitterTrend.cs" company="Patrick 'Ricky' Smith"> // This file is part of the Twitterizer library (http://www.twitterizer.net/) // // Copyright (c) 2010, Patrick "Ricky" Smith (<EMAIL>) // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, are // permitted provided that the following conditions are met: // // - Redistributions of source code must retain the above copyright notice, this list // of conditions and the following disclaimer. // - Redistributions in binary form must reproduce the above copyright notice, this list // of conditions and the following disclaimer in the documentation and/or other // materials provided with the distribution. // - Neither the name of the Twitterizer nor the names of its contributors may be // used to endorse or promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. // IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, // INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT // NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // </copyright> // <author><NAME></author> // <summary>The Twitter Trend class</summary> //----------------------------------------------------------------------- namespace Twitterizer { using System; using System.Runtime.Serialization; using Twitterizer.Core; /// <summary> /// The TwitterTrend class. /// </summary> #if !SILVERLIGHT [Serializable] #endif [DataContract] public class TwitterTrend : TwitterObject { /// <summary> /// Gets or sets the name. /// </summary> /// <value>The name of the trend.</value> [DataMember] public string Name { get; set; } /// <summary> /// Gets or sets the address. /// </summary> /// <value>The address.</value> [DataMember] public string Address { get; set; } /// <summary> /// Gets or sets the search query. /// </summary> /// <value>The search query.</value> [DataMember] public string SearchQuery { get; set; } /// <summary> /// Gets or sets the promoted content value. /// </summary> /// <value>Promoted Content.</value> [DataMember] public string PromotedContent { get; set; } /// <summary> /// Gets or sets the events. /// </summary> /// <value>The events.</value> [DataMember] public string Events { get; set; } /// <summary> /// Gets the trends with the specified WOEID. /// </summary> /// <param name="tokens">The request tokens.</param> /// <param name="WoeID">The WOEID.</param> /// <param name="options">The options.</param> /// <returns> /// A collection of <see cref="Twitterizer.TwitterTrend"/> objects. /// </returns> public static TwitterResponse<TwitterTrendCollection> Trends(OAuthTokens tokens, int WoeID, LocalTrendsOptions options) { Commands.TrendsCommand command = new Twitterizer.Commands.TrendsCommand(tokens, WoeID, options); return Core.CommandPerformer.PerformAction(command); } /// <summary> /// Gets the current trends. /// </summary> /// <param name="tokens">The request tokens.</param> /// <param name="WoeID">The WOEID.</param> /// <returns> /// A collection of <see cref="Twitterizer.TwitterTrend"/> objects. /// </returns> public static TwitterResponse<TwitterTrendCollection> Trends(OAuthTokens tokens, int WoeID) { return Trends(tokens, WoeID, null); } /// <summary> /// Gets the trends with the specified WOEID. /// </summary> /// <param name="WoeID">The WOEID.</param> /// <param name="options">The options.</param> /// <returns> /// A collection of <see cref="Twitterizer.TwitterTrend"/> objects. /// </returns> public static TwitterResponse<TwitterTrendCollection> Trends(int WoeID, LocalTrendsOptions options) { return Trends(null, WoeID, options); } /// <summary> /// Gets the current trends. /// </summary> /// <param name="WoeID">The WOEID.</param> /// <returns> /// A collection of <see cref="Twitterizer.TwitterTrend"/> objects. /// </returns> public static TwitterResponse<TwitterTrendCollection> Trends(int WoeID) { return Trends(null, WoeID, null); } /// <summary> /// Gets the locations where trends are available. /// </summary> /// <param name="tokens">The request tokens.</param> /// <param name="options">The options.</param> /// <returns> /// A collection of <see cref="Twitterizer.TwitterTrendLocation"/> objects. /// </returns> public static TwitterResponse<TwitterTrendLocationCollection> Available(OAuthTokens tokens, AvailableTrendsOptions options) { Commands.AvailableTrendsCommand command = new Twitterizer.Commands.AvailableTrendsCommand(tokens, options); return Core.CommandPerformer.PerformAction(command); } /// <summary> /// Gets the locations where trends are available. /// </summary> /// <param name="options">The options.</param> /// <returns> /// A collection of <see cref="Twitterizer.TwitterTrendLocation"/> objects. /// </returns> public static TwitterResponse<TwitterTrendLocationCollection> Available(AvailableTrendsOptions options) { return Available(null, options); } /// <summary> /// Gets the locations where trends are available. /// </summary> /// <returns> /// A collection of <see cref="Twitterizer.TwitterTrendLocation"/> objects. /// </returns> public static TwitterResponse<TwitterTrendLocationCollection> Available() { return Available(null, null); } /// <summary> /// Gets the daily global trends /// </summary> /// <param name="tokens">The request tokens.</param> /// <param name="options">The options.</param> public static TwitterResponse<TwitterTrendDictionary> Daily(OAuthTokens tokens, TrendsOptions options) { Commands.DailyTrendsCommand command = new Twitterizer.Commands.DailyTrendsCommand(tokens, options); return Core.CommandPerformer.PerformAction(command); } /// <summary> /// Gets the daily global trends /// </summary> /// <param name="options">The options.</param> public static TwitterResponse<TwitterTrendDictionary> Daily(TrendsOptions options) { return Daily(null, options); } /// <summary> /// Gets the daily global trends /// </summary> public static TwitterResponse<TwitterTrendDictionary> Daily() { return Daily(null, null); } /// <summary> /// Gets the weekly global trends /// </summary> /// <param name="tokens">The request tokens.</param> /// <param name="options">The options.</param> public static TwitterResponse<TwitterTrendDictionary> Weekly(OAuthTokens tokens, TrendsOptions options) { Commands.WeeklyTrendsCommand command = new Twitterizer.Commands.WeeklyTrendsCommand(tokens, options); return Core.CommandPerformer.PerformAction(command); } /// <summary> /// Gets the weekly global trends /// </summary> /// <param name="options">The options.</param> public static TwitterResponse<TwitterTrendDictionary> Weekly(TrendsOptions options) { return Weekly(null, options); } /// <summary> /// Gets the weekly global trends /// </summary> public static TwitterResponse<TwitterTrendDictionary> Weekly() { return Weekly(null, null); } } } <file_sep>/web/studio/ASC.Web.Studio/Products/Community/Modules/Wiki/WikiUC/fckeditor/editor/plugins/quote/lang/fr.js  FCKLang.QuoteDlgTitle = "Propriétés de la citation"; FCKLang.QuoteBtn = "Insérer une citation"; FCKLang.QuoteOwnerAlert = "Le champ du nom est vide."; FCKLang.QuoteWrote = "a écrit:"; FCKLang.QuoteLnkBody = "Citation:";<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/RTP/RTCP_PacketType.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.RTP { /// <summary> /// This class holds known RTCP packet types. /// </summary> public class RTCP_PacketType { #region Members /// <summary> /// Application specifiec data. /// </summary> public const int APP = 204; /// <summary> /// BYE. /// </summary> public const int BYE = 203; /// <summary> /// Receiver report. /// </summary> public const int RR = 201; /// <summary> /// Session description. /// </summary> public const int SDES = 202; /// <summary> /// Sender report. /// </summary> public const int SR = 200; #endregion } }<file_sep>/module/ASC.Api/ASC.Specific/WarmupApi/WarmUpEntryPoint.cs using System; using ASC.Api.Attributes; using ASC.Api.Impl; using ASC.Api.Interfaces; using ASC.Web.Studio.Core; namespace ASC.Specific.WarmupApi { public class WarmUpEntryPoint : IApiEntryPoint { /// <summary> /// Entry point name /// </summary> public string Name { get { return "warmup"; } } ///<summary> /// Constructor ///</summary> ///<param name="context"></param> public WarmUpEntryPoint(ApiContext context) { } /// <summary> /// Request of warmup progress /// </summary> /// <visible>false</visible> [Read(@"progress", false, false)] //NOTE: this method doesn't requires auth!!! public string GetWarmupProgress() { try { return WarmUp.Instance.GetSerializedProgress(); } catch (Exception ex) { return ex.Message; } } /// <visible>false</visible> [Read(@"restart", false, false)] //NOTE: this method doesn't requires auth!!! public string Restart() { try { WarmUp.Instance.Restart(); return "Ok"; } catch (Exception ex) { return ex.Message; } } } } <file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Autoreply/ParameterResolvers/TaskResponsiblesResolver.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using ASC.Core; using ASC.Core.Users; using ASC.Mail.Autoreply.Utility; using ASC.Mail.Net.Mail; namespace ASC.Mail.Autoreply.ParameterResolvers { internal class TaskResponsiblesResolver : IParameterResolver { public static readonly Regex Pattern = new Regex(@"@\w+\s+\w+", RegexOptions.CultureInvariant | RegexOptions.Compiled); public object ResolveParameterValue(Mail_Message mailMessage) { if (!Pattern.IsMatch(mailMessage.Subject)) return null; var users = new List<object>(); foreach (Match match in Pattern.Matches(mailMessage.Subject)) { var words = match.Value.Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries); Guid user; if (TryGetUser(words[0], words[1], out user)) { users.Add(user); } } return users; } private static bool TryGetUser(string word1, string word2, out Guid userId) { userId = Guid.Empty; var users = CoreContext.UserManager.GetUsers() .GroupBy(u => GetDistance(u, word1, word2)) .OrderBy(g => g.Key) .FirstOrDefault(g => g.Key < 3); if (users != null && users.Count() == 1) { userId = users.First().ID; return true; } return false; } private static int GetDistance(UserInfo user, string word1, string word2) { var distance1 = StringDistance.LevenshteinDistance(user.FirstName, word1) + StringDistance.LevenshteinDistance(user.LastName, word2); var distance2 = StringDistance.LevenshteinDistance(user.FirstName, word2) + StringDistance.LevenshteinDistance(user.LastName, word1); return Math.Min(distance1, distance2); } } internal class TaskResponsibleResolver : IParameterResolver { public object ResolveParameterValue(Mail_Message mailMessage) { var responsibles = new TaskResponsiblesResolver().ResolveParameterValue(mailMessage) as List<object>; return responsibles != null ? responsibles.FirstOrDefault() : null; } } } <file_sep>/module/ASC.Api/ASC.Api.MailServer/MailServerApi.MailGroup.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System.Collections.Generic; using ASC.Api.Attributes; using ASC.Mail.Data.Contracts; // ReSharper disable InconsistentNaming namespace ASC.Api.MailServer { public partial class MailServerApi { /// <summary> /// Create group address /// </summary> /// <param name="name"></param> /// <param name="domain_id"></param> /// <param name="address_ids"></param> /// <returns>MailGroupData associated with tenant</returns> /// <short>Create mail group address</short> /// <category>MailGroup</category> [Create(@"groupaddress/add")] public ServerDomainGroupData CreateMailGroup(string name, int domain_id, List<int> address_ids) { var group = MailEngineFactory.ServerMailgroupEngine.CreateMailGroup(name, domain_id, address_ids); return group; } /// <summary> /// Add addresses to group /// </summary> /// <param name="mailgroup_id">id of group address</param> /// <param name="address_id"></param> /// <returns>MailGroupData associated with tenant</returns> /// <short>Add group's addresses</short> /// <category>MailGroup</category> [Update(@"groupaddress/address/add")] public ServerDomainGroupData AddMailGroupAddress(int mailgroup_id, int address_id) { var group = MailEngineFactory.ServerMailgroupEngine.AddMailGroupMember(mailgroup_id, address_id); return group; } /// <summary> /// Remove address from group /// </summary> /// <param name="mailgroup_id">id of group address</param> /// <param name="address_id"></param> /// <returns>id of group address</returns> /// <short>Remove group's address</short> /// <category>MailGroup</category> [Delete(@"groupaddress/addresses/remove")] public int RemoveMailGroupAddress(int mailgroup_id, int address_id) { MailEngineFactory.ServerMailgroupEngine.RemoveMailGroupMember(mailgroup_id, address_id); return address_id; } /// <summary> /// Returns list of group addresses associated with tenant /// </summary> /// <returns>List of MailGroupData for current tenant</returns> /// <short>Get mail group list</short> /// <category>MailGroup</category> [Read(@"groupaddress/get")] public List<ServerDomainGroupData> GetMailGroups() { var groups = MailEngineFactory.ServerMailgroupEngine.GetMailGroups(); return groups; } /// <summary> /// Deletes the selected group address /// </summary> /// <param name="id">id of group address</param> /// <returns>id of group address</returns> /// <short>Remove group address from mail server</short> /// <category>MailGroup</category> [Delete(@"groupaddress/remove/{id}")] public int RemoveMailGroup(int id) { MailEngineFactory.ServerMailgroupEngine.RemoveMailGroup(id); return id; } } } <file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/RTP/Debug/wfrm_RTP_Debug.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.RTP.Debug { #region usings using System; using System.Drawing; using System.Net; using System.Windows.Forms; #endregion /// <summary> /// This class implements RTP multimedia session debugger/monitoring UI. /// </summary> public class wfrm_RTP_Debug : Form { #region Nested type: ComboBoxItem /// <summary> /// This class implements ComboBaox item. /// </summary> private class ComboBoxItem { #region Members private readonly object m_pTag; private readonly string m_Text = ""; #endregion #region Properties /// <summary> /// Gets text. /// </summary> public string Text { get { return m_Text; } } /// <summary> /// Gets user data. /// </summary> public object Tag { get { return m_pTag; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="text">Text.</param> /// <param name="tag">User data.</param> public ComboBoxItem(string text, object tag) { m_Text = text; m_pTag = tag; } #endregion #region Methods /// <summary> /// Returns ComboBox text. /// </summary> /// <returns>eturns ComboBox text.</returns> public override string ToString() { return m_Text; } #endregion } #endregion #region Nested type: RTP_ParticipantInfo /// <summary> /// This class provides data for RTP participant property grid. /// </summary> private class RTP_ParticipantInfo { #region Members private readonly RTP_Participant m_pParticipant; #endregion #region Properties /// <summary> /// Gets or sets the real name, eg. "<NAME>". Value null means not specified. /// </summary> public string Name { get { if (m_pParticipant is RTP_Participant_Local) { return ((RTP_Participant_Local) m_pParticipant).Name; } else { return ((RTP_Participant_Remote) m_pParticipant).Name; } } } /// <summary> /// Gets or sets email address. For example "<EMAIL>". Value null means not specified. /// </summary> public string Email { get { if (m_pParticipant is RTP_Participant_Local) { return ((RTP_Participant_Local) m_pParticipant).Email; } else { return ((RTP_Participant_Remote) m_pParticipant).Email; } } } /// <summary> /// Gets or sets phone number. For example "+1 908 555 1212". Value null means not specified. /// </summary> public string Phone { get { if (m_pParticipant is RTP_Participant_Local) { return ((RTP_Participant_Local) m_pParticipant).Phone; } else { return ((RTP_Participant_Remote) m_pParticipant).Phone; } } } /// <summary> /// Gets or sets location string. It may be geographic address or for example chat room name. /// Value null means not specified. /// </summary> public string Location { get { if (m_pParticipant is RTP_Participant_Local) { return ((RTP_Participant_Local) m_pParticipant).Location; } else { return ((RTP_Participant_Remote) m_pParticipant).Location; } } } /// <summary> /// Gets or sets streaming application name/version. /// Value null means not specified. /// </summary> public string Tool { get { if (m_pParticipant is RTP_Participant_Local) { return ((RTP_Participant_Local) m_pParticipant).Tool; } else { return ((RTP_Participant_Remote) m_pParticipant).Tool; } } } /// <summary> /// Gets or sets note text. The NOTE item is intended for transient messages describing the current state /// of the source, e.g., "on the phone, can't talk". Value null means not specified. /// </summary> public string Note { get { if (m_pParticipant is RTP_Participant_Local) { return ((RTP_Participant_Local) m_pParticipant).Note; } else { return ((RTP_Participant_Remote) m_pParticipant).Note; } } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="participant">RTP local participant.</param> /// <exception cref="ArgumentNullException">Is raised when <b>participant</b> null reference.</exception> public RTP_ParticipantInfo(RTP_Participant participant) { if (participant == null) { throw new ArgumentNullException("participant"); } m_pParticipant = participant; } #endregion } #endregion #region Nested type: RTP_ReceiveStreamInfo /// <summary> /// This class provides data for RTP "receive stream" property grid. /// </summary> private class RTP_ReceiveStreamInfo { #region Members private readonly RTP_ReceiveStream m_pStream; #endregion #region Properties /// <summary> /// Gets stream owner RTP session. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public int Session { get { return m_pStream.Session.GetHashCode(); } } /// <summary> /// Gets number of times <b>SeqNo</b> has wrapped around. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public int SeqNoWrapCount { get { return m_pStream.SeqNoWrapCount; } } /// <summary> /// Gets first sequence number what this stream got. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public int FirstSeqNo { get { return m_pStream.FirstSeqNo; } } /// <summary> /// Gets maximum sequnce number that stream has got. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public int MaxSeqNo { get { return m_pStream.MaxSeqNo; } } /// <summary> /// Gets how many RTP packets has received by this stream. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public long PacketsReceived { get { return m_pStream.PacketsReceived; } } /// <summary> /// Gets how many RTP misorder packets has received by this stream. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public long PacketsMisorder { get { return m_pStream.PacketsMisorder; } } /// <summary> /// Gets how many RTP data has received by this stream. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public long BytesReceived { get { return m_pStream.BytesReceived; } } /// <summary> /// Gets how many RTP packets has lost during transmission. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public long PacketsLost { get { return m_pStream.PacketsLost; } } /// <summary> /// Gets inter arrival jitter. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public double Jitter { get { return m_pStream.Jitter; } } /// <summary> /// Gets time when last SR(sender report) was received. Returns <b>DateTime.MinValue</b> if no SR received. /// </summary> public string LastSRTime { get { return m_pStream.LastSRTime.ToString("HH:mm:ss"); } } /// <summary> /// Gets delay between las SR(sender report) and now in seconds. /// </summary> public int DelaySinceLastSR { get { return m_pStream.DelaySinceLastSR/1000; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="stream">RTP receive stream.</param> public RTP_ReceiveStreamInfo(RTP_ReceiveStream stream) { if (stream == null) { throw new ArgumentNullException("stream"); } m_pStream = stream; } #endregion } #endregion #region Nested type: RTP_SendStreamInfo /// <summary> /// This class provides data for RTP "send stream" property grid. /// </summary> private class RTP_SendStreamInfo { #region Members private readonly RTP_SendStream m_pStream; #endregion #region Properties /// <summary> /// Gets stream owner RTP session. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public int Session { get { return m_pStream.Session.GetHashCode(); } } /// <summary> /// Gets number of times <b>SeqNo</b> has wrapped around. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public int SeqNoWrapCount { get { return m_pStream.SeqNoWrapCount; } } /// <summary> /// Gets next packet sequence number. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public int SeqNo { get { return m_pStream.SeqNo; } } /// <summary> /// Gets last packet send time. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public string LastPacketTime { get { return m_pStream.LastPacketTime.ToString("HH:mm:ss"); } } /// <summary> /// Gets last sent RTP packet RTP timestamp header value. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public uint LastPacketRtpTimestamp { get { return m_pStream.LastPacketRtpTimestamp; } } /// <summary> /// Gets how many RTP packets has sent by this stream. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public long RtpPacketsSent { get { return m_pStream.RtpPacketsSent; } } /// <summary> /// Gets how many RTP bytes has sent by this stream. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public long RtpBytesSent { get { return m_pStream.RtpBytesSent; } } /// <summary> /// Gets how many RTP data(no RTP header included) bytes has sent by this stream. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public long RtpDataBytesSent { get { return m_pStream.RtpDataBytesSent; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="stream">RTP send stream.</param> /// <exception cref="ArgumentNullException">Is raised when <b>stream</b> is null reference.</exception> public RTP_SendStreamInfo(RTP_SendStream stream) { if (stream == null) { throw new ArgumentNullException("stream"); } m_pStream = stream; } #endregion } #endregion #region Nested type: RTP_SessionStatistics /// <summary> /// This class provides data for RTP global statistic property grid. /// </summary> private class RTP_SessionStatistics { #region Members private readonly RTP_Session m_pSession; #endregion #region Properties /// <summary> /// Gets total members count. /// </summary> public long Members { get { return m_pSession.Members.Length; } } /// <summary> /// Gets total members who send RPT data. /// </summary> public long Senders { get { return m_pSession.Senders.Length; } } /// <summary> /// Gets total of RTP packets sent by this session. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public long RtpPacketsSent { get { return m_pSession.RtpPacketsSent; } } /// <summary> /// Gets total of RTP bytes(RTP headers included) sent by this session. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public long RtpBytesSent { get { return m_pSession.RtpBytesSent; } } /// <summary> /// Gets total of RTP packets received by this session. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public long RtpPacketsReceived { get { return m_pSession.RtpPacketsReceived; } } /// <summary> /// Gets total of RTP bytes(RTP headers included) received by this session. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public long RtpBytesReceived { get { return m_pSession.RtpBytesReceived; } } /// <summary> /// Gets number of times RTP packet sending has failed. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public long RtpFailedTransmissions { get { return m_pSession.RtpFailedTransmissions; } } /// <summary> /// Gets total of RTCP packets sent by this session. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public long RtcpPacketsSent { get { return m_pSession.RtcpPacketsSent; } } /// <summary> /// Gets total of RTCP bytes(RTCP headers included) sent by this session. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public long RtcpBytesSent { get { return m_pSession.RtcpBytesSent; } } /// <summary> /// Gets total of RTCP packets received by this session. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public long RtcpPacketsReceived { get { return m_pSession.RtcpPacketsReceived; } } /// <summary> /// Gets total of RTCP bytes(RTCP headers included) received by this session. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public long RtcpBytesReceived { get { return m_pSession.RtcpBytesReceived; } } /// <summary> /// Gets number of times RTCP packet sending has failed. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public long RtcpFailedTransmissions { get { return m_pSession.RtcpFailedTransmissions; } } /// <summary> /// Current RTCP reporting interval in seconds. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public int RtcpInterval { get { return m_pSession.RtcpInterval; } } /// <summary> /// Gets time when last RTCP report was sent. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public string RtcpLastTransmission { get { return m_pSession.RtcpLastTransmission.ToString("HH:mm:ss"); } } /// <summary> /// Gets number of times local SSRC collision dedected. /// </summary> public long LocalCollisions { get { return m_pSession.LocalCollisions; } } /// <summary> /// Gets number of times remote SSRC collision dedected. /// </summary> public long RemoteCollisions { get { return m_pSession.RemoteCollisions; } } /// <summary> /// Gets number of times local packets loop dedected. /// </summary> public long LocalPacketsLooped { get { return m_pSession.LocalPacketsLooped; } } /// <summary> /// Gets number of times remote packets loop dedected. /// </summary> public long RemotePacketsLooped { get { return m_pSession.RemotePacketsLooped; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="session">RTP session.</param> /// <exception cref="ArgumentNullException">Is raised when <b>session</b></exception> public RTP_SessionStatistics(RTP_Session session) { if (session == null) { throw new ArgumentNullException("session"); } m_pSession = session; } #endregion } #endregion #region Nested type: RTP_SourceInfo /// <summary> /// This class provides data for RTP "source" property grid. /// </summary> private class RTP_SourceInfo { #region Members private readonly RTP_Source m_pSource; #endregion #region Properties /// <summary> /// Gets source state. /// </summary> public RTP_SourceState State { get { return m_pSource.State; } } /// <summary> /// Gets owner RTP session. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public int Session { get { return m_pSource.Session.GetHashCode(); } } /// <summary> /// Gets synchronization source ID. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public uint SSRC { get { return m_pSource.SSRC; } } /// <summary> /// Gets source RTCP end point. Value null means source haven't sent any RTCP packet. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public IPEndPoint RtcpEP { get { return m_pSource.RtcpEP; } } /// <summary> /// Gets source RTP end point. Value null means source haven't sent any RTCP packet. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public IPEndPoint RtpEP { get { return m_pSource.RtpEP; } } /// <summary> /// Gets last time when source sent RTP or RCTP packet. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public string LastActivity { get { return m_pSource.LastActivity.ToString("HH:mm:ss"); } } /// <summary> /// Gets last time when source sent RTCP packet. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public string LastRtcpPacket { get { return m_pSource.LastRtcpPacket.ToString("HH:mm:ss"); } } /// <summary> /// Gets last time when source sent RTP packet. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public string LastRtpPacket { get { return m_pSource.LastRtpPacket.ToString("HH:mm:ss"); } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="source">RTP source.</param> /// <exception cref="ArgumentNullException">Is raised when <b>source</b> is null reference.</exception> public RTP_SourceInfo(RTP_Source source) { if (source == null) { throw new ArgumentNullException("source"); } m_pSource = source; } #endregion } #endregion #region Members private readonly RTP_MultimediaSession m_pSession; private readonly Timer m_pTimer; private bool m_IsDisposed; private ListView m_pErrors; private PropertyGrid m_pGlobalSessionInfo; private PropertyGrid m_pParticipantData; private TreeView m_pParticipants; private SplitContainer m_pParticipantsSplitter; private ComboBox m_pSessions; private TabControl m_pTab; #endregion #region Properties /// <summary> /// Gets RTP session what UI debugs. /// </summary> public RTP_MultimediaSession Session { get { return m_pSession; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="session">RTP multimedia session.</param> public wfrm_RTP_Debug(RTP_MultimediaSession session) { if (session == null) { throw new ArgumentNullException("session"); } m_pSession = session; InitUI(); m_pSession.Error += m_pSession_Error; m_pSession.SessionCreated += m_pSession_SessionCreated; m_pSession.NewParticipant += m_pSession_NewParticipant; m_pSession.LocalParticipant.SourceAdded += Participant_SourceAdded; m_pSession.LocalParticipant.SourceRemoved += Participant_SourceRemoved; m_pTimer = new Timer(); m_pTimer.Interval = 1000; m_pTimer.Tick += m_pTimer_Tick; m_pTimer.Enabled = true; TreeNode nodeParticipant = new TreeNode(session.LocalParticipant.CNAME); nodeParticipant.Tag = new RTP_ParticipantInfo(session.LocalParticipant); nodeParticipant.Nodes.Add("Sources"); m_pParticipants.Nodes.Add(nodeParticipant); } #endregion #region Event handlers private void m_pParticipants_AfterSelect(object sender, TreeViewEventArgs e) { m_pParticipantData.SelectedObject = e.Node.Tag; } private void m_pSessions_SelectedIndexChanged(object sender, EventArgs e) { m_pGlobalSessionInfo.SelectedObject = ((ComboBoxItem) m_pSessions.SelectedItem).Tag; } private void m_pErrors_DoubleClick(object sender, EventArgs e) { if (m_pErrors.SelectedItems.Count > 0) { MessageBox.Show(this, "Error: " + (m_pErrors.SelectedItems[0].Tag), "Error:", MessageBoxButtons.OK, MessageBoxIcon.Error); } } /// <summary> /// Is called when RTP session gets unhandled error. /// </summary> /// <param name="sender">Sender.</param> /// <param name="e">Event data.</param> private void m_pSession_Error(object sender, ExceptionEventArgs e) { if (m_IsDisposed) { return; } // Move processing to UI thread. BeginInvoke(new MethodInvoker(delegate { ListViewItem item = new ListViewItem(e.Exception.Message); item.Tag = e.Exception; m_pErrors.Items.Add(item); })); } /// <summary> /// Is called when RTP multimedia session creates new session. /// </summary> /// <param name="sender">Sender.</param> /// <param name="e">Event data.</param> private void m_pSession_SessionCreated(object sender, EventArgs<RTP_Session> e) { if (m_IsDisposed) { return; } // Move processing to UI thread. BeginInvoke(new MethodInvoker(delegate { ComboBoxItem item = new ComboBoxItem("Session: " + e.Value.GetHashCode(), new RTP_SessionStatistics(e.Value)); m_pSessions.Items.Add(item); if (m_pSessions.SelectedIndex == -1) { m_pSessions.SelectedIndex = 0; } })); } /// <summary> /// This method is called when RTP session sees new remote participant. /// </summary> /// <param name="sender">Sender.</param> /// <param name="e">Event data.</param> private void m_pSession_NewParticipant(object sender, RTP_ParticipantEventArgs e) { if (m_IsDisposed) { return; } e.Participant.Removed += Participant_Removed; e.Participant.SourceAdded += Participant_SourceAdded; e.Participant.SourceRemoved += Participant_SourceRemoved; // Move processing to UI thread. BeginInvoke(new MethodInvoker(delegate { TreeNode nodeParticipant = new TreeNode(e.Participant.CNAME); nodeParticipant.Tag = new RTP_ParticipantInfo(e.Participant); nodeParticipant.Nodes.Add("Sources"); m_pParticipants.Nodes.Add(nodeParticipant); })); } /// <summary> /// This method is called when RTP remote participant has disjoined the multimedia session. /// </summary> /// <param name="sender">Sender.</param> /// <param name="e">Event data.</param> private void Participant_Removed(object sender, EventArgs e) { if (m_IsDisposed) { return; } // Move processing to UI thread. BeginInvoke(new MethodInvoker(delegate { TreeNode nodeParticipant = FindParticipantNode((RTP_Participant) sender); if (nodeParticipant != null) { nodeParticipant.Remove(); } })); } /// <summary> /// This method is called when participant creates new source. /// </summary> /// <param name="sender">Sender.</param> /// <param name="e">Event data.</param> private void Participant_SourceAdded(object sender, RTP_SourceEventArgs e) { if (m_IsDisposed) { return; } e.Source.StateChanged += Source_StateChanged; // Move processing to UI thread. BeginInvoke(new MethodInvoker(delegate { TreeNode nodeParticipant = null; if (e.Source is RTP_Source_Remote) { nodeParticipant = FindParticipantNode( ((RTP_Source_Remote) e.Source).Participant); } else { nodeParticipant = FindParticipantNode( ((RTP_Source_Local) e.Source).Participant); } TreeNode nodeSource = nodeParticipant.Nodes[0].Nodes.Add( e.Source.SSRC.ToString()); nodeSource.Tag = new RTP_SourceInfo(e.Source); if (e.Source.State == RTP_SourceState.Active) { TreeNode nodeSourceStream = nodeSource.Nodes.Add("RTP Stream"); if (e.Source is RTP_Source_Local) { nodeSourceStream.Tag = new RTP_SendStreamInfo( ((RTP_Source_Local) e.Source).Stream); } else { nodeSourceStream.Tag = new RTP_ReceiveStreamInfo( ((RTP_Source_Remote) e.Source).Stream); } } })); } /// <summary> /// This method is called when participant source state changes. /// </summary> /// <param name="sender">Sender.</param> /// <param name="e">Event data.</param> private void Source_StateChanged(object sender, EventArgs e) { if (m_IsDisposed) { return; } RTP_Source source = (RTP_Source) sender; if (source.State == RTP_SourceState.Disposed) { return; } // Move processing to UI thread. BeginInvoke(new MethodInvoker(delegate { TreeNode nodeParticipant = null; if (source is RTP_Source_Remote) { nodeParticipant = FindParticipantNode( ((RTP_Source_Remote) source).Participant); } else { nodeParticipant = FindParticipantNode( ((RTP_Source_Local) source).Participant); } if (nodeParticipant != null) { foreach ( TreeNode nodeSource in nodeParticipant.Nodes[0].Nodes) { if (nodeSource.Text == source.SSRC.ToString()) { if (source.State == RTP_SourceState.Active) { TreeNode nodeSourceStream = nodeSource.Nodes.Add("RTP Stream"); if (source is RTP_Source_Local) { nodeSourceStream.Tag = new RTP_SendStreamInfo( ((RTP_Source_Local) source). Stream); } else { nodeSourceStream.Tag = new RTP_ReceiveStreamInfo( ((RTP_Source_Remote) source). Stream); } } break; } } } })); } /// <summary> /// This method is called when participant closes source. /// </summary> /// <param name="sender">Sender.</param> /// <param name="e">Event data.</param> private void Participant_SourceRemoved(object sender, RTP_SourceEventArgs e) { if (m_IsDisposed) { return; } // Get SSRC here, BeginInvoke is anynchronous and source may dispose at same time. uint ssrc = e.Source.SSRC; // Move processing to UI thread. BeginInvoke(new MethodInvoker(delegate { TreeNode nodeParticipant = FindParticipantNode((RTP_Participant) sender); if (nodeParticipant != null) { foreach ( TreeNode nodeSource in nodeParticipant.Nodes[0].Nodes) { if (nodeSource.Text == ssrc.ToString()) { nodeSource.Remove(); break; } } } })); } private void m_pTimer_Tick(object sender, EventArgs e) { m_pParticipantData.Refresh(); m_pGlobalSessionInfo.Refresh(); } private void wfrm_RTP_Debug_FormClosing(object sender, FormClosingEventArgs e) { m_IsDisposed = true; m_pSession.Error -= m_pSession_Error; m_pSession.SessionCreated -= m_pSession_SessionCreated; m_pSession.NewParticipant -= m_pSession_NewParticipant; m_pSession.LocalParticipant.SourceAdded -= Participant_SourceAdded; m_pSession.LocalParticipant.SourceRemoved -= Participant_SourceRemoved; } #endregion #region Utility methods /// <summary> /// Creates and initializes UI. /// </summary> private void InitUI() { ClientSize = new Size(400, 450); Text = "RTP debug"; //this.Icon = ; TODO: FormClosing += wfrm_RTP_Debug_FormClosing; m_pTab = new TabControl(); m_pTab.Dock = DockStyle.Fill; m_pTab.TabPages.Add("participants", "Participants"); m_pParticipantsSplitter = new SplitContainer(); m_pParticipantsSplitter.Dock = DockStyle.Fill; m_pParticipantsSplitter.Orientation = Orientation.Vertical; m_pParticipantsSplitter.SplitterDistance = 60; m_pTab.TabPages["participants"].Controls.Add(m_pParticipantsSplitter); m_pParticipants = new TreeView(); m_pParticipants.Dock = DockStyle.Fill; m_pParticipants.BorderStyle = BorderStyle.None; m_pParticipants.FullRowSelect = true; m_pParticipants.HideSelection = false; m_pParticipants.AfterSelect += m_pParticipants_AfterSelect; m_pParticipantsSplitter.Panel1.Controls.Add(m_pParticipants); m_pParticipantData = new PropertyGrid(); m_pParticipantData.Dock = DockStyle.Fill; m_pParticipantsSplitter.Panel2.Controls.Add(m_pParticipantData); m_pTab.TabPages.Add("global_statistics", "Global statistics"); m_pGlobalSessionInfo = new PropertyGrid(); m_pGlobalSessionInfo.Dock = DockStyle.Fill; m_pTab.TabPages["global_statistics"].Controls.Add(m_pGlobalSessionInfo); m_pSessions = new ComboBox(); m_pSessions.Size = new Size(200, 20); m_pSessions.Location = new Point(100, 2); m_pSessions.DropDownStyle = ComboBoxStyle.DropDownList; m_pSessions.SelectedIndexChanged += m_pSessions_SelectedIndexChanged; m_pTab.TabPages["global_statistics"].Controls.Add(m_pSessions); m_pSessions.BringToFront(); m_pTab.TabPages.Add("errors", "Errors"); m_pErrors = new ListView(); m_pErrors.Dock = DockStyle.Fill; m_pErrors.View = View.Details; m_pErrors.FullRowSelect = true; m_pErrors.HideSelection = false; m_pErrors.Columns.Add("Message", 300); m_pErrors.DoubleClick += m_pErrors_DoubleClick; m_pTab.TabPages["errors"].Controls.Add(m_pErrors); Controls.Add(m_pTab); } /// <summary> /// Searches specified participant tree node. /// </summary> /// <param name="participant">RTP participant.</param> /// <returns>Returns specified participant tree node or null if no matching node.</returns> private TreeNode FindParticipantNode(RTP_Participant participant) { if (participant == null) { throw new ArgumentNullException("participant"); } foreach (TreeNode node in m_pParticipants.Nodes) { if (node.Text == participant.CNAME) { return node; } } return null; } #endregion } }<file_sep>/module/ASC.ElasticSearch/Core/WrapperWithDoc.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.IO; using System.Text; using ASC.Common.Logging; using Nest; using Newtonsoft.Json; namespace ASC.ElasticSearch.Core { public abstract class WrapperWithDoc : Wrapper { public Document Document { get; set; } public const long MaxContentLength = 2 * 1024 *1024 *1024L; protected abstract Stream GetDocumentStream(); [Ignore, JsonIgnore] public abstract string SettingsTitle { get; } internal void InitDocument(bool index) { Document = new Document { Data = Convert.ToBase64String(Encoding.UTF8.GetBytes("")) }; try { if (!index) return; using (var stream = GetDocumentStream()) { if (stream == null) return; Document = new Document { Data = Convert.ToBase64String(stream.GetCorrectBuffer()) }; } } catch (FileNotFoundException e) { LogManager.GetLogger("ASC.Indexer").Error("InitDocument FileNotFoundException", e); } catch (Exception e) { LogManager.GetLogger("ASC.Indexer").Error("InitDocument", e); } } } } <file_sep>/web/studio/ASC.Web.Studio/Products/Community/Modules/Birthdays/js/birthdays.js /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ if (typeof ASC === "undefined") ASC = {}; if (typeof ASC.Community === "undefined") ASC.Community = (function () { return {} })(); ASC.Community.Birthdays = (function() { return { openContact: function(obj) { var name = jq(obj).attr("username"), tcExist = false; try { tcExist = !!ASC.Controls.JabberClient; } catch (err) { tcExist = false; } if (tcExist === true) { try { ASC.Controls.JabberClient.open(name); } catch (err) { } } }, remind: function(obj) { var userCard = jq(obj).parents(".small-user-card"), userId = jq(userCard).find("input[type=hidden]").val(); Teamlab.subscribeCmtBirthday( { userCard: userCard }, { userid: userId, onRemind: true }, { error: function(params, errors) { toastr.error(errors[0]); return false; }, success: function(params, response){ jq(params.userCard).addClass("active"); } }); }, clearRemind: function(obj) { var userCard = jq(obj).parents(".small-user-card"), userId = jq(userCard).find("input[type=hidden]").val(); Teamlab.subscribeCmtBirthday( { userCard: userCard }, { userid: userId, onRemind: false }, { error: function (params, errors) { toastr.error(errors[0]); return false; }, success: function (params, response) { jq(params.userCard).removeClass("active"); } }); } }; })(jQuery);<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/SIP/Stack/SIP_Methods.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.SIP.Stack { /// <summary> /// This class represents known SIP request methods. /// </summary> public class SIP_Methods { #region Constants /// <summary> /// ACK method. Defined in RFC 3261. /// </summary> public const string ACK = "ACK"; /// <summary> /// BYE method. Defined in RFC 3261. /// </summary> public const string BYE = "BYE"; /// <summary> /// CANCEL method. Defined in RFC 3261. /// </summary> public const string CANCEL = "CANCEL"; /// <summary> /// INFO method. Defined in RFC 2976. /// </summary> public const string INFO = "INFO"; /// <summary> /// INVITE method. Defined in RFC 3261. /// </summary> public const string INVITE = "INVITE"; /// <summary> /// MESSAGE method. Defined in RFC 3428. /// </summary> public const string MESSAGE = "MESSAGE"; /// <summary> /// NOTIFY method. Defined in RFC 3265. /// </summary> public const string NOTIFY = "NOTIFY"; /// <summary> /// OPTIONS method. Defined in RFC 3261. /// </summary> public const string OPTIONS = "OPTIONS"; /// <summary> /// PRACK method. Defined in RFC 3262. /// </summary> public const string PRACK = "PRACK"; /// <summary> /// PUBLISH method. Defined in RFC 3903. /// </summary> public const string PUBLISH = "PUBLISH"; /// <summary> /// REFER method. Defined in RFC 3515. /// </summary> public const string REFER = "REFER"; /// <summary> /// REGISTER method. Defined in RFC 3261. /// </summary> public const string REGISTER = "REGISTER"; /// <summary> /// SUBSCRIBE method. Defined in RFC 3265. /// </summary> public const string SUBSCRIBE = "SUBSCRIBE"; /// <summary> /// UPDATE method. Defined in RFC 3311. /// </summary> public const string UPDATE = "UPDATE"; #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/SIP/Proxy/SIP_RegistrationCollection.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.SIP.Proxy { #region usings using System; using System.Collections; using System.Collections.Generic; #endregion /// <summary> /// SIP registration collection. /// </summary> public class SIP_RegistrationCollection : IEnumerable { #region Members private readonly List<SIP_Registration> m_pRegistrations; #endregion #region Properties /// <summary> /// Gets number of registrations in the collection. /// </summary> public int Count { get { return m_pRegistrations.Count; } } /// <summary> /// Gets registration with specified registration name. Returns null if specified registration doesn't exist. /// </summary> /// <param name="addressOfRecord">Address of record of resgistration.</param> /// <returns></returns> public SIP_Registration this[string addressOfRecord] { get { lock (m_pRegistrations) { foreach (SIP_Registration registration in m_pRegistrations) { if (registration.AOR.ToLower() == addressOfRecord.ToLower()) { return registration; } } return null; } } } /// <summary> /// Gets SIP registrations what in the collection. /// </summary> public SIP_Registration[] Values { get { return m_pRegistrations.ToArray(); } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> public SIP_RegistrationCollection() { m_pRegistrations = new List<SIP_Registration>(); } #endregion #region Methods /// <summary> /// Adds specified registration to collection. /// </summary> /// <param name="registration">Registration to add.</param> public void Add(SIP_Registration registration) { lock (m_pRegistrations) { if (Contains(registration.AOR)) { throw new ArgumentException( "Registration with specified registration name already exists !"); } m_pRegistrations.Add(registration); } } /// <summary> /// Deletes specified registration and all it's contacts. /// </summary> /// <param name="addressOfRecord">Registration address of record what to remove.</param> public void Remove(string addressOfRecord) { lock (m_pRegistrations) { foreach (SIP_Registration registration in m_pRegistrations) { if (registration.AOR.ToLower() == addressOfRecord.ToLower()) { m_pRegistrations.Remove(registration); break; } } } } /// <summary> /// Gets if registration with specified name already exists. /// </summary> /// <param name="addressOfRecord">Address of record of resgistration.</param> /// <returns></returns> public bool Contains(string addressOfRecord) { lock (m_pRegistrations) { foreach (SIP_Registration registration in m_pRegistrations) { if (registration.AOR.ToLower() == addressOfRecord.ToLower()) { return true; } } } return false; } /// <summary> /// Removes all expired registrations from the collection. /// </summary> public void RemoveExpired() { lock (m_pRegistrations) { for (int i = 0; i < m_pRegistrations.Count; i++) { SIP_Registration registration = m_pRegistrations[i]; // Force registration to remove all its expired contacts. registration.RemoveExpiredBindings(); // No bindings left, so we need to remove that registration. if (registration.Bindings.Length == 0) { m_pRegistrations.Remove(registration); i--; } } } } /// <summary> /// Gets enumerator. /// </summary> /// <returns></returns> public IEnumerator GetEnumerator() { return m_pRegistrations.GetEnumerator(); } #endregion } }<file_sep>/module/ASC.Thrdparty/ASC.FederatedLogin/LoginProviders/BitlyLoginProvider.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections.Generic; using System.Globalization; using System.Net; using System.Xml.Linq; using System.Xml.XPath; using ASC.Core.Common.Configuration; namespace ASC.FederatedLogin.LoginProviders { public class BitlyLoginProvider : Consumer, IValidateKeysProvider { private static string BitlyClientId { get { return Instance["bitlyClientId"]; } } private static string BitlyClientSecret { get { return Instance["bitlyClientSecret"]; } } private static string BitlyUrl { get { return Instance["bitlyUrl"]; } } private static BitlyLoginProvider Instance { get { return ConsumerFactory.Get<BitlyLoginProvider>(); } } public BitlyLoginProvider() { } public BitlyLoginProvider(string name, int order, Dictionary<string, string> props, Dictionary<string, string> additional = null) : base(name, order, props, additional) { } public bool ValidateKeys() { try { return !string.IsNullOrEmpty(GetShortenLink("https://www.onlyoffice.com")); } catch (Exception) { return false; } } public static bool Enabled { get { return !String.IsNullOrEmpty(BitlyClientId) && !String.IsNullOrEmpty(BitlyClientSecret) && !String.IsNullOrEmpty(BitlyUrl); } } public static String GetShortenLink(String shareLink) { var uri = new Uri(shareLink); var bitly = string.Format(BitlyUrl, BitlyClientId, BitlyClientSecret, Uri.EscapeDataString(uri.ToString())); XDocument response; try { response = XDocument.Load(bitly); } catch (Exception e) { throw new InvalidOperationException(e.Message, e); } var status = response.XPathSelectElement("/response/status_code").Value; if (status != ((int)HttpStatusCode.OK).ToString(CultureInfo.InvariantCulture)) { throw new InvalidOperationException(status); } var data = response.XPathSelectElement("/response/data/url"); return data.Value; } } } <file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/_Obsolete/MIME/HeaderFieldParameter.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.Mime { #region usings using System; #endregion /// <summary> /// Header field parameter. /// </summary> [Obsolete("See LumiSoft.Net.MIME or LumiSoft.Net.Mail namepaces for replacement.")] public class HeaderFieldParameter { #region Members private readonly string m_Name = ""; private readonly string m_Value = ""; #endregion #region Properties /// <summary> /// Gets header field parameter name. /// </summary> public string Name { get { return m_Name; } } /// <summary> /// Gets header field parameter name. /// </summary> public string Value { get { return m_Value; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="parameterName">Header field parameter name.</param> /// <param name="parameterValue">Header field parameter value.</param> public HeaderFieldParameter(string parameterName, string parameterValue) { m_Name = parameterName; m_Value = parameterValue; } #endregion } }<file_sep>/web/studio/ASC.Web.Studio/UserControls/Common/ThirdPartyBanner/ThirdPartyBannerSettings.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Linq; using System.Runtime.Serialization; using ASC.Core.Common.Settings; namespace ASC.Web.Studio.UserControls.Common.ThirdPartyBanner { [Serializable] [DataContract] public class ThirdPartyBannerSettings : BaseSettings<ThirdPartyBannerSettings> { [DataMember(Name = "ClosedSetting")] public string ClosedSetting { get; set; } public override ISettings GetDefault() { return new ThirdPartyBannerSettings { ClosedSetting = null, }; } public override Guid ID { get { return new Guid("{B6E9B080-4B14-4C54-95E7-C2E9E87965EB}"); } } public static bool CheckClosed(string banner) { return (LoadForCurrentUser().ClosedSetting ?? "").Split('|').Contains(banner); } public static void Close(string banner) { var closed = (LoadForCurrentUser().ClosedSetting ?? "").Split('|').ToList(); if (closed.Contains(banner)) return; closed.Add(banner); new ThirdPartyBannerSettings { ClosedSetting = string.Join("|", closed.ToArray()) }.SaveForCurrentUser(); } } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/SIP/Proxy/SIP_GatewayEventArgs.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.SIP.Proxy { #region usings using System; using System.Collections.Generic; #endregion /// <summary> /// This class provides data for SIP_ProxyCore.GetGateways event. /// </summary> public class SIP_GatewayEventArgs { #region Members private readonly List<SIP_Gateway> m_pGateways; private readonly string m_UriScheme = ""; private readonly string m_UserName = ""; #endregion #region Properties /// <summary> /// Gets URI scheme which gateways to get. /// </summary> public string UriScheme { get { return m_UriScheme; } } /// <summary> /// Gets authenticated user name. /// </summary> public string UserName { get { return m_UserName; } } /* /// <summary> /// Gets or sets if specified user has /// </summary> public bool IsForbidden { get{ return false; } set{ } }*/ /// <summary> /// Gets gateways collection. /// </summary> public List<SIP_Gateway> Gateways { get { return m_pGateways; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="uriScheme">URI scheme which gateways to get.</param> /// <param name="userName">Authenticated user name.</param> /// <exception cref="ArgumentException">If any argument has invalid value.</exception> public SIP_GatewayEventArgs(string uriScheme, string userName) { if (string.IsNullOrEmpty(uriScheme)) { throw new ArgumentException("Argument 'uriScheme' value can't be null or empty !"); } m_UriScheme = uriScheme; m_UserName = userName; m_pGateways = new List<SIP_Gateway>(); } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/SIP/Message/SIP_t_EventType.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.SIP.Message { #region usings using System; #endregion /// <summary> /// Implements SIP "event-type" value. Defined in RFC 3265. /// </summary> public class SIP_t_EventType : SIP_t_Value { #region Members private string m_EventType = ""; #endregion #region Properties /// <summary> /// Gets or sets event type. /// </summary> /// <exception cref="ArgumentNullException">Is raised when null value passed as value.</exception> public string EventType { get { return m_EventType; } set { if (value == null) { throw new ArgumentNullException("EventType"); } m_EventType = value; } } #endregion #region Methods /// <summary> /// Parses "event-type" from specified value. /// </summary> /// <param name="value">SIP "event-type" value.</param> /// <exception cref="ArgumentNullException">Raised when <b>value</b> is null.</exception> /// <exception cref="SIP_ParseException">Raised when invalid SIP message.</exception> public void Parse(string value) { if (value == null) { throw new ArgumentNullException("value"); } Parse(new StringReader(value)); } /// <summary> /// Parses "event-type" from specified reader. /// </summary> /// <param name="reader">Reader from where to parse.</param> /// <exception cref="ArgumentNullException">Raised when <b>reader</b> is null.</exception> /// <exception cref="SIP_ParseException">Raised when invalid SIP message.</exception> public override void Parse(StringReader reader) { if (reader == null) { throw new ArgumentNullException("reader"); } // Get Method string word = reader.ReadWord(); if (word == null) { throw new SIP_ParseException("Invalid 'event-type' value, event-type is missing !"); } m_EventType = word; } /// <summary> /// Converts this to valid "event-type" value. /// </summary> /// <returns>Returns "event-type" value.</returns> public override string ToStringValue() { return m_EventType; } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/Data/LDB_DataColumnCollection.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Data.lsDB { #region usings using System; using System.Collections.Generic; #endregion /// <summary> /// lsDB data column collection. /// </summary> public class LDB_DataColumnCollection //: IEnumerable<LDB_DataColumn> { #region Members private readonly List<LDB_DataColumn> m_pColumns; private readonly object m_pOwner; #endregion #region Properties /// <summary> /// Gets column from specified index. /// </summary> public LDB_DataColumn this[int index] { get { return m_pColumns[index]; } } /// <summary> /// Gets column count in the collection. /// </summary> public int Count { get { return m_pColumns.Count; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="owner">Table that owns this collection.</param> internal LDB_DataColumnCollection(object owner) { m_pOwner = owner; m_pColumns = new List<LDB_DataColumn>(); } #endregion #region Methods /// <summary> /// Ads specified data column to collection. /// </summary> /// <param name="column"></param> public void Add(LDB_DataColumn column) { if (Contains(column.ColumnName)) { throw new Exception("Data column with specified name '" + column.ColumnName + "' already exists !"); } if (m_pOwner.GetType() == typeof (DbFile)) { ((DbFile) m_pOwner).AddColumn(column); } else if (m_pOwner.GetType() == typeof (lsDB_FixedLengthTable)) { ((lsDB_FixedLengthTable) m_pOwner).AddColumn(column); } m_pColumns.Add(column); } /// <summary> /// Removes specified data column from collection. /// </summary> /// <param name="columName">Column name which to remove.</param> public void Remove(string columName) { foreach (LDB_DataColumn column in m_pColumns) { if (column.ColumnName.ToLower() == columName.ToLower()) { Remove(column); break; } } } /// <summary> /// Removes specified data column from collection. /// </summary> /// <param name="column">Data column which to remove.</param> public void Remove(LDB_DataColumn column) { m_pColumns.Remove(column); } /// <summary> /// Gets specified data column index in collection. Returns -1 if no such column. /// </summary> /// <param name="columnName"></param> /// <returns></returns> public int IndexOf(string columnName) { for (int i = 0; i < m_pColumns.Count; i++) { if ((m_pColumns[i]).ColumnName.ToLower() == columnName.ToLower()) { return i; } } return -1; } /// <summary> /// Gets specified data column index in collection. Returns -1 if no such column. /// </summary> /// <param name="column">Data column.</param> /// <returns></returns> public int IndexOf(LDB_DataColumn column) { return m_pColumns.IndexOf(column); } /// <summary> /// Gets if data column collection contains specified column. /// </summary> /// <param name="columnName">Column name.</param> /// <returns></returns> public bool Contains(string columnName) { foreach (LDB_DataColumn column in m_pColumns) { if (column.ColumnName.ToLower() == columnName.ToLower()) { return true; } } return false; } /// <summary> /// Gets if data column collection contains specified column. /// </summary> /// <param name="column">Data column.</param> /// <returns></returns> public bool Contains(LDB_DataColumn column) { return m_pColumns.Contains(column); } /// <summary> /// Gets enumerator. /// </summary> /// <returns></returns> public IEnumerator<LDB_DataColumn> GetEnumerator() { return m_pColumns.GetEnumerator(); } #endregion #region Internal methods /// <summary> /// Parses and adds data column to the collection. /// </summary> /// <param name="columnData"></param> internal void Parse(byte[] columnData) { LDB_DataColumn column = new LDB_DataColumn(); column.Parse(columnData); m_pColumns.Add(column); } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/SIP/Stack/SIP_Response.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.SIP.Stack { #region usings using System; using System.Globalization; using System.IO; using System.Text; using Message; #endregion /// <summary> /// SIP server response. Related RFC 3261. /// </summary> public class SIP_Response : SIP_Message { #region Members private readonly SIP_Request m_pRequest; private string m_ReasonPhrase = ""; private double m_SipVersion = 2.0d; private int m_StatusCode = 100; #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> public SIP_Response() {} /// <summary> /// SIP_Request.CreateResponse constructor. /// </summary> /// <param name="request">Owner request.</param> internal SIP_Response(SIP_Request request) { m_pRequest = request; } #endregion #region Properties /// <summary> /// Gets or sets reponse reasong phrase. This just StatusCode describeing text. /// </summary> public string ReasonPhrase { get { return m_ReasonPhrase; } set { if (value == null) { throw new ArgumentNullException("ReasonPhrase"); } m_ReasonPhrase = value; } } /// <summary> /// Gets SIP request which response it is. This value is null if this is stateless response. /// </summary> public SIP_Request Request { get { return m_pRequest; } } /// <summary> /// Gets or sets SIP version. /// </summary> /// <exception cref="ArgumentException">Is raised when invalid SIP version value passed.</exception> public double SipVersion { get { return m_SipVersion; } set { if (value < 1) { throw new ArgumentException("Property SIP version must be >= 1.0 !"); } m_SipVersion = value; } } /// <summary> /// Gets or sets response status code. This value must be between 100 and 999. /// </summary> /// <exception cref="ArgumentException">Is raised when value is out of allowed range.</exception> public int StatusCode { get { return m_StatusCode; } set { if (value < 1 || value > 999) { throw new ArgumentException("Property 'StatusCode' value must be >= 100 && <= 999 !"); } m_StatusCode = value; } } /// <summary> /// Gets or sets SIP Status-Code with Reason-Phrase (Status-Code SP Reason-Phrase). /// </summary> public string StatusCode_ReasonPhrase { get { return m_StatusCode + " " + m_ReasonPhrase; } set { // Status-Code SP Reason-Phrase if (value == null) { throw new ArgumentNullException("StatusCode_ReasonPhrase"); } string[] code_reason = value.Split(new[] {' '}, 2); if (code_reason.Length != 2) { throw new ArgumentException( "Invalid property 'StatusCode_ReasonPhrase' Reason-Phrase value !"); } try { StatusCode = Convert.ToInt32(code_reason[0]); } catch { throw new ArgumentException( "Invalid property 'StatusCode_ReasonPhrase' Status-Code value !"); } ReasonPhrase = code_reason[1]; } } /// <summary> /// Gets SIP status code type. /// </summary> public SIP_StatusCodeType StatusCodeType { get { if (m_StatusCode >= 100 && m_StatusCode < 200) { return SIP_StatusCodeType.Provisional; } else if (m_StatusCode >= 200 && m_StatusCode < 300) { return SIP_StatusCodeType.Success; } else if (m_StatusCode >= 300 && m_StatusCode < 400) { return SIP_StatusCodeType.Redirection; } else if (m_StatusCode >= 400 && m_StatusCode < 500) { return SIP_StatusCodeType.RequestFailure; } else if (m_StatusCode >= 500 && m_StatusCode < 600) { return SIP_StatusCodeType.ServerFailure; } else if (m_StatusCode >= 600 && m_StatusCode < 700) { return SIP_StatusCodeType.GlobalFailure; } else { throw new Exception("Unknown SIP StatusCodeType !"); } } } #endregion #region Methods /// <summary> /// Parses SIP_Response from byte array. /// </summary> /// <param name="data">Valid SIP response data.</param> /// <returns>Returns parsed SIP_Response obeject.</returns> /// <exception cref="ArgumentNullException">Raised when <b>data</b> is null.</exception> /// <exception cref="SIP_ParseException">Raised when invalid SIP message.</exception> public static SIP_Response Parse(byte[] data) { if (data == null) { throw new ArgumentNullException("data"); } return Parse(new MemoryStream(data)); } /// <summary> /// Parses SIP_Response from stream. /// </summary> /// <param name="stream">Stream what contains valid SIP response.</param> /// <returns>Returns parsed SIP_Response obeject.</returns> /// <exception cref="ArgumentNullException">Raised when <b>stream</b> is null.</exception> /// <exception cref="SIP_ParseException">Raised when invalid SIP message.</exception> public static SIP_Response Parse(Stream stream) { /* Syntax: SIP-Version SP Status-Code SP Reason-Phrase SIP-Message */ if (stream == null) { throw new ArgumentNullException("stream"); } SIP_Response retVal = new SIP_Response(); // Parse Response-line StreamLineReader r = new StreamLineReader(stream); r.Encoding = "utf-8"; string[] version_code_text = r.ReadLineString().Split(new[] {' '}, 3); if (version_code_text.Length != 3) { throw new SIP_ParseException( "Invalid SIP Status-Line syntax ! Syntax: {SIP-Version SP Status-Code SP Reason-Phrase}."); } // SIP-Version try { retVal.SipVersion = Convert.ToDouble(version_code_text[0].Split('/')[1], NumberFormatInfo.InvariantInfo); } catch { throw new SIP_ParseException("Invalid Status-Line SIP-Version value !"); } // Status-Code try { retVal.StatusCode = Convert.ToInt32(version_code_text[1]); } catch { throw new SIP_ParseException("Invalid Status-Line Status-Code value !"); } // Reason-Phrase retVal.ReasonPhrase = version_code_text[2]; // Parse SIP-Message retVal.InternalParse(stream); return retVal; } /// <summary> /// Clones this request. /// </summary> /// <returns>Returns new cloned request.</returns> public SIP_Response Copy() { SIP_Response retVal = Parse(ToByteData()); return retVal; } /// <summary> /// Checks if SIP response has all required values as response line,header fields and their values. /// Throws Exception if not valid SIP response. /// </summary> public void Validate() { // Via: + branch prameter // To: // From: // CallID: // CSeq if (Via.GetTopMostValue() == null) { throw new SIP_ParseException("Via: header field is missing !"); } if (Via.GetTopMostValue().Branch == null) { throw new SIP_ParseException("Via: header fields branch parameter is missing !"); } if (To == null) { throw new SIP_ParseException("To: header field is missing !"); } if (From == null) { throw new SIP_ParseException("From: header field is missing !"); } if (CallID == null) { throw new SIP_ParseException("CallID: header field is missing !"); } if (CSeq == null) { throw new SIP_ParseException("CSeq: header field is missing !"); } // TODO: INVITE 2xx must have only 1 contact header with SIP or SIPS. } /// <summary> /// Stores SIP_Response to specified stream. /// </summary> /// <param name="stream">Stream where to store.</param> public void ToStream(Stream stream) { // Status-Line = SIP-Version SP Status-Code SP Reason-Phrase CRLF // Add response-line byte[] responseLine = Encoding.UTF8.GetBytes("SIP/" + SipVersion.ToString("f1").Replace(',', '.') + " " + StatusCode + " " + ReasonPhrase + "\r\n"); stream.Write(responseLine, 0, responseLine.Length); // Add SIP-message InternalToStream(stream); } /// <summary> /// Converts this response to raw srver response data. /// </summary> /// <returns></returns> public byte[] ToByteData() { MemoryStream retVal = new MemoryStream(); ToStream(retVal); return retVal.ToArray(); } /// <summary> /// Returns response as string. /// </summary> /// <returns>Returns response as string.</returns> public override string ToString() { return Encoding.UTF8.GetString(ToByteData()); } #endregion } }<file_sep>/module/ASC.Api/ASC.Api.Mail/MailApi.Autoreply.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using ASC.Api.Attributes; using System; using ASC.Mail.Core.Engine; using ASC.Mail.Data.Contracts; namespace ASC.Api.Mail { public partial class MailApi { /// <summary> /// This method needed for update or create autoreply. /// </summary> /// <param name="mailboxId">Id of updated mailbox.</param> /// <param name="turnOn">New autoreply status.</param> /// <param name="onlyContacts">If true then send autoreply only for contacts.</param> /// <param name="turnOnToDate">If true then field To is active.</param> /// <param name="fromDate">Start date of autoreply sending.</param> /// <param name="toDate">End date of autoreply sending.</param> /// <param name="subject">New autoreply subject.</param> /// <param name="html">New autoreply value.</param> [Create(@"autoreply/update/{mailboxId:[0-9]+}")] public MailAutoreplyData UpdateAutoreply(int mailboxId, bool turnOn, bool onlyContacts, bool turnOnToDate, DateTime fromDate, DateTime toDate, string subject, string html) { var result = MailEngineFactory .AutoreplyEngine .SaveAutoreply(mailboxId, turnOn, onlyContacts, turnOnToDate, fromDate, toDate, subject, html); CacheEngine.Clear(Username); return result; } } } <file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/TCP/TCP_ServerSessionEventArgs.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.TCP { #region usings using System; #endregion /// <summary> /// This class provides data to .... . /// </summary> public class TCP_ServerSessionEventArgs<T> : EventArgs where T : TCP_ServerSession, new() { #region Members private readonly TCP_Server<T> m_pServer; private readonly T m_pSession; #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="server">TCP server.</param> /// <param name="session">TCP server session.</param> internal TCP_ServerSessionEventArgs(TCP_Server<T> server, T session) { m_pServer = server; m_pSession = session; } #endregion #region Properties /// <summary> /// Gets TCP server. /// </summary> public TCP_Server<T> Server { get { return m_pServer; } } /// <summary> /// Gets TCP server session. /// </summary> public T Session { get { return m_pSession; } } #endregion } }<file_sep>/module/ASC.AuditTrail/AuditActionsMapper.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections.Generic; using ASC.AuditTrail.Model; using ASC.MessagingSystem.Contracts; using System.Linq; namespace ASC.AuditTrail.Data { public class AuditActionsMapper { private static readonly Dictionary<MessageAction, MessageMaps> actions = new Dictionary <MessageAction, MessageMaps> { #region login {MessageAction.LoginSuccess, new MessageMaps {ActionText = AuditReportResource.LoginSuccess}}, {MessageAction.LoginSuccessThirdParty, new MessageMaps {ActionText = AuditReportResource.LoginSuccessThirdParty}}, {MessageAction.LoginFail, new MessageMaps {ActionText = AuditReportResource.LoginFail}}, {MessageAction.LoginFailInvalidCombination, new MessageMaps {ActionText = AuditReportResource.LoginFailInvalidCombination}}, {MessageAction.LoginFailThirdPartyNotFound, new MessageMaps {ActionText = AuditReportResource.LoginFailThirdPartyNotFound}}, {MessageAction.LoginFailDisabledProfile, new MessageMaps {ActionText = AuditReportResource.LoginFailDisabledProfile}}, {MessageAction.Logout, new MessageMaps {ActionText = AuditReportResource.Logout}}, #endregion #region projects { MessageAction.ProjectCreated, new MessageMaps { ActionTypeText = AuditReportResource.CreateActionType, ActionText = AuditReportResource.ProjectCreated, Product = AuditReportResource.ProjectsProduct, Module = AuditReportResource.ProjectsModule } }, { MessageAction.ProjectCreatedFromTemplate, new MessageMaps { ActionTypeText = AuditReportResource.CreateActionType, ActionText = AuditReportResource.ProjectCreatedFromTemplate, Product = AuditReportResource.ProjectsProduct, Module = AuditReportResource.ProjectsModule } }, { MessageAction.ProjectUpdated, new MessageMaps { ActionTypeText = AuditReportResource.UpdateActionType, ActionText = AuditReportResource.ProjectUpdated, Product = AuditReportResource.ProjectsProduct, Module = AuditReportResource.ProjectsModule } }, { MessageAction.ProjectUpdatedStatus, new MessageMaps { ActionTypeText = AuditReportResource.UpdateActionType, ActionText = AuditReportResource.ProjectUpdatedStatus, Product = AuditReportResource.ProjectsProduct, Module = AuditReportResource.ProjectsModule } }, { MessageAction.ProjectDeleted, new MessageMaps { ActionTypeText = AuditReportResource.DeleteActionType, ActionText = AuditReportResource.ProjectDeleted, Product = AuditReportResource.ProjectsProduct, Module = AuditReportResource.ProjectsModule } }, { MessageAction.ProjectFollowed, new MessageMaps { ActionTypeText = AuditReportResource.FollowActionType, ActionText = AuditReportResource.ProjectFollowed, Product = AuditReportResource.ProjectsProduct, Module = AuditReportResource.ProjectsModule } }, { MessageAction.ProjectUnfollowed, new MessageMaps { ActionTypeText = AuditReportResource.UnfollowActionType, ActionText = AuditReportResource.ProjectUnfollowed, Product = AuditReportResource.ProjectsProduct, Module = AuditReportResource.ProjectsModule } }, { MessageAction.ProjectExcludedMember, new MessageMaps { ActionTypeText = AuditReportResource.UpdateActionType, ActionText = AuditReportResource.ProjectExcludedMember, Product = AuditReportResource.ProjectsProduct, Module = AuditReportResource.ProjectsModule } }, { MessageAction.ProjectUpdatedMembers, new MessageMaps { ActionTypeText = AuditReportResource.UpdateActionType, ActionText = AuditReportResource.ProjectUpdatedMembers, Product = AuditReportResource.ProjectsProduct, Module = AuditReportResource.ProjectsModule } }, { MessageAction.ProjectUpdatedMemberRights, new MessageMaps { ActionTypeText = AuditReportResource.UpdateAccessActionType, ActionText = AuditReportResource.ProjectUpdatedMemberRights, Product = AuditReportResource.ProjectsProduct, Module = AuditReportResource.ProjectsModule } }, { MessageAction.MilestoneCreated, new MessageMaps { ActionTypeText = AuditReportResource.CreateActionType, ActionText = AuditReportResource.MilestoneCreated, Product = AuditReportResource.ProjectsProduct, Module = AuditReportResource.MilestonesModule } }, { MessageAction.MilestoneUpdated, new MessageMaps { ActionTypeText = AuditReportResource.UpdateActionType, ActionText = AuditReportResource.MilestoneUpdated, Product = AuditReportResource.ProjectsProduct, Module = AuditReportResource.MilestonesModule } }, { MessageAction.MilestoneUpdatedStatus, new MessageMaps { ActionTypeText = AuditReportResource.UpdateActionType, ActionText = AuditReportResource.MilestoneUpdatedStatus, Product = AuditReportResource.ProjectsProduct, Module = AuditReportResource.MilestonesModule } }, { MessageAction.MilestoneDeleted, new MessageMaps { ActionTypeText = AuditReportResource.DeleteActionType, ActionText = AuditReportResource.MilestoneDeleted, Product = AuditReportResource.ProjectsProduct, Module = AuditReportResource.MilestonesModule } }, { MessageAction.TaskCreated, new MessageMaps { ActionTypeText = AuditReportResource.CreateActionType, ActionText = AuditReportResource.TaskCreated, Product = AuditReportResource.ProjectsProduct, Module = AuditReportResource.TasksModule } }, { MessageAction.TaskCreatedFromDiscussion, new MessageMaps { ActionTypeText = AuditReportResource.CreateActionType, ActionText = AuditReportResource.TaskCreatedFromDiscussion, Product = AuditReportResource.ProjectsProduct, Module = AuditReportResource.TasksModule } }, { MessageAction.TaskUpdated, new MessageMaps { ActionTypeText = AuditReportResource.UpdateActionType, ActionText = AuditReportResource.TaskUpdated, Product = AuditReportResource.ProjectsProduct, Module = AuditReportResource.TasksModule } }, { MessageAction.TaskUpdatedStatus, new MessageMaps { ActionTypeText = AuditReportResource.UpdateActionType, ActionText = AuditReportResource.TaskUpdatedStatus, Product = AuditReportResource.ProjectsProduct, Module = AuditReportResource.TasksModule } }, { MessageAction.TaskMovedToMilestone, new MessageMaps { ActionTypeText = AuditReportResource.UpdateActionType, ActionText = AuditReportResource.TaskMovedToMilestone, Product = AuditReportResource.ProjectsProduct, Module = AuditReportResource.TasksModule } }, { MessageAction.TaskDeleted, new MessageMaps { ActionTypeText = AuditReportResource.DeleteActionType, ActionText = AuditReportResource.TaskDeleted, Product = AuditReportResource.ProjectsProduct, Module = AuditReportResource.TasksModule } }, { MessageAction.TaskUpdatedFollowing, new MessageMaps { ActionTypeText = AuditReportResource.FollowActionType, ActionText = AuditReportResource.TaskUpdatedFollowing, Product = AuditReportResource.ProjectsProduct, Module = AuditReportResource.TasksModule } }, { MessageAction.TaskCommentCreated, new MessageMaps { ActionTypeText = AuditReportResource.CreateActionType, ActionText = AuditReportResource.TaskCommentCreated, Product = AuditReportResource.ProjectsProduct, Module = AuditReportResource.TasksModule } }, { MessageAction.TaskCommentUpdated, new MessageMaps { ActionTypeText = AuditReportResource.UpdateActionType, ActionText = AuditReportResource.TaskCommentUpdated, Product = AuditReportResource.ProjectsProduct, Module = AuditReportResource.TasksModule } }, { MessageAction.TaskCommentDeleted, new MessageMaps { ActionTypeText = AuditReportResource.DeleteActionType, ActionText = AuditReportResource.TaskCommentDeleted, Product = AuditReportResource.ProjectsProduct, Module = AuditReportResource.TasksModule } }, { MessageAction.TasksLinked, new MessageMaps { ActionTypeText = AuditReportResource.LinkActionType, ActionText = AuditReportResource.TasksLinked, Product = AuditReportResource.ProjectsProduct, Module = AuditReportResource.TasksModule } }, { MessageAction.TasksUnlinked, new MessageMaps { ActionTypeText = AuditReportResource.UnlinkActionType, ActionText = AuditReportResource.TasksUnlinked, Product = AuditReportResource.ProjectsProduct, Module = AuditReportResource.TasksModule } }, { MessageAction.TaskAttachedFiles, new MessageMaps { ActionTypeText = AuditReportResource.AttachActionType, ActionText = AuditReportResource.TaskAttachedFiles, Product = AuditReportResource.ProjectsProduct, Module = AuditReportResource.TasksModule } }, { MessageAction.TaskDetachedFile, new MessageMaps { ActionTypeText = AuditReportResource.DetachActionType, ActionText = AuditReportResource.TaskDetachedFile, Product = AuditReportResource.ProjectsProduct, Module = AuditReportResource.TasksModule } }, { MessageAction.TaskUnlinkedMilestone, new MessageMaps { ActionTypeText = AuditReportResource.UpdateActionType, ActionText = AuditReportResource.TaskUnlinkedMilestone, Product = AuditReportResource.ProjectsProduct, Module = AuditReportResource.TasksModule } }, { MessageAction.SubtaskCreated, new MessageMaps { ActionTypeText = AuditReportResource.CreateActionType, ActionText = AuditReportResource.SubtaskCreated, Product = AuditReportResource.ProjectsProduct, Module = AuditReportResource.TasksModule } }, { MessageAction.SubtaskUpdated, new MessageMaps { ActionTypeText = AuditReportResource.UpdateActionType, ActionText = AuditReportResource.SubtaskUpdated, Product = AuditReportResource.ProjectsProduct, Module = AuditReportResource.TasksModule } }, { MessageAction.SubtaskUpdatedStatus, new MessageMaps { ActionTypeText = AuditReportResource.UpdateActionType, ActionText = AuditReportResource.SubtaskUpdatedStatus, Product = AuditReportResource.ProjectsProduct, Module = AuditReportResource.TasksModule } }, { MessageAction.SubtaskDeleted, new MessageMaps { ActionTypeText = AuditReportResource.DeleteActionType, ActionText = AuditReportResource.SubtaskDeleted, Product = AuditReportResource.ProjectsProduct, Module = AuditReportResource.TasksModule } }, { MessageAction.TaskTimeCreated, new MessageMaps { ActionTypeText = AuditReportResource.CreateActionType, ActionText = AuditReportResource.TaskTimeCreated, Product = AuditReportResource.ProjectsProduct, Module = AuditReportResource.TimeTrackingModule } }, { MessageAction.TaskTimeUpdated, new MessageMaps { ActionTypeText = AuditReportResource.UpdateActionType, ActionText = AuditReportResource.TaskTimeUpdated, Product = AuditReportResource.ProjectsProduct, Module = AuditReportResource.TimeTrackingModule } }, { MessageAction.TaskTimesUpdatedStatus, new MessageMaps { ActionTypeText = AuditReportResource.UpdateActionType, ActionText = AuditReportResource.TaskTimesUpdatedStatus, Product = AuditReportResource.ProjectsProduct, Module = AuditReportResource.TimeTrackingModule } }, { MessageAction.TaskTimesDeleted, new MessageMaps { ActionTypeText = AuditReportResource.DeleteActionType, ActionText = AuditReportResource.TaskTimesDeleted, Product = AuditReportResource.ProjectsProduct, Module = AuditReportResource.TimeTrackingModule } }, { MessageAction.DiscussionCreated, new MessageMaps { ActionTypeText = AuditReportResource.CreateActionType, ActionText = AuditReportResource.DiscussionCreated, Product = AuditReportResource.ProjectsProduct, Module = AuditReportResource.DiscussionsModule } }, { MessageAction.DiscussionUpdated, new MessageMaps { ActionTypeText = AuditReportResource.UpdateActionType, ActionText = AuditReportResource.DiscussionUpdated, Product = AuditReportResource.ProjectsProduct, Module = AuditReportResource.DiscussionsModule } }, { MessageAction.DiscussionDeleted, new MessageMaps { ActionTypeText = AuditReportResource.DeleteActionType, ActionText = AuditReportResource.DiscussionDeleted, Product = AuditReportResource.ProjectsProduct, Module = AuditReportResource.DiscussionsModule } }, { MessageAction.DiscussionUpdatedFollowing, new MessageMaps { ActionTypeText = AuditReportResource.FollowActionType, ActionText = AuditReportResource.DiscussionUpdatedFollowing, Product = AuditReportResource.ProjectsProduct, Module = AuditReportResource.DiscussionsModule } }, { MessageAction.DiscussionCommentCreated, new MessageMaps { ActionTypeText = AuditReportResource.CreateActionType, ActionText = AuditReportResource.DiscussionCommentCreated, Product = AuditReportResource.ProjectsProduct, Module = AuditReportResource.DiscussionsModule } }, { MessageAction.DiscussionCommentUpdated, new MessageMaps { ActionTypeText = AuditReportResource.UpdateActionType, ActionText = AuditReportResource.DiscussionCommentUpdated, Product = AuditReportResource.ProjectsProduct, Module = AuditReportResource.DiscussionsModule } }, { MessageAction.DiscussionCommentDeleted, new MessageMaps { ActionTypeText = AuditReportResource.DeleteActionType, ActionText = AuditReportResource.DiscussionCommentDeleted, Product = AuditReportResource.ProjectsProduct, Module = AuditReportResource.DiscussionsModule } }, { MessageAction.DiscussionAttachedFiles, new MessageMaps { ActionTypeText = AuditReportResource.AttachActionType, ActionText = AuditReportResource.DiscussionAttachedFiles, Product = AuditReportResource.ProjectsProduct, Module = AuditReportResource.DiscussionsModule } }, { MessageAction.DiscussionDetachedFile, new MessageMaps { ActionTypeText = AuditReportResource.DetachActionType, ActionText = AuditReportResource.DiscussionDetachedFile, Product = AuditReportResource.ProjectsProduct, Module = AuditReportResource.DiscussionsModule } }, { MessageAction.ProjectTemplateCreated, new MessageMaps { ActionTypeText = AuditReportResource.CreateActionType, ActionText = AuditReportResource.ProjectTemplateCreated, Product = AuditReportResource.ProjectsProduct, Module = AuditReportResource.TemplatesModule } }, { MessageAction.ProjectTemplateUpdated, new MessageMaps { ActionTypeText = AuditReportResource.UpdateActionType, ActionText = AuditReportResource.ProjectTemplateUpdated, Product = AuditReportResource.ProjectsProduct, Module = AuditReportResource.TemplatesModule } }, { MessageAction.ProjectTemplateDeleted, new MessageMaps { ActionTypeText = AuditReportResource.DeleteActionType, ActionText = AuditReportResource.ProjectTemplateDeleted, Product = AuditReportResource.ProjectsProduct, Module = AuditReportResource.TemplatesModule } }, { MessageAction.ReportTemplateCreated, new MessageMaps { ActionTypeText = AuditReportResource.CreateActionType, ActionText = AuditReportResource.ReportTemplateCreated, Product = AuditReportResource.ProjectsProduct, Module = AuditReportResource.ReportsModule } }, { MessageAction.ReportTemplateUpdated, new MessageMaps { ActionTypeText = AuditReportResource.UpdateActionType, ActionText = AuditReportResource.ReportTemplateUpdated, Product = AuditReportResource.ProjectsProduct, Module = AuditReportResource.ReportsModule } }, { MessageAction.ReportTemplateDeleted, new MessageMaps { ActionTypeText = AuditReportResource.DeleteActionType, ActionText = AuditReportResource.ReportTemplateDeleted, Product = AuditReportResource.ProjectsProduct, Module = AuditReportResource.ReportsModule } }, { MessageAction.ProjectLinkedCompany, new MessageMaps { ActionTypeText = AuditReportResource.LinkActionType, ActionText = AuditReportResource.ProjectLinkedCompany, Product = AuditReportResource.ProjectsProduct, Module = AuditReportResource.ProjectsModule } }, { MessageAction.ProjectUnlinkedCompany, new MessageMaps { ActionTypeText = AuditReportResource.UnlinkActionType, ActionText = AuditReportResource.ProjectUnlinkedCompany, Product = AuditReportResource.ProjectsProduct, Module = AuditReportResource.ProjectsModule } }, { MessageAction.ProjectLinkedPerson, new MessageMaps { ActionTypeText = AuditReportResource.LinkActionType, ActionText = AuditReportResource.ProjectLinkedPerson, Product = AuditReportResource.ProjectsProduct, Module = AuditReportResource.ProjectsModule } }, { MessageAction.ProjectUnlinkedPerson, new MessageMaps { ActionTypeText = AuditReportResource.UnlinkActionType, ActionText = AuditReportResource.ProjectUnlinkedPerson, Product = AuditReportResource.ProjectsProduct, Module = AuditReportResource.ProjectsModule } }, { MessageAction.ProjectLinkedContacts, new MessageMaps { ActionTypeText = AuditReportResource.LinkActionType, ActionText = AuditReportResource.ProjectLinkedContacts, Product = AuditReportResource.ProjectsProduct, Module = AuditReportResource.ProjectsModule } }, { MessageAction.ProjectsImportedFromBasecamp, new MessageMaps { ActionTypeText = AuditReportResource.ImportActionType, ActionText = AuditReportResource.ProjectsImportedFromBasecamp, Product = AuditReportResource.ProjectsProduct, Module = AuditReportResource.ProjectsModule } }, #endregion #region crm #region companies { MessageAction.CompanyCreated, new MessageMaps { ActionTypeText = AuditReportResource.CreateActionType, ActionText = AuditReportResource.CompanyCreated, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.CompaniesModule } }, { MessageAction.CompanyUpdated, new MessageMaps { ActionTypeText = AuditReportResource.UpdateActionType, ActionText = AuditReportResource.CompanyUpdated, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.CompaniesModule } }, { MessageAction.CompanyUpdatedStatus, new MessageMaps { ActionTypeText = AuditReportResource.UpdateActionType, ActionText = AuditReportResource.CompanyUpdatedStatus, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.CompaniesModule } }, { MessageAction.CompanyUpdatedPersonsStatus, new MessageMaps { ActionTypeText = AuditReportResource.UpdateActionType, ActionText = AuditReportResource.CompanyUpdatedPersonsStatus, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.CompaniesModule } }, { MessageAction.CompanyUpdatedPrincipalInfo, new MessageMaps { ActionTypeText = AuditReportResource.UpdateActionType, ActionText = AuditReportResource.CompanyUpdatedPrincipalInfo, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.CompaniesModule } }, { MessageAction.CompanyUpdatedPhoto, new MessageMaps { ActionTypeText = AuditReportResource.UpdateActionType, ActionText = AuditReportResource.CompanyUpdatedPhoto, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.CompaniesModule } }, { MessageAction.CompanyLinkedProject, new MessageMaps { ActionTypeText = AuditReportResource.LinkActionType, ActionText = AuditReportResource.CompanyLinkedProject, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.CompaniesModule } }, { MessageAction.CompanyUnlinkedProject, new MessageMaps { ActionTypeText = AuditReportResource.UnlinkActionType, ActionText = AuditReportResource.CompanyUnlinkedProject, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.CompaniesModule } }, { MessageAction.CompaniesMerged, new MessageMaps { ActionTypeText = AuditReportResource.UpdateActionType, ActionText = AuditReportResource.CompaniesMerged, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.CompaniesModule } }, { MessageAction.CompanyCreatedTag, new MessageMaps { ActionTypeText = AuditReportResource.CreateActionType, ActionText = AuditReportResource.CompanyCreatedTag, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.CompaniesModule } }, { MessageAction.CompanyCreatedPersonsTag, new MessageMaps { ActionTypeText = AuditReportResource.CreateActionType, ActionText = AuditReportResource.CompanyCreatedPersonsTag, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.CompaniesModule } }, { MessageAction.CompanyDeletedTag, new MessageMaps { ActionTypeText = AuditReportResource.DeleteActionType, ActionText = AuditReportResource.CompanyDeletedTag, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.CompaniesModule } }, { MessageAction.CompanyCreatedHistory, new MessageMaps { ActionTypeText = AuditReportResource.CreateActionType, ActionText = AuditReportResource.CompanyCreatedHistory, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.CompaniesModule } }, { MessageAction.CompanyDeletedHistory, new MessageMaps { ActionTypeText = AuditReportResource.DeleteActionType, ActionText = AuditReportResource.CompanyDeletedHistory, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.CompaniesModule } }, { MessageAction.CompanyLinkedPerson, new MessageMaps { ActionTypeText = AuditReportResource.LinkActionType, ActionText = AuditReportResource.CompanyLinkedPerson, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.CompaniesModule } }, { MessageAction.CompanyUnlinkedPerson, new MessageMaps { ActionTypeText = AuditReportResource.UnlinkActionType, ActionText = AuditReportResource.CompanyUnlinkedPerson, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.CompaniesModule } }, { MessageAction.CompanyUploadedFiles, new MessageMaps { ActionTypeText = AuditReportResource.AttachActionType, ActionText = AuditReportResource.CompanyUploadedFiles, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.CompaniesModule } }, { MessageAction.CompanyAttachedFiles, new MessageMaps { ActionTypeText = AuditReportResource.AttachActionType, ActionText = AuditReportResource.CompanyAttachedFiles, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.CompaniesModule } }, { MessageAction.CompanyDeleted, new MessageMaps { ActionTypeText = AuditReportResource.DeleteActionType, ActionText = AuditReportResource.CompanyDeleted, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.CompaniesModule } }, #endregion #region persons { MessageAction.PersonCreated, new MessageMaps { ActionTypeText = AuditReportResource.CreateActionType, ActionText = AuditReportResource.PersonCreated, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.PersonsModule } }, { MessageAction.PersonsCreated, new MessageMaps { ActionTypeText = AuditReportResource.CreateActionType, ActionText = AuditReportResource.PersonsCreated, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.PersonsModule } }, { MessageAction.PersonUpdated, new MessageMaps { ActionTypeText = AuditReportResource.UpdateActionType, ActionText = AuditReportResource.PersonUpdated, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.PersonsModule } }, { MessageAction.PersonUpdatedStatus, new MessageMaps { ActionTypeText = AuditReportResource.UpdateActionType, ActionText = AuditReportResource.PersonUpdatedStatus, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.PersonsModule } }, { MessageAction.PersonUpdatedCompanyStatus, new MessageMaps { ActionTypeText = AuditReportResource.UpdateActionType, ActionText = AuditReportResource.PersonUpdatedCompanyStatus, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.PersonsModule } }, { MessageAction.PersonUpdatedPrincipalInfo, new MessageMaps { ActionTypeText = AuditReportResource.UpdateActionType, ActionText = AuditReportResource.PersonUpdatedPrincipalInfo, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.PersonsModule } }, { MessageAction.PersonUpdatedPhoto, new MessageMaps { ActionTypeText = AuditReportResource.UpdateActionType, ActionText = AuditReportResource.PersonUpdatedPhoto, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.PersonsModule } }, { MessageAction.PersonLinkedProject, new MessageMaps { ActionTypeText = AuditReportResource.LinkActionType, ActionText = AuditReportResource.PersonLinkedProject, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.PersonsModule } }, { MessageAction.PersonUnlinkedProject, new MessageMaps { ActionTypeText = AuditReportResource.UnlinkActionType, ActionText = AuditReportResource.PersonUnlinkedProject, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.PersonsModule } }, { MessageAction.PersonsMerged, new MessageMaps { ActionTypeText = AuditReportResource.UpdateActionType, ActionText = AuditReportResource.PersonsMerged, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.PersonsModule } }, { MessageAction.PersonCreatedTag, new MessageMaps { ActionTypeText = AuditReportResource.CreateActionType, ActionText = AuditReportResource.PersonCreatedTag, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.PersonsModule } }, { MessageAction.PersonCreatedCompanyTag, new MessageMaps { ActionTypeText = AuditReportResource.CreateActionType, ActionText = AuditReportResource.PersonCreatedCompanyTag, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.PersonsModule } }, { MessageAction.PersonDeletedTag, new MessageMaps { ActionTypeText = AuditReportResource.DeleteActionType, ActionText = AuditReportResource.PersonDeletedTag, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.PersonsModule } }, { MessageAction.PersonCreatedHistory, new MessageMaps { ActionTypeText = AuditReportResource.CreateActionType, ActionText = AuditReportResource.PersonCreatedHistory, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.PersonsModule } }, { MessageAction.PersonDeletedHistory, new MessageMaps { ActionTypeText = AuditReportResource.DeleteActionType, ActionText = AuditReportResource.PersonDeletedHistory, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.PersonsModule } }, { MessageAction.PersonUploadedFiles, new MessageMaps { ActionTypeText = AuditReportResource.AttachActionType, ActionText = AuditReportResource.PersonUploadedFiles, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.PersonsModule } }, { MessageAction.PersonAttachedFiles, new MessageMaps { ActionTypeText = AuditReportResource.AttachActionType, ActionText = AuditReportResource.PersonAttachedFiles, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.PersonsModule } }, { MessageAction.PersonDeleted, new MessageMaps { ActionTypeText = AuditReportResource.DeleteActionType, ActionText = AuditReportResource.PersonDeleted, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.PersonsModule } }, #endregion #region contacts { MessageAction.ContactLinkedProject, new MessageMaps { ActionTypeText = AuditReportResource.LinkActionType, ActionText = AuditReportResource.ContactLinkedProject, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.ContactsModule } }, { MessageAction.ContactUnlinkedProject, new MessageMaps { ActionTypeText = AuditReportResource.UnlinkActionType, ActionText = AuditReportResource.ContactUnlinkedProject, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.ContactsModule } }, { MessageAction.ContactsDeleted, new MessageMaps { ActionTypeText = AuditReportResource.DeleteActionType, ActionText = AuditReportResource.ContactsDeleted, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.ContactsModule } }, #endregion #region tasks { MessageAction.CrmTaskCreated, new MessageMaps { ActionTypeText = AuditReportResource.CreateActionType, ActionText = AuditReportResource.CrmTaskCreated, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.CrmTasksModule } }, { MessageAction.CrmTaskUpdated, new MessageMaps { ActionTypeText = AuditReportResource.UpdateActionType, ActionText = AuditReportResource.CrmTaskUpdated, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.CrmTasksModule } }, { MessageAction.CrmTaskOpened, new MessageMaps { ActionTypeText = AuditReportResource.UpdateActionType, ActionText = AuditReportResource.CrmTaskOpened, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.CrmTasksModule } }, { MessageAction.CrmTaskClosed, new MessageMaps { ActionTypeText = AuditReportResource.UpdateActionType, ActionText = AuditReportResource.CrmTaskClosed, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.CrmTasksModule } }, { MessageAction.CrmTaskDeleted, new MessageMaps { ActionTypeText = AuditReportResource.DeleteActionType, ActionText = AuditReportResource.CrmTaskDeleted, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.CrmTasksModule } }, { MessageAction.ContactsCreatedCrmTasks, new MessageMaps { ActionTypeText = AuditReportResource.CreateActionType, ActionText = AuditReportResource.ContactsCreatedCrmTasks, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.CrmTasksModule } }, #endregion #region opportunities { MessageAction.OpportunityCreated, new MessageMaps { ActionTypeText = AuditReportResource.CreateActionType, ActionText = AuditReportResource.OpportunityCreated, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.OpportunitiesModule } }, { MessageAction.OpportunityUpdated, new MessageMaps { ActionTypeText = AuditReportResource.UpdateActionType, ActionText = AuditReportResource.OpportunityUpdated, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.OpportunitiesModule } }, { MessageAction.OpportunityUpdatedStage, new MessageMaps { ActionTypeText = AuditReportResource.UpdateActionType, ActionText = AuditReportResource.OpportunityUpdatedStage, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.OpportunitiesModule } }, { MessageAction.OpportunityCreatedTag, new MessageMaps { ActionTypeText = AuditReportResource.CreateActionType, ActionText = AuditReportResource.OpportunityCreatedTag, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.OpportunitiesModule } }, { MessageAction.OpportunityDeletedTag, new MessageMaps { ActionTypeText = AuditReportResource.DeleteActionType, ActionText = AuditReportResource.OpportunityDeletedTag, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.OpportunitiesModule } }, { MessageAction.OpportunityCreatedHistory, new MessageMaps { ActionTypeText = AuditReportResource.CreateActionType, ActionText = AuditReportResource.OpportunityCreatedHistory, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.OpportunitiesModule } }, { MessageAction.OpportunityDeletedHistory, new MessageMaps { ActionTypeText = AuditReportResource.DeleteActionType, ActionText = AuditReportResource.OpportunityDeletedHistory, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.OpportunitiesModule } }, { MessageAction.OpportunityLinkedCompany, new MessageMaps { ActionTypeText = AuditReportResource.LinkActionType, ActionText = AuditReportResource.OpportunityLinkedCompany, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.OpportunitiesModule } }, { MessageAction.OpportunityUnlinkedCompany, new MessageMaps { ActionTypeText = AuditReportResource.UnlinkActionType, ActionText = AuditReportResource.OpportunityUnlinkedCompany, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.OpportunitiesModule } }, { MessageAction.OpportunityLinkedPerson, new MessageMaps { ActionTypeText = AuditReportResource.LinkActionType, ActionText = AuditReportResource.OpportunityLinkedPerson, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.OpportunitiesModule } }, { MessageAction.OpportunityUnlinkedPerson, new MessageMaps { ActionTypeText = AuditReportResource.UnlinkActionType, ActionText = AuditReportResource.OpportunityUnlinkedPerson, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.OpportunitiesModule } }, { MessageAction.OpportunityUploadedFiles, new MessageMaps { ActionTypeText = AuditReportResource.AttachActionType, ActionText = AuditReportResource.OpportunityUploadedFiles, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.OpportunitiesModule } }, { MessageAction.OpportunityAttachedFiles, new MessageMaps { ActionTypeText = AuditReportResource.AttachActionType, ActionText = AuditReportResource.OpportunityAttachedFiles, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.OpportunitiesModule } }, { MessageAction.OpportunityOpenedAccess, new MessageMaps { ActionTypeText = AuditReportResource.UpdateAccessActionType, ActionText = AuditReportResource.OpportunityOpenedAccess, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.OpportunitiesModule } }, { MessageAction.OpportunityRestrictedAccess, new MessageMaps { ActionTypeText = AuditReportResource.UpdateAccessActionType, ActionText = AuditReportResource.OpportunityRestrictedAccess, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.OpportunitiesModule } }, { MessageAction.OpportunityDeleted, new MessageMaps { ActionTypeText = AuditReportResource.DeleteActionType, ActionText = AuditReportResource.OpportunityDeleted, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.OpportunitiesModule } }, { MessageAction.OpportunitiesDeleted, new MessageMaps { ActionTypeText = AuditReportResource.DeleteActionType, ActionText = AuditReportResource.OpportunitiesDeleted, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.OpportunitiesModule } }, #endregion #region cases { MessageAction.CaseCreated, new MessageMaps { ActionTypeText = AuditReportResource.CreateActionType, ActionText = AuditReportResource.CaseCreated, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.CasesModule } }, { MessageAction.CaseUpdated, new MessageMaps { ActionTypeText = AuditReportResource.UpdateActionType, ActionText = AuditReportResource.CaseUpdated, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.CasesModule } }, { MessageAction.CaseOpened, new MessageMaps { ActionTypeText = AuditReportResource.UpdateActionType, ActionText = AuditReportResource.CaseOpened, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.CasesModule } }, { MessageAction.CaseClosed, new MessageMaps { ActionTypeText = AuditReportResource.UpdateActionType, ActionText = AuditReportResource.CaseClosed, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.CasesModule } }, { MessageAction.CaseCreatedTag, new MessageMaps { ActionTypeText = AuditReportResource.CreateActionType, ActionText = AuditReportResource.CaseCreatedTag, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.CasesModule } }, { MessageAction.CaseDeletedTag, new MessageMaps { ActionTypeText = AuditReportResource.DeleteActionType, ActionText = AuditReportResource.CaseDeletedTag, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.CasesModule } }, { MessageAction.CaseCreatedHistory, new MessageMaps { ActionTypeText = AuditReportResource.CreateActionType, ActionText = AuditReportResource.CaseCreatedHistory, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.CasesModule } }, { MessageAction.CaseDeletedHistory, new MessageMaps { ActionTypeText = AuditReportResource.DeleteActionType, ActionText = AuditReportResource.CaseDeletedHistory, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.CasesModule } }, { MessageAction.CaseLinkedCompany, new MessageMaps { ActionTypeText = AuditReportResource.LinkActionType, ActionText = AuditReportResource.CaseLinkedCompany, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.CasesModule } }, { MessageAction.CaseUnlinkedCompany, new MessageMaps { ActionTypeText = AuditReportResource.UnlinkActionType, ActionText = AuditReportResource.CaseUnlinkedCompany, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.CasesModule } }, { MessageAction.CaseLinkedPerson, new MessageMaps { ActionTypeText = AuditReportResource.LinkActionType, ActionText = AuditReportResource.CaseLinkedPerson, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.CasesModule } }, { MessageAction.CaseUnlinkedPerson, new MessageMaps { ActionTypeText = AuditReportResource.UnlinkActionType, ActionText = AuditReportResource.CaseUnlinkedPerson, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.CasesModule } }, { MessageAction.CaseUploadedFiles, new MessageMaps { ActionTypeText = AuditReportResource.AttachActionType, ActionText = AuditReportResource.CaseUploadedFiles, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.CasesModule } }, { MessageAction.CaseAttachedFiles, new MessageMaps { ActionTypeText = AuditReportResource.AttachActionType, ActionText = AuditReportResource.CaseAttachedFiles, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.CasesModule } }, { MessageAction.CaseOpenedAccess, new MessageMaps { ActionTypeText = AuditReportResource.UpdateAccessActionType, ActionText = AuditReportResource.CaseOpenedAccess, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.CasesModule } }, { MessageAction.CaseRestrictedAccess, new MessageMaps { ActionTypeText = AuditReportResource.UpdateAccessActionType, ActionText = AuditReportResource.CaseRestrictedAccess, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.CasesModule } }, { MessageAction.CaseDeleted, new MessageMaps { ActionTypeText = AuditReportResource.DeleteActionType, ActionText = AuditReportResource.CaseDeleted, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.CasesModule } }, { MessageAction.CasesDeleted, new MessageMaps { ActionTypeText = AuditReportResource.DeleteActionType, ActionText = AuditReportResource.CasesDeleted, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.CasesModule } }, #endregion #region import { MessageAction.ContactsImportedFromCSV, new MessageMaps { ActionTypeText = AuditReportResource.ImportActionType, ActionText = AuditReportResource.ContactsImportedFromCSV, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.ContactsModule } }, { MessageAction.CrmTasksImportedFromCSV, new MessageMaps { ActionTypeText = AuditReportResource.ImportActionType, ActionText = AuditReportResource.CrmTasksImportedFromCSV, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.CrmTasksModule } }, { MessageAction.OpportunitiesImportedFromCSV, new MessageMaps { ActionTypeText = AuditReportResource.ImportActionType, ActionText = AuditReportResource.OpportunitiesImportedFromCSV, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.OpportunitiesModule } }, { MessageAction.CasesImportedFromCSV, new MessageMaps { ActionTypeText = AuditReportResource.ImportActionType, ActionText = AuditReportResource.CasesImportedFromCSV, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.CasesModule } }, #endregion #region export { MessageAction.ContactsExportedToCsv, new MessageMaps { ActionTypeText = AuditReportResource.ExportActionType, ActionText = AuditReportResource.ContactsExportedToCsv, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.ContactsModule } }, { MessageAction.CrmTasksExportedToCsv, new MessageMaps { ActionTypeText = AuditReportResource.ExportActionType, ActionText = AuditReportResource.CrmTasksExportedToCsv, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.CrmTasksModule } }, { MessageAction.OpportunitiesExportedToCsv, new MessageMaps { ActionTypeText = AuditReportResource.ExportActionType, ActionText = AuditReportResource.OpportunitiesExportedToCsv, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.OpportunitiesModule } }, { MessageAction.CasesExportedToCsv, new MessageMaps { ActionTypeText = AuditReportResource.ExportActionType, ActionText = AuditReportResource.CasesExportedToCsv, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.CasesModule } }, #endregion #region common settings { MessageAction.CrmSmtpSettingsUpdated, new MessageMaps { ActionTypeText = AuditReportResource.UpdateActionType, ActionText = AuditReportResource.CrmSmtpSettingsUpdated, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.CommonCrmSettingsModule } }, { MessageAction.CrmTestMailSent, new MessageMaps { ActionTypeText = AuditReportResource.SendActionType, ActionText = AuditReportResource.CrmTestMailSent, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.CommonCrmSettingsModule } }, { MessageAction.CrmDefaultCurrencyUpdated, new MessageMaps { ActionTypeText = AuditReportResource.UpdateActionType, ActionText = AuditReportResource.CrmDefaultCurrencyUpdated, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.CommonCrmSettingsModule } }, { MessageAction.CrmAllDataExported, new MessageMaps { ActionTypeText = AuditReportResource.ExportActionType, ActionText = AuditReportResource.CrmAllDataExported, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.CommonCrmSettingsModule } }, { MessageAction.ContactsTemperatureLevelSettingsUpdated, new MessageMaps { ActionTypeText = AuditReportResource.UpdateActionType, ActionText = AuditReportResource.ContactsTemperatureLevelSettingsUpdated, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.CommonCrmSettingsModule } }, { MessageAction.ContactsTagSettingsUpdated, new MessageMaps { ActionTypeText = AuditReportResource.UpdateActionType, ActionText = AuditReportResource.ContactsTagSettingsUpdated, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.CommonCrmSettingsModule } }, #endregion #region contact settings { MessageAction.ContactsTemperatureLevelCreated, new MessageMaps { ActionTypeText = AuditReportResource.CreateActionType, ActionText = AuditReportResource.ContactsTemperatureLevelCreated, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.ContactsSettingsModule } }, { MessageAction.ContactsTemperatureLevelUpdated, new MessageMaps { ActionTypeText = AuditReportResource.UpdateActionType, ActionText = AuditReportResource.ContactsTemperatureLevelUpdated, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.ContactsSettingsModule } }, { MessageAction.ContactsTemperatureLevelUpdatedColor, new MessageMaps { ActionTypeText = AuditReportResource.UpdateActionType, ActionText = AuditReportResource.ContactsTemperatureLevelUpdatedColor, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.ContactsSettingsModule } }, { MessageAction.ContactsTemperatureLevelsUpdatedOrder, new MessageMaps { ActionTypeText = AuditReportResource.UpdateActionType, ActionText = AuditReportResource.ContactsTemperatureLevelsUpdatedOrder, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.ContactsSettingsModule } }, { MessageAction.ContactsTemperatureLevelDeleted, new MessageMaps { ActionTypeText = AuditReportResource.DeleteActionType, ActionText = AuditReportResource.ContactsTemperatureLevelDeleted, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.ContactsSettingsModule } }, { MessageAction.ContactTypeCreated, new MessageMaps { ActionTypeText = AuditReportResource.CreateActionType, ActionText = AuditReportResource.ContactTypeCreated, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.ContactTypesModule } }, { MessageAction.ContactTypeUpdated, new MessageMaps { ActionTypeText = AuditReportResource.UpdateActionType, ActionText = AuditReportResource.ContactTypeUpdated, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.ContactTypesModule } }, { MessageAction.ContactTypesUpdatedOrder, new MessageMaps { ActionTypeText = AuditReportResource.UpdateActionType, ActionText = AuditReportResource.ContactTypesUpdatedOrder, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.ContactTypesModule } }, { MessageAction.ContactTypeDeleted, new MessageMaps { ActionTypeText = AuditReportResource.DeleteActionType, ActionText = AuditReportResource.ContactTypeDeleted, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.ContactTypesModule } }, #endregion #region user fields settings { MessageAction.ContactsCreatedUserField, new MessageMaps { ActionTypeText = AuditReportResource.CreateActionType, ActionText = AuditReportResource.ContactsCreatedUserField, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.OtherCrmSettingsModule } }, { MessageAction.ContactsUpdatedUserField, new MessageMaps { ActionTypeText = AuditReportResource.UpdateActionType, ActionText = AuditReportResource.ContactsUpdatedUserField, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.OtherCrmSettingsModule } }, { MessageAction.ContactsUpdatedUserFieldsOrder, new MessageMaps { ActionTypeText = AuditReportResource.UpdateActionType, ActionText = AuditReportResource.ContactsUpdatedUserFieldsOrder, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.OtherCrmSettingsModule } }, { MessageAction.ContactsDeletedUserField, new MessageMaps { ActionTypeText = AuditReportResource.DeleteActionType, ActionText = AuditReportResource.ContactsDeletedUserField, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.OtherCrmSettingsModule } }, { MessageAction.PersonsCreatedUserField, new MessageMaps { ActionTypeText = AuditReportResource.CreateActionType, ActionText = AuditReportResource.PersonsCreatedUserField, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.OtherCrmSettingsModule } }, { MessageAction.PersonsUpdatedUserField, new MessageMaps { ActionTypeText = AuditReportResource.UpdateActionType, ActionText = AuditReportResource.PersonsUpdatedUserField, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.OtherCrmSettingsModule } }, { MessageAction.PersonsUpdatedUserFieldsOrder, new MessageMaps { ActionTypeText = AuditReportResource.UpdateActionType, ActionText = AuditReportResource.PersonsUpdatedUserFieldsOrder, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.OtherCrmSettingsModule } }, { MessageAction.PersonsDeletedUserField, new MessageMaps { ActionTypeText = AuditReportResource.DeleteActionType, ActionText = AuditReportResource.PersonsDeletedUserField, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.OtherCrmSettingsModule } }, { MessageAction.CompaniesCreatedUserField, new MessageMaps { ActionTypeText = AuditReportResource.CreateActionType, ActionText = AuditReportResource.CompaniesCreatedUserField, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.OtherCrmSettingsModule } }, { MessageAction.CompaniesUpdatedUserField, new MessageMaps { ActionTypeText = AuditReportResource.UpdateActionType, ActionText = AuditReportResource.CompaniesUpdatedUserField, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.OtherCrmSettingsModule } }, { MessageAction.CompaniesUpdatedUserFieldsOrder, new MessageMaps { ActionTypeText = AuditReportResource.UpdateActionType, ActionText = AuditReportResource.CompaniesUpdatedUserFieldsOrder, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.OtherCrmSettingsModule } }, { MessageAction.CompaniesDeletedUserField, new MessageMaps { ActionTypeText = AuditReportResource.DeleteActionType, ActionText = AuditReportResource.CompaniesDeletedUserField, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.OtherCrmSettingsModule } }, { MessageAction.OpportunitiesCreatedUserField, new MessageMaps { ActionTypeText = AuditReportResource.CreateActionType, ActionText = AuditReportResource.OpportunitiesCreatedUserField, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.OtherCrmSettingsModule } }, { MessageAction.OpportunitiesUpdatedUserField, new MessageMaps { ActionTypeText = AuditReportResource.UpdateActionType, ActionText = AuditReportResource.OpportunitiesUpdatedUserField, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.OtherCrmSettingsModule } }, { MessageAction.OpportunitiesUpdatedUserFieldsOrder, new MessageMaps { ActionTypeText = AuditReportResource.UpdateActionType, ActionText = AuditReportResource.OpportunitiesUpdatedUserFieldsOrder, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.OtherCrmSettingsModule } }, { MessageAction.OpportunitiesDeletedUserField, new MessageMaps { ActionTypeText = AuditReportResource.DeleteActionType, ActionText = AuditReportResource.OpportunitiesDeletedUserField, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.OtherCrmSettingsModule } }, { MessageAction.CasesCreatedUserField, new MessageMaps { ActionTypeText = AuditReportResource.CreateActionType, ActionText = AuditReportResource.CasesCreatedUserField, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.OtherCrmSettingsModule } }, { MessageAction.CasesUpdatedUserField, new MessageMaps { ActionTypeText = AuditReportResource.UpdateActionType, ActionText = AuditReportResource.CasesUpdatedUserField, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.OtherCrmSettingsModule } }, { MessageAction.CasesUpdatedUserFieldsOrder, new MessageMaps { ActionTypeText = AuditReportResource.UpdateActionType, ActionText = AuditReportResource.CasesUpdatedUserFieldsOrder, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.OtherCrmSettingsModule } }, { MessageAction.CasesDeletedUserField, new MessageMaps { ActionTypeText = AuditReportResource.DeleteActionType, ActionText = AuditReportResource.CasesDeletedUserField, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.OtherCrmSettingsModule } }, #endregion #region history categories settings { MessageAction.HistoryCategoryCreated, new MessageMaps { ActionTypeText = AuditReportResource.CreateActionType, ActionText = AuditReportResource.HistoryCategoryCreated, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.OtherCrmSettingsModule } }, { MessageAction.HistoryCategoryUpdated, new MessageMaps { ActionTypeText = AuditReportResource.UpdateActionType, ActionText = AuditReportResource.HistoryCategoryUpdated, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.OtherCrmSettingsModule } }, { MessageAction.HistoryCategoryUpdatedIcon, new MessageMaps { ActionTypeText = AuditReportResource.UpdateActionType, ActionText = AuditReportResource.HistoryCategoryUpdatedIcon, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.OtherCrmSettingsModule } }, { MessageAction.HistoryCategoriesUpdatedOrder, new MessageMaps { ActionTypeText = AuditReportResource.UpdateActionType, ActionText = AuditReportResource.HistoryCategoriesUpdatedOrder, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.OtherCrmSettingsModule } }, { MessageAction.HistoryCategoryDeleted, new MessageMaps { ActionTypeText = AuditReportResource.DeleteActionType, ActionText = AuditReportResource.HistoryCategoryDeleted, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.OtherCrmSettingsModule } }, #endregion #region task actegories settings { MessageAction.CrmTaskCategoryCreated, new MessageMaps { ActionTypeText = AuditReportResource.CreateActionType, ActionText = AuditReportResource.CrmTaskCategoryCreated, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.OtherCrmSettingsModule } }, { MessageAction.CrmTaskCategoryUpdated, new MessageMaps { ActionTypeText = AuditReportResource.UpdateActionType, ActionText = AuditReportResource.CrmTaskCategoryUpdated, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.OtherCrmSettingsModule } }, { MessageAction.CrmTaskCategoryUpdatedIcon, new MessageMaps { ActionTypeText = AuditReportResource.UpdateActionType, ActionText = AuditReportResource.CrmTaskCategoryUpdatedIcon, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.OtherCrmSettingsModule } }, { MessageAction.CrmTaskCategoriesUpdatedOrder, new MessageMaps { ActionTypeText = AuditReportResource.UpdateActionType, ActionText = AuditReportResource.CrmTaskCategoriesUpdatedOrder, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.OtherCrmSettingsModule } }, { MessageAction.CrmTaskCategoryDeleted, new MessageMaps { ActionTypeText = AuditReportResource.DeleteActionType, ActionText = AuditReportResource.CrmTaskCategoryDeleted, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.OtherCrmSettingsModule } }, #endregion #region opportunity stages settings { MessageAction.OpportunityStageCreated, new MessageMaps { ActionTypeText = AuditReportResource.CreateActionType, ActionText = AuditReportResource.OpportunityStageCreated, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.OtherCrmSettingsModule } }, { MessageAction.OpportunityStageUpdated, new MessageMaps { ActionTypeText = AuditReportResource.UpdateActionType, ActionText = AuditReportResource.OpportunityStageUpdated, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.OtherCrmSettingsModule } }, { MessageAction.OpportunityStageUpdatedColor, new MessageMaps { ActionTypeText = AuditReportResource.UpdateActionType, ActionText = AuditReportResource.OpportunityStageUpdatedColor, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.OtherCrmSettingsModule } }, { MessageAction.OpportunityStagesUpdatedOrder, new MessageMaps { ActionTypeText = AuditReportResource.UpdateActionType, ActionText = AuditReportResource.OpportunityStagesUpdatedOrder, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.OtherCrmSettingsModule } }, { MessageAction.OpportunityStageDeleted, new MessageMaps { ActionTypeText = AuditReportResource.DeleteActionType, ActionText = AuditReportResource.OpportunityStageDeleted, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.OtherCrmSettingsModule } }, #endregion #region tags settings { MessageAction.ContactsCreatedTag, new MessageMaps { ActionTypeText = AuditReportResource.CreateActionType, ActionText = AuditReportResource.ContactsCreatedTag, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.OtherCrmSettingsModule } }, { MessageAction.ContactsDeletedTag, new MessageMaps { ActionTypeText = AuditReportResource.DeleteActionType, ActionText = AuditReportResource.ContactsDeletedTag, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.OtherCrmSettingsModule } }, { MessageAction.OpportunitiesCreatedTag, new MessageMaps { ActionTypeText = AuditReportResource.CreateActionType, ActionText = AuditReportResource.OpportunitiesCreatedTag, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.OtherCrmSettingsModule } }, { MessageAction.OpportunitiesDeletedTag, new MessageMaps { ActionTypeText = AuditReportResource.DeleteActionType, ActionText = AuditReportResource.OpportunitiesDeletedTag, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.OtherCrmSettingsModule } }, { MessageAction.CasesCreatedTag, new MessageMaps { ActionTypeText = AuditReportResource.CreateActionType, ActionText = AuditReportResource.CasesCreatedTag, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.OtherCrmSettingsModule } }, { MessageAction.CasesDeletedTag, new MessageMaps { ActionTypeText = AuditReportResource.DeleteActionType, ActionText = AuditReportResource.CasesDeletedTag, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.OtherCrmSettingsModule } }, #endregion { MessageAction.WebsiteContactFormUpdatedKey, new MessageMaps { ActionTypeText = AuditReportResource.UpdateActionType, ActionText = AuditReportResource.WebsiteContactFormUpdatedKey, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.OtherCrmSettingsModule } }, { MessageAction.CrmEntityDetachedFile, new MessageMaps { ActionTypeText = AuditReportResource.DetachActionType, ActionText = AuditReportResource.CrmEntityDetachedFile, Product = AuditReportResource.CrmProduct, Module = AuditReportResource.CrmFilesModule } }, #endregion #region people { MessageAction.UserCreated, new MessageMaps { ActionTypeText = AuditReportResource.CreateActionType, ActionText = AuditReportResource.UserCreated, Product = AuditReportResource.PeopleProduct, Module = AuditReportResource.UsersModule } }, { MessageAction.GuestCreated, new MessageMaps { ActionTypeText = AuditReportResource.CreateActionType, ActionText = AuditReportResource.GuestCreated, Product = AuditReportResource.PeopleProduct, Module = AuditReportResource.UsersModule } }, { MessageAction.UserUpdated, new MessageMaps { ActionTypeText = AuditReportResource.UpdateActionType, ActionText = AuditReportResource.UserUpdated, Product = AuditReportResource.PeopleProduct, Module = AuditReportResource.UsersModule } }, { MessageAction.UserUpdatedAvatar, new MessageMaps { ActionTypeText = AuditReportResource.UpdateActionType, ActionText = AuditReportResource.UserUpdatedAvatar, Product = AuditReportResource.PeopleProduct, Module = AuditReportResource.UsersModule } }, { MessageAction.UserSentActivationInstructions, new MessageMaps { ActionTypeText = AuditReportResource.SendActionType, ActionText = AuditReportResource.UserSentActivationInstructions, Product = AuditReportResource.PeopleProduct, Module = AuditReportResource.UsersModule } }, { MessageAction.UserSentPasswordInstructions, new MessageMaps { ActionTypeText = AuditReportResource.SendActionType, ActionText = AuditReportResource.UserSentPasswordInstructions, Product = AuditReportResource.PeopleProduct, Module = AuditReportResource.UsersModule } }, { MessageAction.UserSentEmailInstructions, new MessageMaps { ActionTypeText = AuditReportResource.SendActionType, ActionText = AuditReportResource.UserSentEmailInstructions, Product = AuditReportResource.PeopleProduct, Module = AuditReportResource.UsersModule } }, { MessageAction.UserDeleted, new MessageMaps { ActionTypeText = AuditReportResource.DeleteActionType, ActionText = AuditReportResource.UserDeleted, Product = AuditReportResource.PeopleProduct, Module = AuditReportResource.UsersModule } }, { MessageAction.UsersUpdatedType, new MessageMaps { ActionTypeText = AuditReportResource.UpdateActionType, ActionText = AuditReportResource.UsersUpdatedType, Product = AuditReportResource.PeopleProduct, Module = AuditReportResource.UsersModule } }, { MessageAction.UsersUpdatedStatus, new MessageMaps { ActionTypeText = AuditReportResource.UpdateActionType, ActionText = AuditReportResource.UsersUpdatedStatus, Product = AuditReportResource.PeopleProduct, Module = AuditReportResource.UsersModule } }, { MessageAction.UsersSentActivationInstructions, new MessageMaps { ActionTypeText = AuditReportResource.SendActionType, ActionText = AuditReportResource.UsersSentActivationInstructions, Product = AuditReportResource.PeopleProduct, Module = AuditReportResource.UsersModule } }, { MessageAction.UsersDeleted, new MessageMaps { ActionTypeText = AuditReportResource.DeleteActionType, ActionText = AuditReportResource.UsersDeleted, Product = AuditReportResource.PeopleProduct, Module = AuditReportResource.UsersModule } }, { MessageAction.GroupCreated, new MessageMaps { ActionTypeText = AuditReportResource.CreateActionType, ActionText = AuditReportResource.GroupCreated, Product = AuditReportResource.PeopleProduct, Module = AuditReportResource.GroupsModule } }, { MessageAction.GroupUpdated, new MessageMaps { ActionTypeText = AuditReportResource.UpdateActionType, ActionText = AuditReportResource.GroupUpdated, Product = AuditReportResource.PeopleProduct, Module = AuditReportResource.GroupsModule } }, { MessageAction.GroupDeleted, new MessageMaps { ActionTypeText = AuditReportResource.DeleteActionType, ActionText = AuditReportResource.GroupDeleted, Product = AuditReportResource.PeopleProduct, Module = AuditReportResource.GroupsModule } }, { MessageAction.UserUpdatedPassword, new MessageMaps { ActionTypeText = AuditReportResource.UpdateActionType, ActionText = AuditReportResource.UserUpdatedPassword, Product = AuditReportResource.PeopleProduct, Module = AuditReportResource.UsersModule } }, { MessageAction.UserLinkedSocialAccount, new MessageMaps { ActionTypeText = AuditReportResource.LinkActionType, ActionText = AuditReportResource.UserLinkedSocialAccount, Product = AuditReportResource.PeopleProduct, Module = AuditReportResource.UsersModule } }, { MessageAction.UserUnlinkedSocialAccount, new MessageMaps { ActionTypeText = AuditReportResource.UnlinkActionType, ActionText = AuditReportResource.UserUnlinkedSocialAccount, Product = AuditReportResource.PeopleProduct, Module = AuditReportResource.UsersModule } }, { MessageAction.UserUpdatedLanguage, new MessageMaps { ActionTypeText = AuditReportResource.UpdateActionType, ActionText = AuditReportResource.UserUpdatedLanguage, Product = AuditReportResource.PeopleProduct, Module = AuditReportResource.UsersModule } }, { MessageAction.UserActivatedEmail, new MessageMaps { ActionTypeText = AuditReportResource.UpdateActionType, ActionText = AuditReportResource.UserActivatedEmail, Product = AuditReportResource.PeopleProduct, Module = AuditReportResource.UsersModule } }, { MessageAction.UserUpdatedAvatarThumbnails, new MessageMaps { ActionTypeText = AuditReportResource.UpdateActionType, ActionText = AuditReportResource.UserUpdatedAvatarThumbnails, Product = AuditReportResource.PeopleProduct, Module = AuditReportResource.UsersModule } }, { MessageAction.UserSentDeleteInstructions, new MessageMaps { ActionTypeText = AuditReportResource.SendActionType, ActionText = AuditReportResource.UserSentDeleteInstructions, Product = AuditReportResource.PeopleProduct, Module = AuditReportResource.UsersModule } }, #endregion #region documents { MessageAction.FolderCreated, new MessageMaps { ActionTypeText = AuditReportResource.CreateActionType, ActionText = AuditReportResource.FolderCreated, Product = AuditReportResource.DocumentsProduct, Module = AuditReportResource.FoldersModule } }, { MessageAction.FolderRenamed, new MessageMaps { ActionTypeText = AuditReportResource.UpdateActionType, ActionText = AuditReportResource.FolderRenamed, Product = AuditReportResource.DocumentsProduct, Module = AuditReportResource.FoldersModule } }, { MessageAction.FolderUpdatedAccess, new MessageMaps { ActionTypeText = AuditReportResource.UpdateAccessActionType, ActionText = AuditReportResource.FolderUpdatedAccess, Product = AuditReportResource.DocumentsProduct, Module = AuditReportResource.FoldersModule } }, { MessageAction.FileCreated, new MessageMaps { ActionTypeText = AuditReportResource.CreateActionType, ActionText = AuditReportResource.FileCreated, Product = AuditReportResource.DocumentsProduct, Module = AuditReportResource.FilesModule } }, { MessageAction.FileRenamed, new MessageMaps { ActionTypeText = AuditReportResource.UpdateActionType, ActionText = AuditReportResource.FileRenamed, Product = AuditReportResource.DocumentsProduct, Module = AuditReportResource.FilesModule } }, { MessageAction.FileUpdated, new MessageMaps { ActionTypeText = AuditReportResource.UpdateActionType, ActionText = AuditReportResource.FileUpdated, Product = AuditReportResource.DocumentsProduct, Module = AuditReportResource.FilesModule } }, { MessageAction.FileCreatedVersion, new MessageMaps { ActionTypeText = AuditReportResource.CreateActionType, ActionText = AuditReportResource.FileCreatedVersion, Product = AuditReportResource.DocumentsProduct, Module = AuditReportResource.FilesModule } }, { MessageAction.FileUpdatedToVersion, new MessageMaps { ActionTypeText = AuditReportResource.CreateActionType, ActionText = AuditReportResource.FileUpdatedToVersion, Product = AuditReportResource.DocumentsProduct, Module = AuditReportResource.FilesModule } }, { MessageAction.FileDeletedVersion, new MessageMaps { ActionTypeText = AuditReportResource.DeleteActionType, ActionText = AuditReportResource.FileDeletedVersion, Product = AuditReportResource.DocumentsProduct, Module = AuditReportResource.FilesModule } }, { MessageAction.FileUpdatedRevisionComment, new MessageMaps { ActionTypeText = AuditReportResource.UpdateActionType, ActionText = AuditReportResource.FileUpdatedRevisionComment, Product = AuditReportResource.DocumentsProduct, Module = AuditReportResource.FilesModule } }, { MessageAction.FileLocked, new MessageMaps { ActionTypeText = AuditReportResource.UpdateActionType, ActionText = AuditReportResource.FileLocked, Product = AuditReportResource.DocumentsProduct, Module = AuditReportResource.FilesModule } }, { MessageAction.FileUnlocked, new MessageMaps { ActionTypeText = AuditReportResource.UpdateActionType, ActionText = AuditReportResource.FileUnlocked, Product = AuditReportResource.DocumentsProduct, Module = AuditReportResource.FilesModule } }, { MessageAction.FileUpdatedAccess, new MessageMaps { ActionTypeText = AuditReportResource.UpdateAccessActionType, ActionText = AuditReportResource.FileUpdatedAccess, Product = AuditReportResource.DocumentsProduct, Module = AuditReportResource.FilesModule } }, { MessageAction.FileDownloaded, new MessageMaps { ActionTypeText = AuditReportResource.DownloadActionType, ActionText = AuditReportResource.FileDownloaded, Product = AuditReportResource.DocumentsProduct, Module = AuditReportResource.FilesModule } }, { MessageAction.FileDownloadedAs, new MessageMaps { ActionTypeText = AuditReportResource.DownloadActionType, ActionText = AuditReportResource.FileDownloadedAs, Product = AuditReportResource.DocumentsProduct, Module = AuditReportResource.FilesModule } }, { MessageAction.DocumentsDownloaded, new MessageMaps { ActionTypeText = AuditReportResource.DownloadActionType, ActionText = AuditReportResource.DocumentsDownloaded, Product = AuditReportResource.DocumentsProduct, Module = AuditReportResource.DocumentsModule } }, { MessageAction.DocumentsCopied, new MessageMaps { ActionTypeText = AuditReportResource.CopyActionType, ActionText = AuditReportResource.DocumentsCopied, Product = AuditReportResource.DocumentsProduct, Module = AuditReportResource.DocumentsModule } }, { MessageAction.DocumentsMoved, new MessageMaps { ActionTypeText = AuditReportResource.UpdateActionType, ActionText = AuditReportResource.DocumentsMoved, Product = AuditReportResource.DocumentsProduct, Module = AuditReportResource.DocumentsModule } }, { MessageAction.DocumentsDeleted, new MessageMaps { ActionTypeText = AuditReportResource.DeleteActionType, ActionText = AuditReportResource.DocumentsDeleted, Product = AuditReportResource.DocumentsProduct, Module = AuditReportResource.DocumentsModule } }, { MessageAction.TrashCleaned, new MessageMaps { ActionTypeText = AuditReportResource.DeleteActionType, ActionText = AuditReportResource.TrashCleaned, Product = AuditReportResource.DocumentsProduct, Module = AuditReportResource.DocumentsModule } }, { MessageAction.FileMovedToTrash, new MessageMaps { ActionTypeText = AuditReportResource.MoveActionType, ActionText = AuditReportResource.FileMovedToTrash, Product = AuditReportResource.DocumentsProduct, Module = AuditReportResource.FilesModule } }, { MessageAction.FileDeleted, new MessageMaps { ActionTypeText = AuditReportResource.DeleteActionType, ActionText = AuditReportResource.FileDeleted, Product = AuditReportResource.DocumentsProduct, Module = AuditReportResource.FilesModule } }, { MessageAction.FolderMovedToTrash, new MessageMaps { ActionTypeText = AuditReportResource.MoveActionType, ActionText = AuditReportResource.FolderMovedToTrash, Product = AuditReportResource.DocumentsProduct, Module = AuditReportResource.FoldersModule } }, { MessageAction.FolderDeleted, new MessageMaps { ActionTypeText = AuditReportResource.DeleteActionType, ActionText = AuditReportResource.FolderDeleted, Product = AuditReportResource.DocumentsProduct, Module = AuditReportResource.FoldersModule } }, { MessageAction.FileCopied, new MessageMaps { ActionTypeText = AuditReportResource.CopyActionType, ActionText = AuditReportResource.FileCopied, Product = AuditReportResource.DocumentsProduct, Module = AuditReportResource.FilesModule } }, { MessageAction.FileCopiedWithOverwriting, new MessageMaps { ActionTypeText = AuditReportResource.CopyActionType, ActionText = AuditReportResource.FileCopiedWithOverwriting, Product = AuditReportResource.DocumentsProduct, Module = AuditReportResource.FilesModule } }, { MessageAction.FileMoved, new MessageMaps { ActionTypeText = AuditReportResource.MoveActionType, ActionText = AuditReportResource.FileMoved, Product = AuditReportResource.DocumentsProduct, Module = AuditReportResource.FilesModule } }, { MessageAction.FileMovedWithOverwriting, new MessageMaps { ActionTypeText = AuditReportResource.MoveActionType, ActionText = AuditReportResource.FileMovedWithOverwriting, Product = AuditReportResource.DocumentsProduct, Module = AuditReportResource.FilesModule } }, { MessageAction.FolderCopied, new MessageMaps { ActionTypeText = AuditReportResource.CopyActionType, ActionText = AuditReportResource.FolderCopied, Product = AuditReportResource.DocumentsProduct, Module = AuditReportResource.FoldersModule } }, { MessageAction.FolderCopiedWithOverwriting, new MessageMaps { ActionTypeText = AuditReportResource.CopyActionType, ActionText = AuditReportResource.FolderCopiedWithOverwriting, Product = AuditReportResource.DocumentsProduct, Module = AuditReportResource.FoldersModule } }, { MessageAction.FolderMoved, new MessageMaps { ActionTypeText = AuditReportResource.MoveActionType, ActionText = AuditReportResource.FolderMoved, Product = AuditReportResource.DocumentsProduct, Module = AuditReportResource.FoldersModule } }, { MessageAction.FolderMovedWithOverwriting, new MessageMaps { ActionTypeText = AuditReportResource.MoveActionType, ActionText = AuditReportResource.FolderMovedWithOverwriting, Product = AuditReportResource.DocumentsProduct, Module = AuditReportResource.FoldersModule } }, { MessageAction.FilesImportedFromBoxNet, new MessageMaps { ActionTypeText = AuditReportResource.DeleteActionType, ActionText = AuditReportResource.FilesImportedFromBoxNet, Product = AuditReportResource.DocumentsProduct, Module = AuditReportResource.FilesModule } }, { MessageAction.FilesImportedFromGoogleDocs, new MessageMaps { ActionTypeText = AuditReportResource.DeleteActionType, ActionText = AuditReportResource.FilesImportedFromGoogleDocs, Product = AuditReportResource.DocumentsProduct, Module = AuditReportResource.FilesModule } }, { MessageAction.FilesImportedFromZoho, new MessageMaps { ActionTypeText = AuditReportResource.DeleteActionType, ActionText = AuditReportResource.FilesImportedFromZoho, Product = AuditReportResource.DocumentsProduct, Module = AuditReportResource.FilesModule } }, { MessageAction.FileImported, new MessageMaps { ActionTypeText = AuditReportResource.ImportActionType, ActionText = AuditReportResource.FileImported, Product = AuditReportResource.DocumentsProduct, Module = AuditReportResource.FilesModule } }, { MessageAction.DocumentsThirdPartySettingsUpdated, new MessageMaps { ActionTypeText = AuditReportResource.UpdateActionType, ActionText = AuditReportResource.DocumentsThirdPartySettingsUpdated, Product = AuditReportResource.DocumentsProduct, Module = AuditReportResource.DocumentsSettingsModule } }, { MessageAction.DocumentsOverwritingSettingsUpdated, new MessageMaps { ActionTypeText = AuditReportResource.UpdateActionType, ActionText = AuditReportResource.DocumentsOverwritingSettingsUpdated, Product = AuditReportResource.DocumentsProduct, Module = AuditReportResource.DocumentsSettingsModule } }, { MessageAction.DocumentsUploadingFormatsSettingsUpdated, new MessageMaps { ActionTypeText = AuditReportResource.UpdateActionType, ActionText = AuditReportResource.DocumentsUploadingFormatsSettingsUpdated, Product = AuditReportResource.DocumentsProduct, Module = AuditReportResource.DocumentsSettingsModule } }, { MessageAction.FileUploaded, new MessageMaps { ActionTypeText = AuditReportResource.UploadActionType, ActionText = AuditReportResource.FileUploaded, Product = AuditReportResource.DocumentsProduct, Module = AuditReportResource.FilesModule } }, { MessageAction.ThirdPartyCreated, new MessageMaps { ActionTypeText = AuditReportResource.CreateActionType, ActionText = AuditReportResource.ThirdPartyCreated, Product = AuditReportResource.DocumentsProduct, Module = AuditReportResource.DocumentsSettingsModule } }, { MessageAction.ThirdPartyUpdated, new MessageMaps { ActionTypeText = AuditReportResource.UpdateActionType, ActionText = AuditReportResource.ThirdPartyUpdated, Product = AuditReportResource.DocumentsProduct, Module = AuditReportResource.DocumentsSettingsModule } }, { MessageAction.ThirdPartyDeleted, new MessageMaps { ActionTypeText = AuditReportResource.DeleteActionType, ActionText = AuditReportResource.ThirdPartyDeleted, Product = AuditReportResource.DocumentsProduct, Module = AuditReportResource.DocumentsSettingsModule } }, #endregion #region settings { MessageAction.LanguageSettingsUpdated, new MessageMaps { ActionTypeText = AuditReportResource.UpdateActionType, ActionText = AuditReportResource.LanguageSettingsUpdated, Product = AuditReportResource.SettingsProduct, Module = AuditReportResource.GeneralModule } }, { MessageAction.TimeZoneSettingsUpdated, new MessageMaps { ActionTypeText = AuditReportResource.UpdateActionType, ActionText = AuditReportResource.TimeZoneSettingsUpdated, Product = AuditReportResource.SettingsProduct, Module = AuditReportResource.GeneralModule } }, { MessageAction.DnsSettingsUpdated, new MessageMaps { ActionTypeText = AuditReportResource.UpdateActionType, ActionText = AuditReportResource.DnsSettingsUpdated, Product = AuditReportResource.SettingsProduct, Module = AuditReportResource.GeneralModule } }, { MessageAction.TrustedMailDomainSettingsUpdated, new MessageMaps { ActionTypeText = AuditReportResource.UpdateActionType, ActionText = AuditReportResource.TrustedMailDomainSettingsUpdated, Product = AuditReportResource.SettingsProduct, Module = AuditReportResource.GeneralModule } }, { MessageAction.PasswordStrengthSettingsUpdated, new MessageMaps { ActionTypeText = AuditReportResource.UpdateActionType, ActionText = AuditReportResource.PasswordStrengthSettingsUpdated, Product = AuditReportResource.SettingsProduct, Module = AuditReportResource.GeneralModule } }, { MessageAction.TwoFactorAuthenticationSettingsUpdated, new MessageMaps { ActionTypeText = AuditReportResource.UpdateActionType, ActionText = AuditReportResource.TwoFactorAuthenticationSettingsUpdated, Product = AuditReportResource.SettingsProduct, Module = AuditReportResource.GeneralModule } }, { MessageAction.AdministratorMessageSettingsUpdated, new MessageMaps { ActionTypeText = AuditReportResource.UpdateActionType, ActionText = AuditReportResource.AdministratorMessageSettingsUpdated, Product = AuditReportResource.SettingsProduct, Module = AuditReportResource.GeneralModule } }, { MessageAction.DefaultStartPageSettingsUpdated, new MessageMaps { ActionTypeText = AuditReportResource.UpdateActionType, ActionText = AuditReportResource.DefaultStartPageSettingsUpdated, Product = AuditReportResource.SettingsProduct, Module = AuditReportResource.GeneralModule } }, { MessageAction.ProductsListUpdated, new MessageMaps { ActionTypeText = AuditReportResource.UpdateActionType, ActionText = AuditReportResource.ProductsListUpdated, Product = AuditReportResource.SettingsProduct, Module = AuditReportResource.ProductsModule } }, { MessageAction.OwnerUpdated, new MessageMaps { ActionTypeText = AuditReportResource.UpdateActionType, ActionText = AuditReportResource.OwnerUpdated, Product = AuditReportResource.SettingsProduct, Module = AuditReportResource.ProductsModule } }, { MessageAction.AdministratorUpdatedProductAccess, new MessageMaps { ActionTypeText = AuditReportResource.UpdateActionType, ActionText = AuditReportResource.AdministratorUpdatedProductAccess, Product = AuditReportResource.SettingsProduct, Module = AuditReportResource.ProductsModule } }, { MessageAction.AdministratorAdded, new MessageMaps { ActionTypeText = AuditReportResource.CreateActionType, ActionText = AuditReportResource.AdministratorAdded, Product = AuditReportResource.SettingsProduct, Module = AuditReportResource.ProductsModule } }, #endregion }; public static string GetActionText(AuditEvent evt) { var action = (MessageAction)evt.Action; if (!actions.ContainsKey(action)) throw new ArgumentException(string.Format("There is no action text for \"{0}\" type of event", action)); var text = actions[(MessageAction)evt.Action].ActionText; return evt.Ids == null || !evt.Ids.Any() ? text : string.Format(text, evt.Ids.Select(GetLimitedText).ToArray()); } public static string GetActionText(LoginEvent evt) { var action = (MessageAction)evt.Action; if (!actions.ContainsKey(action)) throw new ArgumentException(string.Format("There is no action text for \"{0}\" type of event", action)); var text = actions[(MessageAction)evt.Action].ActionText; return evt.Ids == null || !evt.Ids.Any() ? text : string.Format(text, evt.Ids.Select(GetLimitedText).ToArray()); } public static string GetActionTypeText(AuditEvent evt) { var action = (MessageAction)evt.Action; return !actions.ContainsKey(action) ? string.Empty : actions[(MessageAction)evt.Action].ActionTypeText; } public static string GetProductText(AuditEvent evt) { var action = (MessageAction)evt.Action; return !actions.ContainsKey(action) ? string.Empty : actions[(MessageAction)evt.Action].Product; } public static string GetModuleText(AuditEvent evt) { var action = (MessageAction)evt.Action; return !actions.ContainsKey(action) ? string.Empty : actions[(MessageAction)evt.Action].Module; } private static string GetLimitedText(string text) { if (text == null) throw new ArgumentException("text"); return text.Length < 50 ? text : string.Format("[{0}...]", text.Substring(0, 47)); } private class MessageMaps { public string ActionTypeText { get; set; } public string ActionText { get; set; } public string Product { get; set; } public string Module { get; set; } } } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/URI/AbsoluteUri.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net { #region usings using System; #endregion /// <summary> /// Implements absolute-URI. Defined in RFC 3986.4.3. /// </summary> public class AbsoluteUri { #region Members private string m_Scheme = ""; private string m_Value = ""; #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> internal AbsoluteUri() {} #endregion #region Properties /// <summary> /// Gets URI scheme. /// </summary> public virtual string Scheme { get { return m_Scheme; } } /// <summary> /// Gets URI value after scheme. /// </summary> public string Value { get { return ToString().Split(new[] {':'}, 2)[1]; } } #endregion #region Methods /// <summary> /// Parse URI from string value. /// </summary> /// <param name="value">String URI value.</param> /// <exception cref="ArgumentNullException">Is raised when <b>value</b> is null reference.</exception> /// <exception cref="ArgumentException">Is raised when <b>value</b> has invalid URI value.</exception> public static AbsoluteUri Parse(string value) { if (value == null) { throw new ArgumentNullException("value"); } if (value == "") { throw new ArgumentException("Argument 'value' value must be specified."); } string[] scheme_value = value.Split(new[] {':'}, 2); if (scheme_value[0].ToLower() == UriSchemes.sip || scheme_value[0].ToLower() == UriSchemes.sips) { SIP_Uri uri = new SIP_Uri(); uri.ParseInternal(value); return uri; } else { AbsoluteUri uri = new AbsoluteUri(); uri.ParseInternal(value); return uri; } } /// <summary> /// Converts URI to string. /// </summary> /// <returns>Returns URI as string.</returns> public override string ToString() { return m_Scheme + ":" + m_Value; } #endregion #region Virtual methods /// <summary> /// Parses URI from the specified string. /// </summary> /// <param name="value">URI string.</param> /// <exception cref="ArgumentNullException">Is raised when <b>value</b> is null reference.</exception> protected virtual void ParseInternal(string value) { if (value == null) { throw new ArgumentNullException("value"); } string[] scheme_value = value.Split(new[] {':'}, 1); m_Scheme = scheme_value[0].ToLower(); if (scheme_value.Length == 2) { m_Value = scheme_value[1]; } } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/_Obsolete/ReadException.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net { #region usings using System; #endregion #region public enum ReadReplyCode /// <summary> /// Reply reading return codes. /// </summary> public enum ReadReplyCode { /// <summary> /// Read completed successfully. /// </summary> Ok = 0, /// <summary> /// Read timed out. /// </summary> TimeOut = 1, /// <summary> /// Maximum allowed Length exceeded. /// </summary> LengthExceeded = 2, /// <summary> /// Connected client closed connection. /// </summary> SocketClosed = 3, /// <summary> /// UnKnown error, eception raised. /// </summary> UnKnownError = 4, } #endregion /// <summary> /// Summary description for ReadException. /// </summary> public class ReadException : Exception { #region Members private readonly ReadReplyCode m_ReadReplyCode; #endregion #region Properties /// <summary> /// Gets read error. /// </summary> public ReadReplyCode ReadReplyCode { get { return m_ReadReplyCode; } } #endregion #region Constructor /// <summary> /// /// </summary> /// <param name="code"></param> /// <param name="message"></param> public ReadException(ReadReplyCode code, string message) : base(message) { m_ReadReplyCode = code; } #endregion } }<file_sep>/module/ASC.AuditTrail/Mappers/PeopleActionMapper.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System.Collections.Generic; using ASC.MessagingSystem; namespace ASC.AuditTrail.Mappers { internal class PeopleActionMapper { public static Dictionary<MessageAction, MessageMaps> GetMaps() { return new Dictionary<MessageAction, MessageMaps> { { MessageAction.UserCreated, new MessageMaps { ActionTypeTextResourceName = "CreateActionType", ActionTextResourceName = "UserCreated", ProductResourceName = "PeopleProduct", ModuleResourceName = "UsersModule" } }, { MessageAction.GuestCreated, new MessageMaps { ActionTypeTextResourceName = "CreateActionType", ActionTextResourceName = "GuestCreated", ProductResourceName = "PeopleProduct", ModuleResourceName = "UsersModule" } }, { MessageAction.UserCreatedViaInvite, new MessageMaps { ActionTypeTextResourceName = "CreateActionType", ActionTextResourceName = "UserCreatedViaInvite", ProductResourceName = "PeopleProduct", ModuleResourceName = "UsersModule" } }, { MessageAction.GuestCreatedViaInvite, new MessageMaps { ActionTypeTextResourceName = "CreateActionType", ActionTextResourceName = "GuestCreatedViaInvite", ProductResourceName = "PeopleProduct", ModuleResourceName = "UsersModule" } }, { MessageAction.UserActivated, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "UserActivated", ProductResourceName = "PeopleProduct", ModuleResourceName = "UsersModule" } }, { MessageAction.GuestActivated, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "GuestActivated", ProductResourceName = "PeopleProduct", ModuleResourceName = "UsersModule" } }, { MessageAction.UserUpdated, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "UserUpdated", ProductResourceName = "PeopleProduct", ModuleResourceName = "UsersModule" } }, { MessageAction.UserUpdatedMobileNumber, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "UserUpdatedMobileNumber", ProductResourceName = "PeopleProduct", ModuleResourceName = "UsersModule" } }, { MessageAction.UserUpdatedLanguage, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "UserUpdatedLanguage", ProductResourceName = "PeopleProduct", ModuleResourceName = "UsersModule" } }, { MessageAction.UserAddedAvatar, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "UserAddedAvatar", ProductResourceName = "PeopleProduct", ModuleResourceName = "UsersModule" } }, { MessageAction.UserDeletedAvatar, new MessageMaps { ActionTypeTextResourceName = "DeleteActionType", ActionTextResourceName = "UserDeletedAvatar", ProductResourceName = "PeopleProduct", ModuleResourceName = "UsersModule" } }, { MessageAction.UserUpdatedAvatarThumbnails, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "UserUpdatedAvatarThumbnails", ProductResourceName = "PeopleProduct", ModuleResourceName = "UsersModule" } }, { MessageAction.UserLinkedSocialAccount, new MessageMaps { ActionTypeTextResourceName = "LinkActionType", ActionTextResourceName = "UserLinkedSocialAccount", ProductResourceName = "PeopleProduct", ModuleResourceName = "UsersModule" } }, { MessageAction.UserUnlinkedSocialAccount, new MessageMaps { ActionTypeTextResourceName = "UnlinkActionType", ActionTextResourceName = "UserUnlinkedSocialAccount", ProductResourceName = "PeopleProduct", ModuleResourceName = "UsersModule" } }, { MessageAction.UserSentActivationInstructions, new MessageMaps { ActionTypeTextResourceName = "SendActionType", ActionTextResourceName = "UserSentActivationInstructions", ProductResourceName = "PeopleProduct", ModuleResourceName = "UsersModule" } }, { MessageAction.UserSentEmailChangeInstructions, new MessageMaps { ActionTypeTextResourceName = "SendActionType", ActionTextResourceName = "UserSentEmailInstructions", ProductResourceName = "PeopleProduct", ModuleResourceName = "UsersModule" } }, { MessageAction.UserSentPasswordChangeInstructions, new MessageMaps { ActionTypeTextResourceName = "SendActionType", ActionTextResourceName = "UserSentPasswordInstructions", ProductResourceName = "PeopleProduct", ModuleResourceName = "UsersModule" } }, { MessageAction.UserSentDeleteInstructions, new MessageMaps { ActionTypeTextResourceName = "SendActionType", ActionTextResourceName = "UserSentDeleteInstructions", ProductResourceName = "PeopleProduct", ModuleResourceName = "UsersModule" } }, { MessageAction.UserUpdatedEmail, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "UserUpdatedEmail", ProductResourceName = "PeopleProduct", ModuleResourceName = "UsersModule" } }, { MessageAction.UserUpdatedPassword, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "UserUpdatedPassword", ProductResourceName = "PeopleProduct", ModuleResourceName = "UsersModule" } }, { MessageAction.UserDeleted, new MessageMaps { ActionTypeTextResourceName = "DeleteActionType", ActionTextResourceName = "UserDeleted", ProductResourceName = "PeopleProduct", ModuleResourceName = "UsersModule" } }, { MessageAction.UsersUpdatedType, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "UsersUpdatedType", ProductResourceName = "PeopleProduct", ModuleResourceName = "UsersModule" } }, { MessageAction.UsersUpdatedStatus, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "UsersUpdatedStatus", ProductResourceName = "PeopleProduct", ModuleResourceName = "UsersModule" } }, { MessageAction.UsersSentActivationInstructions, new MessageMaps { ActionTypeTextResourceName = "SendActionType", ActionTextResourceName = "UsersSentActivationInstructions", ProductResourceName = "PeopleProduct", ModuleResourceName = "UsersModule" } }, { MessageAction.UsersDeleted, new MessageMaps { ActionTypeTextResourceName = "DeleteActionType", ActionTextResourceName = "UsersDeleted", ProductResourceName = "PeopleProduct", ModuleResourceName = "UsersModule" } }, { MessageAction.SentInviteInstructions, new MessageMaps { ActionTypeTextResourceName = "SendActionType", ActionTextResourceName = "SentInviteInstructions", ProductResourceName = "PeopleProduct", ModuleResourceName = "UsersModule" } }, { MessageAction.UserImported, new MessageMaps { ActionTypeTextResourceName = "ImportActionType", ActionTextResourceName = "UserImported", ProductResourceName = "PeopleProduct", ModuleResourceName = "UsersModule" } }, { MessageAction.GuestImported, new MessageMaps { ActionTypeTextResourceName = "ImportActionType", ActionTextResourceName = "GuestImported", ProductResourceName = "PeopleProduct", ModuleResourceName = "UsersModule" } }, { MessageAction.GroupCreated, new MessageMaps { ActionTypeTextResourceName = "CreateActionType", ActionTextResourceName = "GroupCreated", ProductResourceName = "PeopleProduct", ModuleResourceName = "GroupsModule" } }, { MessageAction.GroupUpdated, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "GroupUpdated", ProductResourceName = "PeopleProduct", ModuleResourceName = "GroupsModule" } }, { MessageAction.GroupDeleted, new MessageMaps { ActionTypeTextResourceName = "DeleteActionType", ActionTextResourceName = "GroupDeleted", ProductResourceName = "PeopleProduct", ModuleResourceName = "GroupsModule" } }, { MessageAction.UserDataReassigns, new MessageMaps { ActionTypeTextResourceName = "ReassignsActionType", ActionTextResourceName = "UserDataReassigns", ProductResourceName = "PeopleProduct", ModuleResourceName = "UsersModule" } }, { MessageAction.UserDataRemoving, new MessageMaps { ActionTypeTextResourceName = "DeleteActionType", ActionTextResourceName = "UserDataRemoving", ProductResourceName = "PeopleProduct", ModuleResourceName = "UsersModule" } }, { MessageAction.UserConnectedTfaApp, new MessageMaps { ActionTypeTextResourceName = "LinkActionType", ActionTextResourceName = "UserTfaGenerateCodes", ProductResourceName = "PeopleProduct", ModuleResourceName = "UsersModule" } }, { MessageAction.UserDisconnectedTfaApp, new MessageMaps { ActionTypeTextResourceName = "DeleteActionType", ActionTextResourceName = "UserTfaDisconnected", ProductResourceName = "PeopleProduct", ModuleResourceName = "UsersModule" } } }; } } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/POP3/Client/POP3_ClientMessage.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.POP3.Client { #region usings using System; using System.IO; using System.Text; using System.Security.Cryptography; using System.Globalization; #endregion /// <summary> /// This class represents POP3 client message. /// </summary> public class POP3_ClientMessage { #region Members private readonly int m_SequenceNumber = 1; private readonly int m_Size; private bool m_IsDisposed; private bool m_IsMarkedForDeletion; private POP3_Client m_Pop3Client; #endregion #region Properties /// <summary> /// Gets if POP3 message is Disposed. /// </summary> public bool IsDisposed { get { return m_IsDisposed; } } /// <summary> /// Gets message 1 based sequence number. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> public int SequenceNumber { get { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_SequenceNumber; } } /// <summary> /// Gets message UID. NOTE: Before accessing this property, check that server supports UIDL command. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> /// <exception cref="NotSupportedException">Is raised when POP3 server doesnt support UIDL command.</exception> public string UIDL {get; set;} /// <summary> /// Gets message size in bytes. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> public int Size { get { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_Size; } } /// <summary> /// Gets if message is marked for deletion. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> public bool IsMarkedForDeletion { get { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_IsMarkedForDeletion; } } public string MD5 { get; set; } public bool IsNew { get; set; } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="pop3">Owner POP3 client.</param> /// <param name="seqNumber">Message 1 based sequence number.</param> /// <param name="size">Message size in bytes.</param> internal POP3_ClientMessage(POP3_Client pop3, int seqNumber, int size) { m_Pop3Client = pop3; m_SequenceNumber = seqNumber; m_Size = size; } #endregion #region Methods /// <summary> /// Marks message as deleted. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="POP3_ClientException">Is raised when POP3 serveer returns error.</exception> public void MarkForDeletion() { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (IsMarkedForDeletion) { return; } m_IsMarkedForDeletion = true; m_Pop3Client.MarkMessageForDeletion(SequenceNumber); } /// <summary> /// Gets message header as string. /// </summary> /// <returns>Returns message header as string.</returns> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when message is marked for deletion and this method is accessed.</exception> /// <exception cref="POP3_ClientException">Is raised when POP3 serveer returns error.</exception> public string HeaderToString() { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (IsMarkedForDeletion) { throw new InvalidOperationException("Can't access message, it's marked for deletion."); } return Encoding.Default.GetString(HeaderToByte()); } /// <summary> /// Gets message header as byte[] data. /// </summary> /// <returns>Returns message header as byte[] data.</returns> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when message is marked for deletion and this method is accessed.</exception> /// <exception cref="POP3_ClientException">Is raised when POP3 serveer returns error.</exception> public byte[] HeaderToByte() { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (IsMarkedForDeletion) { throw new InvalidOperationException("Can't access message, it's marked for deletion."); } MemoryStream retVal = new MemoryStream(); MessageTopLinesToStream(retVal, 0); return retVal.ToArray(); } /// <summary> /// Stores message header to the specified stream. /// </summary> /// <param name="stream">Stream where to store data.</param> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="ArgumentNullException">Is raised when argument <b>stream</b> value is null.</exception> /// <exception cref="POP3_ClientException">Is raised when POP3 serveer returns error.</exception> public void HeaderToStream(Stream stream) { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (stream == null) { throw new ArgumentNullException("Argument 'stream' value can't be null."); } if (IsMarkedForDeletion) { throw new InvalidOperationException("Can't access message, it's marked for deletion."); } MessageTopLinesToStream(stream, 0); } /// <summary> /// Gets message as byte[] data. /// </summary> /// <returns>Returns message as byte[] data.</returns> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when message is marked for deletion and this method is accessed.</exception> /// <exception cref="POP3_ClientException">Is raised when POP3 serveer returns error.</exception> public byte[] MessageToByte() { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (IsMarkedForDeletion) { throw new InvalidOperationException("Can't access message, it's marked for deletion."); } MemoryStream retVal = new MemoryStream(); MessageToStream(retVal); return retVal.ToArray(); } /// <summary> /// Stores message to specified stream. /// </summary> /// <param name="stream">Stream where to store message.</param> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="ArgumentNullException">Is raised when argument <b>stream</b> value is null.</exception> /// <exception cref="InvalidOperationException">Is raised when message is marked for deletion and this method is accessed.</exception> /// <exception cref="POP3_ClientException">Is raised when POP3 serveer returns error.</exception> public void MessageToStream(Stream stream) { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (stream == null) { throw new ArgumentNullException("Argument 'stream' value can't be null."); } if (IsMarkedForDeletion) { throw new InvalidOperationException("Can't access message, it's marked for deletion."); } m_Pop3Client.GetMessage(SequenceNumber, stream); } /// <summary> /// Gets message header + specified number lines of message body. /// </summary> /// <param name="lineCount">Number of lines to get from message body.</param> /// <returns>Returns message header + specified number lines of message body.</returns> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="ArgumentException">Is raised when <b>numberOfLines</b> is negative value.</exception> /// <exception cref="InvalidOperationException">Is raised when message is marked for deletion and this method is accessed.</exception> /// <exception cref="POP3_ClientException">Is raised when POP3 serveer returns error.</exception> public byte[] MessageTopLinesToByte(int lineCount) { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (lineCount < 0) { throw new ArgumentException("Argument 'lineCount' value must be >= 0."); } if (IsMarkedForDeletion) { throw new InvalidOperationException("Can't access message, it's marked for deletion."); } MemoryStream retVal = new MemoryStream(); MessageTopLinesToStream(retVal, lineCount); return retVal.ToArray(); } /// <summary> /// Stores message header + specified number lines of message body to the specified stream. /// </summary> /// <param name="stream">Stream where to store data.</param> /// <param name="lineCount">Number of lines to get from message body.</param> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="ArgumentNullException">Is raised when argument <b>stream</b> value is null.</exception> /// <exception cref="InvalidOperationException">Is raised when message is marked for deletion and this method is accessed.</exception> /// <exception cref="POP3_ClientException">Is raised when POP3 serveer returns error.</exception> public void MessageTopLinesToStream(Stream stream, int lineCount) { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (stream == null) { throw new ArgumentNullException("Argument 'stream' value can't be null."); } if (IsMarkedForDeletion) { throw new InvalidOperationException("Can't access message, it's marked for deletion."); } m_Pop3Client.GetTopOfMessage(SequenceNumber, stream, lineCount); } #endregion #region Internal methods /// <summary> /// Disposes message. /// </summary> internal void Dispose() { if (m_IsDisposed) { return; } m_IsDisposed = true; m_Pop3Client = null; } /// <summary> /// Sets IsMarkedForDeletion flag value. /// </summary> /// <param name="isMarkedForDeletion">New IsMarkedForDeletion value.</param> internal void SetMarkedForDeletion(bool isMarkedForDeletion) { m_IsMarkedForDeletion = isMarkedForDeletion; } public void CalculateMD5() { if (!string.IsNullOrEmpty(MD5)) return; MD5 hash = System.Security.Cryptography.MD5.Create(); byte[] data = hash.ComputeHash(HeaderToByte()); string result_md5 = ""; for (int i = 0; i < data.Length; i++) { result_md5 += data[i].ToString("x2", CultureInfo.InvariantCulture); } MD5 = result_md5; } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/RTP/RTP_Source_Local.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.RTP { #region usings using System; using System.Net; #endregion /// <summary> /// This class represents local source what we send. /// </summary> /// <remarks>Source indicates an entity sending packets, either RTP and/or RTCP. /// Sources what send RTP packets are called "active", only RTCP sending ones are "passive". /// </remarks> public class RTP_Source_Local : RTP_Source { #region Members private RTP_SendStream m_pStream; #endregion #region Properties /// <summary> /// Returns true. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public override bool IsLocal { get { if (State == RTP_SourceState.Disposed) { throw new ObjectDisposedException(GetType().Name); } return true; } } /// <summary> /// Gets local participant. /// </summary> public RTP_Participant_Local Participant { get { return Session.Session.LocalParticipant; } } /// <summary> /// Gets the stream we send. Value null means that source is passive and doesn't send any RTP data. /// </summary> public RTP_SendStream Stream { get { return m_pStream; } } /// <summary> /// Gets source CNAME. Value null means that source not binded to participant. /// </summary> internal override string CName { get { if (Participant != null) { return null; } else { return Participant.CNAME; } } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="session">Owner RTP session.</param> /// <param name="ssrc">Synchronization source ID.</param> /// <param name="rtcpEP">RTCP end point.</param> /// <param name="rtpEP">RTP end point.</param> /// <exception cref="ArgumentNullException">Is raised when <b>session</b>,<b>rtcpEP</b> or <b>rtpEP</b> is null reference.</exception> internal RTP_Source_Local(RTP_Session session, uint ssrc, IPEndPoint rtcpEP, IPEndPoint rtpEP) : base(session, ssrc) { if (rtcpEP == null) { throw new ArgumentNullException("rtcpEP"); } if (rtpEP == null) { throw new ArgumentNullException("rtpEP"); } SetRtcpEP(rtcpEP); SetRtpEP(rtpEP); } #endregion #region Methods /// <summary> /// Sends specified application packet to the RTP session target(s). /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this method is accessed.</exception> /// <param name="packet">Is raised when <b>packet</b> is null reference.</param> public void SendApplicationPacket(RTCP_Packet_APP packet) { if (State == RTP_SourceState.Disposed) { throw new ObjectDisposedException(GetType().Name); } if (packet == null) { throw new ArgumentNullException("packet"); } packet.Source = SSRC; RTCP_CompoundPacket p = new RTCP_CompoundPacket(); RTCP_Packet_RR rr = new RTCP_Packet_RR(); rr.SSRC = SSRC; p.Packets.Add(packet); // Send APP packet. Session.SendRtcpPacket(p); } #endregion #region Overrides /// <summary> /// Closes this source, sends BYE to remote party. /// </summary> /// <param name="closeReason">Stream closing reason text what is reported to the remote party. Value null means not specified.</param> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this method is accessed.</exception> internal override void Close(string closeReason) { if (State == RTP_SourceState.Disposed) { throw new ObjectDisposedException(GetType().Name); } RTCP_CompoundPacket packet = new RTCP_CompoundPacket(); RTCP_Packet_RR rr = new RTCP_Packet_RR(); rr.SSRC = SSRC; packet.Packets.Add(rr); RTCP_Packet_BYE bye = new RTCP_Packet_BYE(); bye.Sources = new[] {SSRC}; if (!string.IsNullOrEmpty(closeReason)) { bye.LeavingReason = closeReason; } packet.Packets.Add(bye); // Send packet. Session.SendRtcpPacket(packet); base.Close(closeReason); } #endregion #region Internal methods /// <summary> /// Creates RTP send stream for this source. /// </summary> /// <exception cref="InvalidOperationException">Is raised when this method is called more than 1 times(source already created).</exception> internal void CreateStream() { if (m_pStream != null) { throw new InvalidOperationException("Stream is already created."); } m_pStream = new RTP_SendStream(this); m_pStream.Disposed += delegate { m_pStream = null; Dispose(); }; SetState(RTP_SourceState.Active); } /// <summary> /// Sends specified RTP packet to the session remote party. /// </summary> /// <param name="packet">RTP packet.</param> /// <returns>Returns packet size in bytes.</returns> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this method is accessed.</exception> /// <exception cref="ArgumentNullException">Is raised when <b>packet</b> is null reference.</exception> /// <exception cref="InvalidOperationException">Is raised when <b>CreateStream</b> method has been not called.</exception> internal int SendRtpPacket(RTP_Packet packet) { if (packet == null) { throw new ArgumentNullException("packet"); } if (m_pStream == null) { throw new InvalidOperationException("RTP stream is not created by CreateStream method."); } SetLastRtpPacket(DateTime.Now); SetState(RTP_SourceState.Active); return Session.SendRtpPacket(m_pStream, packet); } #endregion } }<file_sep>/common/ASC.Core.Common/Context/Impl/SubscriptionManager.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Linq; namespace ASC.Core { public class SubscriptionManager { private readonly ISubscriptionService service; public SubscriptionManager(ISubscriptionService service) { if (service == null) throw new ArgumentNullException("subscriptionManager"); this.service = service; } public void Subscribe(string sourceID, string actionID, string objectID, string recipientID) { var s = new SubscriptionRecord { Tenant = GetTenant(), SourceId = sourceID, ActionId = actionID, RecipientId = recipientID, ObjectId = objectID, Subscribed = true, }; service.SaveSubscription(s); } public void Unsubscribe(string sourceID, string actionID, string objectID, string recipientID) { var s = new SubscriptionRecord { Tenant = GetTenant(), SourceId = sourceID, ActionId = actionID, RecipientId = recipientID, ObjectId = objectID, Subscribed = false, }; service.SaveSubscription(s); } public void UnsubscribeAll(string sourceID, string actionID, string objectID) { service.RemoveSubscriptions(GetTenant(), sourceID, actionID, objectID); } public void UnsubscribeAll(string sourceID, string actionID) { service.RemoveSubscriptions(GetTenant(), sourceID, actionID); } public string[] GetSubscriptionMethod(string sourceID, string actionID, string recipientID) { var m = service.GetSubscriptionMethods(GetTenant(), sourceID, actionID, recipientID) .FirstOrDefault(x => x.ActionId.Equals(actionID, StringComparison.OrdinalIgnoreCase)); if (m == null) { m = service.GetSubscriptionMethods(GetTenant(), sourceID, actionID, recipientID).FirstOrDefault(); } if (m == null) { m = service.GetSubscriptionMethods(GetTenant(), sourceID, actionID, Guid.Empty.ToString()).FirstOrDefault(); } return m != null ? m.Methods : new string[0]; } public string[] GetRecipients(string sourceID, string actionID, string objectID) { return service.GetSubscriptions(GetTenant(), sourceID, actionID, null, objectID) .Where(s => s.Subscribed) .Select(s => s.RecipientId) .ToArray(); } public object GetSubscriptionRecord(string sourceID, string actionID, string recipientID, string objectID) { return service.GetSubscription(GetTenant(), sourceID, actionID, recipientID, objectID); } public string[] GetSubscriptions(string sourceID, string actionID, string recipientID, bool checkSubscribe = true) { return service.GetSubscriptions(GetTenant(), sourceID, actionID, recipientID, null) .Where(s => !checkSubscribe || s.Subscribed) .Select(s => s.ObjectId) .ToArray(); } public bool IsUnsubscribe(string sourceID, string recipientID, string actionID, string objectID) { var s = service.GetSubscription(GetTenant(), sourceID, actionID, recipientID, objectID); if (s == null && !string.IsNullOrEmpty(objectID)) { s = service.GetSubscription(GetTenant(), sourceID, actionID, recipientID, null); } return s != null && !s.Subscribed; } public void UpdateSubscriptionMethod(string sourceID, string actionID, string recipientID, string[] senderNames) { var m = new SubscriptionMethod { Tenant = GetTenant(), SourceId = sourceID, ActionId = actionID, RecipientId = recipientID, Methods = senderNames, }; service.SetSubscriptionMethod(m); } private int GetTenant() { return CoreContext.TenantManager.GetCurrentTenant().TenantId; } } } <file_sep>/common/ASC.ActiveDirectory/ComplexOperations/LdapOperation.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Globalization; using System.Linq; using System.Security; using System.Threading; using System.Threading.Tasks; using ASC.ActiveDirectory.Base; using ASC.ActiveDirectory.Base.Settings; using ASC.ActiveDirectory.Novell; using ASC.Common.Logging; using ASC.Common.Security.Authorizing; using ASC.Common.Threading; using ASC.Core; using ASC.Core.Tenants; using SecurityContext = ASC.Core.SecurityContext; namespace ASC.ActiveDirectory.ComplexOperations { public abstract class LdapOperation: IDisposable { public const string OWNER = "LDAPOwner"; public const string OPERATION_TYPE = "LDAPOperationType"; public const string SOURCE = "LDAPSource"; public const string PROGRESS = "LDAPProgress"; public const string RESULT = "LDAPResult"; public const string ERROR = "LDAPError"; public const string WARNING = "LDAPWarning"; public const string CERT_REQUEST = "LDAPCertRequest"; public const string FINISHED = "LDAPFinished"; private readonly string _culture; public LdapSettings LDAPSettings { get; private set; } public LdapUserImporter Importer { get; private set; } public LdapUserManager LDAPUserManager { get; private set; } protected DistributedTask TaskInfo { get; private set; } protected int Progress { get; private set; } protected string Source { get; private set; } protected string Status { get; set; } protected string Error { get; set; } protected string Warning { get; set; } protected Tenant CurrentTenant { get; private set; } protected ILog Logger { get; private set; } protected CancellationToken CancellationToken { get; private set; } public LdapOperationType OperationType { get; private set; } public static LdapLocalization Resource { get; private set; } protected LdapOperation(LdapSettings settings, Tenant tenant, LdapOperationType operationType, LdapLocalization resource = null) { CurrentTenant = tenant; OperationType = operationType; _culture = Thread.CurrentThread.CurrentCulture.Name; LDAPSettings = settings; Source = ""; Progress = 0; Status = ""; Error = ""; Warning = ""; Source = ""; TaskInfo = new DistributedTask(); Resource = resource ?? new LdapLocalization(); LDAPUserManager = new LdapUserManager(Resource); } public void RunJob(DistributedTask _, CancellationToken cancellationToken) { try { CancellationToken = cancellationToken; CoreContext.TenantManager.SetCurrentTenant(CurrentTenant); SecurityContext.AuthenticateMe(Core.Configuration.Constants.CoreSystem); Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo(_culture); Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(_culture); Logger = LogManager.GetLogger("ASC"); if (LDAPSettings == null) { Error = Resource.LdapSettingsErrorCantGetLdapSettings; Logger.Error("Can't save default LDAP settings."); return; } switch (OperationType) { case LdapOperationType.Save: case LdapOperationType.SaveTest: Logger.InfoFormat("Start '{0}' operation", Enum.GetName(typeof(LdapOperationType), OperationType)); SetProgress(1, Resource.LdapSettingsStatusCheckingLdapSettings); Logger.Debug("PrepareSettings()"); PrepareSettings(LDAPSettings); if (!string.IsNullOrEmpty(Error)) { Logger.DebugFormat("PrepareSettings() Error: {0}", Error); return; } Importer = new NovellLdapUserImporter(LDAPSettings, Resource); if (LDAPSettings.EnableLdapAuthentication) { var ldapSettingsChecker = new NovellLdapSettingsChecker(Importer); SetProgress(5, Resource.LdapSettingsStatusLoadingBaseInfo); var result = ldapSettingsChecker.CheckSettings(); if (result != LdapSettingsStatus.Ok) { if (result == LdapSettingsStatus.CertificateRequest) { TaskInfo.SetProperty(CERT_REQUEST, ldapSettingsChecker.CertificateConfirmRequest); } Error = GetError(result); Logger.DebugFormat("ldapSettingsChecker.CheckSettings() Error: {0}", Error); return; } } break; case LdapOperationType.Sync: case LdapOperationType.SyncTest: Logger.InfoFormat("Start '{0}' operation", Enum.GetName(typeof(LdapOperationType), OperationType)); Importer = new NovellLdapUserImporter(LDAPSettings, Resource); break; default: throw new ArgumentOutOfRangeException(); } Do(); } catch (AuthorizingException authError) { Error = Resource.ErrorAccessDenied; Logger.Error(Error, new SecurityException(Error, authError)); } catch (AggregateException ae) { ae.Flatten().Handle(e => e is TaskCanceledException || e is OperationCanceledException); } catch (TenantQuotaException e) { Error = Resource.LdapSettingsTenantQuotaSettled; Logger.ErrorFormat("TenantQuotaException. {0}", e); } catch (FormatException e) { Error = Resource.LdapSettingsErrorCantCreateUsers; Logger.ErrorFormat("FormatException error. {0}", e); } catch (Exception e) { Error = Resource.LdapSettingsInternalServerError; Logger.ErrorFormat("Internal server error. {0}", e); } finally { try { TaskInfo.SetProperty(FINISHED, true); PublishTaskInfo(); Dispose(); SecurityContext.Logout(); } catch (Exception ex) { Logger.ErrorFormat("LdapOperation finalization problem. {0}", ex); } } } public virtual DistributedTask GetDistributedTask() { FillDistributedTask(); return TaskInfo; } protected virtual void FillDistributedTask() { TaskInfo.SetProperty(SOURCE, Source); TaskInfo.SetProperty(OPERATION_TYPE, OperationType); TaskInfo.SetProperty(OWNER, CurrentTenant.TenantId); TaskInfo.SetProperty(PROGRESS, Progress < 100 ? Progress : 100); TaskInfo.SetProperty(RESULT, Status); TaskInfo.SetProperty(ERROR, Error); TaskInfo.SetProperty(WARNING, Warning); //TaskInfo.SetProperty(PROCESSED, successProcessed); } protected int GetProgress() { return Progress; } const string PROGRESS_STRING = "Progress: {0}% {1} {2}"; public void SetProgress(int? currentPercent = null, string currentStatus = null, string currentSource = null) { if (!currentPercent.HasValue && currentStatus == null && currentSource == null) return; if (currentPercent.HasValue) Progress = currentPercent.Value; if (currentStatus != null) Status = currentStatus; if (currentSource != null) Source = currentSource; Logger.InfoFormat(PROGRESS_STRING, Progress, Status, Source); PublishTaskInfo(); } protected void PublishTaskInfo() { FillDistributedTask(); TaskInfo.PublishChanges(); } protected abstract void Do(); private void PrepareSettings(LdapSettings settings) { if (settings == null) { Logger.Error("Wrong LDAP settings were received from client."); Error = Resource.LdapSettingsErrorCantGetLdapSettings; return; } if (!settings.EnableLdapAuthentication) { settings.Password = string.Empty; return; } if (!string.IsNullOrWhiteSpace(settings.Server)) settings.Server = settings.Server.Trim(); else { Logger.Error("settings.Server is null or empty."); Error = Resource.LdapSettingsErrorCantGetLdapSettings; return; } if (!settings.Server.StartsWith("LDAP://")) settings.Server = "LDAP://" + settings.Server.Trim(); if (!string.IsNullOrWhiteSpace(settings.UserDN)) settings.UserDN = settings.UserDN.Trim(); else { Logger.Error("settings.UserDN is null or empty."); Error = Resource.LdapSettingsErrorCantGetLdapSettings; return; } if (!string.IsNullOrWhiteSpace(settings.LoginAttribute)) settings.LoginAttribute = settings.LoginAttribute.Trim(); else { Logger.Error("settings.LoginAttribute is null or empty."); Error = Resource.LdapSettingsErrorCantGetLdapSettings; return; } if (!string.IsNullOrWhiteSpace(settings.UserFilter)) settings.UserFilter = settings.UserFilter.Trim(); if (!string.IsNullOrWhiteSpace(settings.FirstNameAttribute)) settings.FirstNameAttribute = settings.FirstNameAttribute.Trim(); if (!string.IsNullOrWhiteSpace(settings.SecondNameAttribute)) settings.SecondNameAttribute = settings.SecondNameAttribute.Trim(); if (!string.IsNullOrWhiteSpace(settings.MailAttribute)) settings.MailAttribute = settings.MailAttribute.Trim(); if (!string.IsNullOrWhiteSpace(settings.TitleAttribute)) settings.TitleAttribute = settings.TitleAttribute.Trim(); if (!string.IsNullOrWhiteSpace(settings.MobilePhoneAttribute)) settings.MobilePhoneAttribute = settings.MobilePhoneAttribute.Trim(); if (settings.GroupMembership) { if (!string.IsNullOrWhiteSpace(settings.GroupDN)) settings.GroupDN = settings.GroupDN.Trim(); else { Logger.Error("settings.GroupDN is null or empty."); Error = Resource.LdapSettingsErrorCantGetLdapSettings; return; } if (!string.IsNullOrWhiteSpace(settings.GroupFilter)) settings.GroupFilter = settings.GroupFilter.Trim(); if (!string.IsNullOrWhiteSpace(settings.GroupAttribute)) settings.GroupAttribute = settings.GroupAttribute.Trim(); else { Logger.Error("settings.GroupAttribute is null or empty."); Error = Resource.LdapSettingsErrorCantGetLdapSettings; return; } if (!string.IsNullOrWhiteSpace(settings.UserAttribute)) settings.UserAttribute = settings.UserAttribute.Trim(); else { Logger.Error("settings.UserAttribute is null or empty."); Error = Resource.LdapSettingsErrorCantGetLdapSettings; return; } } if (!settings.Authentication) { settings.Password = string.Empty; return; } if (!string.IsNullOrWhiteSpace(settings.Login)) settings.Login = settings.Login.Trim(); else { Logger.Error("settings.Login is null or empty."); Error = Resource.LdapSettingsErrorCantGetLdapSettings; return; } if (settings.PasswordBytes == null || !settings.PasswordBytes.Any()) { if (!string.IsNullOrEmpty(settings.Password)) { settings.PasswordBytes = LdapHelper.GetPasswordBytes(settings.Password); if (settings.PasswordBytes == null) { Logger.Error("settings.PasswordBytes is null."); Error = Resource.LdapSettingsErrorCantGetLdapSettings; return; } } else { Logger.Error("settings.Password is null or empty."); Error = Resource.LdapSettingsErrorCantGetLdapSettings; return; } } settings.Password = string.Empty; } private static string GetError(LdapSettingsStatus result) { switch (result) { case LdapSettingsStatus.Ok: return string.Empty; case LdapSettingsStatus.WrongServerOrPort: return Resource.LdapSettingsErrorWrongServerOrPort; case LdapSettingsStatus.WrongUserDn: return Resource.LdapSettingsErrorWrongUserDn; case LdapSettingsStatus.IncorrectLDAPFilter: return Resource.LdapSettingsErrorIncorrectLdapFilter; case LdapSettingsStatus.UsersNotFound: return Resource.LdapSettingsErrorUsersNotFound; case LdapSettingsStatus.WrongLoginAttribute: return Resource.LdapSettingsErrorWrongLoginAttribute; case LdapSettingsStatus.WrongGroupDn: return Resource.LdapSettingsErrorWrongGroupDn; case LdapSettingsStatus.IncorrectGroupLDAPFilter: return Resource.LdapSettingsErrorWrongGroupFilter; case LdapSettingsStatus.GroupsNotFound: return Resource.LdapSettingsErrorGroupsNotFound; case LdapSettingsStatus.WrongGroupAttribute: return Resource.LdapSettingsErrorWrongGroupAttribute; case LdapSettingsStatus.WrongUserAttribute: return Resource.LdapSettingsErrorWrongUserAttribute; case LdapSettingsStatus.WrongGroupNameAttribute: return Resource.LdapSettingsErrorWrongGroupNameAttribute; case LdapSettingsStatus.CredentialsNotValid: return Resource.LdapSettingsErrorCredentialsNotValid; case LdapSettingsStatus.ConnectError: return Resource.LdapSettingsConnectError; case LdapSettingsStatus.StrongAuthRequired: return Resource.LdapSettingsStrongAuthRequired; case LdapSettingsStatus.WrongSidAttribute: return Resource.LdapSettingsWrongSidAttribute; case LdapSettingsStatus.TlsNotSupported: return Resource.LdapSettingsTlsNotSupported; case LdapSettingsStatus.DomainNotFound: return Resource.LdapSettingsErrorDomainNotFound; case LdapSettingsStatus.CertificateRequest: return Resource.LdapSettingsStatusCertificateVerification; default: return Resource.LdapSettingsErrorUnknownError; } } public void Dispose() { if (Importer != null) Importer.Dispose(); } } }<file_sep>/module/ASC.MessagingSystem/MessageFactory.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections.Generic; using System.Web; using ASC.Common.Logging; using ASC.Core; namespace ASC.MessagingSystem { static class MessageFactory { private static readonly ILog log = LogManager.GetLogger("ASC.Messaging"); private const string userAgentHeader = "User-Agent"; private const string forwardedHeader = "X-Forwarded-For"; private const string hostHeader = "Host"; private const string refererHeader = "Referer"; public static EventMessage Create(HttpRequest request, string initiator, MessageAction action, MessageTarget target, params string[] description) { try { return new EventMessage { IP = request != null ? request.Headers[forwardedHeader] ?? request.UserHostAddress : null, Initiator = initiator, Date = DateTime.UtcNow, TenantId = CoreContext.TenantManager.GetCurrentTenant().TenantId, UserId = SecurityContext.CurrentAccount.ID, Page = request != null && request.UrlReferrer != null ? request.UrlReferrer.ToString() : null, Action = action, Description = description, Target = target, UAHeader = request != null ? request.Headers[userAgentHeader] : null }; } catch (Exception ex) { log.ErrorFormat("Error while parse Http Request for {0} type of event: {1}", action, ex); return null; } } public static EventMessage Create(MessageUserData userData, Dictionary<string, string> headers, MessageAction action, MessageTarget target, params string[] description) { try { var message = new EventMessage { Date = DateTime.UtcNow, TenantId = userData == null ? CoreContext.TenantManager.GetCurrentTenant().TenantId : userData.TenantId, UserId = userData == null ? SecurityContext.CurrentAccount.ID : userData.UserId, Action = action, Description = description, Target = target }; if (headers != null) { var userAgent = headers.ContainsKey(userAgentHeader) ? headers[userAgentHeader] : null; var forwarded = headers.ContainsKey(forwardedHeader) ? headers[forwardedHeader] : null; var host = headers.ContainsKey(hostHeader) ? headers[hostHeader] : null; var referer = headers.ContainsKey(refererHeader) ? headers[refererHeader] : null; message.IP = forwarded ?? host; message.UAHeader = userAgent; message.Page = referer; } return message; } catch (Exception ex) { log.Error(string.Format("Error while parse Http Message for \"{0}\" type of event: {1}", action, ex)); return null; } } public static EventMessage Create(string initiator, MessageAction action, MessageTarget target, params string[] description) { try { return new EventMessage { Initiator = initiator, Date = DateTime.UtcNow, TenantId = CoreContext.TenantManager.GetCurrentTenant().TenantId, Action = action, Description = description, Target = target }; } catch (Exception ex) { log.Error(string.Format("Error while parse Initiator Message for \"{0}\" type of event: {1}", action, ex)); return null; } } } }<file_sep>/web/studio/ASC.Web.Studio/Products/Community/Modules/Wiki/WikiUC/fckeditor/editor/plugins/ascuser/lang/de.js  FCKLang.AscUserDlgTitle = "Benutzerliste"; FCKLang.AscUserBtn = "Link zum Benutzer einfügen/bearbeiten"; FCKLang.AscUserOwnerAlert = "Wählen Sie einen Benutzer"; FCKLang.AscUserSearchLnkName ="Suche:"; FCKLang.AscUserList = "Benutzerliste:";<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/vCard/ItemCollection.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.Mime.vCard { #region usings using System.Collections; using System.Collections.Generic; #endregion /// <summary> /// vCard item collection. /// </summary> public class ItemCollection : IEnumerable { #region Members private readonly List<Item> m_pItems; #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> internal ItemCollection() { m_pItems = new List<Item>(); } #endregion #region Properties /// <summary> /// Gets number of vCard items in the collection. /// </summary> public int Count { get { return m_pItems.Count; } } #endregion #region Methods /// <summary> /// Adds new vCard item to the collection. /// </summary> /// <param name="name">Item name.</param> /// <param name="parametes">Item parameters.</param> /// <param name="value">Item value.</param> public Item Add(string name, string parametes, string value) { Item item = new Item(name, parametes, value); m_pItems.Add(item); return item; } /// <summary> /// Removes all items with the specified name. /// </summary> /// <param name="name">Item name.</param> public void Remove(string name) { for (int i = 0; i < m_pItems.Count; i++) { if (m_pItems[i].Name.ToLower() == name.ToLower()) { m_pItems.RemoveAt(i); i--; } } } /// <summary> /// Removes specified item from the collection. /// </summary> /// <param name="item">Item to remove.</param> public void Remove(Item item) { m_pItems.Remove(item); } /// <summary> /// Clears all items in the collection. /// </summary> public void Clear() { m_pItems.Clear(); } /// <summary> /// Gets first item with specified name. Returns null if specified item doesn't exists. /// </summary> /// <param name="name">Item name. Name compare is case-insensitive.</param> /// <returns>Returns first item with specified name or null if specified item doesn't exists.</returns> public Item GetFirst(string name) { foreach (Item item in m_pItems) { if (item.Name.ToLower() == name.ToLower()) { return item; } } return null; } /// <summary> /// Gets items with specified name. /// </summary> /// <param name="name">Item name.</param> /// <returns></returns> public Item[] Get(string name) { List<Item> retVal = new List<Item>(); foreach (Item item in m_pItems) { if (item.Name.ToLower() == name.ToLower()) { retVal.Add(item); } } return retVal.ToArray(); } /// <summary> /// Sets first item with specified value. If item doesn't exist, item will be appended to the end. /// If value is null, all items with specified name will be removed. /// Value is encoed as needed and specified item.ParametersString will be updated accordingly. /// </summary> /// <param name="name">Item name.</param> /// <param name="value">Item value.</param> public void SetDecodedValue(string name, string value) { if (value == null) { Remove(name); return; } Item item = GetFirst(name); if (item != null) { item.SetDecodedValue(value); } else { item = new Item(name, "", ""); m_pItems.Add(item); item.SetDecodedValue(value); } } /// <summary> /// Sets first item with specified encoded value. If item doesn't exist, item will be appended to the end. /// If value is null, all items with specified name will be removed. /// </summary> /// <param name="name">Item name.</param> /// <param name="value">Item encoded value.</param> public void SetValue(string name, string value) { SetValue(name, "", value); } /// <summary> /// Sets first item with specified name encoded value. If item doesn't exist, item will be appended to the end. /// If value is null, all items with specified name will be removed. /// </summary> /// <param name="name">Item name.</param> /// <param name="parametes">Item parameters.</param> /// <param name="value">Item encoded value.</param> public void SetValue(string name, string parametes, string value) { if (value == null) { Remove(name); return; } Item item = GetFirst(name); if (item != null) { item.Value = value; } else { m_pItems.Add(new Item(name, parametes, value)); } } /// <summary> /// Gets enumerator. /// </summary> /// <returns></returns> public IEnumerator GetEnumerator() { return m_pItems.GetEnumerator(); } #endregion } }<file_sep>/common/ASC.Core.Common/Core/DBResourceManager.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Configuration; using System.Globalization; using System.Linq; using System.Reflection; using System.Resources; using System.Runtime.Caching; using System.Text.RegularExpressions; using ASC.Core; using System.Web; using ASC.Common.Data; using ASC.Common.Data.Sql; using ASC.Common.Data.Sql.Expressions; using ASC.Common.Logging; namespace TMResourceData { public class DBResourceManager : ResourceManager { public static bool WhiteLableEnabled = false; public static bool ResourcesFromDataBase { get; private set; } private static readonly ILog log = LogManager.GetLogger("ASC.Resources"); private readonly ConcurrentDictionary<string, ResourceSet> resourceSets = new ConcurrentDictionary<string, ResourceSet>(); static DBResourceManager() { ResourcesFromDataBase = string.Equals(ConfigurationManagerExtension.AppSettings["resources.from-db"], "true"); } public DBResourceManager(string filename, Assembly assembly) : base(filename, assembly) { } public static void PatchAssemblies() { AppDomain.CurrentDomain.AssemblyLoad += (_, a) => PatchAssembly(a.LoadedAssembly); Array.ForEach(AppDomain.CurrentDomain.GetAssemblies(), a => PatchAssembly(a)); } public static void PatchAssembly(Assembly a, bool onlyAsc = true) { if (!onlyAsc || Accept(a)) { var types = new Type[0]; try { types = a.GetTypes(); } catch (ReflectionTypeLoadException rtle) { log.WarnFormat("Can not GetTypes() from assembly {0}, try GetExportedTypes(), error: {1}", a.FullName, rtle.Message); foreach (var e in rtle.LoaderExceptions) { log.Info(e.Message); } try { types = a.GetExportedTypes(); } catch (Exception err) { log.ErrorFormat("Can not GetExportedTypes() from assembly {0}: {1}", a.FullName, err.Message); } } foreach (var type in types) { var prop = type.GetProperty("ResourceManager", BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public); if (prop != null) { var rm = (ResourceManager)prop.GetValue(type); if (!(rm is DBResourceManager)) { var dbrm = new DBResourceManager(rm.BaseName, a); type.InvokeMember("resourceMan", BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.SetField, null, type, new object[] { dbrm }); } } } } } private static bool Accept(Assembly a) { var n = a.GetName().Name; return (n.StartsWith("ASC.") || n.StartsWith("App_GlobalResources")) && a.GetManifestResourceNames().Any(); } public override Type ResourceSetType { get { return typeof(DBResourceSet); } } protected override ResourceSet InternalGetResourceSet(CultureInfo culture, bool createIfNotExists, bool tryParents) { ResourceSet set; resourceSets.TryGetValue(culture.Name, out set); if (set == null) { var invariant = culture == CultureInfo.InvariantCulture ? base.InternalGetResourceSet(CultureInfo.InvariantCulture, true, true) : null; set = new DBResourceSet(invariant, culture, BaseName); resourceSets.AddOrUpdate(culture.Name, set, (k, v) => set); } return set; } class DBResourceSet : ResourceSet { private const string NEUTRAL_CULTURE = "Neutral"; private static readonly TimeSpan cacheTimeout = TimeSpan.FromMinutes(120); // for performance private readonly object locker = new object(); private readonly MemoryCache cache; private readonly ResourceSet invariant; private readonly string culture; private readonly string filename; static DBResourceSet() { try { var defaultValue = ((int)cacheTimeout.TotalMinutes).ToString(); cacheTimeout = TimeSpan.FromMinutes(Convert.ToInt32(ConfigurationManagerExtension.AppSettings["resources.cache-timeout"] ?? defaultValue)); } catch (Exception err) { log.Error(err); } } public DBResourceSet(ResourceSet invariant, CultureInfo culture, string filename) { if (culture == null) { throw new ArgumentNullException("culture"); } if (string.IsNullOrEmpty(filename)) { throw new ArgumentNullException("filename"); } this.invariant = invariant; this.culture = invariant != null ? NEUTRAL_CULTURE : culture.Name; this.filename = filename.Split('.').Last() + ".resx"; cache = MemoryCache.Default; } public override string GetString(string name, bool ignoreCase) { var result = (string)null; try { var dic = GetResources(); dic.TryGetValue(name, out result); } catch (Exception err) { log.ErrorFormat("Can not get resource from {0} for {1}: GetString({2}), {3}", filename, culture, name, err); } if (invariant != null && result == null) { result = invariant.GetString(name, ignoreCase); } if (WhiteLableEnabled) { result = WhiteLabelHelper.ReplaceLogo(name, result); } return result; } public override IDictionaryEnumerator GetEnumerator() { var result = new Hashtable(); if (invariant != null) { foreach (DictionaryEntry e in invariant) { result[e.Key] = e.Value; } } try { var dic = GetResources(); foreach (var e in dic) { result[e.Key] = e.Value; } } catch (Exception err) { log.Error(err); } return result.GetEnumerator(); } private Dictionary<string, string> GetResources() { var key = string.Format("{0}/{1}", filename, culture); var dic = cache.Get(key) as Dictionary<string, string>; if (dic == null) { lock (locker) { dic = cache.Get(key) as Dictionary<string, string>; if (dic == null) { var policy = cacheTimeout == TimeSpan.Zero ? null : new CacheItemPolicy() { AbsoluteExpiration = DateTimeOffset.Now.Add(cacheTimeout) }; cache.Set(key, dic = LoadResourceSet(filename, culture), policy); } } } return dic; } private static Dictionary<string, string> LoadResourceSet(string filename, string culture) { using (var dbManager = DbManager.FromHttpContext("tmresource")) { var q = new SqlQuery("res_data d") .Select("d.title", "d.textvalue") .InnerJoin("res_files f", Exp.EqColumns("f.id", "d.fileid")) .Where("f.resname", filename) .Where("d.culturetitle", culture); return dbManager.ExecuteList(q) .ToDictionary(r => (string) r[0], r => (string) r[1], StringComparer.InvariantCultureIgnoreCase); } } } } public class WhiteLabelHelper { private static readonly ILog log = LogManager.GetLogger("ASC.Resources"); private static readonly ConcurrentDictionary<int, string> whiteLabelDictionary = new ConcurrentDictionary<int, string>(); private static readonly string replPattern = ConfigurationManagerExtension.AppSettings["resources.whitelabel-text.replacement.pattern"] ?? "(?<=[^@/\\\\]|^)({0})(?!\\.com)"; public static string DefaultLogoText = ""; public static void SetNewText(int tenantId, string newText) { try { whiteLabelDictionary.AddOrUpdate(tenantId, r => newText, (i, s) => newText); } catch (Exception e) { log.Error("SetNewText", e); } } public static void RestoreOldText(int tenantId) { try { string text; whiteLabelDictionary.TryRemove(tenantId, out text); } catch (Exception e) { log.Error("RestoreOldText", e); } } internal static string ReplaceLogo(string resourceName, string resourceValue) { if (string.IsNullOrEmpty(resourceValue)) { return resourceValue; } if (HttpContext.Current != null) //if in Notify Service or other process without HttpContext { try { var tenant = CoreContext.TenantManager.GetCurrentTenant(false); if (tenant == null) return resourceValue; string newText; if (whiteLabelDictionary.TryGetValue(tenant.TenantId, out newText)) { var newTextReplacement = newText; if (resourceValue.Contains("<") && resourceValue.Contains(">") || resourceName.StartsWith("pattern_")) { newTextReplacement = HttpUtility.HtmlEncode(newTextReplacement); } if (resourceValue.Contains("{0")) { //Hack for string which used in string.Format newTextReplacement = newTextReplacement.Replace("{", "{{").Replace("}", "}}"); } var pattern = string.Format(replPattern, DefaultLogoText); //Hack for resource strings with mails looked like ...@onlyoffice... or with website http://www.onlyoffice.com link or with the https://www.facebook.com/pages/OnlyOffice/833032526736775 return Regex.Replace(resourceValue, pattern, newTextReplacement, RegexOptions.IgnoreCase).Replace("™", ""); } } catch (Exception e) { log.Error("ReplaceLogo", e); } } return resourceValue; } } } <file_sep>/web/studio/ASC.Web.Studio/Products/Community/Modules/Wiki/WikiUC/fckeditor/editor/plugins/ascuser/lang/fr.js  FCKLang.AscUserDlgTitle = "Liste des utilisateurs"; FCKLang.AscUserBtn = "Insérer/Modifier lien vers l'utilisateur"; FCKLang.AscUserOwnerAlert = "Sélectionnez un utilisateur."; FCKLang.AscUserSearchLnkName ="Recherche:"; FCKLang.AscUserList = "Liste des utilisateurs:";<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/MIME/MIME_b_Provider.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.MIME { #region usings using System; using System.Collections.Generic; using System.Reflection; using IO; #endregion /// <summary> /// This class represent MIME entity body provider. /// </summary> public class MIME_b_Provider { #region Members private readonly Dictionary<string, Type> m_pBodyTypes; #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> public MIME_b_Provider() { m_pBodyTypes = new Dictionary<string, Type>(StringComparer.CurrentCultureIgnoreCase); m_pBodyTypes.Add("message/rfc822", typeof (MIME_b_MessageRfc822)); m_pBodyTypes.Add("multipart/alternative", typeof (MIME_b_MultipartAlternative)); m_pBodyTypes.Add("multipart/digest", typeof (MIME_b_MultipartDigest)); m_pBodyTypes.Add("multipart/encrypted", typeof (MIME_b_MultipartEncrypted)); m_pBodyTypes.Add("multipart/form-data", typeof (MIME_b_MultipartFormData)); m_pBodyTypes.Add("multipart/mixed", typeof (MIME_b_MultipartMixed)); m_pBodyTypes.Add("multipart/parallel", typeof (MIME_b_MultipartParallel)); m_pBodyTypes.Add("multipart/related", typeof (MIME_b_MultipartRelated)); m_pBodyTypes.Add("multipart/report", typeof (MIME_b_MultipartReport)); m_pBodyTypes.Add("multipart/signed", typeof (MIME_b_MultipartSigned)); } #endregion #region Methods /// <summary> /// Parses MIME entity body from specified stream. /// </summary> /// <param name="owner">Owner MIME entity.</param> /// <param name="stream">Stream from where to parse entity body.</param> /// <param name="defaultContentType">Default content type.</param> /// <returns>Returns parsed body.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>owner</b>, <b>strean</b> or <b>defaultContentType</b> is null reference.</exception> /// <exception cref="ParseException">Is raised when header field parsing errors.</exception> public MIME_b Parse(MIME_Entity owner, SmartStream stream, MIME_h_ContentType defaultContentType) { if (owner == null) { throw new ArgumentNullException("owner"); } if (stream == null) { throw new ArgumentNullException("stream"); } if (defaultContentType == null) { throw new ArgumentNullException("defaultContentType"); } string mediaType = defaultContentType.TypeWithSubype; string mediaTypeWithParams = defaultContentType.ToString().Split(':')[1].TrimStart(' '); if (owner.ContentType != null) { mediaType = owner.ContentType.TypeWithSubype; mediaTypeWithParams = owner.ContentType.ToString().Split(':')[1].TrimStart(' '); } Type bodyType = null; // We have exact body provider for specified mediaType. if (m_pBodyTypes.ContainsKey(mediaType)) { bodyType = m_pBodyTypes[mediaType]; } // Use default mediaType. else { // Registered list of mediaTypes are available: http://www.iana.org/assignments/media-types/. string mediaRootType = mediaType.Split('/')[0].ToLowerInvariant(); if (mediaRootType == "application") { bodyType = typeof (MIME_b_Application); } else if (mediaRootType == "audio") { bodyType = typeof (MIME_b_Audio); } else if (mediaRootType == "image") { bodyType = typeof (MIME_b_Image); } else if (mediaRootType == "message") { bodyType = typeof (MIME_b_Message); } else if (mediaRootType == "multipart") { bodyType = typeof (MIME_b_Multipart); } else if (mediaRootType == "text") { bodyType = typeof (MIME_b_Text); } else if (mediaRootType == "video") { bodyType = typeof (MIME_b_Video); } else { throw new ParseException("Invalid media-type '" + mediaType + "'."); } } return (MIME_b) bodyType.GetMethod("Parse", BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy).Invoke(null, new object[] { owner, mediaTypeWithParams, stream }); } #endregion } }<file_sep>/common/ASC.Core.Common/Billing/CouponManager.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Net; using System.Net.Http; using System.Security.Cryptography; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Web; using ASC.Common.Logging; using Newtonsoft.Json; namespace ASC.Core.Common.Billing { public class CouponManager { private static IEnumerable<AvangateProduct> Products { get; set; } private static IEnumerable<string> Groups { get; set; } private static readonly int Percent; private static readonly int Schedule; private static readonly string VendorCode; private static readonly byte[] Secret; private static readonly Uri BaseAddress; private static readonly string ApiVersion; private static readonly SemaphoreSlim SemaphoreSlim = new SemaphoreSlim(1, 1); private static readonly ILog Log; static CouponManager() { SemaphoreSlim = new SemaphoreSlim(1, 1); Log = LogManager.GetLogger("ASC"); try { var cfg = (AvangateCfgSectionHandler)ConfigurationManagerExtension.GetSection("avangate"); Secret = Encoding.UTF8.GetBytes(cfg.Secret); VendorCode = cfg.Vendor; Percent = cfg.Percent; Schedule = cfg.Schedule; BaseAddress = new Uri(cfg.BaseAddress); ApiVersion = "/rest/" + cfg.ApiVersion.TrimStart('/'); Groups = (cfg.Groups ?? "").Split(',', '|', ' '); } catch (Exception e) { Secret = Encoding.UTF8.GetBytes(""); VendorCode = ""; Percent = AvangateCfgSectionHandler.DefaultPercent; Schedule = AvangateCfgSectionHandler.DefaultShedule; BaseAddress = new Uri(AvangateCfgSectionHandler.DefaultAdress); ApiVersion = AvangateCfgSectionHandler.DefaultApiVersion; Groups = new List<string>(); Log.Fatal(e); } } public static string CreateCoupon() { return CreatePromotionAsync().Result; } private static async Task<string> CreatePromotionAsync() { try { using (var httpClient = PrepaireClient()) using (var content = new StringContent(await Promotion.GeneratePromotion(Percent, Schedule), Encoding.Default, "application/json")) using (var response = await httpClient.PostAsync(string.Format("{0}/promotions/", ApiVersion), content)) { if (!response.IsSuccessStatusCode) throw new HttpException((int) response.StatusCode, response.ReasonPhrase); var result = await response.Content.ReadAsStringAsync(); await Task.Delay(1000 - DateTime.UtcNow.Millisecond); // otherwise authorize exception var createdPromotion = JsonConvert.DeserializeObject<Promotion>(result); return createdPromotion.Coupon.Code; } } catch (Exception ex) { Log.Error(ex.Message, ex); throw; } } internal static async Task<IEnumerable<AvangateProduct>> GetProducts() { if (Products != null) return Products; await SemaphoreSlim.WaitAsync(); if (Products != null) { SemaphoreSlim.Release(); return Products; } try { using (var httpClient = PrepaireClient()) using (var response = await httpClient.GetAsync(string.Format("{0}/products/?Limit=1000&Enabled=true", ApiVersion))) { if (!response.IsSuccessStatusCode) throw new HttpException((int) response.StatusCode, response.ReasonPhrase); var result = await response.Content.ReadAsStringAsync(); Log.Debug(result); var products = JsonConvert.DeserializeObject<List<AvangateProduct>>(result); products = products.Where(r => r.ProductGroup != null && Groups.Contains(r.ProductGroup.Code)).ToList(); return Products = products; } } catch (Exception ex) { Log.Error(ex.Message, ex); throw; } finally { SemaphoreSlim.Release(); } } private static HttpClient PrepaireClient() { ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls; const string applicationJson = "application/json"; var httpClient = new HttpClient {BaseAddress = BaseAddress, Timeout = TimeSpan.FromMinutes(3)}; httpClient.DefaultRequestHeaders.TryAddWithoutValidation("accept", applicationJson); httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", applicationJson); httpClient.DefaultRequestHeaders.TryAddWithoutValidation("X-Avangate-Authentication", CreateAuthHeader()); return httpClient; } private static string CreateAuthHeader() { using (var hmac = new HMACMD5(Secret)) { var date = DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss"); var hash = VendorCode.Length + VendorCode + date.Length + date; var data = hmac.ComputeHash(Encoding.UTF8.GetBytes(hash)); var sBuilder = new StringBuilder(); foreach (var t in data) { sBuilder.Append(t.ToString("x2")); } var stringBuilder = new StringBuilder(); stringBuilder.AppendFormat("code='{0}' ", VendorCode); stringBuilder.AppendFormat("date='{0}' ", date); stringBuilder.AppendFormat("hash='{0}'", sBuilder); return stringBuilder.ToString(); } } } class Promotion { public string Code { get; set; } public string Name { get; set; } public string Type { get; set; } public string StartDate { get; set; } public string EndDate { get; set; } public bool Enabled { get; set; } public int MaximumOrdersNumber { get; set; } public bool InstantDiscount { get; set; } public string ChannelType { get; set; } public string ApplyRecurring { get; set; } public Coupon Coupon { get; set; } public Discount Discount { get; set; } public IEnumerable<CouponProduct> Products { get; set; } public int PublishToAffiliatesNetwork {get; set;} public int AutoApply { get; set; } public static async Task<string> GeneratePromotion(int percent, int schedule) { try { var tenant = CoreContext.TenantManager.GetCurrentTenant(); var startDate = DateTime.UtcNow.Date; var endDate = startDate.AddDays(schedule); var code = tenant.TenantAlias; var promotion = new Promotion { Type = "REGULAR", Enabled = true, MaximumOrdersNumber = 1, InstantDiscount = false, ChannelType = "ECOMMERCE", ApplyRecurring = "NONE", PublishToAffiliatesNetwork = 0, AutoApply = 0, StartDate = startDate.ToString("yyyy-MM-dd"), EndDate = endDate.ToString("yyyy-MM-dd"), Name = string.Format("{0} {1}% off", code, percent), Coupon = new Coupon {Type = "SINGLE", Code = code}, Discount = new Discount {Type = "PERCENT", Value = percent}, Products = (await CouponManager.GetProducts()).Select(r => new CouponProduct { Code = r.ProductCode }) }; return JsonConvert.SerializeObject(promotion); } catch (Exception ex) { LogManager.GetLogger("ASC").Error(ex.Message, ex); throw; } } } class Coupon { public string Type { get; set; } public string Code { get; set; } } class Discount { public string Type { get; set; } public int Value { get; set; } } class AvangateProduct { public string ProductCode { get; set; } public string ProductName { get; set; } public AvangateProductGroup ProductGroup { get; set; } } class AvangateProductGroup { public string Name { get; set; } public string Code { get; set; } } class CouponProduct { public string Code { get; set; } } class AvangateCfgSectionHandler : ConfigurationSection { public const string DefaultAdress = "https://api.avangate.com/"; public const string DefaultApiVersion = "4.0"; public const int DefaultPercent = 5; public const int DefaultShedule = 10; [ConfigurationProperty("secret")] public string Secret { get { return (string)this["secret"]; } } [ConfigurationProperty("vendor")] public string Vendor { get { return (string)this["vendor"]; } set { this["vendor"] = value; } } [ConfigurationProperty("percent", DefaultValue = DefaultPercent)] public int Percent { get { return Convert.ToInt32(this["percent"]); } set { this["percent"] = value; } } [ConfigurationProperty("schedule", DefaultValue = DefaultShedule)] public int Schedule { get { return Convert.ToInt32(this["schedule"]); } set { this["schedule"] = value; } } [ConfigurationProperty("groups")] public string Groups { get { return (string)this["groups"]; } } [ConfigurationProperty("address", DefaultValue = DefaultAdress)] public string BaseAddress { get { return (string)this["address"]; } set { this["address"] = value; } } [ConfigurationProperty("apiVersion", DefaultValue = DefaultApiVersion)] public string ApiVersion { get { return (string)this["apiVersion"]; } set { this["apiVersion"] = value; } } } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/UDP/UDP_Server.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.UDP { #region usings using System; using System.Collections.Generic; using System.Diagnostics; using System.Net; using System.Net.Sockets; using System.Threading; #endregion #region Delegates Declarations /// <summary> /// Represents the method that will handle the <b>UdpServer.PacketReceived</b> event. /// </summary> /// <param name="e">Event data.</param> public delegate void PacketReceivedHandler(UDP_PacketEventArgs e); #endregion /// <summary> /// This class implements generic UDP server. /// </summary> public class UDP_Server { #region Events /// <summary> /// This event is raised when unexpected error happens. /// </summary> public event ErrorEventHandler Error = null; /// <summary> /// This event is raised when new UDP packet received. /// </summary> public event PacketReceivedHandler PacketReceived = null; #endregion #region Members private long m_BytesReceived; private long m_BytesSent; private bool m_IsDisposed; private bool m_IsRunning; private int m_MaxQueueSize = 200; private int m_MTU = 1400; private long m_PacketsReceived; private long m_PacketsSent; private IPEndPoint[] m_pBindings; private Queue<UdpPacket> m_pQueuedPackets; private UDP_ProcessMode m_ProcessMode = UDP_ProcessMode.Sequential; private CircleCollection<Socket> m_pSendSocketsIPv4; private CircleCollection<Socket> m_pSendSocketsIPv6; private List<Socket> m_pSockets; private DateTime m_StartTime; #endregion #region Properties /// <summary> /// Gets or sets IP end point where UDP server is binded. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> /// <exception cref="ArgumentNullException">Is raised when null value is passed.</exception> public IPEndPoint[] Bindings { get { if (m_IsDisposed) { throw new ObjectDisposedException("UdpServer"); } return m_pBindings; } set { if (m_IsDisposed) { throw new ObjectDisposedException("UdpServer"); } if (value == null) { throw new ArgumentNullException(); } // See if changed. Also if server running we must restart it. bool changed = false; if (m_pBindings == null) { changed = true; } else if (m_pBindings.Length != value.Length) { changed = true; } else { for (int i = 0; i < m_pBindings.Length; i++) { if (!m_pBindings[i].Equals(value[i])) { changed = true; break; } } } if (changed) { m_pBindings = value; Restart(); } } } /// <summary> /// Gets how many bytes this UDP server has received since start. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised whan UDP server is not running and this property is accessed.</exception> public long BytesReceived { get { if (m_IsDisposed) { throw new ObjectDisposedException("UdpServer"); } if (!m_IsRunning) { throw new InvalidOperationException("UDP server is not running."); } return m_BytesReceived; } } /// <summary> /// Gets how many bytes this UDP server has sent since start. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised whan UDP server is not running and this property is accessed.</exception> public long BytesSent { get { if (m_IsDisposed) { throw new ObjectDisposedException("UdpServer"); } if (!m_IsRunning) { throw new InvalidOperationException("UDP server is not running."); } return m_BytesSent; } } /// <summary> /// Gets if this object is disposed. /// </summary> public bool IsDisposed { get { return m_IsDisposed; } } /// <summary> /// Gets if UDP server is running. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> public bool IsRunning { get { if (m_IsDisposed) { throw new ObjectDisposedException("UdpServer"); } return m_IsRunning; } } /// <summary> /// Gets maximum UDP packets to queue. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> public int MaxQueueSize { get { if (m_IsDisposed) { throw new ObjectDisposedException("UdpServer"); } return m_MaxQueueSize; } } /// <summary> /// Gets or sets maximum network transmission unit. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when server is running and this property value is tried to set.</exception> public int MTU { get { if (m_IsDisposed) { throw new ObjectDisposedException("UdpServer"); } return m_MTU; } set { if (m_IsDisposed) { throw new ObjectDisposedException("UdpServer"); } if (m_IsRunning) { throw new InvalidOperationException( "MTU value can be changed only if UDP server is not running."); } m_MTU = value; } } /// <summary> /// Gets how many UDP packets this UDP server has received since start. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised whan UDP server is not running and this property is accessed.</exception> public long PacketsReceived { get { if (m_IsDisposed) { throw new ObjectDisposedException("UdpServer"); } if (!m_IsRunning) { throw new InvalidOperationException("UDP server is not running."); } return m_PacketsReceived; } } /// <summary> /// Gets how many UDP packets this UDP server has sent since start. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised whan UDP server is not running and this property is accessed.</exception> public long PacketsSent { get { if (m_IsDisposed) { throw new ObjectDisposedException("UdpServer"); } if (!m_IsRunning) { throw new InvalidOperationException("UDP server is not running."); } return m_PacketsSent; } } /// <summary> /// Gets or sets UDP packets process mode. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when server is running and this property value is tried to set.</exception> public UDP_ProcessMode ProcessMode { get { if (m_IsDisposed) { throw new ObjectDisposedException("UdpServer"); } return m_ProcessMode; } set { if (m_IsDisposed) { throw new ObjectDisposedException("UdpServer"); } if (m_IsRunning) { throw new InvalidOperationException( "ProcessMode value can be changed only if UDP server is not running."); } m_ProcessMode = value; } } /// <summary> /// Gets time when server was started. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised whan UDP server is not running and this property is accessed.</exception> public DateTime StartTime { get { if (m_IsDisposed) { throw new ObjectDisposedException("UdpServer"); } if (!m_IsRunning) { throw new InvalidOperationException("UDP server is not running."); } return m_StartTime; } } #endregion #region Methods /// <summary> /// Cleans up any resources being used. /// </summary> public void Dispose() { if (m_IsDisposed) { return; } m_IsDisposed = false; Stop(); // Release all events. Error = null; PacketReceived = null; } /// <summary> /// Starts UDP server. /// </summary> public void Start() { if (m_IsRunning) { return; } m_IsRunning = true; m_StartTime = DateTime.Now; m_pQueuedPackets = new Queue<UdpPacket>(); // Run only if we have some listening point. if (m_pBindings != null) { // We must replace IPAddress.Any to all available IPs, otherwise it's impossible to send // reply back to UDP packet sender on same local EP where packet received. This is very // important when clients are behind NAT. List<IPEndPoint> listeningEPs = new List<IPEndPoint>(); foreach (IPEndPoint ep in m_pBindings) { if (ep.Address.Equals(IPAddress.Any)) { // Add localhost. IPEndPoint epLocalhost = new IPEndPoint(IPAddress.Loopback, ep.Port); if (!listeningEPs.Contains(epLocalhost)) { listeningEPs.Add(epLocalhost); } // Add all host IPs. foreach (IPAddress ip in Dns.GetHostAddresses("")) { IPEndPoint epNew = new IPEndPoint(ip, ep.Port); if (!listeningEPs.Contains(epNew)) { listeningEPs.Add(epNew); } } } else { if (!listeningEPs.Contains(ep)) { listeningEPs.Add(ep); } } } // Create sockets. m_pSockets = new List<Socket>(); foreach (IPEndPoint ep in listeningEPs) { try { m_pSockets.Add(Core.CreateSocket(ep, ProtocolType.Udp)); } catch (Exception x) { OnError(x); } } // Create round-robin send sockets. NOTE: We must skip localhost, it can't be used // for sending out of server. m_pSendSocketsIPv4 = new CircleCollection<Socket>(); m_pSendSocketsIPv6 = new CircleCollection<Socket>(); foreach (Socket socket in m_pSockets) { if ((socket.LocalEndPoint).AddressFamily == AddressFamily.InterNetwork) { if (!((IPEndPoint) socket.LocalEndPoint).Address.Equals(IPAddress.Loopback)) { m_pSendSocketsIPv4.Add(socket); } } else if ((socket.LocalEndPoint).AddressFamily == AddressFamily.InterNetworkV6) { m_pSendSocketsIPv6.Add(socket); } } Thread tr = new Thread(ProcessIncomingUdp); tr.Start(); Thread tr2 = new Thread(ProcessQueuedPackets); tr2.Start(); } } /// <summary> /// Stops UDP server. /// </summary> public void Stop() { if (!m_IsRunning) { return; } m_IsRunning = false; m_pQueuedPackets = null; // Close sockets. foreach (Socket socket in m_pSockets) { socket.Close(); } m_pSockets = null; m_pSendSocketsIPv4 = null; m_pSendSocketsIPv6 = null; } /// <summary> /// Restarts running server. If server is not running, this methods has no efffect. /// </summary> public void Restart() { if (m_IsRunning) { Stop(); Start(); } } /// <summary> /// Sends specified UDP packet to the specified remote end point. /// </summary> /// <param name="packet">UDP packet to send.</param> /// <param name="offset">Offset in the buffer.</param> /// <param name="count">Number of bytes to send.</param> /// <param name="remoteEP">Remote end point.</param> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised whan UDP server is not running and this method is accessed.</exception> /// <exception cref="ArgumentNullException">Is raised when any of the arumnets is null.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> public void SendPacket(byte[] packet, int offset, int count, IPEndPoint remoteEP) { IPEndPoint localEP = null; SendPacket(packet, offset, count, remoteEP, out localEP); } /// <summary> /// Sends specified UDP packet to the specified remote end point. /// </summary> /// <param name="packet">UDP packet to send.</param> /// <param name="offset">Offset in the buffer.</param> /// <param name="count">Number of bytes to send.</param> /// <param name="remoteEP">Remote end point.</param> /// <param name="localEP">Returns local IP end point which was used to send UDP packet.</param> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised whan UDP server is not running and this method is accessed.</exception> /// <exception cref="ArgumentNullException">Is raised when any of the arumnets is null.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> public void SendPacket(byte[] packet, int offset, int count, IPEndPoint remoteEP, out IPEndPoint localEP) { if (m_IsDisposed) { throw new ObjectDisposedException("UdpServer"); } if (!m_IsRunning) { throw new InvalidOperationException("UDP server is not running."); } if (packet == null) { throw new ArgumentNullException("packet"); } if (remoteEP == null) { throw new ArgumentNullException("remoteEP"); } localEP = null; SendPacket(null, packet, offset, count, remoteEP, out localEP); } /// <summary> /// Sends specified UDP packet to the specified remote end point. /// </summary> /// <param name="localEP">Local end point to use for sending.</param> /// <param name="packet">UDP packet to send.</param> /// <param name="offset">Offset in the buffer.</param> /// <param name="count">Number of bytes to send.</param> /// <param name="remoteEP">Remote end point.</param> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised whan UDP server is not running and this method is accessed.</exception> /// <exception cref="ArgumentNullException">Is raised when any of the arumnets is null.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> public void SendPacket(IPEndPoint localEP, byte[] packet, int offset, int count, IPEndPoint remoteEP) { if (m_IsDisposed) { throw new ObjectDisposedException("UdpServer"); } if (!m_IsRunning) { throw new InvalidOperationException("UDP server is not running."); } if (packet == null) { throw new ArgumentNullException("packet"); } if (localEP == null) { throw new ArgumentNullException("localEP"); } if (remoteEP == null) { throw new ArgumentNullException("remoteEP"); } if (localEP.AddressFamily != remoteEP.AddressFamily) { throw new ArgumentException("Argumnet localEP and remoteEP AddressFamily won't match."); } // Search specified local end point socket. Socket socket = null; if (localEP.AddressFamily == AddressFamily.InterNetwork) { foreach (Socket s in m_pSendSocketsIPv4.ToArray()) { if (localEP.Equals(s.LocalEndPoint)) { socket = s; break; } } } else if (localEP.AddressFamily == AddressFamily.InterNetworkV6) { foreach (Socket s in m_pSendSocketsIPv6.ToArray()) { if (localEP.Equals(s.LocalEndPoint)) { socket = s; break; } } } else { throw new ArgumentException("Argument 'localEP' has unknown AddressFamily."); } // We don't have specified local end point. if (socket == null) { throw new ArgumentException("Specified local end point '" + localEP + "' doesn't exist."); } IPEndPoint lEP = null; SendPacket(socket, packet, offset, count, remoteEP, out lEP); } /// <summary> /// Gets suitable local IP end point for the specified remote endpoint. /// If there are multiple sending local end points, they will be load-balanched with round-robin. /// </summary> /// <param name="remoteEP">Remote end point.</param> /// <returns>Returns local IP end point.</returns> /// <exception cref="ArgumentNullException">Is raised when argument <b>remoteEP</b> is null.</exception> /// <exception cref="ArgumentException">Is raised when argument <b>remoteEP</b> has invalid value.</exception> /// <exception cref="InvalidOperationException">Is raised when no suitable IPv4 or IPv6 socket for <b>remoteEP</b>.</exception> public IPEndPoint GetLocalEndPoint(IPEndPoint remoteEP) { if (remoteEP == null) { throw new ArgumentNullException("remoteEP"); } if (remoteEP.AddressFamily == AddressFamily.InterNetwork) { // We don't have any IPv4 local end point. if (m_pSendSocketsIPv4.Count == 0) { throw new InvalidOperationException( "There is no suitable IPv4 local end point in this.Bindings."); } return (IPEndPoint) m_pSendSocketsIPv4.Next().LocalEndPoint; } else if (remoteEP.AddressFamily == AddressFamily.InterNetworkV6) { // We don't have any IPv6 local end point. if (m_pSendSocketsIPv6.Count == 0) { throw new InvalidOperationException( "There is no suitable IPv6 local end point in this.Bindings."); } return (IPEndPoint) m_pSendSocketsIPv6.Next().LocalEndPoint; } else { throw new ArgumentException("Argument 'remoteEP' has unknown AddressFamily."); } } #endregion #region Internal methods /// <summary> /// Sends specified UDP packet to the specified remote end point. /// </summary> /// <param name="socket">UDP socket to use for data sending.</param> /// <param name="packet">UDP packet to send.</param> /// <param name="offset">Offset in the buffer.</param> /// <param name="count">Number of bytes to send.</param> /// <param name="remoteEP">Remote end point.</param> /// <param name="localEP">Returns local IP end point which was used to send UDP packet.</param> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised whan UDP server is not running and this method is accessed.</exception> /// <exception cref="ArgumentNullException">Is raised when any of the arumnets is null.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> internal void SendPacket(Socket socket, byte[] packet, int offset, int count, IPEndPoint remoteEP, out IPEndPoint localEP) { // Round-Robin all local end points, if no end point specified. if (socket == null) { // Get right IP address family socket which matches remote end point. if (remoteEP.AddressFamily == AddressFamily.InterNetwork) { if (m_pSendSocketsIPv4.Count == 0) { throw new ArgumentException( "There is no suitable IPv4 local end point in this.Bindings."); } socket = m_pSendSocketsIPv4.Next(); } else if (remoteEP.AddressFamily == AddressFamily.InterNetworkV6) { if (m_pSendSocketsIPv6.Count == 0) { throw new ArgumentException( "There is no suitable IPv6 local end point in this.Bindings."); } socket = m_pSendSocketsIPv6.Next(); } else { throw new ArgumentException("Invalid remote end point address family."); } } // Send packet. socket.SendTo(packet, 0, count, SocketFlags.None, remoteEP); localEP = (IPEndPoint) socket.LocalEndPoint; m_BytesSent += count; m_PacketsSent++; } #endregion #region Utility methods /// <summary> /// Processes incoming UDP data and queues it for processing. /// </summary> private void ProcessIncomingUdp() { // Create Round-Robin for listening points. CircleCollection<Socket> listeningEPs = new CircleCollection<Socket>(); foreach (Socket socket in m_pSockets) { listeningEPs.Add(socket); } byte[] buffer = new byte[m_MTU]; while (m_IsRunning) { try { // Maximum allowed UDP queued packts exceeded. if (m_pQueuedPackets.Count >= m_MaxQueueSize) { Thread.Sleep(1); } else { // Roun-Robin sockets. bool receivedData = false; for (int i = 0; i < listeningEPs.Count; i++) { Socket socket = listeningEPs.Next(); // Read data only when there is some, otherwise we block thread. if (socket.Poll(0, SelectMode.SelectRead)) { // Receive data. EndPoint remoteEP = new IPEndPoint(IPAddress.Any, 0); int received = socket.ReceiveFrom(buffer, ref remoteEP); m_BytesReceived += received; m_PacketsReceived++; // Queue received packet. byte[] data = new byte[received]; Array.Copy(buffer, data, received); lock (m_pQueuedPackets) { m_pQueuedPackets.Enqueue(new UdpPacket(socket, (IPEndPoint) remoteEP, data)); } // We received data, so exit round-robin loop. receivedData = true; break; } } // We didn't get any data from any listening point, we must sleep or we use 100% CPU. if (!receivedData) { Thread.Sleep(1); } } } catch (Exception x) { OnError(x); } } } /// <summary> /// This method processes queued UDP packets. /// </summary> private void ProcessQueuedPackets() { while (m_IsRunning) { try { // There are no packets to process. if (m_pQueuedPackets.Count == 0) { Thread.Sleep(1); } else { UdpPacket udpPacket = null; lock (m_pQueuedPackets) { udpPacket = m_pQueuedPackets.Dequeue(); } // Sequential, call PacketReceived event on same thread. if (m_ProcessMode == UDP_ProcessMode.Sequential) { OnUdpPacketReceived(udpPacket); } // Parallel, call PacketReceived event on Thread pool thread. else { ThreadPool.QueueUserWorkItem(ProcessPacketOnTrPool, udpPacket); } } } catch (Exception x) { OnError(x); } } } /// <summary> /// Processes UDP packet on thread pool thread. /// </summary> /// <param name="state">User data.</param> private void ProcessPacketOnTrPool(object state) { try { OnUdpPacketReceived((UdpPacket) state); } catch (Exception x) { OnError(x); } } /// <summary> /// Raises PacketReceived event. /// </summary> /// <param name="packet">UDP packet.</param> private void OnUdpPacketReceived(UdpPacket packet) { if (PacketReceived != null) { PacketReceived(new UDP_PacketEventArgs(this, packet.Socket, packet.RemoteEndPoint, packet.Data)); } } /// <summary> /// Raises Error event. /// </summary> /// <param name="x">Exception occured.</param> private void OnError(Exception x) { if (Error != null) { Error(this, new Error_EventArgs(x, new StackTrace())); } } #endregion #region Nested type: UdpPacket /// <summary> /// This class represents UDP packet. /// </summary> private class UdpPacket { #region Members private readonly byte[] m_pData; private readonly IPEndPoint m_pRemoteEP; private readonly Socket m_pSocket; #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="socket">Socket which received packet.</param> /// <param name="remoteEP">Remote end point from where packet was received.</param> /// <param name="data">UDP packet data.</param> public UdpPacket(Socket socket, IPEndPoint remoteEP, byte[] data) { m_pSocket = socket; m_pRemoteEP = remoteEP; m_pData = data; } #endregion #region Properties /// <summary> /// Gets UDP packet data. /// </summary> public byte[] Data { get { return m_pData; } } /// <summary> /// Gets remote end point from where packet was received. /// </summary> public IPEndPoint RemoteEndPoint { get { return m_pRemoteEP; } } /// <summary> /// Gets socket which received packet. /// </summary> public Socket Socket { get { return m_pSocket; } } #endregion } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/SIP/Stack/SIP_StatusCodeType.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.SIP.Stack { /// <summary> /// Specifies SIP status code type. Defined in rfc 3261. /// </summary> public enum SIP_StatusCodeType { /// <summary> /// Request received, continuing to process the request. 1xx status code. /// </summary> Provisional, /// <summary> /// Action was successfully received, understood, and accepted. 2xx status code. /// </summary> Success, /// <summary> /// Request must be redirected(forwarded). 3xx status code. /// </summary> Redirection, /// <summary> /// Request contains bad syntax or cannot be fulfilled at this server. 4xx status code. /// </summary> RequestFailure, /// <summary> /// Server failed to fulfill a valid request. 5xx status code. /// </summary> ServerFailure, /// <summary> /// Request cannot be fulfilled at any server. 6xx status code. /// </summary> GlobalFailure } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/SIP/Message/SIP_MultiValueHF.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.SIP.Message { #region usings using System; using System.Collections.Generic; using System.Text; #endregion /// <summary> /// Implements generic multi value SIP header field. /// This is used by header fields like Via,Contact, ... . /// </summary> public class SIP_MultiValueHF<T> : SIP_HeaderField where T : SIP_t_Value, new() { #region Members private readonly List<T> m_pValues; #endregion #region Properties /// <summary> /// Gets or sets header field value. /// </summary> public override string Value { get { return ToStringValue(); } set { if (value != null) { throw new ArgumentNullException("Property Value value may not be null !"); } Parse(value); base.Value = value; } } /// <summary> /// Gets header field values. /// </summary> public List<T> Values { get { return m_pValues; } } /// <summary> /// Gets values count. /// </summary> public int Count { get { return m_pValues.Count; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="name">Header field name.</param> /// <param name="value">Header field value.</param> public SIP_MultiValueHF(string name, string value) : base(name, value) { m_pValues = new List<T>(); SetMultiValue(true); Parse(value); } #endregion #region Methods /// <summary> /// Gets header field values. /// </summary> /// <returns></returns> public object[] GetValues() { return m_pValues.ToArray(); } /// <summary> /// Removes value from specified index. /// </summary> /// <param name="index">Index of value to remove.</param> public void Remove(int index) { if (index > -1 && index < m_pValues.Count) { m_pValues.RemoveAt(index); } } #endregion #region Utility methods /// <summary> /// Parses multi value header field values. /// </summary> /// <param name="value">Header field value.</param> private void Parse(string value) { m_pValues.Clear(); StringReader r = new StringReader(value); while (r.Available > 0) { r.ReadToFirstChar(); // If we have COMMA, just consume it, it last value end. if (r.StartsWith(",")) { r.ReadSpecifiedLength(1); } // Allow xxx-param to pasre 1 value from reader. T param = new T(); param.Parse(r); m_pValues.Add(param); } } /// <summary> /// Converts to valid mutli value header field value. /// </summary> /// <returns></returns> private string ToStringValue() { StringBuilder retVal = new StringBuilder(); // Syntax: xxx-parm *(COMMA xxx-parm) for (int i = 0; i < m_pValues.Count; i++) { retVal.Append(m_pValues[i].ToStringValue()); // Don't add comma for last item. if (i < m_pValues.Count - 1) { retVal.Append(','); } } return retVal.ToString(); } #endregion } }<file_sep>/web/studio/ASC.Web.Studio/Products/Files/js/actionmanager.js /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ window.ASC.Files.Actions = (function () { var isInit = false; var clipGetLink = null; var clipGetExternalLink = null; var currentEntryData = null; var init = function () { if (isInit === false) { isInit = true; jq(document).click(function (event) { jq.dropdownToggle().registerAutoHide(event, "#filesActionsPanel", "#filesActionsPanel", function () { ASC.Files.Mouse.disableHover = false; }); jq.dropdownToggle().registerAutoHide(event, ".row-selected .menu-small", "#filesActionPanel", function () { jq(".row-selected .menu-small.active").removeClass("active"); jq(".row-selected.row-lonely-select").removeClass("row-lonely-select"); ASC.Files.Mouse.disableHover = false; }); }); jq.dropdownToggle( { switcherSelector: "#mainContentHeader .menuActionSelectAll", dropdownID: "filesSelectorPanel", anchorSelector: ".menuActionSelectAll", addTop: 4 }); jq.dropdownToggle({ addLeft: 4, addTop: -4, dropdownID: "filesVersionPanel", sideToggle: true, switcherSelector: "#filesVersion", toggleOnOver: true, }); jq.dropdownToggle({ addLeft: 4, addTop: -4, dropdownID: "filesMovePanel", sideToggle: true, switcherSelector: "#filesMove", toggleOnOver: true, }); jq.dropdownToggle({ addLeft: 4, addTop: -4, dropdownID: "foldersMovePanel", sideToggle: true, switcherSelector: "#foldersMove", toggleOnOver: true, }); ASC.Files.ServiceManager.bind(ASC.Files.ServiceManager.events.GetFileSharedInfo, onGetFileSharedInfo); ASC.Files.ServiceManager.bind(ASC.Files.ServiceManager.events.SetAceFileLink, onSetAceFileLink); } }; /* Methods*/ var afterShowFunction = function (dropdownPanel) { showSeporators(dropdownPanel); resizeDropdownPanel(dropdownPanel); createClipboardLinks(); }; var showSeporators = function(dropdownPanel) { var first = !!dropdownPanel.find(".dropdown-item.first-section:visible").length; var second = !!dropdownPanel.find(".dropdown-item.second-section:visible").length; var third = !!dropdownPanel.find(".dropdown-item.third-section:visible").length; var fourth = !!dropdownPanel.find(".dropdown-item.fourth-section:visible").length; dropdownPanel.find(".dropdown-item-seporator.first-section").toggle(first && (second || third || fourth)); dropdownPanel.find(".dropdown-item-seporator.second-section").toggle(second && (third || fourth)); dropdownPanel.find(".dropdown-item-seporator.third-section").toggle(third && fourth); }; var resizeDropdownPanel = function (dropdownPanel) { var content = dropdownPanel.find(".dropdown-content:visible"); if (content.get(0).style.minWidth) return; var items = content.find("li"); var itemsWidth = items.map(function () { return jq(this).width(); }); var maxItemWidth = Math.max.apply(Math, itemsWidth); var correction = maxItemWidth - content.width(); content.css({ minWidth: maxItemWidth }); var dropdownPanelPosition = dropdownPanel.position(); if (dropdownPanelPosition.left + dropdownPanel.outerWidth() > document.documentElement.clientWidth) { dropdownPanel.css({ left: dropdownPanelPosition.left - correction }); } }; var createClipboardLinks = function () { var link = jq("#filesGetLink:visible, #foldersGetLink:visible").first(); if (link.length) { createClipboardLink(link.attr("id")); } if (jq("#filesGetExternalLink").is(":visible")) { getFileSharedInfo(); } }; var createClipboardLink = function (id) { var url = ASC.Files.Actions.currentEntryData.entryObject.find(".entry-title .name a").prop("href"); ASC.Files.Actions.clipGetLink = ASC.Clipboard.destroy(ASC.Files.Actions.clipGetLink); ASC.Files.Actions.clipGetLink = ASC.Clipboard.create(url, id, { onComplete: function () { ASC.Files.UI.displayInfoPanel(ASC.Resources.Master.Resource.LinkCopySuccess); ASC.Files.Actions.hideAllActionPanels(); } }); }; var getFileSharedInfo = function () { ASC.Files.ServiceManager.getSharedInfo(ASC.Files.ServiceManager.events.GetFileSharedInfo, { showLoading: true, }, { stringList: { entry: [ASC.Files.Actions.currentEntryData.entryType + "_" + ASC.Files.Actions.currentEntryData.id] } }); }; var onGetFileSharedInfo = function (jsonData, params, errorMessage) { if (errorMessage) { ASC.Files.UI.displayInfoPanel(errorMessage, true); return; } var data = jsonData[0]; var toggleSwitcher = jq("#filesGetExternalLink .toggle"); toggleSwitcher.toggleClass("off", data.ace_status == 3); ASC.Files.Actions.clipGetExternalLink = ASC.Clipboard.destroy(ASC.Files.Actions.clipGetExternalLink); ASC.Files.Actions.clipGetExternalLink = ASC.Clipboard.create(data.link, "filesGetExternalLink", { onComplete: function () { if (toggleSwitcher.hasClass("off")) { ASC.Files.Actions.setAceFileLink(); } ASC.Files.UI.displayInfoPanel(ASC.Resources.Master.Resource.LinkCopySuccess); if (!ASC.Files.Actions.clipGetExternalLink.fromToggleBtn) { ASC.Files.Actions.hideAllActionPanels(); } ASC.Files.Actions.clipGetExternalLink.fromToggleBtn = false; } }); }; var setAceFileLink = function () { ASC.Files.ServiceManager.setAceLink(ASC.Files.ServiceManager.events.SetAceFileLink, { showLoading: true, fileId: ASC.Files.Actions.currentEntryData.entryId, share: jq("#filesGetExternalLink .toggle").hasClass("off") ? ASC.Files.Constants.AceStatusEnum.Read : ASC.Files.Constants.AceStatusEnum.Restrict }); }; var onSetAceFileLink = function (jsonData, params, errorMessage) { if (errorMessage) { ASC.Files.UI.displayInfoPanel(errorMessage, true); return; } jq("#filesGetExternalLink .toggle").toggleClass("off"); ASC.Files.Actions.currentEntryData.entryObject.toggleClass("__active", jsonData); }; var showActionsViewPanel = function (event) { jq("#buttonUnsubscribe, #buttonDelete, #buttonMoveto, #buttonCopyto, #buttonShare, #buttonMarkRead, #buttonSendInEmail, #buttonAddFaforite").hide(); jq("#mainContentHeader .unlockAction").removeClass("unlockAction"); var count = jq("#filesMainContent .file-row:not(.checkloading):not(.new-folder):not(.new-file):not(.error-entry):has(.checkbox input:checked)").length; var filesCount = jq("#filesMainContent .file-row:not(.checkloading):not(.new-folder):not(.new-file):not(.error-entry):not(.folder-row):has(.checkbox input:checked)").length; var countNotFavorite = 0; if (ASC.Files.Tree.displayFavorites() && ASC.Files.Folders.folderContainer != "trash") { countNotFavorite = jq("#filesMainContent .file-row:not(.checkloading):not(.new-folder):not(.new-file):not(.error-entry):not(.on-favorite):not(.folder-row):has(.checkbox input:checked)").length; } var countWithRights = count; var countIsNew = 0; var onlyThirdParty = (ASC.Files.ThirdParty && !ASC.Files.ThirdParty.isThirdParty()); var countThirdParty = 0; var canConvert = false; var countCanShare = 0; jq("#filesMainContent .file-row:not(.checkloading):not(.new-folder):not(.new-file):not(.error-entry):has(.checkbox input:checked)").each(function () { var entryObj = jq(this); if (ASC.Files.UI.editingFile(entryObj) || !ASC.Files.UI.accessDelete(entryObj) || ASC.Files.UI.lockedForMe(entryObj)) { countWithRights--; } if (entryObj.find(".is-new:visible").length > 0) { countIsNew++; } var entryData = ASC.Files.UI.getObjectData(entryObj); if (ASC.Files.ThirdParty) { if (!ASC.Files.ThirdParty.isThirdParty() && ASC.Files.ThirdParty.isThirdParty(entryData)) { countThirdParty++; } else { onlyThirdParty = false; } } else { onlyThirdParty = false; } if (!canConvert && !entryObj.hasClass("folder-row")) { var entryTitle = entryData.title; var formats = ASC.Files.Utility.GetConvertFormats(entryTitle); canConvert = formats.length > 0 && !entryData.encrypted && entryData.content_length <= ASC.Files.Constants.AvailableFileSize; } if (!ASC.Resources.Master.Personal && entryObj.is(":not(.without-share)") && ASC.Files.Share && ASC.Files.Folders.currentFolder.shareable && (!entryData.encrypted || ASC.Files.Folders.folderContainer == "privacy" && ASC.Files.Utility.CanWebEncrypt(entryData.title) && ASC.Desktop && ASC.Desktop.setAccess)) { countCanShare++; } }); if (count > 0) { jq("#buttonDownload, #buttonRemoveFavorite, #buttonRemoveTemplate, #buttonUnsubscribe, #buttonRestore, #buttonCopyto").show().find("span").html(count); jq("#mainDownload, #mainRemoveFavorite, #mainRemoveTemplate, #mainUnsubscribe, #mainRestore, #mainCopy").addClass("unlockAction"); if (ASC.Files.Folders.folderContainer == "privacy") { jq("#buttonCopyto").hide(); } if (ASC.Files.Folders.folderContainer != "forme") { jq("#buttonUnsubscribe").hide(); } if (ASC.Files.Folders.folderContainer == "favorites") { jq("#buttonMoveto").hide(); } else { jq("#buttonRemoveFavorite").hide(); } if (ASC.Files.Folders.folderContainer == "templates") { jq("#buttonMoveto").hide(); } else { jq("#buttonRemoveTemplate").hide(); } } if (filesCount > 0 && countCanShare > 0 || ASC.Files.Folders.folderContainer == "project" && filesCount > 0) { jq("#buttonSendInEmail").show().find("span").html(filesCount); } if (countNotFavorite > 0) { jq("#buttonAddFavorite").show().find("span").html(countNotFavorite); } else { jq("#buttonAddFavorite").hide(); } if (canConvert) { jq("#buttonConvert").show().find("span").html(count); } else { jq("#buttonConvert").hide(); } jq("#mainConvert").toggleClass("unlockAction", canConvert); if (countIsNew > 0) { jq("#buttonMarkRead").show().find("span").html(countIsNew); jq("#mainMarkRead").addClass("unlockAction"); } if (countWithRights > 0) { jq("#buttonDelete, #buttonMoveto").show().find("span").html(countWithRights - countThirdParty); jq("#mainDelete, #mainMove").addClass("unlockAction"); } if (ASC.Files.Folders.folderContainer == "trash") { jq("#buttonDelete, #buttonMoveto, #buttonCopyto, #buttonMarkRead").hide(); jq("#mainDelete, #mainMove, #mainCopy").removeClass("unlockAction"); } jq("#buttonRestore, #buttonEmptyTrash").hide(); jq("#mainRestore, #mainEmptyTrash").removeClass("unlockAction"); if (ASC.Files.Folders.folderContainer == "trash") { if (count > 0) { jq("#buttonDownload, #buttonDelete, #buttonRestore").show(); jq("#mainDownload, #mainDelete, #mainRestore").addClass("unlockAction"); } else { jq("#buttonDownload, #buttonConvert").hide(); jq("#mainDownload, #mainConvert").removeClass("unlockAction"); } jq("#buttonEmptyTrash").show(); jq("#mainEmptyTrash").addClass("unlockAction"); } else if (ASC.Files.Folders.folderContainer != "project" && countCanShare > 0) { jq("#buttonShare").show().find("span").html(countCanShare); jq("#mainShare").addClass("unlockAction"); } if (onlyThirdParty) { jq("#buttonDelete, #buttonMoveto").hide(); jq("#mainDelete, #mainMove").removeClass("unlockAction"); } if (typeof event != "undefined") { var e = jq.fixEvent(event), dropdownItem = jq("#filesActionsPanel"), correctionX = document.body.clientWidth - (e.pageX - pageXOffset + dropdownItem.innerWidth()) > 0 ? 0 : dropdownItem.innerWidth(), correctionY = document.body.clientHeight - (e.pageY - pageYOffset + dropdownItem.innerHeight()) > 0 ? 0 : dropdownItem.innerHeight(); dropdownItem.css({ "top": e.pageY - correctionY, "left": e.pageX - correctionX }); dropdownItem.toggle(); afterShowFunction(dropdownItem); ASC.Files.Mouse.disableHover = true; } }; var showActionsPanel = function (event, entryData) { ASC.Files.Actions.clipGetLink = ASC.Clipboard.destroy(ASC.Files.Actions.clipGetLink); var e = jq.fixEvent(event); var target = jq(e.srcElement || e.target); if (target.hasClass("active")) { ASC.Files.Actions.hideAllActionPanels(); return true; } entryData = entryData || ASC.Files.UI.getObjectData(target); var entryObj = entryData.entryObject; if (entryObj.is(".loading")) { return true; } ASC.Files.Actions.currentEntryData = entryData; ASC.Files.UI.checkSelectAll(false); ASC.Files.UI.selectRow(entryObj, true); ASC.Files.UI.updateMainContentHeader(); var accessibleObj = ASC.Files.UI.accessEdit(entryData, entryObj); var accessAdminObj = ASC.Files.UI.accessDelete(entryObj); var isVisitor = Teamlab.profile.isVisitor === true; jq("#actionPanelFolders, #actionPanelFiles").hide(); if (entryData.entryType === "file") { jq("#filesOpen,\ #filesGotoParent,\ #filesEdit,\ #filesByTemplate,\ #filesConvert,\ #filesDownload,\ #filesGetLink,\ #filesShareAccess,\ #filesGetExternalLink,\ #filesChangeOwner,\ #filesSendInEmail,\ #filesLock,\ #filesUnlock,\ #filesDocuSign,\ #filesUnsubscribe,\ #filesVersion,\ #filesCompleteVersion,\ #filesVersions,\ #filesMove,\ #filesMoveto,\ #filesCopyto,\ #filesCopy,\ #filesMarkRead,\ #filesAddFavorite,\ #filesRemoveFavorite,\ #filesAddTemplate,\ #filesRemoveTemplate,\ #filesRename,\ #filesRestore,\ #filesRemove").show().removeClass("display-none"); var entryTitle = entryData.title; if (!ASC.Files.Utility.GetConvertFormats(entryTitle).length || entryData.encrypted || entryData.content_length > ASC.Files.Constants.AvailableFileSize) { jq("#filesConvert").hide().addClass("display-none"); } if (!ASC.Files.Utility.CanWebView(entryTitle) && (typeof ASC.Files.ImageViewer == "undefined" || !ASC.Files.Utility.CanImageView(entryTitle)) && (typeof ASC.Files.MediaPlayer == "undefined" || !ASC.Files.MediaPlayer.canPlay(entryTitle, true))) { jq("#filesOpen").hide().addClass("display-none"); } if (!ASC.Files.ThirdParty || !ASC.Files.ThirdParty.thirdpartyAvailable() || jq.inArray(ASC.Files.Utility.GetFileExtension(entryTitle), ASC.Files.Constants.DocuSignFormats) == -1 || entryData.encrypted) { jq("#filesDocuSign").hide(); } if (entryObj.find("#contentVersions").length != 0 || ASC.Files.ThirdParty && ASC.Files.ThirdParty.isThirdParty()) { jq("#filesVersions").hide().addClass("display-none"); } var editingFile = ASC.Files.UI.editingFile(entryObj); if (editingFile) { jq("#filesCompleteVersion,\ #filesMoveto,\ #filesRemove").hide().addClass("display-none"); if (ASC.Files.ThirdParty && ASC.Files.ThirdParty.isThirdParty()) { jq("#filesRename").hide(); } } if (entryObj.hasClass("on-favorite")) { jq("#filesAddFavorite").hide().addClass("display-none"); } else { jq("#filesRemoveFavorite").hide().addClass("display-none"); if (!ASC.Files.Tree.displayFavorites()) { jq("#filesAddFavorite").hide().addClass("display-none"); } } if (ASC.Files.Folders.folderContainer == "favorites") { jq("#filesMoveto,\ #filesRemove").hide().addClass("display-none"); } if (entryObj.hasClass("is-template")) { jq("#filesAddTemplate").hide().addClass("display-none"); } else { jq("#filesByTemplate, #filesRemoveTemplate").hide().addClass("display-none"); if (!ASC.Files.Tree.displayTemplates() || !ASC.Files.Utility.CanBeTemplate(entryTitle)) { jq("#filesAddTemplate").hide().addClass("display-none"); } } if (ASC.Files.Folders.folderContainer == "templates") { jq("#filesMoveto,\ #filesRemove").hide().addClass("display-none"); } var lockedForMe = ASC.Files.UI.lockedForMe(entryObj); if (!ASC.Files.UI.editableFile(entryData) || editingFile && (!ASC.Files.Utility.CanCoAuhtoring(entryTitle) || entryObj.hasClass("on-edit-alone")) || lockedForMe) { jq("#filesEdit").hide().addClass("display-none"); } if (entryData.encrypted) { jq("#filesEdit,\ #filesOpen,\ #filesGetLink,\ #filesGetExternalLink,\ #filesSendInEmail,\ #filesCompleteVersion,\ #filesLock,\ #filesUnlock,\ #filesAddTemplate,\ #filesCopyto,\ #filesCopy,\ #filesByTemplate,\ #filesAddFavorite").hide().addClass("display-none"); } if (entryObj.hasClass("file-locked")) { jq("#filesLock").hide().addClass("display-none"); } else { jq("#filesUnlock").hide().addClass("display-none"); } if (ASC.Files.Folders.folderContainer == "trash") { jq("#filesOpen,\ #filesGotoParent,\ #filesEdit,\ #filesByTemplate,\ #filesGetLink,\ #filesShareAccess,\ #filesGetExternalLink,\ #filesSendInEmail,\ #filesCompleteVersion,\ #filesLock,\ #filesUnlock,\ #filesDocuSign,\ #filesVersions,\ #filesMoveto,\ #filesCopyto,\ #filesMarkRead,\ #filesAddFavorite,\ #filesRemoveFavorite,\ #filesAddTemplate,\ #filesRemoveTemplate,\ #filesRename").hide().addClass("display-none"); } else { jq("#filesRestore").hide().addClass("display-none"); } if (!accessibleObj || lockedForMe) { jq("#filesCompleteVersion,\ #filesRename,\ #filesLock").hide().addClass("display-none"); if (!ASC.Files.Constants.ADMIN && ASC.Files.Folders.folderContainer != "my") { jq("#filesUnlock").hide().addClass("display-none"); } } if (isVisitor) { jq("#filesByTemplate,\ #filesLock,\ #filesDocuSign,\ #filesCompleteVersion,\ #filesAddFavorite,\ #filesRemoveFavorite,\ #filesAddTemplate,\ #filesRemoveTemplate").hide().addClass("display-none"); if (!accessAdminObj) { jq("#filesRename").hide().addClass("display-none"); } } if (ASC.Files.Folders.folderContainer != "corporate") { jq("#filesChangeOwner").hide().addClass("display-none"); } if (ASC.Files.ThirdParty && ASC.Files.ThirdParty.isThirdParty(entryData)) { jq("#filesChangeOwner,\ #filesCompleteVersion,\ #filesCopy").hide().addClass("display-none"); } if (!accessAdminObj || lockedForMe) { jq("#filesChangeOwner,\ #filesMoveto,\ #filesRemove").hide().addClass("display-none"); } if (entryObj.is(".without-share *, .without-share")) { jq("#filesShareAccess").hide().addClass("display-none"); jq("#filesGetExternalLink").hide().addClass("display-none"); } else if (jq("#filesGetExternalLink").data("trial") && !ASC.Files.Utility.CanWebView(entryTitle)) { jq("#filesGetExternalLink").hide().addClass("display-none"); } if (entryObj.find(".is-new:visible").length == 0) { jq("#filesMarkRead").hide().addClass("display-none"); } if (ASC.Files.Folders.folderContainer != "forme" && (ASC.Files.Folders.folderContainer != "privacy" || accessAdminObj)) { jq("#filesUnsubscribe").hide().addClass("display-none"); } if (!ASC.Files.UI.accessEdit()) { jq("#filesCopy").hide().addClass("display-none"); } if (ASC.Files.Folders.folderContainer != "favorites" && ASC.Files.Folders.folderContainer != "templates" && ASC.Files.Folders.folderContainer != "recent" && (!ASC.Files.Filter || !ASC.Files.Filter.getFilterSettings().isSet || ASC.Files.ThirdParty && ASC.Files.ThirdParty.isThirdParty())) { jq("#filesGotoParent").hide().addClass("display-none"); } if (!jq("#filesVersionPanel li:not(.display-none)").length) { jq("#filesVersion").hide().addClass("display-none"); } if (!jq("#filesMovePanel li:not(.display-none)").length) { jq("#filesMove").hide().addClass("display-none"); } jq("#actionPanelFiles").show(); } else { jq("#foldersOpen,\ #foldersGotoParent,\ #foldersDownload,\ #foldersGetLink,\ #foldersShareAccess,\ #foldersChangeOwner,\ #foldersUnsubscribe,\ #foldersMove,\ #foldersMoveto,\ #foldersCopyto,\ #foldersMarkRead,\ #foldersRename,\ #foldersRestore,\ #foldersRemove,\ #foldersRemoveThirdparty,\ #foldersChangeThirdparty").show().removeClass("display-none"); if (ASC.Files.Folders.folderContainer == "privacy") { jq("#foldersCopyto").hide().addClass("display-none"); } if (ASC.Files.Folders.folderContainer == "trash") { jq("#foldersOpen,\ #foldersGotoParent,\ #foldersGetLink,\ #foldersShareAccess,\ #foldersMove,\ #foldersMoveto,\ #foldersCopyto,\ #foldersMarkRead,\ #foldersRename").hide().addClass("display-none"); } else { jq("#foldersRestore").hide().addClass("display-none"); } if (!accessibleObj || ASC.Files.Folders.currentFolder.id == ASC.Files.Constants.FOLDER_ID_PROJECT) { jq("#foldersRename,\ #foldersRemoveThirdparty,\ #foldersChangeThirdparty").hide().addClass("display-none"); } if (ASC.Files.Folders.folderContainer != "corporate") { jq("#foldersChangeOwner").hide().addClass("display-none"); } if (!accessAdminObj) { jq("#foldersChangeOwner,\ #foldersMoveto,\ #foldersRemove,\ #foldersRemoveThirdparty,\ #foldersChangeThirdparty").hide().addClass("display-none"); if (isVisitor) { jq("#foldersRename").hide().addClass("display-none"); } } if (entryObj.is(".without-share *, .without-share")) { jq("#foldersShareAccess").hide().addClass("display-none"); } if (entryObj.find(".is-new:visible").length == 0) { jq("#foldersMarkRead").hide().addClass("display-none"); } if (ASC.Files.Folders.folderContainer != "forme") { jq("#foldersUnsubscribe").hide().addClass("display-none"); } if (ASC.Files.ThirdParty && ASC.Files.ThirdParty.isThirdParty(entryData)) { jq("#foldersChangeOwner").hide().addClass("display-none"); if (ASC.Files.ThirdParty.isThirdParty() || ASC.Files.Folders.currentFolder.id == ASC.Files.Constants.FOLDER_ID_SHARE) { jq("#foldersRemoveThirdparty,\ #foldersChangeThirdparty").hide().addClass("display-none"); } else { if (ASC.Desktop) { jq("#foldersRemoveThirdparty,\ #foldersChangeThirdparty").hide().addClass("display-none"); } if (entryData.create_by_id != Teamlab.profile.id) { jq("#foldersChangeThirdparty").hide().addClass("display-none"); } jq("#foldersRemove,\ #foldersMoveto").hide().addClass("display-none"); if (entryData.error) { jq("#foldersOpen,\ #foldersDownload,\ #foldersCopyto,\ #foldersRename").hide().addClass("display-none"); } } } else { jq("#foldersRemoveThirdparty,\ #foldersChangeThirdparty").hide().addClass("display-none"); } if (!ASC.Files.Filter || !ASC.Files.Filter.getFilterSettings().isSet || ASC.Files.ThirdParty && ASC.Files.ThirdParty.isThirdParty()) { jq("#foldersGotoParent").hide().addClass("display-none"); } if (!jq("#foldersMovePanel li:not(.display-none)").length) { jq("#foldersMove").hide().addClass("display-none"); } jq("#actionPanelFolders").show(); } if (!ASC.Clipboard.enable) { jq("#filesGetLink, #foldersGetLink").remove(); } var dropdownItem = jq("#filesActionPanel"); jq.showDropDownByContext(e, target, dropdownItem, function () { ASC.Files.Mouse.disableHover = true; }); afterShowFunction(dropdownItem); if (target.is(".menu-small")) { entryObj.addClass("row-lonely-select"); } return true; }; var onContextMenu = function (event) { var e = jq.fixEvent(event); if (typeof e == "undefined" || !e) { return true; } var target = jq(e.srcElement || e.target); if (target.is("input[type=text]")) { return true; } if (target.parents(".studio-action-panel").length) { return !ASC.Desktop; } ASC.Files.Actions.hideAllActionPanels(); if (!target.parents("#filesMainContent").length) { return !ASC.Desktop; } var entryData = ASC.Files.UI.getObjectData(target); if (!entryData) { if (target.is("a[href]")) { return true; } return false; } var entryObj = entryData.entryObject; if (entryObj.hasClass("new-folder") || entryObj.hasClass("row-rename") || entryObj.hasClass("error-entry")) { return true; } jq("#filesMainContent .row-hover").removeClass("row-hover"); jq("#filesMainContent .row-lonely-select").removeClass("row-lonely-select"); jq("#filesMainContent .menu-small").removeClass("active"); var count = jq("#filesMainContent .file-row.row-selected").length; if (count > 1 && entryObj.hasClass("row-selected")) { ASC.Files.Actions.showActionsViewPanel(event); } else { ASC.Files.Actions.showActionsPanel(event, entryData); } return false; }; var hideAllActionPanels = function () { ASC.Files.Actions.clipGetLink = ASC.Clipboard.destroy(ASC.Files.Actions.clipGetLink); jq(".studio-action-panel:visible").hide(); jq("#filesMainContent .file-row.row-lonely-select").removeClass("row-lonely-select"); jq("#filesMainContent .file-row .menu-small").removeClass("active"); ASC.Files.UI.hideEntryTooltip(); }; var checkEditFile = function (fileId, winEditor) { var fileObj = ASC.Files.UI.getEntryObject("file", fileId); ASC.Files.UI.lockEditFile(fileObj, true); var url = ASC.Files.Utility.GetFileWebEditorUrl(fileId); if (winEditor && winEditor.location) { winEditor.location.href = url; } else { winEditor = window.open(url, "_blank"); } var onloadFunction = function () { var fileIdLocal = fileId; if (fileIdLocal) { ASC.Files.UI.lockEditFileById(fileIdLocal, true); ASC.Files.UI.checkEditing(); ASC.Files.Socket.subscribeChangeEditors(fileIdLocal); } }; if (winEditor == undefined) { ASC.Files.UI.lockEditFile(fileObj, true); ASC.Files.Socket.subscribeChangeEditors(fileId); ASC.Files.UI.checkEditingDefer(); } else { try { winEditor.onload = onloadFunction; if (jq.browser.msie) { var bodyIe; var checkIeLoaded = function () { bodyIe = winEditor.document.getElementsByTagName("body"); if (bodyIe[0] == null) { setTimeout(checkIeLoaded, 10); } else { onloadFunction(); } }; checkIeLoaded(); } } catch (ex) { } try { winEditor.onunload = function () { if (fileId) { ASC.Files.UI.checkEditing(); } }; } catch (ex) { } } return ASC.Files.Marker.removeNewIcon("file", fileId); }; var showMoveToSelector = function (isCopy) { ASC.Files.Folders.isCopyTo = (isCopy === true); ASC.Files.Actions.hideAllActionPanels(); if (ASC.Files.Folders.folderContainer != "trash" && !ASC.Files.Folders.isCopyTo) { if (!ASC.Files.UI.accessEdit()) { var listWithAccess = jq.grep(jq("#filesMainContent .file-row:not(.checkloading):not(.new-folder):not(.new-file):not(.error-entry):has(.checkbox input:checked)"), function (item) { return ASC.Files.UI.accessDelete(item); }); if (!listWithAccess.length) { ASC.Files.UI.displayInfoPanel(ASC.Files.FilesJSResources.InfoMoveGroup.format(0)); return; } } } ASC.Files.Tree.updateTreePath(); if (!isCopy && jq("#filesMainContent .file-row:not(.checkloading):not(.new-folder):not(.new-file):not(.error-entry):not(.on-edit):has(.checkbox input:checked)").length == 0) { ASC.Files.UI.displayInfoPanel(ASC.Files.FilesJSResources.InfoMoveGroup.format(0)); return; } if (ASC.Files.ThirdParty && !ASC.Files.Folders.isCopyTo && !ASC.Files.ThirdParty.isThirdParty() && jq("#filesMainContent .file-row:not(.checkloading):not(.new-folder):not(.new-file):not(.error-entry):not(.third-party-entry):has(.checkbox input:checked)").length == 0) { ASC.Files.UI.displayInfoPanel(ASC.Files.FilesJSResources.InfoMoveGroup.format(0)); return; } if (jq("#filesMainContent .file-row:not(.checkloading):not(.new-folder):not(.new-file):not(.error-entry):has(.checkbox input:checked)").length == 0) { return; } jq("#treeViewPanelSelector").removeClass("without-third-party"); if (!jq("#treeViewPanelSelector").next().is("#mainContentHeader")) { jq("#treeViewPanelSelector").insertBefore("#mainContentHeader"); } ASC.Files.Tree.showSelect(ASC.Files.Folders.currentFolder.id); jq.dropdownToggle().toggle(".menuActionSelectAll", "treeViewPanelSelector"); jq("#treeViewPanelSelector").scrollTo(jq("#treeViewPanelSelector").find(".tree-node" + ASC.Files.UI.getSelectorId(ASC.Files.Folders.currentFolder.id))); jq("body").bind("click", ASC.Files.Actions.registerHideTree); }; var registerHideTree = function (event) { if (!jq((event.target) ? event.target : event.srcElement).parents().addBack() .is("#treeViewPanelSelector, #foldersMoveto, #filesMoveto, #foldersCopyto, #filesCopyto,\ #foldersRestore, #filesRestore, #buttonMoveto, #buttonCopyto, #buttonRestore,\ #mainMove, #mainCopy, #mainRestore")) { ASC.Files.Actions.hideAllActionPanels(); jq("body").unbind("click", ASC.Files.Actions.registerHideTree); } }; return { init: init, showActionsViewPanel: showActionsViewPanel, showActionsPanel: showActionsPanel, onContextMenu: onContextMenu, checkEditFile: checkEditFile, hideAllActionPanels: hideAllActionPanels, clipGetLink: clipGetLink, clipGetExternalLink: clipGetExternalLink, currentEntryData: currentEntryData, showMoveToSelector: showMoveToSelector, registerHideTree: registerHideTree, setAceFileLink: setAceFileLink }; })(); (function ($) { ASC.Files.Actions.init(); $(function () { jq("#filesSelectAll").click(function () { ASC.Files.Actions.hideAllActionPanels(); ASC.Files.UI.checkSelectAll(true); }); jq("#filesSelectFile, #filesSelectFolder, #filesSelectDocument,\ #filesSelectPresentation, #filesSelectSpreadsheet, #filesSelectImage, #filesSelectMedia, #filesSelectArchive").click(function () { var filter = this.id.replace("filesSelect", "").toLowerCase(); ASC.Files.UI.checkSelect(filter); }); jq("#filesDownload, #foldersDownload").click(function () { ASC.Files.Actions.hideAllActionPanels(); ASC.Files.Folders.download(ASC.Files.Actions.currentEntryData.entryType, ASC.Files.Actions.currentEntryData.id); }); jq("#filesRename, #foldersRename").click(function () { ASC.Files.Actions.hideAllActionPanels(); ASC.Files.Folders.rename(ASC.Files.Actions.currentEntryData.entryType, ASC.Files.Actions.currentEntryData.id); }); jq("#filesAddFavorite, #filesRemoveFavorite").click(function () { ASC.Files.Actions.hideAllActionPanels(); ASC.Files.Folders.toggleFavorite(ASC.Files.Actions.currentEntryData.entryObject); }); jq("#filesAddTemplate, #filesRemoveTemplate").click(function () { ASC.Files.Actions.hideAllActionPanels(); ASC.Files.Folders.toggleTemplate(ASC.Files.Actions.currentEntryData.entryObject); }); jq("#filesRemove, #foldersRemove").click(function () { ASC.Files.Actions.hideAllActionPanels(); ASC.Files.Folders.deleteItem(ASC.Files.Actions.currentEntryData.entryType, ASC.Files.Actions.currentEntryData.id); }); jq("#filesShareAccess, #foldersShareAccess").click(function () { ASC.Files.Actions.hideAllActionPanels(); ASC.Files.Share.getSharedInfo(ASC.Files.Actions.currentEntryData.entryType + "_" + ASC.Files.Actions.currentEntryData.id, ASC.Files.Actions.currentEntryData.title); }); jq("#filesGetExternalLink .toggle").click(function(e) { if (jq(this).hasClass("off")) { ASC.Files.Actions.clipGetExternalLink.fromToggleBtn = true; } else { e.stopPropagation(); ASC.Files.Actions.setAceFileLink(); } }); jq("#filesMarkRead, #foldersMarkRead").click(function () { ASC.Files.Actions.hideAllActionPanels(); ASC.Files.Marker.markAsRead(ASC.Files.Actions.currentEntryData); }); jq("#filesChangeOwner, #foldersChangeOwner").click(function () { ASC.Files.Actions.hideAllActionPanels(); ASC.Files.Folders.changeOwnerDialog(ASC.Files.Actions.currentEntryData); }); jq("#filesSendInEmail").click(function () { ASC.Files.Actions.hideAllActionPanels(); window.location.href = ASC.Mail.Utility.GetDraftUrl(ASC.Files.Actions.currentEntryData.entryId); }); jq("#studioPageContent").on("click", "#buttonSendInEmail", function () { ASC.Files.Actions.hideAllActionPanels(); var fileIds = jq("#filesMainContent .file-row:not(.checkloading):not(.new-folder):not(.new-file):not(.error-entry):not(.folder-row):has(.checkbox input:checked)").map(function () { var entryRowData = ASC.Files.UI.getObjectData(this); var entryRowId = entryRowData.entryId; return entryRowId; }); window.location.href = ASC.Mail.Utility.GetDraftUrl(fileIds.get()); }); jq("#filesUnsubscribe, #foldersUnsubscribe").click(function () { ASC.Files.Actions.hideAllActionPanels(); ASC.Files.Share.unSubscribeMe(ASC.Files.Actions.currentEntryData.entryType, ASC.Files.Actions.currentEntryData.id); }); jq("#filesConvert").click(function () { ASC.Files.Actions.hideAllActionPanels(); ASC.Files.Converter.showToConvert(ASC.Files.Actions.currentEntryData.entryObject); }); jq("#filesOpen").click(function () { ASC.Files.Actions.hideAllActionPanels(); ASC.Files.Folders.clickOnFile(ASC.Files.Actions.currentEntryData, false); return false; }); jq("#filesLock, #filesUnlock").click(function () { ASC.Files.Actions.hideAllActionPanels(); ASC.Files.Folders.lockFile(ASC.Files.Actions.currentEntryData.entryObject, ASC.Files.Actions.currentEntryData.id); }); jq("#filesLock .toggle, #filesUnlock .toggle").click(function (e) { e.stopPropagation(); jq("#filesLock, #filesUnlock").toggle(); ASC.Files.Folders.lockFile(ASC.Files.Actions.currentEntryData.entryObject, ASC.Files.Actions.currentEntryData.id); }); jq("#filesCompleteVersion").click(function () { ASC.Files.Actions.hideAllActionPanels(); ASC.Files.Folders.versionComplete(ASC.Files.Actions.currentEntryData.id, 0, false); }); jq("#filesVersions").click(function () { ASC.Files.Actions.hideAllActionPanels(); ASC.Files.Folders.showVersions(ASC.Files.Actions.currentEntryData.entryObject, ASC.Files.Actions.currentEntryData.id); }); jq("#filesEdit").click(function () { ASC.Files.Actions.hideAllActionPanels(); ASC.Files.Folders.clickOnFile(ASC.Files.Actions.currentEntryData, true); }); jq("#filesByTemplate").click(function () { ASC.Files.Actions.hideAllActionPanels(); ASC.Files.Folders.createNewDoc(ASC.Files.Actions.currentEntryData); }); jq("#filesCopy").click(function () { ASC.Files.Actions.hideAllActionPanels(); ASC.Files.Folders.createDuplicate(ASC.Files.Actions.currentEntryData); }); jq("#foldersOpen").click(function () { ASC.Files.Actions.hideAllActionPanels(); ASC.Files.Folders.clickOnFolder(ASC.Files.Actions.currentEntryData.id); }); jq("#filesGotoParent, #foldersGotoParent").click(function () { ASC.Files.Actions.hideAllActionPanels(); ASC.Files.Folders.clickOnFolder(ASC.Files.Actions.currentEntryData.folder_id); }); jq("#foldersRemoveThirdparty").click(function () { ASC.Files.Actions.hideAllActionPanels(); ASC.Files.ThirdParty.showDeleteDialog(null, null, null, ASC.Files.Actions.currentEntryData.title, ASC.Files.Actions.currentEntryData); }); jq("#foldersChangeThirdparty").click(function () { ASC.Files.Actions.hideAllActionPanels(); ASC.Files.ThirdParty.showChangeDialog(ASC.Files.Actions.currentEntryData); }); jq("body").bind("contextmenu", function (event) { return ASC.Files.Actions.onContextMenu(event); }); jq("#filesMainContent").on("click", ".menu-small", ASC.Files.Actions.showActionsPanel); jq("#studioPageContent").on("click", "#buttonMoveto, #buttonCopyto, #buttonRestore,\ #mainMove.unlockAction, #mainCopy.unlockAction, #mainRestore.unlockAction,\ #filesMoveto, #filesRestore, #filesCopyto,\ #foldersMoveto, #foldersRestore, #foldersCopyto", function () { ASC.Files.Actions.showMoveToSelector(this.id == "buttonCopyto" || this.id == "mainCopy" || this.id == "filesCopyto" || this.id == "foldersCopyto"); }); jq("#filesDocuSign").click(function () { ASC.Files.ThirdParty.showDocuSignDialog(ASC.Files.Actions.currentEntryData); ASC.Files.Actions.hideAllActionPanels(); return false; }); }); })(jQuery);<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/SIP/Message/SIP_t_ValueWithParams.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.SIP.Message { #region usings using System.Text; #endregion /// <summary> /// This base class for SIP data types what has parameters support. /// </summary> public abstract class SIP_t_ValueWithParams : SIP_t_Value { #region Members private readonly SIP_ParameterCollection m_pParameters; #endregion #region Properties /// <summary> /// Gets via parameters. /// </summary> public SIP_ParameterCollection Parameters { get { return m_pParameters; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> public SIP_t_ValueWithParams() { m_pParameters = new SIP_ParameterCollection(); } #endregion /// <summary> /// Parses parameters from specified reader. Reader position must be where parameters begin. /// </summary> /// <param name="reader">Reader from where to read parameters.</param> /// <exception cref="SIP_ParseException">Raised when invalid SIP message.</exception> protected void ParseParameters(StringReader reader) { // Remove all old parameters. m_pParameters.Clear(); // Parse parameters while (reader.Available > 0) { reader.ReadToFirstChar(); // We have parameter if (reader.SourceString.StartsWith(";")) { reader.ReadSpecifiedLength(1); string paramString = reader.QuotedReadToDelimiter(new[] {';', ','}, false); if (paramString != "") { string[] name_value = paramString.Split(new[] {'='}, 2); if (name_value.Length == 2) { Parameters.Add(name_value[0], name_value[1]); } else { Parameters.Add(name_value[0], null); } } } // Next value else if (reader.SourceString.StartsWith(",")) { break; } // Unknown data else { throw new SIP_ParseException("Unexpected value '" + reader.SourceString + "' !"); } } } /// <summary> /// Convert parameters to valid parameters string. /// </summary> /// <returns>Returns parameters string.</returns> protected string ParametersToString() { StringBuilder retVal = new StringBuilder(); foreach (SIP_Parameter parameter in m_pParameters) { if (!string.IsNullOrEmpty(parameter.Value)) { retVal.Append(";" + parameter.Name + "=" + parameter.Value); } else { retVal.Append(";" + parameter.Name); } } return retVal.ToString(); } } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/MIME/MIME_h.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.MIME { #region usings using System; using System.Text; #endregion /// <summary> /// This is base class for MIME header fields. Defined in RFC 2045 3. /// </summary> public abstract class MIME_h { #region Properties /// <summary> /// Gets if this header field is modified since it has loaded. /// </summary> /// <remarks>All new added header fields has <b>IsModified = true</b>.</remarks> /// <exception cref="ObjectDisposedException">Is riased when this class is disposed and this property is accessed.</exception> public abstract bool IsModified { get; } /// <summary> /// Gets header field name. For example "Content-Type". /// </summary> public abstract string Name { get; } #endregion #region Methods /// <summary> /// Returns header field as string. /// </summary> /// <returns>Returns header field as string.</returns> public override string ToString() { return ToString(null, null); } /// <summary> /// Returns header field as string. /// </summary> /// <param name="wordEncoder">8-bit words ecnoder. Value null means that words are not encoded.</param> /// <param name="parmetersCharset">Charset to use to encode 8-bit characters. Value null means parameters not encoded. /// If encoding needed, UTF-8 is strongly reccomended if not sure.</param> /// <returns>Returns header field as string.</returns> public abstract string ToString(MIME_Encoding_EncodedWord wordEncoder, Encoding parmetersCharset); #endregion } }<file_sep>/module/ASC.ElasticSearch/Config/ElasticSection.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Configuration; namespace ASC.ElasticSearch.Config { class ElasticSection : ConfigurationSection { [ConfigurationProperty("host", IsRequired = true, DefaultValue = "localhost")] public string Host { get { return (string)this["host"]; } } [ConfigurationProperty("port", IsRequired = false, DefaultValue = "9200")] public int Port { get { return Convert.ToInt32(this["port"]); } } [ConfigurationProperty("scheme", IsRequired = false, DefaultValue = "http")] public string Scheme { get { return (string)this["scheme"]; } } [ConfigurationProperty("period", IsRequired = false, DefaultValue = 1)] public int Period { get { return Convert.ToInt32(this["period"]); } } [ConfigurationProperty("memoryLimit", IsRequired = false, DefaultValue = 10 * 1024 * 1024L)] public long MemoryLimit { get { return Convert.ToInt64(this["memoryLimit"]); } } } } <file_sep>/common/ASC.Data.Backup/Storage/S3BackupStorage.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.IO; using ASC.Common.Logging; using Amazon; using Amazon.S3; using Amazon.S3.Model; using Amazon.S3.Transfer; namespace ASC.Data.Backup.Storage { internal class S3BackupStorage : IBackupStorage { private readonly string accessKeyId; private readonly string secretAccessKey; private readonly string bucket; private readonly string region; private readonly ILog log = LogManager.GetLogger("ASC.Backup.Service"); public S3BackupStorage(string accessKeyId, string secretAccessKey, string bucket, string region) { this.accessKeyId = accessKeyId; this.secretAccessKey = secretAccessKey; this.bucket = bucket; this.region = region; } public string Upload(string storageBasePath, string localPath, Guid userId) { String key = String.Empty; if (String.IsNullOrEmpty(storageBasePath)) key = "backup/" + Path.GetFileName(localPath); else key = String.Concat(storageBasePath.Trim(new char[] {' ', '/', '\\'}), "/", Path.GetFileName(localPath)); using (var fileTransferUtility = new TransferUtility(accessKeyId, secretAccessKey, RegionEndpoint.GetBySystemName(region))) { fileTransferUtility.Upload( new TransferUtilityUploadRequest { BucketName = bucket, FilePath = localPath, StorageClass = S3StorageClass.StandardInfrequentAccess, PartSize = 6291456, // 6 MB. Key = key }); } return key; } public void Download(string storagePath, string targetLocalPath) { var request = new GetObjectRequest { BucketName = bucket, Key = GetKey(storagePath), }; using (var s3 = GetClient()) using (var response = s3.GetObject(request)) { response.WriteResponseStreamToFile(targetLocalPath); } } public void Delete(string storagePath) { using (var s3 = GetClient()) { s3.DeleteObject(new DeleteObjectRequest { BucketName = bucket, Key = GetKey(storagePath) }); } } public bool IsExists(string storagePath) { using (var s3 = GetClient()) { try { var request = new ListObjectsRequest { BucketName = bucket, Prefix = GetKey(storagePath) }; var response = s3.ListObjects(request); return response.S3Objects.Count > 0; } catch (AmazonS3Exception ex) { log.Warn(ex); return false; } } } public string GetPublicLink(string storagePath) { using (var s3 = GetClient()) { return s3.GetPreSignedURL( new GetPreSignedUrlRequest { BucketName = bucket, Key = GetKey(storagePath), Expires = DateTime.UtcNow.AddDays(1), Verb = HttpVerb.GET }); } } private string GetKey(string fileName) { // return "backup/" + Path.GetFileName(fileName); return fileName; } private AmazonS3Client GetClient() { return new AmazonS3Client(accessKeyId, secretAccessKey, new AmazonS3Config { RegionEndpoint = RegionEndpoint.GetBySystemName(region) }); } } } <file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/SIP/Message/SIP_MVGroupHFCollection.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.SIP.Message { #region usings using System.Collections.Generic; #endregion /// <summary> /// Implements same multi value header fields group. Group can contain one type header fields only. /// This is class is used by Via:,Route:, ... . /// </summary> public class SIP_MVGroupHFCollection<T> where T : SIP_t_Value, new() { #region Members private readonly string m_FieldName = ""; private readonly List<SIP_MultiValueHF<T>> m_pFields; private readonly SIP_Message m_pMessage; #endregion #region Properties /// <summary> /// Gets header field name what this group holds. /// </summary> public string FieldName { get { return m_FieldName; } } /// <summary> /// Gets number of header fields in this group. /// </summary> public int Count { get { return m_pFields.Count; } } /// <summary> /// Gets header fields what are in this group. /// </summary> public SIP_MultiValueHF<T>[] HeaderFields { get { return m_pFields.ToArray(); } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="owner">Owner message that owns this group.</param> /// <param name="fieldName">Header field name what group holds.</param> public SIP_MVGroupHFCollection(SIP_Message owner, string fieldName) { m_pMessage = owner; m_FieldName = fieldName; m_pFields = new List<SIP_MultiValueHF<T>>(); Refresh(); } #endregion #region Methods /// <summary> /// Add new header field on the top of the whole header. /// </summary> /// <param name="value">Header field value.</param> public void AddToTop(string value) { m_pMessage.Header.Insert(0, m_FieldName, value); Refresh(); } /// <summary> /// Add new header field on the bottom of the whole header. /// </summary> /// <param name="value">Header field value.</param> public void Add(string value) { m_pMessage.Header.Add(m_FieldName, value); Refresh(); } /// <summary> /// Removes all specified header fields with their values. /// </summary> public void RemoveAll() { m_pMessage.Header.RemoveAll(m_FieldName); m_pFields.Clear(); } /// <summary> /// Gets top most header field first value. /// </summary> public T GetTopMostValue() { if (m_pFields.Count > 0) { return m_pFields[0].Values[0]; } return null; } /// <summary> /// Removes top most header field first value. If value is the last value, /// the whole header field will be removed. /// </summary> public void RemoveTopMostValue() { if (m_pFields.Count > 0) { SIP_MultiValueHF<T> h = m_pFields[0]; if (h.Count > 1) { h.Remove(0); } else { m_pMessage.Header.Remove(m_pFields[0]); m_pFields.Remove(m_pFields[0]); } } } /// <summary> /// Removes last value. If value is the last value n header field, the whole header field will be removed. /// </summary> public void RemoveLastValue() { SIP_MultiValueHF<T> h = m_pFields[m_pFields.Count - 1]; if (h.Count > 1) { h.Remove(h.Count - 1); } else { m_pMessage.Header.Remove(m_pFields[0]); m_pFields.Remove(h); } } /// <summary> /// Gets all header field values. /// </summary> /// <returns></returns> public T[] GetAllValues() { List<T> retVal = new List<T>(); foreach (SIP_MultiValueHF<T> h in m_pFields) { foreach (SIP_t_Value v in h.Values) { retVal.Add((T) v); } } return retVal.ToArray(); } #endregion #region Utility methods /// <summary> /// Refreshes header fields in group from actual header. /// </summary> private void Refresh() { m_pFields.Clear(); foreach (SIP_HeaderField h in m_pMessage.Header) { if (h.Name.ToLower() == m_FieldName.ToLower()) { m_pFields.Add((SIP_MultiValueHF<T>) h); } } } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Autoreply/AddressParsers/AddressParser.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System.Collections.Generic; using System.Net.Mail; using System.Text.RegularExpressions; using System.Linq; using ASC.Core; using ASC.Core.Tenants; namespace ASC.Mail.Autoreply.AddressParsers { internal abstract class AddressParser : IAddressParser { private Regex _routeRegex; private Regex RouteRegex { get { return _routeRegex ?? (_routeRegex = GetRouteRegex()); } } protected abstract Regex GetRouteRegex(); protected abstract ApiRequest ParseRequestInfo(IDictionary<string, string> groups, Tenant t); protected bool IsLastVersion(Tenant t) { return t.Version > 1; } public ApiRequest ParseRequestInfo(string address) { try { var mailAddress = new MailAddress(address); var match = RouteRegex.Match(mailAddress.User); if (!match.Success) return null; var tenant = CoreContext.TenantManager.GetTenant(mailAddress.Host); if (tenant == null) return null; var groups = RouteRegex.GetGroupNames().ToDictionary(groupName => groupName, groupName => match.Groups[groupName].Value); var requestInfo = ParseRequestInfo(groups, tenant); requestInfo.Method = "POST"; requestInfo.Tenant = tenant; if (!string.IsNullOrEmpty(requestInfo.Url)) requestInfo.Url = string.Format("api/2.0/{0}.json", requestInfo.Url); return requestInfo; } catch { return null; } } } } <file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/RTP/RTP_Session.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.RTP { #region usings using System; using System.Collections.Generic; using System.Net; using System.Net.Sockets; using System.Threading; #endregion /// <summary> /// Implements RTP session. Defined in RFC 3550. /// </summary> /// <remarks>RTP session can exchange 1 payload type at time. /// For example if application wants to send audio and video, it must create two different RTP sessions. /// Though RTP session can send multiple streams of same payload.</remarks> public class RTP_Session : IDisposable { #region Events /// <summary> /// Is raised when RTP session has closed. /// </summary> public event EventHandler Closed = null; /// <summary> /// Is raised when RTP session has disposed. /// </summary> public event EventHandler Disposed = null; /// <summary> /// Is raised when new recieve stream received from remote target. /// </summary> public event EventHandler<RTP_ReceiveStreamEventArgs> NewReceiveStream = null; /// <summary> /// Is raised when new send stream created. /// </summary> public event EventHandler<RTP_SendStreamEventArgs> NewSendStream = null; #endregion #region Members private readonly RTP_Clock m_pRtpClock; private int m_Bandwidth = 64000; private bool m_IsDisposed; private long m_LocalCollisions; private long m_LocalPacketsLooped; private int m_MTU = 1400; private int m_Payload; private Dictionary<string, DateTime> m_pConflictingEPs; private RTP_Address m_pLocalEP; private List<RTP_Source_Local> m_pLocalSources; private object m_pLock = new object(); private Dictionary<uint, RTP_Source> m_pMembers; private int m_PMembersCount; private byte[] m_pRtcpReceiveBuffer; private Socket m_pRtcpSocket; private RTP_Source m_pRtcpSource; private TimerEx m_pRtcpTimer; private byte[] m_pRtpReceiveBuffer; private Socket m_pRtpSocket; private Dictionary<uint, RTP_Source> m_pSenders; private RTP_MultimediaSession m_pSession; private List<RTP_Address> m_pTargets; private long m_RemoteCollisions; private long m_RemotePacketsLooped; private double m_RtcpAvgPacketSize; private long m_RtcpBytesReceived; private long m_RtcpBytesSent; private long m_RtcpFailedTransmissions; private DateTime m_RtcpLastTransmission = DateTime.MinValue; private long m_RtcpPacketsReceived; private long m_RtcpPacketsSent; private long m_RtcpUnknownPacketsReceived; private long m_RtpBytesReceived; private long m_RtpBytesSent; private long m_RtpFailedTransmissions; private long m_RtpPacketsReceived; private long m_RtpPacketsSent; #endregion #region Properties /// <summary> /// Gets if this object is disposed. /// </summary> public bool IsDisposed { get { return m_IsDisposed; } } /// <summary> /// Gets owner RTP multimedia session. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public RTP_MultimediaSession Session { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_pSession; } } /// <summary> /// Gets local RTP end point. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public RTP_Address LocalEP { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_pLocalEP; } } /// <summary> /// Gets RTP media clock. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public RTP_Clock RtpClock { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_pRtpClock; } } /// <summary> /// Gets RTP session remote targets. /// </summary> /// <remarks>Normally RTP session has only 1 remote target, for multi-unicast session, there may be more than 1 target.</remarks> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public RTP_Address[] Targets { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_pTargets.ToArray(); } } /// <summary> /// Gets maximum transfet unit size in bytes. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public int MTU { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_MTU; } } /// <summary> /// Gets or sets sending payload. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public int Payload { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_Payload; } set { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } m_Payload = value; } } /// <summary> /// Gets or sets session bandwidth in bits per second. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> /// <exception cref="ArgumentException">Is raised when invalid value is passed.</exception> public int Bandwidth { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_Bandwidth; } set { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (value < 8) { throw new ArgumentException("Property 'Bandwidth' value must be >= 8."); } m_Bandwidth = value; } } /// <summary> /// Gets session members. Session member is local/remote source what sends RTCP,RTP or RTCP-RTP data. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public RTP_Source[] Members { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } lock (m_pMembers) { RTP_Source[] sources = new RTP_Source[m_pMembers.Count]; m_pMembers.Values.CopyTo(sources, 0); return sources; } } } /// <summary> /// Gets session senders. Sender is local/remote source what sends RTP data. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public RTP_Source[] Senders { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } lock (m_pSenders) { RTP_Source[] sources = new RTP_Source[m_pSenders.Count]; m_pSenders.Values.CopyTo(sources, 0); return sources; } } } /// <summary> /// Gets the RTP streams what we send. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public RTP_SendStream[] SendStreams { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } lock (m_pLocalSources) { List<RTP_SendStream> retVal = new List<RTP_SendStream>(); foreach (RTP_Source_Local source in m_pLocalSources) { if (source.Stream != null) { retVal.Add(source.Stream); } } return retVal.ToArray(); } } } /// <summary> /// Gets the RTP streams what we receive. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public RTP_ReceiveStream[] ReceiveStreams { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } lock (m_pSenders) { List<RTP_ReceiveStream> retVal = new List<RTP_ReceiveStream>(); foreach (RTP_Source source in m_pSenders.Values) { if (!source.IsLocal) { retVal.Add(((RTP_Source_Remote) source).Stream); } } return retVal.ToArray(); } } } /// <summary> /// Gets total of RTP packets sent by this session. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public long RtpPacketsSent { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_RtpPacketsSent; } } /// <summary> /// Gets total of RTP bytes(RTP headers included) sent by this session. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public long RtpBytesSent { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_RtpBytesSent; } } /// <summary> /// Gets total of RTP packets received by this session. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public long RtpPacketsReceived { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_RtpPacketsReceived; } } /// <summary> /// Gets total of RTP bytes(RTP headers included) received by this session. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public long RtpBytesReceived { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_RtpBytesReceived; } } /// <summary> /// Gets number of times RTP packet sending has failed. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public long RtpFailedTransmissions { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_RtpFailedTransmissions; } } /// <summary> /// Gets total of RTCP packets sent by this session. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public long RtcpPacketsSent { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_RtcpPacketsSent; } } /// <summary> /// Gets total of RTCP bytes(RTCP headers included) sent by this session. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public long RtcpBytesSent { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_RtcpBytesSent; } } /// <summary> /// Gets total of RTCP packets received by this session. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public long RtcpPacketsReceived { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_RtcpPacketsReceived; } } /// <summary> /// Gets total of RTCP bytes(RTCP headers included) received by this session. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public long RtcpBytesReceived { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_RtcpBytesReceived; } } /// <summary> /// Gets number of times RTCP packet sending has failed. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public long RtcpFailedTransmissions { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_RtcpFailedTransmissions; } } /// <summary> /// Current RTCP reporting interval in seconds. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public int RtcpInterval { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return (int) (m_pRtcpTimer.Interval/1000); } } /// <summary> /// Gets time when last RTCP report was sent. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public DateTime RtcpLastTransmission { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_RtcpLastTransmission; } } /// <summary> /// Gets number of times local SSRC collision dedected. /// </summary> public long LocalCollisions { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_LocalCollisions; } } /// <summary> /// Gets number of times remote SSRC collision dedected. /// </summary> public long RemoteCollisions { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_RemoteCollisions; } } /// <summary> /// Gets number of times local packets loop dedected. /// </summary> public long LocalPacketsLooped { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_LocalPacketsLooped; } } /// <summary> /// Gets number of times remote packets loop dedected. /// </summary> public long RemotePacketsLooped { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_RemotePacketsLooped; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="session">Owner RTP multimedia session.</param> /// <param name="localEP">Local RTP end point.</param> /// <param name="clock">RTP media clock.</param> /// <exception cref="ArgumentNullException">Is raised when <b>localEP</b>, <b>localEP</b> or <b>clock</b> is null reference.</exception> internal RTP_Session(RTP_MultimediaSession session, RTP_Address localEP, RTP_Clock clock) { if (session == null) { throw new ArgumentNullException("session"); } if (localEP == null) { throw new ArgumentNullException("localEP"); } if (clock == null) { throw new ArgumentNullException("clock"); } m_pSession = session; m_pLocalEP = localEP; m_pRtpClock = clock; m_pRtpReceiveBuffer = new byte[Workaround.Definitions.MaxStreamLineLength]; m_pRtcpReceiveBuffer = new byte[Workaround.Definitions.MaxStreamLineLength]; m_pLocalSources = new List<RTP_Source_Local>(); m_pTargets = new List<RTP_Address>(); m_pMembers = new Dictionary<uint, RTP_Source>(); m_pSenders = new Dictionary<uint, RTP_Source>(); m_pConflictingEPs = new Dictionary<string, DateTime>(); m_pRtpSocket = new Socket(localEP.IP.AddressFamily, SocketType.Dgram, ProtocolType.Udp); m_pRtpSocket.Bind(localEP.RtpEP); m_pRtcpSocket = new Socket(localEP.IP.AddressFamily, SocketType.Dgram, ProtocolType.Udp); m_pRtcpSocket.Bind(localEP.RtcpEP); m_pRtcpTimer = new TimerEx(); m_pRtcpTimer.Elapsed += delegate { SendRtcp(); }; m_pRtcpTimer.AutoReset = false; } #endregion #region Methods /// <summary> /// Cleans up any resources being used. /// </summary> public void Dispose() { if (m_IsDisposed) { return; } m_IsDisposed = true; if (m_pRtcpTimer != null) { m_pRtcpTimer.Dispose(); m_pRtcpTimer = null; } m_pSession = null; m_pLocalEP = null; m_pTargets = null; foreach (RTP_Source_Local source in m_pLocalSources.ToArray()) { source.Dispose(); } m_pLocalSources = null; m_pRtcpSource = null; foreach (RTP_Source source in m_pMembers.Values) { source.Dispose(); } m_pMembers = null; m_pSenders = null; m_pConflictingEPs = null; m_pRtpReceiveBuffer = null; m_pRtcpReceiveBuffer = null; m_pRtpSocket.Close(); m_pRtpSocket = null; m_pRtcpSocket.Close(); m_pRtcpSocket = null; OnDisposed(); Disposed = null; Closed = null; NewSendStream = null; NewReceiveStream = null; } /// <summary> /// Closes RTP session, sends BYE with optional reason text to remote targets. /// </summary> /// <param name="closeReason">Close reason. Value null means not specified.</param> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this method is accessed.</exception> public void Close(string closeReason) { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } // Generate BYE packet(s). RTCP_CompoundPacket compundPacket = new RTCP_CompoundPacket(); RTCP_Packet_RR rr = new RTCP_Packet_RR(); rr.SSRC = m_pRtcpSource.SSRC; compundPacket.Packets.Add(rr); int sourcesProcessed = 0; while (sourcesProcessed < m_pLocalSources.Count) { uint[] sources = new uint[Math.Min(m_pLocalSources.Count - sourcesProcessed, 31)]; for (int i = 0; i < sources.Length; i++) { sources[i] = m_pLocalSources[sourcesProcessed].SSRC; sourcesProcessed++; } RTCP_Packet_BYE bye = new RTCP_Packet_BYE(); bye.Sources = sources; compundPacket.Packets.Add(bye); } // Send BYE. SendRtcpPacket(compundPacket); OnClosed(); Dispose(); } /// <summary> /// Starts RTP session. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this method is accessed.</exception> public void Start() { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } /* RFC 3550 6.3.2 Initialization Upon joining the session, the participant initializes tp to 0, tc to 0, senders to 0, pmembers to 1, members to 1, we_sent to false, rtcp_bw to the specified fraction of the session bandwidth, initial to true, and avg_rtcp_size to the probable size of the first RTCP packet that the application will later construct. The calculated interval T is then computed, and the first packet is scheduled for time tn = T. This means that a transmission timer is set which expires at time T. Note that an application MAY use any desired approach for implementing this timer. The participant adds its own SSRC to the member table. */ m_PMembersCount = 1; m_RtcpAvgPacketSize = 100; // Add ourself to members list. m_pRtcpSource = CreateLocalSource(); m_pMembers.Add(m_pRtcpSource.SSRC, m_pRtcpSource); #region IO completion ports if (Net_Utils.IsIoCompletionPortsSupported()) { // Start receiving RTP packet. SocketAsyncEventArgs rtpArgs = new SocketAsyncEventArgs(); rtpArgs.Completed += delegate(object s, SocketAsyncEventArgs e) { if (m_IsDisposed) { return; } if (e.SocketError == SocketError.Success) { ProcessRtp(m_pRtpReceiveBuffer, e.BytesTransferred, (IPEndPoint) rtpArgs.RemoteEndPoint); } // Start receiving next packet. RtpIOCompletionReceive(e); }; // Move processing off the active thread, because ReceiveFromAsync can complete synchronously. ThreadPool.QueueUserWorkItem(delegate { RtpIOCompletionReceive(rtpArgs); }); // Start receiving RTCP packet. SocketAsyncEventArgs rtcpArgs = new SocketAsyncEventArgs(); rtcpArgs.SetBuffer(m_pRtcpReceiveBuffer, 0, m_pRtcpReceiveBuffer.Length); rtcpArgs.Completed += delegate(object s, SocketAsyncEventArgs e) { if (m_IsDisposed) { return; } if (e.SocketError == SocketError.Success) { ProcessRtcp(m_pRtcpReceiveBuffer, e.BytesTransferred, (IPEndPoint) e.RemoteEndPoint); } // Start receiving next packet. RtcpIOCompletionReceive(e); }; // Move processing off the active thread, because ReceiveFromAsync can complete synchronously. ThreadPool.QueueUserWorkItem(delegate { RtcpIOCompletionReceive(rtcpArgs); }); } #endregion #region Async sockets else { // Start receiving RTP packet. EndPoint rtpRemoteEP = new IPEndPoint( m_pRtpSocket.AddressFamily == AddressFamily.InterNetwork ? IPAddress.Any : IPAddress.IPv6Any, 0); m_pRtpSocket.BeginReceiveFrom(m_pRtpReceiveBuffer, 0, m_pRtpReceiveBuffer.Length, SocketFlags.None, ref rtpRemoteEP, RtpAsyncSocketReceiveCompleted, null); // Start receiving RTCP packet. EndPoint rtcpRemoteEP = new IPEndPoint( m_pRtcpSocket.AddressFamily == AddressFamily.InterNetwork ? IPAddress.Any : IPAddress.IPv6Any, 0); m_pRtcpSocket.BeginReceiveFrom(m_pRtcpReceiveBuffer, 0, m_pRtcpReceiveBuffer.Length, SocketFlags.None, ref rtcpRemoteEP, RtcpAsyncSocketReceiveCompleted, null); } #endregion // Start RTCP reporting. Schedule(ComputeRtcpTransmissionInterval(m_pMembers.Count, m_pSenders.Count, m_Bandwidth*0.25, false, m_RtcpAvgPacketSize, true)); } /// <summary> /// Stops RTP session. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this method is accessed.</exception> public void Stop() { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } // TODO: throw new NotImplementedException(); } /// <summary> /// Creates new send stream. /// </summary> /// <returns>Returns new created send stream.</returns> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this method is accessed.</exception> public RTP_SendStream CreateSendStream() { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } RTP_Source_Local source = CreateLocalSource(); source.CreateStream(); OnNewSendStream(source.Stream); return source.Stream; } /// <summary> /// Opens RTP session to the specified remote target. /// </summary> /// <remarks>Once RTP session opened, RTCP reports sent to that target and also each local sending stream data.</remarks> /// <param name="target">Session remote target.</param> /// <exception cref="ArgumentNullException">Is raised when <b>target</b> is null reference.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid values.</exception> public void AddTarget(RTP_Address target) { if (target == null) { throw new ArgumentNullException("target"); } if (m_pLocalEP.Equals(target)) { throw new ArgumentException("Argument 'target' value collapses with property 'LocalEP'.", "target"); } foreach (RTP_Address t in Targets) { if (t.Equals(target)) { throw new ArgumentException("Specified target already exists.", "target"); } } m_pTargets.Add(target); } /// <summary> /// Removes specified target. /// </summary> /// <param name="target">Session remote target.</param> /// <exception cref="ArgumentNullException">Is raised when <b>target</b> is null reference.</exception> public void RemoveTarget(RTP_Address target) { if (target == null) { throw new ArgumentNullException("target"); } m_pTargets.Remove(target); } #endregion #region Utility methods /// <summary> /// Processes specified RTCP data. /// </summary> /// <param name="buffer">Data buffer.</param> /// <param name="count">Number of bytes in data buffer.</param> /// <param name="remoteEP">IP end point what sent RTCP packet.</param> /// <exception cref="ArgumentNullException">Is raised when <b>buffer</b> or <b>remoteEP</b> is null reference.</exception> private void ProcessRtcp(byte[] buffer, int count, IPEndPoint remoteEP) { if (buffer == null) { throw new ArgumentNullException("buffer"); } if (remoteEP == null) { throw new ArgumentNullException("remoteEP"); } /* RFC 3550 6.3.3 Receiving an RTP or Non-BYE RTCP Packet When an RTP or RTCP packet is received from a participant whose SSRC is not in the member table, the SSRC is added to the table, and the value for members is updated once the participant has been validated as described in Section 6.2.1. The same processing occurs for each CSRC in a validated RTP packet. For each compound RTCP packet received, the value of avg_rtcp_size is updated: avg_rtcp_size = (1/16) * packet_size + (15/16) * avg_rtcp_size where packet_size is the size of the RTCP packet just received. 6.3.4 Receiving an RTCP BYE Packet Except as described in Section 6.3.7 for the case when an RTCP BYE is to be transmitted, if the received packet is an RTCP BYE packet, the SSRC is checked against the member table. If present, the entry is removed from the table, and the value for members is updated. The SSRC is then checked against the sender table. If present, the entry is removed from the table, and the value for senders is updated. Furthermore, to make the transmission rate of RTCP packets more adaptive to changes in group membership, the following "reverse reconsideration" algorithm SHOULD be executed when a BYE packet is received. */ m_RtcpPacketsReceived++; m_RtcpBytesReceived += count; // RFC requires IP header counted too, we just don't do it. m_RtcpAvgPacketSize = (1/16)*count + (15/16)*m_RtcpAvgPacketSize; try { RTCP_CompoundPacket compoundPacket = RTCP_CompoundPacket.Parse(buffer, count); // Process each RTCP packet. foreach (RTCP_Packet packet in compoundPacket.Packets) { #region APP if (packet.Type == RTCP_PacketType.APP) { RTCP_Packet_APP app = ((RTCP_Packet_APP) packet); RTP_Source_Remote source = GetOrCreateSource(true, app.Source, null, remoteEP); if (source != null) { source.SetLastRtcpPacket(DateTime.Now); source.OnAppPacket(app); } } #endregion #region BYE else if (packet.Type == RTCP_PacketType.BYE) { RTCP_Packet_BYE bye = ((RTCP_Packet_BYE) packet); bool membersChanges = false; foreach (uint src in bye.Sources) { RTP_Source source = GetOrCreateSource(true, src, null, remoteEP); if (source != null) { membersChanges = true; m_pMembers.Remove(src); source.Close(bye.LeavingReason); // Closing source will take care of closing it's underlaying stream, if source is "active". } m_pSenders.Remove(src); } if (membersChanges) { DoReverseReconsideration(); } } #endregion #region RR else if (packet.Type == RTCP_PacketType.RR) { RTCP_Packet_RR rr = ((RTCP_Packet_RR) packet); RTP_Source source = GetOrCreateSource(true, rr.SSRC, null, remoteEP); if (source != null) { source.SetLastRtcpPacket(DateTime.Now); foreach (RTCP_Packet_ReportBlock reportBlock in rr.ReportBlocks) { source = GetOrCreateSource(true, rr.SSRC, null, remoteEP); if (source != null) { source.SetLastRtcpPacket(DateTime.Now); source.SetRR(reportBlock); } } } } #endregion #region SDES else if (packet.Type == RTCP_PacketType.SDES) { foreach (RTCP_Packet_SDES_Chunk sdes in ((RTCP_Packet_SDES) packet).Chunks) { RTP_Source source = GetOrCreateSource(true, sdes.Source, sdes.CName, remoteEP); if (source != null) { source.SetLastRtcpPacket(DateTime.Now); RTP_Participant_Remote participant = m_pSession.GetOrCreateParticipant(sdes.CName); // Map participant to source. ((RTP_Source_Remote) source).SetParticipant(participant); // Map source to participant. participant.EnsureSource(source); // Update participant SDES items. participant.Update(sdes); } } } #endregion #region SR else if (packet.Type == RTCP_PacketType.SR) { RTCP_Packet_SR sr = ((RTCP_Packet_SR) packet); RTP_Source_Remote source = GetOrCreateSource(true, sr.SSRC, null, remoteEP); if (source != null) { source.SetLastRtcpPacket(DateTime.Now); source.OnSenderReport(new RTCP_Report_Sender(sr)); foreach (RTCP_Packet_ReportBlock reportBlock in sr.ReportBlocks) { source = GetOrCreateSource(true, sr.SSRC, null, remoteEP); if (source != null) { source.SetLastRtcpPacket(DateTime.Now); source.SetRR(reportBlock); } } } } #endregion // Unknown packet. else { m_RtcpUnknownPacketsReceived++; } } } catch (Exception x) { m_pSession.OnError(x); } } /// <summary> /// Processes specified RTP data. /// </summary> /// <param name="buffer">Data buffer.</param> /// <param name="count">Number of bytes in data buffer.</param> /// <param name="remoteEP">IP end point what sent RTCP packet.</param> /// <exception cref="ArgumentNullException">Is raised when <b>buffer</b> or <b>remoteEP</b> is null reference.</exception> private void ProcessRtp(byte[] buffer, int count, IPEndPoint remoteEP) { if (buffer == null) { throw new ArgumentNullException("buffer"); } if (remoteEP == null) { throw new ArgumentNullException("remoteEP"); } /* RFC 3550 6.3.3 Receiving an RTP or Non-BYE RTCP Packet When an RTP or RTCP packet is received from a participant whose SSRC is not in the member table, the SSRC is added to the table, and the value for members is updated once the participant has been validated as described in Section 6.2.1. The same processing occurs for each CSRC in a validated RTP packet. When an RTP packet is received from a participant whose SSRC is not in the sender table, the SSRC is added to the table, and the value for senders is updated. */ m_RtpPacketsReceived++; m_RtpBytesReceived += count; try { RTP_Packet packet = RTP_Packet.Parse(buffer, count); RTP_Source source = GetOrCreateSource(false, packet.SSRC, null, remoteEP); if (source != null) { // Process CSRC. foreach (uint csrc in packet.CSRC) { RTP_Source dummy = GetOrCreateSource(false, packet.SSRC, null, remoteEP); } lock (m_pSenders) { if (!m_pSenders.ContainsKey(source.SSRC)) { m_pSenders.Add(source.SSRC, source); } } // Let source to process RTP packet. ((RTP_Source_Remote) source).OnRtpPacketReceived(packet, count); } } catch (Exception x) { m_pSession.OnError(x); } } /// <summary> /// Gets or creates source. This method also does RFC 3550 8.2 "Collision Resolution and Loop Detection". /// </summary> /// <param name="rtcp_rtp">If true <b>src</b> is RTCP identifier, otherwise RTP identifier.</param> /// <param name="src">Source SSRC or CSRC identifier.</param> /// <param name="cname">RTCP SDES chunk CNAME. Must be passed only if <b>src</b> if from RTCP SDES chunk.</param> /// <param name="packetEP">Packet sender end point.</param> /// <returns>Returns specified source. Returns null if source has "collision or loop".</returns> /// <exception cref="ArgumentNullException">Is raised when <b>packetEP</b> is null reference.</exception> private RTP_Source_Remote GetOrCreateSource(bool rtcp_rtp, uint src, string cname, IPEndPoint packetEP) { if (packetEP == null) { throw new ArgumentNullException("packetEP"); } /* RFC 3550 8.2. if(SSRC or CSRC identifier is not found in the source identifier table){ create a new entry storing the data or control source transport address, the SSRC or CSRC and other state; } else if(table entry was created on receipt of a control packet and this is the first data packet or vice versa){ store the source transport address from this packet; } else if(source transport address from the packet does not match the one saved in the table entry for this identifier){ // An identifier collision or a loop is indicated if(source identifier is not the participant's own){ // OPTIONAL error counter step if(source identifier is from an RTCP SDES chunk containing a CNAME item that differs from the CNAME in the table entry){ count a third-party collision; } else{ count a third-party loop; } abort processing of data packet or control element; // MAY choose a different policy to keep new source } // A collision or loop of the participant's own packets else if(source transport address is found in the list of conflicting data or control source transport addresses){ // OPTIONAL error counter step if(source identifier is not from an RTCP SDES chunk containing a CNAME item or CNAME is the participant's own){ count occurrence of own traffic looped; } mark current time in conflicting address list entry; abort processing of data packet or control element; } // New collision, change SSRC identifier else{ log occurrence of a collision; create a new entry in the conflicting data or control source transport address list and mark current time; send an RTCP BYE packet with the old SSRC identifier; choose a new SSRC identifier; create a new entry in the source identifier table with the old SSRC plus the source transport address from the data or control packet being processed; } } */ RTP_Source source = null; lock (m_pMembers) { m_pMembers.TryGetValue(src, out source); // SSRC or CSRC identifier is not found in the source identifier table. if (source == null) { source = new RTP_Source_Remote(this, src); if (rtcp_rtp) { source.SetRtcpEP(packetEP); } else { source.SetRtpEP(packetEP); } m_pMembers.Add(src, source); } // Table entry was created on receipt of a control packet and this is the first data packet or vice versa. else if ((rtcp_rtp ? source.RtcpEP : source.RtpEP) == null) { if (rtcp_rtp) { source.SetRtcpEP(packetEP); } else { source.SetRtpEP(packetEP); } } // Source transport address from the packet does not match the one saved in the table entry for this identifier. else if (!packetEP.Equals((rtcp_rtp ? source.RtcpEP : source.RtpEP))) { // Source identifier is not the participant's own. if (!source.IsLocal) { if (cname != null && cname != source.CName) { m_RemoteCollisions++; } else { m_RemotePacketsLooped++; } return null; } // A collision or loop of the participant's own packets. else if (m_pConflictingEPs.ContainsKey(packetEP.ToString())) { if (cname == null || cname == source.CName) { m_LocalPacketsLooped++; } m_pConflictingEPs[packetEP.ToString()] = DateTime.Now; return null; } // New collision, change SSRC identifier. else { m_LocalCollisions++; m_pConflictingEPs.Add(packetEP.ToString(), DateTime.Now); // Remove SSRC from members,senders. Choose new SSRC, CNAME new and BYE old. m_pMembers.Remove(source.SSRC); m_pSenders.Remove(source.SSRC); uint oldSSRC = source.SSRC; source.GenerateNewSSRC(); // Ensure that new SSRC is not in use, if so repaeat while not conflicting SSRC. while (m_pMembers.ContainsKey(source.SSRC)) { source.GenerateNewSSRC(); } m_pMembers.Add(source.SSRC, source); RTCP_CompoundPacket compoundPacket = new RTCP_CompoundPacket(); RTCP_Packet_RR rr = new RTCP_Packet_RR(); rr.SSRC = m_pRtcpSource.SSRC; compoundPacket.Packets.Add(rr); RTCP_Packet_SDES sdes = new RTCP_Packet_SDES(); RTCP_Packet_SDES_Chunk sdes_chunk = new RTCP_Packet_SDES_Chunk(source.SSRC, m_pSession. LocalParticipant. CNAME); sdes.Chunks.Add(sdes_chunk); compoundPacket.Packets.Add(sdes); RTCP_Packet_BYE bye = new RTCP_Packet_BYE(); bye.Sources = new[] {oldSSRC}; bye.LeavingReason = "Collision, changing SSRC."; compoundPacket.Packets.Add(bye); SendRtcpPacket(compoundPacket); //---------------------------------------------------------------------- // Add new source to members, it's not conflicting any more, we changed SSRC. source = new RTP_Source_Remote(this, src); if (rtcp_rtp) { source.SetRtcpEP(packetEP); } else { source.SetRtpEP(packetEP); } m_pMembers.Add(src, source); } } } return (RTP_Source_Remote) source; } /// <summary> /// Schedules RTCP transmission. /// </summary> /// <param name="seconds">After number of seconds to transmit next RTCP.</param> private void Schedule(int seconds) { m_pRtcpTimer.Stop(); m_pRtcpTimer.Interval = seconds*1000; m_pRtcpTimer.Enabled = true; } /// <summary> /// Computes RTCP transmission interval. Defined in RFC 3550 6.3.1. /// </summary> /// <param name="members">Current mebers count.</param> /// <param name="senders">Current sender count.</param> /// <param name="rtcp_bw">RTCP bandwidth.</param> /// <param name="we_sent">Specifies if we have sent data after last 2 RTCP interval.</param> /// <param name="avg_rtcp_size">Average RTCP raw packet size, IP headers included.</param> /// <param name="initial">Specifies if we ever have sent data to target.</param> /// <returns>Returns transmission interval in seconds.</returns> private int ComputeRtcpTransmissionInterval(int members, int senders, double rtcp_bw, bool we_sent, double avg_rtcp_size, bool initial) { // RFC 3550 A.7. /* Minimum average time between RTCP packets from this site (in seconds). This time prevents the reports from `clumping' when sessions are small and the law of large numbers isn't helping to smooth out the traffic. It also keeps the report interval from becoming ridiculously small during transient outages like a network partition. */ double RTCP_MIN_TIME = 5; /* Fraction of the RTCP bandwidth to be shared among active senders. (This fraction was chosen so that in a typical session with one or two active senders, the computed report time would be roughly equal to the minimum report time so that we don't unnecessarily slow down receiver reports.) The receiver fraction must be 1 - the sender fraction. */ double RTCP_SENDER_BW_FRACTION = 0.25; double RTCP_RCVR_BW_FRACTION = (1 - RTCP_SENDER_BW_FRACTION); /* To compensate for "timer reconsideration" converging to a value below the intended average. */ double COMPENSATION = 2.71828 - 1.5; double t; /* interval */ double rtcp_min_time = RTCP_MIN_TIME; int n; /* no. of members for computation */ /* Very first call at application start-up uses half the min delay for quicker notification while still allowing some time before reporting for randomization and to learn about other sources so the report interval will converge to the correct interval more quickly. */ if (initial) { rtcp_min_time /= 2; } /* Dedicate a fraction of the RTCP bandwidth to senders unless the number of senders is large enough that their share is more than that fraction. */ n = members; if (senders <= (members*RTCP_SENDER_BW_FRACTION)) { if (we_sent) { rtcp_bw = (rtcp_bw*RTCP_SENDER_BW_FRACTION); n = senders; } else { rtcp_bw = (rtcp_bw*RTCP_SENDER_BW_FRACTION); n -= senders; } } /* The effective number of sites times the average packet size is the total number of octets sent when each site sends a report. Dividing this by the effective bandwidth gives the time interval over which those packets must be sent in order to meet the bandwidth target, with a minimum enforced. In that time interval we send one report so this time is also our average time between reports. */ t = avg_rtcp_size*n/rtcp_bw; if (t < rtcp_min_time) { t = rtcp_min_time; } /* To avoid traffic bursts from unintended synchronization with other sites, we then pick our actual next report interval as a random number uniformly distributed between 0.5*t and 1.5*t. */ t = t*(new Random().Next(5, 15)/10.0); t = t/COMPENSATION; return (int) Math.Max(t, 2.0); } /// <summary> /// Does "reverse reconsideration" algorithm. Defined in RFC 3550 6.3.4. /// </summary> private void DoReverseReconsideration() { /* RFC 3550 6.3.4. "reverse reconsideration" o The value for tn is updated according to the following formula: tn = tc + (members/pmembers) * (tn - tc) o The value for tp is updated according the following formula: tp = tc - (members/pmembers) * (tc - tp). o The next RTCP packet is rescheduled for transmission at time tn, which is now earlier. o The value of pmembers is set equal to members. This algorithm does not prevent the group size estimate from incorrectly dropping to zero for a short time due to premature timeouts when most participants of a large session leave at once but some remain. The algorithm does make the estimate return to the correct value more rapidly. This situation is unusual enough and the consequences are sufficiently harmless that this problem is deemed only a secondary concern. */ DateTime timeNext = m_RtcpLastTransmission == DateTime.MinValue ? DateTime.Now : m_RtcpLastTransmission.AddMilliseconds(m_pRtcpTimer.Interval); Schedule( (int) Math.Max((m_pMembers.Count/m_PMembersCount)*((timeNext - DateTime.Now)).TotalSeconds, 2)); m_PMembersCount = m_pMembers.Count; } /// <summary> /// Does RFC 3550 6.3.5 Timing Out an SSRC. /// </summary> private void TimeOutSsrc() { /* RFC 3550 6.3.5 Timing Out an SSRC. At occasional intervals, the participant MUST check to see if any of the other participants time out. To do this, the participant computes the deterministic (without the randomization factor) calculated interval Td for a receiver, that is, with we_sent false. Any other session member who has not sent an RTP or RTCP packet since time tc - MTd (M is the timeout multiplier, and defaults to 5) is timed out. This means that its SSRC is removed from the member list, and members is updated. A similar check is performed on the sender list. Any member on the sender list who has not sent an RTP packet since time tc - 2T (within the last two RTCP report intervals) is removed from the sender list, and senders is updated. If any members time out, the reverse reconsideration algorithm described in Section 6.3.4 SHOULD be performed. The participant MUST perform this check at least once per RTCP transmission interval. */ bool membersUpdated = false; // Senders check. RTP_Source[] senders = new RTP_Source[m_pSenders.Count]; m_pSenders.Values.CopyTo(senders, 0); foreach (RTP_Source sender in senders) { // Sender has not sent RTP data since last two RTCP intervals. if (sender.LastRtpPacket.AddMilliseconds(2*m_pRtcpTimer.Interval) < DateTime.Now) { m_pSenders.Remove(sender.SSRC); // Mark source "passive". sender.SetActivePassive(false); } } int Td = ComputeRtcpTransmissionInterval(m_pMembers.Count, m_pSenders.Count, m_Bandwidth*0.25, false, m_RtcpAvgPacketSize, false); // Members check. foreach (RTP_Source member in Members) { // Source timed out. if (member.LastActivity.AddSeconds(5*Td) < DateTime.Now) { m_pMembers.Remove(member.SSRC); // Don't dispose local source, just remove only from members. if (!member.IsLocal) { member.Dispose(); } membersUpdated = true; } } if (membersUpdated) { DoReverseReconsideration(); } } /// <summary> /// Sends RTCP report. /// </summary> private void SendRtcp() { /* RFC 3550 6.4 Sender and Receiver Reports RTP receivers provide reception quality feedback using RTCP report packets which may take one of two forms depending upon whether or not the receiver is also a sender. The only difference between the sender report (SR) and receiver report (RR) forms, besides the packet type code, is that the sender report includes a 20-byte sender information section for use by active senders. The SR is issued if a site has sent any data packets during the interval since issuing the last report or the previous one, otherwise the RR is issued. Both the SR and RR forms include zero or more reception report blocks, one for each of the synchronization sources from which this receiver has received RTP data packets since the last report. Reports are not issued for contributing sources listed in the CSRC list. Each reception report block provides statistics about the data received from the particular source indicated in that block. Since a maximum of 31 reception report blocks will fit in an SR or RR packet, additional RR packets SHOULD be stacked after the initial SR or RR packet as needed to contain the reception reports for all sources heard during the interval since the last report. If there are too many sources to fit all the necessary RR packets into one compound RTCP packet without exceeding the MTU of the network path, then only the subset that will fit into one MTU SHOULD be included in each interval. The subsets SHOULD be selected round-robin across multiple intervals so that all sources are reported. */ bool we_sent = false; try { m_pRtcpSource.SetLastRtcpPacket(DateTime.Now); RTCP_CompoundPacket compundPacket = new RTCP_CompoundPacket(); RTCP_Packet_RR rr = null; // Find active send streams. List<RTP_SendStream> activeSendStreams = new List<RTP_SendStream>(); foreach (RTP_SendStream stream in SendStreams) { if (stream.RtcpCyclesSinceWeSent < 2) { activeSendStreams.Add(stream); we_sent = true; } // Notify stream about RTCP cycle. stream.RtcpCycle(); } #region SR(s) / RR // We are sender. if (we_sent) { // Create SR for each active send stream. for (int i = 0; i < activeSendStreams.Count; i++) { RTP_SendStream sendStream = activeSendStreams[i]; RTCP_Packet_SR sr = new RTCP_Packet_SR(sendStream.Source.SSRC); sr.NtpTimestamp = RTP_Utils.DateTimeToNTP64(DateTime.Now); sr.RtpTimestamp = m_pRtpClock.RtpTimestamp; sr.SenderPacketCount = (uint) sendStream.RtpPacketsSent; sr.SenderOctetCount = (uint) sendStream.RtpBytesSent; compundPacket.Packets.Add(sr); } } // We are receiver. else { rr = new RTCP_Packet_RR(); rr.SSRC = m_pRtcpSource.SSRC; compundPacket.Packets.Add(rr); // Report blocks added later. } #endregion #region SDES RTCP_Packet_SDES sdes = new RTCP_Packet_SDES(); // Add default SSRC. RTCP_Packet_SDES_Chunk sdesChunk = new RTCP_Packet_SDES_Chunk(m_pRtcpSource.SSRC, m_pSession.LocalParticipant. CNAME); // Add next optional SDES item, if any. (We round-robin optional items) m_pSession.LocalParticipant.AddNextOptionalSdesItem(sdesChunk); sdes.Chunks.Add(sdesChunk); // Add all active send streams SSRC -> CNAME. This enusres that all send streams will be mapped to participant. foreach (RTP_SendStream stream in activeSendStreams) { sdes.Chunks.Add(new RTCP_Packet_SDES_Chunk(stream.Source.SSRC, m_pSession.LocalParticipant.CNAME)); } compundPacket.Packets.Add(sdes); #endregion #region RR filling /* RR reporting: Report up to 31 active senders, if more senders, reoprt next with next interval. Report oldest not reported first,then ventually all sources will be reported with this algorythm. */ RTP_Source[] senders = Senders; DateTime[] acitveSourceRRTimes = new DateTime[senders.Length]; RTP_ReceiveStream[] activeSenders = new RTP_ReceiveStream[senders.Length]; int activeSenderCount = 0; foreach (RTP_Source sender in senders) { // Remote sender sent RTP data during last RTCP interval. if (!sender.IsLocal && sender.LastRtpPacket > m_RtcpLastTransmission) { acitveSourceRRTimes[activeSenderCount] = sender.LastRRTime; activeSenders[activeSenderCount] = ((RTP_Source_Remote) sender).Stream; activeSenderCount++; } } // Create RR is SR report and no RR created yet. if (rr == null) { rr = new RTCP_Packet_RR(); rr.SSRC = m_pRtcpSource.SSRC; compundPacket.Packets.Add(rr); } // Sort ASC. Array.Sort(acitveSourceRRTimes, activeSenders, 0, activeSenderCount); // Add up to 31 oldest not reported sources to report. for (int i = 1; i < 31; i++) { if ((activeSenderCount - i) < 0) { break; } rr.ReportBlocks.Add(activeSenders[activeSenderCount - i].CreateReceiverReport()); } #endregion // Send RTPC packet. SendRtcpPacket(compundPacket); // Timeout conflicting transport addresses, if not conflicting any more. lock (m_pConflictingEPs) { string[] keys = new string[m_pConflictingEPs.Count]; m_pConflictingEPs.Keys.CopyTo(keys, 0); foreach (string key in keys) { if (m_pConflictingEPs[key].AddMinutes(3) < DateTime.Now) { m_pConflictingEPs.Remove(key); } } } // Since we must check timing out sources at least once per RTCP interval, so we // check this before sending RTCP. TimeOutSsrc(); } catch (Exception x) { m_pSession.OnError(x); } m_RtcpLastTransmission = DateTime.Now; // Schedule next RTCP sending. Schedule(ComputeRtcpTransmissionInterval(m_pMembers.Count, m_pSenders.Count, m_Bandwidth*0.25, we_sent, m_RtcpAvgPacketSize, false)); } /// <summary> /// Is called when RTP socket has received data. /// </summary> /// <param name="ar">The result of the asynchronous operation.</param> private void RtpAsyncSocketReceiveCompleted(IAsyncResult ar) { try { EndPoint remoteEP = new IPEndPoint(IPAddress.Any, 0); int count = m_pRtpSocket.EndReceiveFrom(ar, ref remoteEP); ProcessRtp(m_pRtpReceiveBuffer, count, (IPEndPoint) remoteEP); } catch { // Skip receiving socket errors. } // Start receiving next RTP packet. EndPoint remEP = new IPEndPoint(IPAddress.Any, 0); m_pRtpSocket.BeginReceiveFrom(m_pRtpReceiveBuffer, 0, m_pRtpReceiveBuffer.Length, SocketFlags.None, ref remEP, RtpAsyncSocketReceiveCompleted, null); // TODO: we may get 10054 error here if IP conflict } /// <summary> /// Is called when RTCP socket has received data. /// </summary> /// <param name="ar">The result of the asynchronous operation.</param> private void RtcpAsyncSocketReceiveCompleted(IAsyncResult ar) { try { EndPoint remoteEP = new IPEndPoint(IPAddress.Any, 0); int count = m_pRtcpSocket.EndReceiveFrom(ar, ref remoteEP); ProcessRtcp(m_pRtcpReceiveBuffer, count, (IPEndPoint) remoteEP); } catch { // Skip receiving socket errors. } // Start receiving next RTCP packet. EndPoint remEP = new IPEndPoint(IPAddress.Any, 0); m_pRtcpSocket.BeginReceiveFrom(m_pRtcpReceiveBuffer, 0, m_pRtcpReceiveBuffer.Length, SocketFlags.None, ref remEP, RtcpAsyncSocketReceiveCompleted, null); // TODO: we may get 10054 error here if IP conflict } /// <summary> /// Accepts or starts accepting incoming RTP data. /// </summary> /// <param name="socketArgs">ReceiveFromAsync method data.</param> /// <exception cref="ArgumentNullException">Is raised when <b>socketArgs</b> is null reference.</exception> private void RtpIOCompletionReceive(SocketAsyncEventArgs socketArgs) { if (socketArgs == null) { throw new ArgumentNullException("socketArgs"); } try { // Reset state for reuse. socketArgs.SetBuffer(m_pRtpReceiveBuffer, 0, m_pRtpReceiveBuffer.Length); socketArgs.RemoteEndPoint = new IPEndPoint( m_pRtcpSocket.AddressFamily == AddressFamily.InterNetwork ? IPAddress.Any : IPAddress.IPv6Any, 0); // Use active worker thread as long as ReceiveFromAsync completes synchronously. // (With this approeach we don't have thread context switches while ReceiveFromAsync completes synchronously) while (!m_pRtpSocket.ReceiveFromAsync(socketArgs)) { if (socketArgs.SocketError == SocketError.Success) { ProcessRtp(m_pRtpReceiveBuffer, socketArgs.BytesTransferred, (IPEndPoint) socketArgs.RemoteEndPoint); } } } catch (Exception x) { m_pSession.OnError(x); } } /// <summary> /// Accepts or starts accepting incoming RTCP data. /// </summary> /// <param name="socketArgs">ReceiveFromAsync method data.</param> /// <exception cref="ArgumentNullException">Is raised when <b>socketArgs</b> is null reference.</exception> private void RtcpIOCompletionReceive(SocketAsyncEventArgs socketArgs) { if (socketArgs == null) { throw new ArgumentNullException("socketArgs"); } // Reset state for reuse. socketArgs.SetBuffer(m_pRtcpReceiveBuffer, 0, m_pRtcpReceiveBuffer.Length); socketArgs.RemoteEndPoint = new IPEndPoint( m_pRtcpSocket.AddressFamily == AddressFamily.InterNetwork ? IPAddress.Any : IPAddress.IPv6Any, 0); // Use active worker thread as long as ReceiveFromAsync completes synchronously. // (With this approeach we don't have thread context switches while ReceiveFromAsync completes synchronously) while (!m_pRtcpSocket.ReceiveFromAsync(socketArgs)) { if (socketArgs.SocketError == SocketError.Success) { ProcessRtcp(m_pRtcpReceiveBuffer, socketArgs.BytesTransferred, (IPEndPoint) socketArgs.RemoteEndPoint); } } } /// <summary> /// Raises <b>Disposed</b> event. /// </summary> private void OnDisposed() { if (Disposed != null) { Disposed(this, new EventArgs()); } } /// <summary> /// Raises <b>Closed</b> event. /// </summary> private void OnClosed() { if (Closed != null) { Closed(this, new EventArgs()); } } /// <summary> /// Raises <b>NewSendStream</b> event. /// </summary> /// <param name="stream">New send stream.</param> private void OnNewSendStream(RTP_SendStream stream) { if (NewSendStream != null) { NewSendStream(this, new RTP_SendStreamEventArgs(stream)); } } #endregion #region Internal methods /// <summary> /// Sends specified RTCP packet to the session remote party. /// </summary> /// <param name="packet">RTCP compound packet.</param> /// <returns>Returns packet size in bytes.</returns> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this method is accessed.</exception> /// <exception cref="ArgumentNullException">Is raised when <b>packet</b> is null reference.</exception> internal int SendRtcpPacket(RTCP_CompoundPacket packet) { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (packet == null) { throw new ArgumentNullException("packet"); } byte[] packetBytes = packet.ToByte(); // Send packet to each remote target. foreach (RTP_Address target in Targets) { try { m_pRtcpSocket.SendTo(packetBytes, packetBytes.Length, SocketFlags.None, target.RtcpEP); m_RtcpPacketsSent++; m_RtcpBytesSent += packetBytes.Length; // RFC requires IP header counted too, we just don't do it. m_RtcpAvgPacketSize = (1/16)*packetBytes.Length + (15/16)*m_RtcpAvgPacketSize; } catch { m_RtcpFailedTransmissions++; } } return packetBytes.Length; } /// <summary> /// Sends specified RTP packet to the session remote party. /// </summary> /// <param name="stream">RTP packet sending stream.</param> /// <param name="packet">RTP packet.</param> /// <returns>Returns packet size in bytes.</returns> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this method is accessed.</exception> /// <exception cref="ArgumentNullException">Is raised when <b>stream</b> or <b>packet</b> is null reference.</exception> internal int SendRtpPacket(RTP_SendStream stream, RTP_Packet packet) { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (stream == null) { throw new ArgumentNullException("stream"); } if (packet == null) { throw new ArgumentNullException("packet"); } // Check that we are in members table (because SSRC has timed out), add itself to senders table. lock (m_pMembers) { if (!m_pMembers.ContainsKey(stream.Source.SSRC)) { m_pMembers.Add(stream.Source.SSRC, stream.Source); } } // If we are not in sender table (because SSRC has timed out), add itself to senders table. lock (m_pSenders) { if (!m_pSenders.ContainsKey(stream.Source.SSRC)) { m_pSenders.Add(stream.Source.SSRC, stream.Source); } } byte[] packetBytes = new byte[m_MTU]; int count = 0; packet.ToByte(packetBytes, ref count); // Send packet to each remote target. foreach (RTP_Address target in Targets) { try { m_pRtpSocket.SendTo(packetBytes, count, SocketFlags.None, target.RtpEP); m_RtpPacketsSent++; m_RtpBytesSent += packetBytes.Length; } catch { m_RtpFailedTransmissions++; } } return count; } /// <summary> /// Creates local source. /// </summary> /// <returns>Returns new local source.</returns> internal RTP_Source_Local CreateLocalSource() { uint ssrc = RTP_Utils.GenerateSSRC(); // Ensure that any member don't have such SSRC. while (m_pMembers.ContainsKey(ssrc)) { ssrc = RTP_Utils.GenerateSSRC(); } RTP_Source_Local source = new RTP_Source_Local(this, ssrc, m_pLocalEP.RtcpEP, m_pLocalEP.RtpEP); source.Disposing += delegate { m_pSenders.Remove(source.SSRC); m_pMembers.Remove(source.SSRC); m_pLocalSources.Remove(source); }; m_pLocalSources.Add(source); m_pSession.LocalParticipant.EnsureSource(source); return source; } /// <summary> /// Raises <b>NewReceiveStream</b> event. /// </summary> /// <param name="stream">New receive stream.</param> internal void OnNewReceiveStream(RTP_ReceiveStream stream) { if (NewReceiveStream != null) { NewReceiveStream(this, new RTP_ReceiveStreamEventArgs(stream)); } } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Autoreply/Utility/Html/HtmlSanitizer.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections.Generic; using System.IO; using HtmlAgilityPack; namespace ASC.Mail.Autoreply.Utility.Html { public class HtmlSanitizer { private static readonly List<string> MaliciousTags = new List<string> { "script", "style" }; private static readonly List<string> LineBreakers = new List<string> { "p", "div", "blockquote", "br" }; private static readonly List<string> WhiteList = new List<string> {"b", "strong", "it", "em", "dfn", "sub", "sup", "strike", "s", "del", "code", "kbd", "samp", "ins", "h1", "h2", "h3", "h4", "h5", "h6"}; public static String Sanitize(String html) { if (String.IsNullOrEmpty(html)) return html; var doc = new HtmlDocument(); doc.LoadHtml(html); var sw = new StringWriter(); ProcessNode(doc.DocumentNode, sw); sw.Flush(); return sw.ToString(); } private static void ProcessContent(HtmlNode node, TextWriter outText) { foreach (var child in node.ChildNodes) { ProcessNode(child, outText); } } private static void ProcessNode(HtmlNode node, TextWriter outText) { switch (node.NodeType) { case HtmlNodeType.Comment: break; case HtmlNodeType.Document: ProcessContent(node, outText); break; case HtmlNodeType.Element: var name = node.Name.ToLowerInvariant(); if (MaliciousTags.Contains(name)) break; if (WhiteList.Contains(name) && node.HasChildNodes && node.Closed) { outText.Write("<{0}>", name); ProcessContent(node, outText); outText.Write("</{0}>", name); break; } if (name.Equals("img") && node.HasAttributes && node.Attributes["src"] != null) { outText.Write("<img src=\"{0}\"/>", node.Attributes["src"].Value); } else if (LineBreakers.Contains(name)) { outText.Write("<br>"); } if (node.HasChildNodes) ProcessContent(node, outText); break; case HtmlNodeType.Text: var text = ((HtmlTextNode) node).Text; if (HtmlNode.IsOverlappedClosingElement(text)) break; if (text.Trim().Length > 0) outText.Write(text); break; } } } } <file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/RTP/RTCP_Packet_RR.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.RTP { #region usings using System; using System.Collections.Generic; using System.Text; #endregion /// <summary> /// This class represents RR: Receiver Report RTCP Packet. /// </summary> public class RTCP_Packet_RR : RTCP_Packet { #region Members private readonly List<RTCP_Packet_ReportBlock> m_pReportBlocks; private uint m_SSRC; private int m_Version = 2; #endregion #region Properties /// <summary> /// Gets RTCP version. /// </summary> public override int Version { get { return m_Version; } } /// <summary> /// Gets RTCP packet type. /// </summary> public override int Type { get { return RTCP_PacketType.RR; } } /// <summary> /// Gets or sets sender(local reporting) synchronization source identifier. /// </summary> public uint SSRC { get { return m_SSRC; } set { m_SSRC = value; } } /// <summary> /// Gets reports blocks. /// </summary> public List<RTCP_Packet_ReportBlock> ReportBlocks { get { return m_pReportBlocks; } } /// <summary> /// Gets number of bytes needed for this packet. /// </summary> public override int Size { get { return 8 + (24*m_pReportBlocks.Count); } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> internal RTCP_Packet_RR() { m_pReportBlocks = new List<RTCP_Packet_ReportBlock>(); } /// <summary> /// Default constructor. /// </summary> /// <param name="ssrc">SSRC of this packet sender.</param> internal RTCP_Packet_RR(uint ssrc) { m_pReportBlocks = new List<RTCP_Packet_ReportBlock>(); } #endregion #region Methods /// <summary> /// Stores receiver report(RR) packet to the specified buffer. /// </summary> /// <param name="buffer">Buffer where to store RR packet.</param> /// <param name="offset">Offset in buffer.</param> /// <exception cref="ArgumentNullException">Is raised when <b>buffer</b> is null.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> public override void ToByte(byte[] buffer, ref int offset) { /* RFC 3550 6.4.2 RR: Receiver Report RTCP Packet. 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ header |V=2|P| RC | PT=RR=201 | length | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | SSRC of packet sender | +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ report | SSRC_1 (SSRC of first source) | block +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 1 | fraction lost | cumulative number of packets lost | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | extended highest sequence number received | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | interarrival jitter | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | last SR (LSR) | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | delay since last SR (DLSR) | +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ report | SSRC_2 (SSRC of second source) | block +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 2 : ... : +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ | profile-specific extensions | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ if (buffer == null) { throw new ArgumentNullException("buffer"); } if (offset < 0) { throw new ArgumentException("Argument 'offset' value must be >= 0."); } // NOTE: Size in 32-bit boundary, header not included. int length = (4 + (m_pReportBlocks.Count*24))/4; // V P RC buffer[offset++] = (byte) (2 << 6 | 0 << 5 | (m_pReportBlocks.Count & 0x1F)); // PT=RR=201 buffer[offset++] = 201; // length buffer[offset++] = (byte) ((length >> 8) & 0xFF); buffer[offset++] = (byte) ((length) & 0xFF); // SSRC buffer[offset++] = (byte) ((m_SSRC >> 24) & 0xFF); buffer[offset++] = (byte) ((m_SSRC >> 16) & 0xFF); buffer[offset++] = (byte) ((m_SSRC >> 8) & 0xFF); buffer[offset++] = (byte) ((m_SSRC) & 0xFF); // Report blocks foreach (RTCP_Packet_ReportBlock block in m_pReportBlocks) { block.ToByte(buffer, ref offset); } } /// <summary> /// Returns RR packet as string. /// </summary> /// <returns>Returns RR packet as string.</returns> public override string ToString() { StringBuilder retVal = new StringBuilder(); retVal.AppendLine("Type: RR"); retVal.AppendLine("Version: " + m_Version); retVal.AppendLine("SSRC: " + m_SSRC); retVal.AppendLine("Report blocks: " + m_pReportBlocks.Count); return retVal.ToString(); } #endregion #region Overrides /// <summary> /// Parses receiver report(RR) from byte buffer. /// </summary> /// <param name="buffer">Buffer wihich contains receiver report.</param> /// <param name="offset">Offset in buufer.</param> /// <exception cref="ArgumentNullException">Is raised when <b>buffer</b> is null.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> protected override void ParseInternal(byte[] buffer, ref int offset) { /* RFC 3550 6.4.2 RR: Receiver Report RTCP Packet. 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ header |V=2|P| RC | PT=RR=201 | length | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | SSRC of packet sender | +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ report | SSRC_1 (SSRC of first source) | block +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 1 | fraction lost | cumulative number of packets lost | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | extended highest sequence number received | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | interarrival jitter | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | last SR (LSR) | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | delay since last SR (DLSR) | +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ report | SSRC_2 (SSRC of second source) | block +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 2 : ... : +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ | profile-specific extensions | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ if (buffer == null) { throw new ArgumentNullException("buffer"); } if (offset < 0) { throw new ArgumentException("Argument 'offset' value must be >= 0."); } m_Version = buffer[offset] >> 6; bool isPadded = Convert.ToBoolean((buffer[offset] >> 5) & 0x1); int reportBlockCount = buffer[offset++] & 0x1F; int type = buffer[offset++]; int length = buffer[offset++] << 8 | buffer[offset++]; if (isPadded) { PaddBytesCount = buffer[offset + length]; } m_SSRC = (uint) (buffer[offset++] << 24 | buffer[offset++] << 16 | buffer[offset++] << 8 | buffer[offset++]); for (int i = 0; i < reportBlockCount; i++) { RTCP_Packet_ReportBlock reportBlock = new RTCP_Packet_ReportBlock(); reportBlock.Parse(buffer, offset); m_pReportBlocks.Add(reportBlock); offset += 24; } // TODO: profile-specific extensions } #endregion } }<file_sep>/common/ASC.IPSecurity/IPSecurity.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Configuration; using System.Linq; using System.Net; using System.Web; using ASC.Common.Logging; using ASC.Core; using ASC.Core.Tenants; namespace ASC.IPSecurity { public static class IPSecurity { private static readonly ILog Log = LogManager.GetLogger("ASC.IPSecurity"); private static bool? _ipSecurityEnabled; public static bool IpSecurityEnabled { get { if (_ipSecurityEnabled.HasValue) return _ipSecurityEnabled.Value; var hideSettings = (ConfigurationManagerExtension.AppSettings["web.hide-settings"] ?? "").Split(new[] { ',', ';', ' ' }); return (_ipSecurityEnabled = !hideSettings.Contains("IpSecurity", StringComparer.CurrentCultureIgnoreCase)).Value; } } private static readonly string CurrentIpForTest = ConfigurationManagerExtension.AppSettings["ipsecurity.test"]; public static bool Verify(Tenant tenant) { if (!IpSecurityEnabled) return true; var httpContext = HttpContext.Current; if (httpContext == null) return true; if (tenant == null || SecurityContext.CurrentAccount.ID == tenant.OwnerId) return true; string requestIps = null; try { var restrictions = IPRestrictionsService.Get(tenant.TenantId).ToList(); if (!restrictions.Any()) return true; if (string.IsNullOrWhiteSpace(requestIps = CurrentIpForTest)) { var request = httpContext.Request; requestIps = request.Headers["X-Forwarded-For"] ?? request.UserHostAddress; } var ips = string.IsNullOrWhiteSpace(requestIps) ? new string[] { } : requestIps.Split(new[] { ",", " " }, StringSplitOptions.RemoveEmptyEntries); if (ips.Any(requestIp => restrictions.Any(restriction => MatchIPs(GetIpWithoutPort(requestIp), restriction.Ip)))) { return true; } } catch (Exception ex) { Log.ErrorFormat("Can't verify request with IP-address: {0}. Tenant: {1}. Error: {2} ", requestIps ?? "", tenant, ex); return false; } Log.InfoFormat("Restricted from IP-address: {0}. Tenant: {1}. Request to: {2}", requestIps ?? "", tenant, httpContext.Request.Url); return false; } private static bool MatchIPs(string requestIp, string restrictionIp) { var dividerIdx = restrictionIp.IndexOf('-'); if (restrictionIp.IndexOf('-') > 0) { var lower = IPAddress.Parse(restrictionIp.Substring(0, dividerIdx).Trim()); var upper = IPAddress.Parse(restrictionIp.Substring(dividerIdx + 1).Trim()); var range = new IPAddressRange(lower, upper); return range.IsInRange(IPAddress.Parse(requestIp)); } return requestIp == restrictionIp; } private static string GetIpWithoutPort(string ip) { var portIdx = ip.IndexOf(':'); return portIdx > 0 ? ip.Substring(0, portIdx) : ip; } } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/ABNF/ABNF_Alternation.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.ABNF { #region usings using System; using System.Collections.Generic; using System.IO; #endregion /// <summary> /// This class represent ABNF "alternation". Defined in RFC 5234 4. /// </summary> public class ABNF_Alternation { #region Members private readonly List<ABNF_Concatenation> m_pItems; #endregion #region Properties /// <summary> /// Gets alternation items. /// </summary> public List<ABNF_Concatenation> Items { get { return m_pItems; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> public ABNF_Alternation() { m_pItems = new List<ABNF_Concatenation>(); } #endregion #region Methods /// <summary> /// /// </summary> /// <param name="reader"></param> /// <returns></returns> public static ABNF_Alternation Parse(StringReader reader) { if (reader == null) { throw new ArgumentNullException("reader"); } // alternation = concatenation *(*c-wsp "/" *c-wsp concatenation) ABNF_Alternation retVal = new ABNF_Alternation(); while (true) { ABNF_Concatenation item = ABNF_Concatenation.Parse(reader); if (item != null) { retVal.m_pItems.Add(item); } // We reached end of string. if (reader.Peek() == -1) { break; } // We have next alternation item. else if (reader.Peek() == '/') { reader.Read(); } // We have unexpected value, probably alternation ends. else { break; } } return retVal; } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/POP3/Client/POP3_ClientMessageCollection.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.POP3.Client { #region usings using System; using System.Collections; using System.Collections.Generic; #endregion /// <summary> /// This class represents POP3 client messages collection. /// </summary> public class POP3_ClientMessageCollection : IEnumerable, IDisposable { #region Members private readonly POP3_Client m_pPop3Client; private bool m_IsDisposed; private List<POP3_ClientMessage> m_pMessages; #endregion #region Properties /// <summary> /// Gets total size of messages, messages marked for deletion are included. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> public long TotalSize { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } long size = 0; foreach (POP3_ClientMessage message in m_pMessages) { size += message.Size; } return size; } } /// <summary> /// Gets number of messages in the collection, messages marked for deletion are included. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> public int Count { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_pMessages.Count; } } /// <summary> /// Gets message from specified index. /// </summary> /// <param name="index">Message zero based index in the collection.</param> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> /// <exception cref="ArgumentOutOfRangeException">Is raised when index is out of range.</exception> public POP3_ClientMessage this[int index] { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (index < 0 || index > m_pMessages.Count) { throw new ArgumentOutOfRangeException(); } return m_pMessages[index]; } } /// <summary> /// Gets message with specified UID value. /// </summary> /// <param name="uid">Message UID value.</param> /// <returns>Returns message or null if message doesn't exist.</returns> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> /// <exception cref="NotSupportedException">Is raised when POP3 server doesn't support UIDL.</exception> public POP3_ClientMessage this[string uidl] { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (!m_pPop3Client.IsUidlSupported) { throw new NotSupportedException(); } foreach (POP3_ClientMessage message in m_pMessages) { if (message.UIDL == uidl) { return message; } } return null; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="pop3">Owner POP3 client.</param> internal POP3_ClientMessageCollection(POP3_Client pop3) { m_pPop3Client = pop3; m_pMessages = new List<POP3_ClientMessage>(); } #endregion #region Methods /// <summary> /// Cleans up any resources being used. /// </summary> public void Dispose() { if (m_IsDisposed) { return; } m_IsDisposed = true; // Release messages. foreach (POP3_ClientMessage message in m_pMessages) { message.Dispose(); } m_pMessages = null; } /// <summary> /// Gets enumerator. /// </summary> /// <returns>Returns IEnumerator interface.</returns> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> public IEnumerator GetEnumerator() { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_pMessages.GetEnumerator(); } #endregion #region Internal methods /// <summary> /// Adds new message to messages collection. /// </summary> /// <param name="size">Message size in bytes.</param> internal void Add(int size) { m_pMessages.Add(new POP3_ClientMessage(m_pPop3Client, m_pMessages.Count + 1, size)); } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/RTP/RTP_Participant.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.RTP { #region usings using System; using System.Collections.Generic; #endregion /// <summary> /// This is base class for <b>RTP_Participant_Local</b> and <b>RTP_Participant_Remote</b> class. /// </summary> public abstract class RTP_Participant { #region Events /// <summary> /// Is raised when participant disjoins(timeout or BYE all sources) the RTP multimedia session. /// </summary> public event EventHandler Removed = null; /// <summary> /// Is raised when participant gets new RTP source. /// </summary> public event EventHandler<RTP_SourceEventArgs> SourceAdded = null; /// <summary> /// Is raised when RTP source removed from(Timeout or BYE) participant. /// </summary> public event EventHandler<RTP_SourceEventArgs> SourceRemoved = null; #endregion #region Members private readonly string m_CNAME = ""; private List<RTP_Source> m_pSources; #endregion #region Properties /// <summary> /// Gets canonical name of participant. /// </summary> public string CNAME { get { return m_CNAME; } } /// <summary> /// Gets the sources what participant owns(sends). /// </summary> public RTP_Source[] Sources { get { return m_pSources.ToArray(); } } /// <summary> /// Gets or sets user data. /// </summary> public object Tag { get; set; } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="cname">Canonical name of participant.</param> /// <exception cref="ArgumentNullException">Is raised when <b>cname</b> is null reference.</exception> public RTP_Participant(string cname) { if (cname == null) { throw new ArgumentNullException("cname"); } if (cname == string.Empty) { throw new ArgumentException("Argument 'cname' value must be specified."); } m_CNAME = cname; m_pSources = new List<RTP_Source>(); } #endregion #region Utility methods /// <summary> /// Raises <b>Removed</b> event. /// </summary> private void OnRemoved() { if (Removed != null) { Removed(this, new EventArgs()); } } /// <summary> /// Raises <b>SourceAdded</b> event. /// </summary> /// <param name="source">RTP source.</param> private void OnSourceAdded(RTP_Source source) { if (source == null) { throw new ArgumentNullException("source"); } if (SourceAdded != null) { SourceAdded(this, new RTP_SourceEventArgs(source)); } } /// <summary> /// Raises <b>SourceRemoved</b> event. /// </summary> /// <param name="source">RTP source.</param> private void OnSourceRemoved(RTP_Source source) { if (source == null) { throw new ArgumentNullException("source"); } if (SourceRemoved != null) { SourceRemoved(this, new RTP_SourceEventArgs(source)); } } #endregion #region Internal methods /// <summary> /// Cleans up any resources being used. /// </summary> internal void Dispose() { m_pSources = null; Removed = null; SourceAdded = null; SourceRemoved = null; } /// <summary> /// Adds specified source to participant if participant doesn't contain the specified source. /// </summary> /// <param name="source">RTP source.</param> /// <exception cref="ArgumentNullException">Is raised when <b>source</b> is null reference.</exception> internal void EnsureSource(RTP_Source source) { if (source == null) { throw new ArgumentNullException("source"); } if (!m_pSources.Contains(source)) { m_pSources.Add(source); OnSourceAdded(source); source.Disposing += delegate { if (m_pSources.Remove(source)) { OnSourceRemoved(source); // If last source removed, the participant is dead, so dispose participant. if (m_pSources.Count == 0) { OnRemoved(); Dispose(); } } }; } } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/Mail/Mail_h_ReturnPath.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.Mail { #region usings using System; using System.Text; using MIME; #endregion /// <summary> /// Represents "Return-Path:" header. Defined in RFC 5322 3.6.7. /// </summary> /// <example> /// <code> /// RFC 5322 3.6.7. /// return = "Return-Path:" path CRLF /// path = angle-addr / ([CFWS] "&lt;" [CFWS] "&gt;" [CFWS]) /// angle-addr = [CFWS] "&lt;" addr-spec "&gt;" [CFWS] /// </code> /// </example> public class Mail_h_ReturnPath : MIME_h { #region Members private string m_Address; private bool m_IsModified; #endregion #region Properties /// <summary> /// Gets if this header field is modified since it has loaded. /// </summary> /// <remarks>All new added header fields has <b>IsModified = true</b>.</remarks> /// <exception cref="ObjectDisposedException">Is riased when this class is disposed and this property is accessed.</exception> public override bool IsModified { get { return m_IsModified; } } /// <summary> /// Gets header field name. For example "Sender". /// </summary> public override string Name { get { return "Return-Path"; } } /// <summary> /// Gets mailbox address. Value null means null-path. /// </summary> public string Address { get { return m_Address; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="address">Address. Value null means null-path.</param> public Mail_h_ReturnPath(string address) { m_Address = address; } #endregion #region Methods /// <summary> /// Parses header field from the specified value. /// </summary> /// <param name="value">Header field value. Header field name must be included. For example: 'Return-Path: &lt;<EMAIL>&gt;'.</param> /// <returns>Returns parsed header field.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>value</b> is null reference.</exception> /// <exception cref="ParseException">Is raised when header field parsing errors.</exception> public static Mail_h_ReturnPath Parse(string value) { if (value == null) { throw new ArgumentNullException("value"); } string[] name_value = value.Split(new[] {':'}, 2); if (name_value.Length != 2) { throw new ParseException("Invalid header field value '" + value + "'."); } Mail_h_ReturnPath retVal = new Mail_h_ReturnPath(null); MIME_Reader r = new MIME_Reader(name_value[1]); r.ToFirstChar(); // Return-Path missing <>, some server won't be honor RFC. if (!r.StartsWith("<")) { retVal.m_Address = r.ToEnd(); } else { retVal.m_Address = r.ReadParenthesized(); } return retVal; } /// <summary> /// Returns header field as string. /// </summary> /// <param name="wordEncoder">8-bit words ecnoder. Value null means that words are not encoded.</param> /// <param name="parmetersCharset">Charset to use to encode 8-bit characters. Value null means parameters not encoded.</param> /// <returns>Returns header field as string.</returns> public override string ToString(MIME_Encoding_EncodedWord wordEncoder, Encoding parmetersCharset) { if (string.IsNullOrEmpty(m_Address)) { return "Return-Path: <>\r\n"; } else { return "Return-Path: <" + m_Address + ">\r\n"; } } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/SIP/Proxy/SIP_Registrar.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.SIP.Proxy { #region usings using System; using System.Timers; using Message; using Stack; #endregion #region Delegates /// <summary> /// Represents the method that will handle the SIP_Registrar.CanRegister event. /// </summary> /// <param name="userName">Authenticated user name.</param> /// <param name="address">Address to be registered.</param> /// <returns>Returns true if specified user can register specified address, otherwise false.</returns> public delegate bool SIP_CanRegisterEventHandler(string userName, string address); #endregion /// <summary> /// This class implements SIP registrar server. Defined in RFC 3261 10.3. /// </summary> public class SIP_Registrar { #region Events /// <summary> /// This event is raised when new AOR(address of record) has been registered. /// </summary> public event EventHandler<SIP_RegistrationEventArgs> AorRegistered = null; /// <summary> /// This event is raised when AOR(address of record) has been unregistered. /// </summary> public event EventHandler<SIP_RegistrationEventArgs> AorUnregistered = null; /// <summary> /// This event is raised when AOR(address of record) has been updated. /// </summary> public event EventHandler<SIP_RegistrationEventArgs> AorUpdated = null; /// <summary> /// This event is raised when SIP registrar need to check if specified user can register specified address. /// </summary> public event SIP_CanRegisterEventHandler CanRegister = null; #endregion #region Members private bool m_IsDisposed; private SIP_ProxyCore m_pProxy; private SIP_RegistrationCollection m_pRegistrations; private SIP_Stack m_pStack; private Timer m_pTimer; #endregion #region Properties /// <summary> /// Gets owner proxy core. /// </summary> public SIP_ProxyCore Proxy { get { return m_pProxy; } } /// <summary> /// Gets current SIP registrations. /// </summary> public SIP_Registration[] Registrations { get { lock (m_pRegistrations) { SIP_Registration[] retVal = new SIP_Registration[m_pRegistrations.Count]; m_pRegistrations.Values.CopyTo(retVal, 0); return retVal; } } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="proxy">Owner proxy.</param> /// <exception cref="ArgumentNullException">Is raised when <b>proxy</b> is null reference.</exception> internal SIP_Registrar(SIP_ProxyCore proxy) { if (proxy == null) { throw new ArgumentNullException("proxy"); } m_pProxy = proxy; m_pStack = m_pProxy.Stack; m_pRegistrations = new SIP_RegistrationCollection(); m_pTimer = new Timer(15000); m_pTimer.Elapsed += m_pTimer_Elapsed; m_pTimer.Enabled = true; } #endregion #region Methods /// <summary> /// Gets specified registration. Returns null if no such registration. /// </summary> /// <param name="aor">Address of record of registration which to get.</param> /// <returns>Returns SIP registration or null if no match.</returns> public SIP_Registration GetRegistration(string aor) { return m_pRegistrations[aor]; } /// <summary> /// Add or updates specified SIP registration info. /// </summary> /// <param name="aor">Registration address of record.</param> /// <param name="contacts">Registration address of record contacts to update.</param> public void SetRegistration(string aor, SIP_t_ContactParam[] contacts) { SetRegistration(aor, contacts, null); } /// <summary> /// Add or updates specified SIP registration info. /// </summary> /// <param name="aor">Registration address of record.</param> /// <param name="contacts">Registration address of record contacts to update.</param> /// <param name="flow">SIP proxy local data flow what accpeted this contact registration.</param> public void SetRegistration(string aor, SIP_t_ContactParam[] contacts, SIP_Flow flow) { lock (m_pRegistrations) { SIP_Registration registration = m_pRegistrations[aor]; if (registration == null) { registration = new SIP_Registration("system", aor); m_pRegistrations.Add(registration); OnAorRegistered(registration); } registration.AddOrUpdateBindings(flow, "", 1, contacts); } } /// <summary> /// Deletes specified registration and all it's contacts. /// </summary> /// <param name="addressOfRecord">Registration address of record what to remove.</param> public void DeleteRegistration(string addressOfRecord) { m_pRegistrations.Remove(addressOfRecord); } #endregion #region Event handlers private void m_pTimer_Elapsed(object sender, ElapsedEventArgs e) { m_pRegistrations.RemoveExpired(); } #endregion #region Utility methods /// <summary> /// Raises <b>AorRegistered</b> event. /// </summary> /// <param name="registration">SIP registration.</param> private void OnAorRegistered(SIP_Registration registration) { if (AorRegistered != null) { AorRegistered(this, new SIP_RegistrationEventArgs(registration)); } } /// <summary> /// Raises <b>AorUnregistered</b> event. /// </summary> /// <param name="registration">SIP registration.</param> private void OnAorUnregistered(SIP_Registration registration) { if (AorUnregistered != null) { AorUnregistered(this, new SIP_RegistrationEventArgs(registration)); } } /// <summary> /// Raises <b>AorUpdated</b> event. /// </summary> /// <param name="registration">SIP registration.</param> private void OnAorUpdated(SIP_Registration registration) { if (AorUpdated != null) { AorUpdated(this, new SIP_RegistrationEventArgs(registration)); } } #endregion #region Internal methods /// <summary> /// Cleans up any resources being used. /// </summary> internal void Dispose() { if (m_IsDisposed) { return; } m_IsDisposed = true; CanRegister = null; AorRegistered = null; AorUnregistered = null; AorUpdated = null; m_pProxy = null; m_pStack = null; m_pRegistrations = null; if (m_pTimer != null) { m_pTimer.Dispose(); m_pTimer = null; } } /// <summary> /// Handles REGISTER method. /// </summary> /// <param name="e">Request event arguments.</param> internal void Register(SIP_RequestReceivedEventArgs e) { /* RFC 3261 10.3 Processing REGISTER Requests. 1. The registrar inspects the Request-URI to determine whether it has access to bindings for the domain identified in the Request-URI. If not, and if the server also acts as a proxy server, the server SHOULD forward the request to the addressed domain, following the general behavior for proxying messages described in Section 16. 2. To guarantee that the registrar supports any necessary extensions, the registrar MUST process the Require header field. 3. A registrar SHOULD authenticate the UAC. 4. The registrar SHOULD determine if the authenticated user is authorized to modify registrations for this address-of-record. For example, a registrar might consult an authorization database that maps user names to a list of addresses-of-record for which that user has authorization to modify bindings. If the authenticated user is not authorized to modify bindings, the registrar MUST return a 403 (Forbidden) and skip the remaining steps. 5. The registrar extracts the address-of-record from the To header field of the request. If the address-of-record is not valid for the domain in the Request-URI, the registrar MUST send a 404 (Not Found) response and skip the remaining steps. The URI MUST then be converted to a canonical form. To do that, all URI parameters MUST be removed (including the user-param), and any escaped characters MUST be converted to their unescaped form. The result serves as an index into the list of bindings. 6. The registrar checks whether the request contains the Contact header field. If not, it skips to the last step. If the Contact header field is present, the registrar checks if there is one Contact field value that contains the special value "*" and an Expires field. If the request has additional Contact fields or an expiration time other than zero, the request is invalid, and the server MUST return a 400 (Invalid Request) and skip the remaining steps. If not, the registrar checks whether the Call-ID agrees with the value stored for each binding. If not, it MUST remove the binding. If it does agree, it MUST remove the binding only if the CSeq in the request is higher than the value stored for that binding. Otherwise, the update MUST be aborted and the request fails. 7. The registrar now processes each contact address in the Contact header field in turn. For each address, it determines the expiration interval as follows: - If the field value has an "expires" parameter, that value MUST be taken as the requested expiration. - If there is no such parameter, but the request has an Expires header field, that value MUST be taken as the requested expiration. - If there is neither, a locally-configured default value MUST be taken as the requested expiration. The registrar MAY choose an expiration less than the requested expiration interval. If and only if the requested expiration interval is greater than zero AND smaller than one hour AND less than a registrar-configured minimum, the registrar MAY reject the registration with a response of 423 (Interval Too Brief). This response MUST contain a Min-Expires header field that states the minimum expiration interval the registrar is willing to honor. It then skips the remaining steps. For each address, the registrar then searches the list of current bindings using the URI comparison rules. If the binding does not exist, it is tentatively added. If the binding does exist, the registrar checks the Call-ID value. If the Call-ID value in the existing binding differs from the Call-ID value in the request, the binding MUST be removed if the expiration time is zero and updated otherwise. If they are the same, the registrar compares the CSeq value. If the value is higher than that of the existing binding, it MUST update or remove the binding as above. If not, the update MUST be aborted and the request fails. This algorithm ensures that out-of-order requests from the same UA are ignored. Each binding record records the Call-ID and CSeq values from the request. The binding updates MUST be committed (that is, made visible to the proxy or redirect server) if and only if all binding updates and additions succeed. If any one of them fails (for example, because the back-end database commit failed), the request MUST fail with a 500 (Server Error) response and all tentative binding updates MUST be removed. 8. The registrar returns a 200 (OK) response. The response MUST contain Contact header field values enumerating all current bindings. Each Contact value MUST feature an "expires" parameter indicating its expiration interval chosen by the registrar. The response SHOULD include a Date header field. */ SIP_ServerTransaction transaction = e.ServerTransaction; SIP_Request request = e.Request; SIP_Uri to = null; string userName = ""; // Probably we need to do validate in SIP stack. #region Validate request if (SIP_Utils.IsSipOrSipsUri(request.To.Address.Uri.ToString())) { to = (SIP_Uri) request.To.Address.Uri; } else { transaction.SendResponse( m_pStack.CreateResponse( SIP_ResponseCodes.x400_Bad_Request + ": To: value must be SIP or SIPS URI.", request)); return; } #endregion #region 1. Check if we are responsible for Request-URI domain // if(m_pProxy.OnIsLocalUri(e.Request.Uri)){ // } // TODO: #endregion #region 2. Check that all required extentions supported #endregion #region 3. Authenticate request if (!m_pProxy.AuthenticateRequest(e, out userName)) { return; } #endregion #region 4. Check if user user is authorized to modify registrations // We do this in next step(5.). #endregion #region 5. Check if address of record exists if (!m_pProxy.OnAddressExists(to.Address)) { transaction.SendResponse(m_pStack.CreateResponse(SIP_ResponseCodes.x404_Not_Found, request)); return; } else if (!OnCanRegister(userName, to.Address)) { transaction.SendResponse(m_pStack.CreateResponse(SIP_ResponseCodes.x403_Forbidden, request)); return; } #endregion #region 6. Process * Contact if exists // Check if we have star contact. SIP_t_ContactParam starContact = null; foreach (SIP_t_ContactParam c in request.Contact.GetAllValues()) { if (c.IsStarContact) { starContact = c; break; } } // We have star contact. if (starContact != null) { if (request.Contact.GetAllValues().Length > 1) { transaction.SendResponse( m_pStack.CreateResponse( SIP_ResponseCodes.x400_Bad_Request + ": RFC 3261 10.3.6 -> If star(*) present, only 1 contact allowed.", request)); return; } else if (starContact.Expires != 0) { transaction.SendResponse( m_pStack.CreateResponse( SIP_ResponseCodes.x400_Bad_Request + ": RFC 3261 10.3.6 -> star(*) contact parameter 'expires' value must be always '0'.", request)); return; } // Remove bindings. SIP_Registration reg = m_pRegistrations[to.Address]; if (reg != null) { foreach (SIP_RegistrationBinding b in reg.Bindings) { if (request.CallID != b.CallID || request.CSeq.SequenceNumber > b.CSeqNo) { b.Remove(); } } } } #endregion #region 7. Process Contact values if (starContact == null) { SIP_Registration reg = m_pRegistrations[to.Address]; if (reg == null) { reg = new SIP_Registration(userName, to.Address); m_pRegistrations.Add(reg); } // We may do updates in batch only. // We just validate all values then do update(this ensures that update doesn't fail). // Check expires and CSeq. foreach (SIP_t_ContactParam c in request.Contact.GetAllValues()) { if (c.Expires == -1) { c.Expires = request.Expires; } if (c.Expires == -1) { c.Expires = m_pProxy.Stack.MinimumExpireTime; } // We must accept 0 values - means remove contact. if (c.Expires != 0 && c.Expires < m_pProxy.Stack.MinimumExpireTime) { SIP_Response resp = m_pStack.CreateResponse( SIP_ResponseCodes.x423_Interval_Too_Brief, request); resp.MinExpires = m_pProxy.Stack.MinimumExpireTime; transaction.SendResponse(resp); return; } SIP_RegistrationBinding currentBinding = reg.GetBinding(c.Address.Uri); if (currentBinding != null && currentBinding.CallID == request.CallID && request.CSeq.SequenceNumber < currentBinding.CSeqNo) { transaction.SendResponse( m_pStack.CreateResponse( SIP_ResponseCodes.x400_Bad_Request + ": CSeq value out of order.", request)); return; } } // Do binding updates. reg.AddOrUpdateBindings(e.ServerTransaction.Flow, request.CallID, request.CSeq.SequenceNumber, request.Contact.GetAllValues()); } #endregion #region 8. Create 200 OK response and return all current bindings SIP_Response response = m_pStack.CreateResponse(SIP_ResponseCodes.x200_Ok, request); response.Date = DateTime.Now; SIP_Registration registration = m_pRegistrations[to.Address]; if (registration != null) { foreach (SIP_RegistrationBinding b in registration.Bindings) { // Don't list expired bindings what wait to be disposed. if (b.TTL > 1) { response.Header.Add("Contact:", b.ToContactValue()); } } } // Add Authentication-Info:, then client knows next nonce. response.AuthenticationInfo.Add("qop=\"auth\",nextnonce=\"" + m_pStack.DigestNonceManager.CreateNonce() + "\""); transaction.SendResponse(response); #endregion } /// <summary> /// Is called by SIP registrar if it needs to check if specified user can register specified address. /// </summary> /// <param name="userName">Authenticated user name.</param> /// <param name="address">Address to be registered.</param> /// <returns>Returns true if specified user can register specified address, otherwise false.</returns> internal bool OnCanRegister(string userName, string address) { if (CanRegister != null) { return CanRegister(userName, address); } return false; } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/PortRange.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net { #region usings using System; #endregion /// <summary> /// This class holds UDP or TCP port range. /// </summary> public class PortRange { #region Members private readonly int m_End = 1100; private readonly int m_Start = 1000; #endregion #region Properties /// <summary> /// Gets start port. /// </summary> public int Start { get { return m_Start; } } /// <summary> /// Gets end port. /// </summary> public int End { get { return m_End; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="start">Start port.</param> /// <param name="end">End port.</param> /// <exception cref="ArgumentOutOfRangeException">Is raised when any of the aruments value is out of range.</exception> public PortRange(int start, int end) { if (start < 1 || start > 0xFFFF) { throw new ArgumentOutOfRangeException("Argument 'start' value must be > 0 and << 65 535."); } if (end < 1 || end > 0xFFFF) { throw new ArgumentOutOfRangeException("Argument 'end' value must be > 0 and << 65 535."); } if (start > end) { throw new ArgumentOutOfRangeException( "Argumnet 'start' value must be >= argument 'end' value."); } m_Start = start; m_End = end; } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/_Obsolete/MIME/ParametizedHeaderField.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.Mime { #region usings using System; using System.Collections; #endregion /// <summary> /// Parametized header field. /// <p/> /// Syntax: value;parameterName=parameterValue;parameterName=parameterValue;... . /// Example: (Content-Type:) text/html; charset="ascii". /// </summary> [Obsolete("See LumiSoft.Net.MIME or LumiSoft.Net.Mail namepaces for replacement.")] public class ParametizedHeaderField { #region Members private readonly HeaderField m_pHeaderField; private readonly HeaderFieldParameterCollection m_pParameters; #endregion #region Properties /// <summary> /// Gets header field name. /// </summary> public string Name { get { return m_pHeaderField.Name; } } /// <summary> /// Gets or sets header field value. /// </summary> public string Value { get { // Syntax: value;parameterName=parameterValue;parameterName=parameterValue;... ; // First item is value return TextUtils.SplitQuotedString(m_pHeaderField.Value, ';')[0]; } set { StoreParameters(value, ParseParameters()); } } /// <summary> /// Gets header field parameters. /// </summary> public HeaderFieldParameterCollection Parameters { get { return m_pParameters; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="headerField">Source header field.</param> public ParametizedHeaderField(HeaderField headerField) { m_pHeaderField = headerField; m_pParameters = new HeaderFieldParameterCollection(this); } #endregion #region Internal methods /// <summary> /// Parses parameters from header field. /// </summary> /// <returns></returns> internal Hashtable ParseParameters() { // Syntax: value;parameterName=parameterValue;parameterName=parameterValue;... string[] paramNameValues = TextUtils.SplitQuotedString(m_pHeaderField.EncodedValue, ';'); Hashtable retVal = new Hashtable(); // Skip value, other entries are parameters for (int i = 1; i < paramNameValues.Length; i++) { string[] paramNameValue = paramNameValues[i].Trim().Split(new[] {'='}, 2); if (!retVal.ContainsKey(paramNameValue[0].ToLower())) { if (paramNameValue.Length == 2) { string value = paramNameValue[1]; // Quotes-string, unqoute. if (value.StartsWith("\"")) { value = TextUtils.UnQuoteString(paramNameValue[1]); } retVal.Add(paramNameValue[0].ToLower(), value); } else { retVal.Add(paramNameValue[0].ToLower(), ""); } } } return retVal; } /// <summary> /// Stores parameters to header field Value property. /// </summary> /// <param name="value"></param> /// <param name="parameters"></param> internal void StoreParameters(string value, Hashtable parameters) { string retVal = value; foreach (DictionaryEntry entry in parameters) { retVal += ";\t" + entry.Key + "=\"" + entry.Value + "\""; } // Syntax: value;parameterName=parameterValue;parameterName=parameterValue;... ; m_pHeaderField.Value = retVal; } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/MIME/MIME_Reader.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.MIME { #region usings using System; using System.Text; #endregion /// <summary> /// MIME lexical tokens parser. /// </summary> public class MIME_Reader { #region Members private static readonly char[] atextChars = new[] { '!', '#', '$', '%', '&', '\'', '*', '+', '-', '/', '=', '?', '^', '_', '`', '{', '|', '}', '~' }; private static readonly char[] specials = new[] { '(', ')', '<', '>', '[', ']', ':', ';', '@', '\\', ',', '.', '"' }; private static readonly char[] tspecials = new[] { '(', ')', '<', '>', '@', ',', ';', ':', '\\', '"', '/' , '[', ']', '?', '=' }; private readonly string m_Source = ""; private int m_Offset; #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="value">Value to read.</param> /// <exception cref="ArgumentNullException">Is raised when <b>value</b> is null.</exception> public MIME_Reader(string value) { if (value == null) { throw new ArgumentNullException("value"); } m_Source = value; } #endregion #region Properties /// <summary> /// Gets number of chars has left for processing. /// </summary> public int Available { get { return m_Source.Length - m_Offset; } } #endregion #region Methods /// <summary> /// Gets if the specified char is RFC 822 'ALPHA'. /// </summary> /// <param name="c">Char to check.</param> /// <returns>Returns true if specified char is RFC 822 'ALPHA'.</returns> public static bool IsAlpha(char c) { /* RFC 822 3.3. ALPHA = <any ASCII alphabetic character>; (65.- 90.); (97.-122.) */ if ((c >= 65 && c <= 90) || (c >= 97 && c <= 122)) { return true; } else { return false; } } /// <summary> /// Gets if the specified char is RFC 2822 'atext'. /// </summary> /// <param name="c">Char to check.</param> /// <returns>Returns true if specified char is RFC 2822 'atext'.</returns> public static bool IsAText(char c) { /* RFC 2822 3.2.4. * atext = ALPHA / DIGIT / * "!" / "#" / "$" / "%" / "&" / "'" / "*" / "+" / * "-" / "/" / "=" / "?" / "^" / "_" / "`" / "{" / * "|" / "}" / "~" */ if (IsAlpha(c) || char.IsDigit(c)) { return true; } else { if (c == '.') { return true; } foreach (char aC in atextChars) { if (c == aC) { return true; } } } return false; } /// <summary> /// Gets if the specified value can be represented as "dot-atom". /// </summary> /// <param name="value">Value to check.</param> /// <returns>Returns true if the specified value can be represented as "dot-atom".</returns> public static bool IsDotAtom(string value) { if (value == null) { throw new ArgumentNullException("value"); } /* RFC 2822 3.2.4. * dot-atom = [CFWS] dot-atom-text [CFWS] * dot-atom-text = 1*atext *("." 1*atext) */ foreach (char c in value) { if (c != '.' && !IsAText(c)) { return false; } } return true; } /// <summary> /// Gets if specified valu is RFC 2045 (section 5) 'token'. /// </summary> /// <param name="text">Text to check.</param> /// <returns>Returns true if specified char is RFC 2045 (section 5) 'token'.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>text</b> is null.</exception> public static bool IsToken(string text) { if (text == null) { throw new ArgumentNullException("text"); } if (text == "") { return false; } foreach (char c in text) { if (!IsToken(c)) { return false; } } return true; } /// <summary> /// Gets if the specified char is RFC 2045 (section 5) 'token'. /// </summary> /// <param name="c">Char to check.</param> /// <returns>Returns true if specified char is RFC 2045 (section 5) 'token'.</returns> public static bool IsToken(char c) { /* RFC 2045 5. * token := 1*<any (US-ASCII) CHAR except SPACE, CTLs, or tspecials> * * RFC 822 3.3. * CTL = <any ASCII control; (0.- 31.); (127.) */ if (c <= 31 || c == 127) { return false; } else if (c == ' ') { return false; } else { foreach (char tsC in tspecials) { if (tsC == c) { return false; } } } return true; } /// <summary> /// Gets if the specified char is RFC 2231 (section 7) 'attribute-char'. /// </summary> /// <param name="c">Char to check.</param> /// <returns>Returns true if specified char is RFC 2231 (section 7) 'attribute-char'.</returns> public static bool IsAttributeChar(char c) { /* RFC 2231 7. * attribute-char := <any (US-ASCII) CHAR except SPACE, CTLs, "*", "'", "%", or tspecials> * * RFC 822 3.3. * CTL = <any ASCII control; (0.- 31.); (127.) */ if (c <= 31 || c > 127) { return false; } else if (c == ' ' || c == '*' || c == '\'' || c == '%') { return false; } else { foreach (char cS in tspecials) { if (c == cS) { return false; } } } return true; } /// <summary> /// Reads RFC 2822 'atom' from source stream. /// </summary> /// <returns>Returns RFC 2822 'atom' or null if end of stream reached.</returns> public string Atom() { /* RFC 2822 3.2.4. * atom = [CFWS] 1*atext [CFWS] */ ToFirstChar(); string retVal = ""; while (true) { int peekChar = Peek(false); // We reached end of string. if (peekChar == -1) { break; } else { char c = (char) peekChar; if (IsAText(c)) { retVal += (char) Char(false); } // Char is not part of 'atom', break. else { break; } } } if (retVal.Length > 0) { return retVal; } else { return null; } } /// <summary> /// Reads RFC 2822 'dot-atom' from source stream. /// </summary> /// <returns>Returns RFC 2822 'dot-atom' or null if end of stream reached.</returns> public string DotAtom() { /* RFC 2822 3.2.4. * dot-atom = [CFWS] dot-atom-text [CFWS] * dot-atom-text = 1*atext *("." 1*atext) */ ToFirstChar(); string retVal = ""; while (true) { string atom = Atom(); // We reached end of string. if (atom == null) { break; } else { retVal += atom; // dot-atom-text continues. if (Peek(false) == '.') { retVal += (char) Char(false); } else { break; } } } if (retVal.Length > 0) { return retVal; } else { return null; } } /// <summary> /// Reads RFC 2045 (section 5) 'token' from source stream. /// </summary> /// <returns>Returns RFC 2045 (section 5) 'token' or null if end of stream reached.</returns> public string Token() { /* RFC 2045 5. * token := 1*<any (US-ASCII) CHAR except SPACE, CTLs, or tspecials> */ ToFirstChar(); string retVal = ""; while (true) { int peekChar = Peek(false); // We reached end of string. if (peekChar == -1) { break; } else { char c = (char) peekChar; if (IsToken(c)) { retVal += (char) Char(false); } // Char is not part of 'token', break. else { break; } } } if (retVal.Length > 0) { return retVal; } else { return null; } } /// <summary> /// Reads RFC 822 'comment' from source stream. /// </summary> /// <returns>Returns RFC 822 'comment' or null if end of stream reached.</returns> public string Comment() { /* RFC 822 3.3. * comment = "(" *(ctext / quoted-pair / comment) ")" * ctext = <any CHAR excluding "(", ")", "\" & CR, & including linear-white-space> * quoted-pair = "\" CHAR */ ToFirstChar(); if (Peek(false) != '(') { throw new InvalidOperationException("No 'comment' value available."); } string retVal = ""; // Remove '('. Char(false); int nestedParenthesis = 0; while (true) { int intC = Char(false); // End of stream reached, invalid 'comment' value. if (intC == -1) { throw new ArgumentException("Invalid 'comment' value, no closing ')'."); } else if (intC == '(') { nestedParenthesis++; } else if (intC == ')') { // We readed whole 'comment' ok. if (nestedParenthesis == 0) { break; } else { nestedParenthesis--; } } else { retVal += (char) intC; } } return retVal; } /// <summary> /// Reads RFC 2822 (section 3.2.6) 'word' from source stream. /// </summary> /// <returns>Returns RFC 2822 (section 3.2.6) 'word' or null if end of stream reached.</returns> public string Word() { /* RFC 2822 3.2.6. * word = atom / quoted-string */ if (Peek(true) == '"') { return QuotedString(); } else { return Atom(); } } /// <summary> /// Reads RFC 2047 'encoded-word' from source stream. /// </summary> /// <returns>Returns RFC 2047 'encoded-word' or null if end of stream reached.</returns> /// <exception cref="InvalidOperationException">Is raised when source stream has no encoded-word at current position.</exception> public string EncodedWord() { /* RFC 2047 2. * encoded-word = "=?" charset "?" encoding "?" encoded-text "?=" * * An 'encoded-word' may not be more than 75 characters long, including * 'charset', 'encoding', 'encoded-text', and delimiters. If it is * desirable to encode more text than will fit in an 'encoded-word' of * 75 characters, multiple 'encoded-word's (separated by CRLF SPACE) may * be used. */ ToFirstChar(); if (Peek(false) != '=') { throw new InvalidOperationException("No encoded-word available."); } string retVal = ""; while (true) { string encodedWord = Atom(); try { string[] parts = encodedWord.Split('?'); if (parts[2].ToUpper() == "Q") { retVal += Core.QDecode(EncodingTools.GetEncodingByCodepageName_Throws(parts[1]), parts[3]); } else if (parts[2].ToUpper() == "B") { retVal += EncodingTools.GetEncodingByCodepageName_Throws(parts[1]).GetString( Core.Base64Decode(Encoding.Default.GetBytes(parts[3]))); } else { throw new Exception(""); } } catch { // Failed to parse encoded-word, leave it as is. RFC 2047 6.3. retVal += encodedWord; } ToFirstChar(); // encoded-word does not continue. if (Peek(false) != '=') { break; } } return retVal; } /// <summary> /// Reads RFC 822 'quoted-string' from source stream. /// </summary> /// <returns>Returns RFC 822 'quoted-string' or null if end of stream reached.</returns> /// <exception cref="InvalidOperationException">Is raised when source stream has no quoted-string at current position.</exception> /// <exception cref="ArgumentException">Is raised when not valid 'quoted-string'.</exception> public string QuotedString() { /* RFC 2822 3.2.5. * qtext = NO-WS-CTL / ; Non white space controls %d33 / ; The rest of the US-ASCII %d35-91 / ; characters not including "\" %d93-126 ; or the quote character qcontent = qtext / quoted-pair quoted-string = [CFWS] DQUOTE *([FWS] qcontent) [FWS] DQUOTE [CFWS] */ ToFirstChar(); if (Peek(false) != '"') { throw new InvalidOperationException("No quoted-string available."); } // Read start DQUOTE. Char(false); string retVal = ""; bool escape = false; while (true) { int intC = Char(false); // We reached end of stream, invalid quoted string, end quote is missing. if (intC == -1) { throw new ArgumentException("Invalid quoted-string, end quote is missing."); } // This char is escaped. else if (escape) { escape = false; retVal += (char) intC; } // Closing DQUOTE. else if (intC == '"') { break; } // Next char is escaped. else if (intC == '\\') { escape = true; } // Skip folding chars. else if (intC == '\r' || intC == '\n') {} // Normal char in quoted-string. else { retVal += (char) intC; } } return MIME_Encoding_EncodedWord.DecodeAll(retVal); } /// <summary> /// Reads RFC 2045 (section 5) 'token' from source stream. /// </summary> /// <returns>Returns 2045 (section 5) 'token' or null if end of stream reached.</returns> public string Value() { // value := token / quoted-string if (Peek(true) == '"') { return QuotedString(); } else { return Token(); } } /// <summary> /// Reads RFC 2047 (section 5) 'phrase' from source stream. /// </summary> /// <returns>Returns RFC 2047 (section 5) 'phrase' or null if end of stream reached.</returns> public string Phrase() { /* RFC 2047 5. * phrase = 1*( encoded-word / word ) * word = atom / quoted-string */ throw new NotImplementedException(); /* int peek = m_pStringReader.Peek(); if(peek == '"'){ return QuotedString(); } else if(peek == '='){ return EncodedWord(); } else{ return Atom(); }*/ //return ""; } /// <summary> /// Reads RFC 822 '*text' from source stream. /// </summary> /// <returns>Returns RFC 822 '*text' or null if end of stream reached.</returns> public string Text() { throw new NotImplementedException(); } /// <summary> /// Reads all white-space chars + CR and LF. /// </summary> /// <returns>Returns readed chars.</returns> public string ToFirstChar() { // NOTE: Never call Peek or Char method here or stack overflow ! string retVal = ""; while (true) { int peekChar = -1; if (m_Offset > m_Source.Length - 1) { peekChar = -1; } else { peekChar = m_Source[m_Offset]; } // We reached end of string. if (peekChar == -1) { break; } else if (peekChar == ' ' || peekChar == '\t' || peekChar == '\r' || peekChar == '\n') { retVal += m_Source[m_Offset++]; } else { break; } } return retVal; } /// <summary> /// Reads 1 char from source stream. /// </summary> /// <param name="readToFirstChar">Specifies if postion is moved to char(skips white spaces).</param> /// <returns>Returns readed char or -1 if end of stream reached.</returns> public int Char(bool readToFirstChar) { if (readToFirstChar) { ToFirstChar(); } if (m_Offset > m_Source.Length - 1) { return -1; } else { return m_Source[m_Offset++]; } } /// <summary> /// Shows next char in source stream, this method won't consume that char. /// </summary> /// <param name="readToFirstChar">Specifies if postion is moved to char(skips white spaces).</param> /// <returns>Returns next char in source stream, returns -1 if end of stream.</returns> public int Peek(bool readToFirstChar) { if (readToFirstChar) { ToFirstChar(); } if (m_Offset > m_Source.Length - 1) { return -1; } else { return m_Source[m_Offset]; } } /// <summary> /// Gets if source stream valu starts with the specified value. Compare is case-insensitive. /// </summary> /// <param name="value">Value to check.</param> /// <returns>Returns true if source steam satrs with specified string.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>value</b> is null.</exception> public bool StartsWith(string value) { if (value == null) { throw new ArgumentNullException("value"); } return m_Source.Substring(m_Offset).StartsWith(value, StringComparison.InvariantCultureIgnoreCase); } /// <summary> /// Reads all data from current postion to the end. /// </summary> /// <returns>Retruns readed data. Returns null if end of string is reached.</returns> public string ToEnd() { if (m_Offset >= m_Source.Length) { return null; } string retVal = m_Source.Substring(m_Offset); m_Offset = m_Source.Length; return retVal; } /// <summary> /// Reads parenthesized value. Supports {},(),[],&lt;&gt; parenthesis. /// Throws exception if there isn't parenthesized value or closing parenthesize is missing. /// </summary> /// <returns>Returns value between parenthesized.</returns> public string ReadParenthesized() { ToFirstChar(); char startingChar = ' '; char closingChar = ' '; if (m_Source[m_Offset] == '{') { startingChar = '{'; closingChar = '}'; } else if (m_Source[m_Offset] == '(') { startingChar = '('; closingChar = ')'; } else if (m_Source[m_Offset] == '[') { startingChar = '['; closingChar = ']'; } else if (m_Source[m_Offset] == '<') { startingChar = '<'; closingChar = '>'; } else { throw new Exception("No parenthesized value '" + m_Source.Substring(m_Offset) + "' !"); } m_Offset++; bool inQuotedString = false; // Holds flag if position is quoted string or not char lastChar = (char) 0; int nestedStartingCharCounter = 0; for (int i = m_Offset; i < m_Source.Length; i++) { // Skip escaped(\) " if (lastChar != '\\' && m_Source[i] == '\"') { // Start/end quoted string area inQuotedString = !inQuotedString; } // We need to skip parenthesis in quoted string else if (!inQuotedString) { // There is nested parenthesis if (m_Source[i] == startingChar) { nestedStartingCharCounter++; } // Closing char else if (m_Source[i] == closingChar) { // There isn't nested parenthesis closing chars left, this is closing char what we want. if (nestedStartingCharCounter == 0) { string retVal = m_Source.Substring(m_Offset, i - m_Offset); m_Offset = i + 1; return retVal; } // This is nested parenthesis closing char else { nestedStartingCharCounter--; } } } lastChar = m_Source[i]; } throw new ArgumentException("There is no closing parenthesize for '" + m_Source.Substring(m_Offset) + "' !"); } /// <summary> /// Reads string to specified delimiter or to end of underlying string. Notes: Delimiters in quoted string is skipped. /// For example: delimiter = ',', text = '"aaaa,eee",qqqq' - then result is '"aaaa,eee"'. /// </summary> /// <param name="delimiters">Data delimiters.</param> /// <returns>Returns readed string or null if end of string reached.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>delimiters</b> is null reference.</exception> public string QuotedReadToDelimiter(char[] delimiters) { if (delimiters == null) { throw new ArgumentNullException("delimiters"); } if (Available == 0) { return null; } ToFirstChar(); string currentSplitBuffer = ""; // Holds active bool inQuotedString = false; // Holds flag if position is quoted string or not char lastChar = (char) 0; for (int i = m_Offset; i < m_Source.Length; i++) { char c = (char) Peek(false); // Skip escaped(\) " if (lastChar != '\\' && c == '\"') { // Start/end quoted string area inQuotedString = !inQuotedString; } // See if char is delimiter bool isDelimiter = false; foreach (char delimiter in delimiters) { if (c == delimiter) { isDelimiter = true; break; } } // Current char is split char and it isn't in quoted string, do split if (!inQuotedString && isDelimiter) { return currentSplitBuffer; } else { currentSplitBuffer += c; m_Offset++; } lastChar = c; } // If we reached so far then we are end of string, return it. return currentSplitBuffer; } #endregion } }<file_sep>/module/ASC.Api/ASC.Api.MailServer/MailServerApi.Mailbox.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections.Generic; using ASC.Api.Attributes; using ASC.Api.Exceptions; using ASC.Core; using ASC.Core.Users; using ASC.Mail; using ASC.Mail.Core.Dao.Expressions.Mailbox; using ASC.Mail.Core.Engine.Operations.Base; using ASC.Mail.Data.Contracts; using ASC.Mail.Enums; using ASC.Web.Studio.Core.Notify; // ReSharper disable InconsistentNaming namespace ASC.Api.MailServer { public partial class MailServerApi { /// <summary> /// Create mailbox /// </summary> /// <param name="name"></param> /// <param name="local_part"></param> /// <param name="domain_id"></param> /// <param name="user_id"></param> /// <param name="notifyCurrent">Send message to creating mailbox's address</param> /// <param name="notifyProfile">Send message to email from user profile</param> /// <returns>MailboxData associated with tenant</returns> /// <short>Create mailbox</short> /// <category>Mailboxes</category> [Create(@"mailboxes/add")] public ServerMailboxData CreateMailbox(string name, string local_part, int domain_id, string user_id, bool notifyCurrent = false, bool notifyProfile = false) { var serverMailbox = MailEngineFactory.ServerMailboxEngine.CreateMailbox(name, local_part, domain_id, user_id); SendMailboxCreated(serverMailbox, notifyCurrent, notifyProfile); return serverMailbox; } /// <summary> /// Create my mailbox /// </summary> /// <param name="name"></param> /// <returns>MailboxData associated with tenant</returns> /// <short>Create mailbox</short> /// <category>Mailboxes</category> [Create(@"mailboxes/addmy")] public ServerMailboxData CreateMyMailbox(string name) { var serverMailbox = MailEngineFactory.ServerMailboxEngine.CreateMyCommonDomainMailbox(name); return serverMailbox; } /// <summary> /// Returns list of the mailboxes associated with tenant /// </summary> /// <returns>List of MailboxData for current tenant</returns> /// <short>Get mailboxes list</short> /// <category>Mailboxes</category> [Read(@"mailboxes/get")] public List<ServerMailboxData> GetMailboxes() { var mailboxes = MailEngineFactory.ServerMailboxEngine.GetMailboxes(); return mailboxes; } /// <summary> /// Deletes the selected mailbox /// </summary> /// <param name="id">id of mailbox</param> /// <returns>MailOperationResult object</returns> /// <exception cref="ArgumentException">Exception happens when some parameters are invalid. Text description contains parameter name and text description.</exception> /// <exception cref="ItemNotFoundException">Exception happens when mailbox wasn't found.</exception> /// <short>Remove mailbox from mail server</short> /// <category>Mailboxes</category> [Delete(@"mailboxes/remove/{id}")] public MailOperationStatus RemoveMailbox(int id) { var status = MailEngineFactory.ServerMailboxEngine.RemoveMailbox(id); return status; } /// <summary> /// Update mailbox /// </summary> /// <param name="mailbox_id">id of mailbox</param> /// <param name="name">sender name</param> /// <returns>Updated MailboxData</returns> /// <short>Update mailbox</short> /// <category>Mailboxes</category> [Update(@"mailboxes/update")] public ServerMailboxData UpdateMailbox(int mailbox_id, string name) { var mailbox = MailEngineFactory.ServerMailboxEngine.UpdateMailboxDisplayName(mailbox_id, name); return mailbox; } /// <summary> /// Add alias to mailbox /// </summary> /// <param name="mailbox_id">id of mailbox</param> /// <param name="alias_name">name of alias</param> /// <returns>MailboxData associated with tenant</returns> /// <short>Add mailbox's aliases</short> /// <category>AddressData</category> [Update(@"mailboxes/alias/add")] public ServerDomainAddressData AddMailboxAlias(int mailbox_id, string alias_name) { var serverAlias = MailEngineFactory.ServerMailboxEngine.AddAlias(mailbox_id, alias_name); return serverAlias; } /// <summary> /// Remove alias from mailbox /// </summary> /// <param name="mailbox_id">id of mailbox</param> /// <param name="address_id"></param> /// <returns>id of mailbox</returns> /// <short>Remove mailbox's aliases</short> /// <category>Mailboxes</category> [Update(@"mailboxes/alias/remove")] public int RemoveMailboxAlias(int mailbox_id, int address_id) { MailEngineFactory.ServerMailboxEngine.RemoveAlias(mailbox_id, address_id); return mailbox_id; } /// <summary> /// Change mailbox password /// </summary> /// <param name="mailbox_id"></param> /// <param name="password"></param> /// <short>Change mailbox password</short> /// <category>Mailboxes</category> [Update(@"mailboxes/changepwd")] public void ChangeMailboxPassword(int mailbox_id, string password) { MailEngineFactory.ServerMailboxEngine.ChangePassword(mailbox_id, password); SendMailboxPasswordChanged(mailbox_id); } /// <summary> /// Check existence of mailbox address /// </summary> /// <param name="local_part"></param> /// <param name="domain_id"></param> /// <short>Is server mailbox address exists</short> /// <returns>True - address exists, False - not exists</returns> /// <category>Mailboxes</category> [Read(@"mailboxes/alias/exists")] public bool IsAddressAlreadyRegistered(string local_part, int domain_id) { return MailEngineFactory.ServerMailboxEngine.IsAddressAlreadyRegistered(local_part, domain_id); } /// <summary> /// Validate mailbox address /// </summary> /// <param name="local_part"></param> /// <param name="domain_id"></param> /// <short>Is server mailbox address valid</short> /// <returns>True - address valid, False - not valid</returns> /// <category>Mailboxes</category> [Read(@"mailboxes/alias/valid")] public bool IsAddressValid(string local_part, int domain_id) { return MailEngineFactory.ServerMailboxEngine.IsAddressValid(local_part, domain_id); } private void SendMailboxCreated(ServerMailboxData serverMailbox, bool toMailboxUser, bool toUserProfile) { try { if (serverMailbox == null) throw new ArgumentNullException("serverMailbox"); if((!toMailboxUser && !toUserProfile)) return; var emails = new List<string>(); if (toMailboxUser) { emails.Add(serverMailbox.Address.Email); } var userInfo = CoreContext.UserManager.GetUsers(new Guid(serverMailbox.UserId)); if (userInfo == null || userInfo.Equals(Core.Users.Constants.LostUser)) throw new Exception(string.Format("SendMailboxCreated(mailboxId={0}): user not found", serverMailbox.Id)); if (toUserProfile) { if (userInfo != null && !userInfo.Equals(Core.Users.Constants.LostUser)) { if (!emails.Contains(userInfo.Email) && userInfo.ActivationStatus == EmployeeActivationStatus.Activated) { emails.Add(userInfo.Email); } } } var mailbox = MailEngineFactory.MailboxEngine.GetMailboxData( new ConcreteUserServerMailboxExp(serverMailbox.Id, TenantId, serverMailbox.UserId)); if (mailbox == null) throw new Exception(string.Format("SendMailboxCreated(mailboxId={0}): mailbox not found", serverMailbox.Id)); if (CoreContext.Configuration.Standalone) { var encType = Enum.GetName(typeof(EncryptionType), mailbox.Encryption) ?? Defines.START_TLS; string mxHost = null; try { mxHost = MailEngineFactory.ServerEngine.GetMailServerMxDomain(); } catch (Exception ex) { Logger.ErrorFormat("GetMailServerMxDomain() failed. Exception: {0}", ex.ToString()); } StudioNotifyService.Instance.SendMailboxCreated(emails, userInfo.DisplayUserName(), mailbox.EMail.Address, string.IsNullOrEmpty(mxHost) ? mailbox.Server : mxHost, encType.ToUpper(), mailbox.Port, mailbox.SmtpPort, mailbox.Account); } else { StudioNotifyService.Instance.SendMailboxCreated(emails, userInfo.DisplayUserName(), mailbox.EMail.Address); } } catch (Exception ex) { Logger.Error(ex.ToString()); } } private void SendMailboxPasswordChanged(int mailboxId) { try { if (!CoreContext.Configuration.Standalone) return; if (mailboxId < 0) throw new ArgumentNullException("mailboxId"); var mailbox = MailEngineFactory.MailboxEngine.GetMailboxData( new ConcreteTenantServerMailboxExp(mailboxId, TenantId, false)); if (mailbox == null) throw new Exception(string.Format("SendMailboxPasswordChanged(mailboxId={0}): mailbox not found", mailboxId)); var userInfo = CoreContext.UserManager.GetUsers(new Guid(mailbox.UserId)); if (userInfo == null || userInfo.Equals(Core.Users.Constants.LostUser)) throw new Exception(string.Format("SendMailboxPasswordChanged(mailboxId={0}): user not found", mailboxId)); var toEmails = new List<string> { userInfo.ActivationStatus == EmployeeActivationStatus.Activated ? userInfo.Email : mailbox.EMail.Address }; StudioNotifyService.Instance.SendMailboxPasswordChanged(toEmails, userInfo.DisplayUserName(), mailbox.EMail.Address); } catch (Exception ex) { Logger.Error(ex.ToString()); } } } } <file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Autoreply/Utility/Html/Text2HtmlConverter.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.IO; namespace ASC.Mail.Autoreply.Utility.Html { public class Text2HtmlConverter { public static String Convert(String text) { if (String.IsNullOrEmpty(text)) return text; text = text.Replace(" ", " &nbsp;"); var sr = new StringReader(text); var sw = new StringWriter(); while (sr.Peek() > -1) { sw.Write(sr.ReadLine() + "<br>"); } return sw.ToString(); } } } <file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/IMAP/Server/IMAP_eArgs_GetMessagesInfo.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.IMAP.Server { /// <summary> /// Provides data to event GetMessagesInfo. /// </summary> public class IMAP_eArgs_GetMessagesInfo { #region Members private readonly IMAP_SelectedFolder m_pFolderInfo; private readonly IMAP_Session m_pSession; #endregion #region Properties /// <summary> /// Gets current IMAP session. /// </summary> public IMAP_Session Session { get { return m_pSession; } } /// <summary> /// Gets folder info. /// </summary> public IMAP_SelectedFolder FolderInfo { get { return m_pFolderInfo; } } /// <summary> /// Gets or sets custom error text, which is returned to client. Null value means no error. /// </summary> public string ErrorText { get; set; } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> public IMAP_eArgs_GetMessagesInfo(IMAP_Session session, IMAP_SelectedFolder folder) { m_pSession = session; m_pFolderInfo = folder; } #endregion } }<file_sep>/common/ASC.Core.Common/Configuration/ConsumerConfigurationSection.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Configuration; using System.Linq; using ASC.Common.DependencyInjection; using Autofac; namespace ASC.Core.Common.Configuration { public class ConsumerConfigurationSection : ConfigurationSection { private const string ComponentsPropertyName = "components"; [ConfigurationProperty(ComponentsPropertyName, IsRequired = false)] public ConsumersElementCollection Containers { get { return (ConsumersElementCollection)this[ComponentsPropertyName]; } } } public class ConsumersElementCollection : ConfigurationElementCollection<ConsumerElement> { [ConfigurationProperty("name", IsRequired = false)] public string Name { get { return (string)this["name"]; } } public ConsumersElementCollection() : base("component") { } } public class ConsumerElement : ComponentElement { public const string OrderElement = "order"; public const string PropsElement = "props"; public const string AdditionalElement = "additional"; [ConfigurationProperty(OrderElement, IsRequired = false)] public int Order { get { return Convert.ToInt32(this[OrderElement]); } } [ConfigurationProperty(PropsElement, IsRequired = false)] public DictionaryElementCollection Props { get { return this[PropsElement] as DictionaryElementCollection; } } [ConfigurationProperty(AdditionalElement, IsRequired = false)] public DictionaryElementCollection Additional { get { return this[AdditionalElement] as DictionaryElementCollection; } } } public class ConsumerConfigLoader { public static ContainerBuilder LoadConsumers(string section) { var container = new ContainerBuilder(); var autofacConfigurationSection = (ConsumerConfigurationSection)ConfigurationManagerExtension.GetSection(section); foreach (var component in autofacConfigurationSection.Containers) { var componentType = Type.GetType(component.Type); var builder = container.RegisterType(componentType) .AsSelf() .As<Consumer>() .SingleInstance(); if (!string.IsNullOrEmpty(component.Name)) { builder .Named<Consumer>(component.Name) .Named(component.Name, componentType) .Named<Consumer>(component.Name.ToLower()) .Named(component.Name.ToLower(), componentType); } builder.WithParameter(new NamedParameter("name", component.Name)); builder.WithParameter(new NamedParameter(ConsumerElement.OrderElement, component.Order)); if (component.Props != null && component.Props.Any()) { builder.WithParameter(new NamedParameter(ConsumerElement.PropsElement, component.Props.ToDictionary(r => r.Key, r => r.Value))); } if (component.Additional != null && component.Additional.Any()) { builder.WithParameter(new NamedParameter(ConsumerElement.AdditionalElement, component.Additional.ToDictionary(r => r.Key, r => r.Value))); } } return container; } } } <file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/_Debug/BitDebuger.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net { #region usings using System; using System.Text; #endregion /// <summary> /// This class provides bit debugging methods. /// </summary> internal class BitDebuger { #region Methods /// <summary> /// Converts byte array to bit(1 byte = 8 bit) representation. /// </summary> /// <param name="buffer">Data buffer.</param> /// <param name="count">Numer of bytes to convert.</param> /// <param name="bytesPerLine">Number of bytes per line.</param> /// <returns>Returns byte array as bit(1 byte = 8 bit) representation.</returns> public static string ToBit(byte[] buffer, int count, int bytesPerLine) { if (buffer == null) { throw new ArgumentNullException("buffer"); } StringBuilder retVal = new StringBuilder(); int offset = 0; int bytesInCurrentLine = 1; while (offset < count) { byte currentByte = buffer[offset]; char[] bits = new char[8]; for (int i = 7; i >= 0; i--) { bits[i] = ((currentByte >> (7 - i)) & 0x1).ToString()[0]; } retVal.Append(bits); if (bytesInCurrentLine == bytesPerLine) { retVal.AppendLine(); bytesInCurrentLine = 0; } else { retVal.Append(" "); } bytesInCurrentLine++; offset++; } return retVal.ToString(); } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/IO/Base64Stream.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.IO { #region usings using System; using System.Collections.Generic; using System.IO; #endregion /// <summary> /// This class implements base64 encoder/decoder. Defined in RFC 4648. /// </summary> public class Base64Stream : Stream, IDisposable { #region Members private static readonly short[] BASE64_DECODE_TABLE = new short[] { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 0 - 9 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, //10 - 19 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, //20 - 29 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, //30 - 39 -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, //40 - 49 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, //50 - 59 -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, //60 - 69 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, //70 - 79 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, //80 - 89 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, //90 - 99 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, //100 - 109 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, //110 - 119 49, 50, 51, -1, -1, -1, -1, -1 //120 - 127 }; private static readonly byte[] BASE64_ENCODE_TABLE = new[] { (byte) 'A', (byte) 'B', (byte) 'C', (byte) 'D', (byte) 'E', (byte) 'F', (byte) 'G', (byte) 'H', (byte) 'I', (byte) 'J', (byte) 'K', (byte) 'L', (byte) 'M', (byte) 'N', (byte) 'O', (byte) 'P', (byte) 'Q', (byte) 'R', (byte) 'S', (byte) 'T', (byte) 'U', (byte) 'V', (byte) 'W', (byte) 'X', (byte) 'Y', (byte) 'Z', (byte) 'a', (byte) 'b', (byte) 'c', (byte) 'd', (byte) 'e', (byte) 'f', (byte) 'g', (byte) 'h', (byte) 'i', (byte) 'j', (byte) 'k', (byte) 'l', (byte) 'm', (byte) 'n', (byte) 'o', (byte) 'p', (byte) 'q', (byte) 'r', (byte) 's', (byte) 't', (byte) 'u', (byte) 'v', (byte) 'w', (byte) 'x', (byte) 'y', (byte) 'z', (byte) '0', (byte) '1', (byte) '2', (byte) '3', (byte) '4', (byte) '5', (byte) '6', (byte) '7', (byte) '8', (byte) '9', (byte) '+', (byte) '/' }; private readonly FileAccess m_AccessMode = FileAccess.ReadWrite; private readonly bool m_AddLineBreaks = true; private readonly bool m_IsOwner; private readonly Queue<byte> m_pDecodeReminder; private readonly byte[] m_pEncode3x8Block = new byte[3]; private readonly byte[] m_pEncodeBuffer = new byte[78]; private readonly Stream m_pStream; private int m_EncodeBufferOffset; private bool m_IsDisposed; private bool m_IsFinished; private int m_OffsetInEncode3x8Block; private static string[] padding_tails = new string[4] { "", "===", "==", "=" }; #endregion #region Properties /// <summary> /// Gets if this object is disposed. /// </summary> public bool IsDisposed { get { return m_IsDisposed; } } /// <summary> /// Gets a value indicating whether the current stream supports reading. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> public override bool CanRead { get { if (m_IsDisposed) { throw new ObjectDisposedException("SmartStream"); } return true; } } /// <summary> /// Gets a value indicating whether the current stream supports seeking. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> public override bool CanSeek { get { if (m_IsDisposed) { throw new ObjectDisposedException("SmartStream"); } return false; } } /// <summary> /// Gets a value indicating whether the current stream supports writing. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> public override bool CanWrite { get { if (m_IsDisposed) { throw new ObjectDisposedException("SmartStream"); } return false; } } /// <summary> /// Gets the length in bytes of the stream. This method is not supported and always throws a NotSupportedException. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> /// <exception cref="NotSupportedException">Is raised when this property is accessed.</exception> public override long Length { get { if (m_IsDisposed) { throw new ObjectDisposedException("SmartStream"); } throw new NotSupportedException(); } } /// <summary> /// Gets or sets the position within the current stream. This method is not supported and always throws a NotSupportedException. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> /// <exception cref="NotSupportedException">Is raised when this property is accessed.</exception> public override long Position { get { if (m_IsDisposed) { throw new ObjectDisposedException("SmartStream"); } throw new NotSupportedException(); } set { if (m_IsDisposed) { throw new ObjectDisposedException("SmartStream"); } throw new NotSupportedException(); } } #endregion private MemoryStream decodedDataStream = null; #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="stream">Stream which to encode/decode.</param> /// <param name="owner">Specifies if Base64Stream is owner of <b>stream</b>.</param> /// <param name="addLineBreaks">Specifies if encoder inserts CRLF after each 76 bytes.</param> /// <exception cref="ArgumentNullException">Is raised when <b>stream</b> is null reference.</exception> public Base64Stream(Stream stream, bool owner, bool addLineBreaks) : this(stream, owner, addLineBreaks, FileAccess.ReadWrite) {} /// <summary> /// Default constructor. /// </summary> /// <param name="stream">Stream which to encode/decode.</param> /// <param name="owner">Specifies if Base64Stream is owner of <b>stream</b>.</param> /// <param name="addLineBreaks">Specifies if encoder inserts CRLF after each 76 bytes.</param> /// <param name="access">This stream access mode.</param> /// <exception cref="ArgumentNullException">Is raised when <b>stream</b> is null reference.</exception> public Base64Stream(Stream stream, bool owner, bool addLineBreaks, FileAccess access) { if (stream == null) { throw new ArgumentNullException("stream"); } // Parse all stream if (stream.Length > 0) { stream.Seek(0, SeekOrigin.Begin); decodedDataStream = new MemoryStream(); using (StreamReader reader = new StreamReader(stream)) { List<string> lines = new List<string>(); while (!reader.EndOfStream) { string next_line = reader.ReadLine(); lines.Add(next_line); int exc_bytes = next_line.Length & 0x03; // If the line length is not multiple of 4 then we need to process possible wrong message content (it really happens) if (exc_bytes != 0) { // Process even part of the line first string even_part = next_line.Substring(0, next_line.Length - exc_bytes); byte[] decoded = Convert.FromBase64String(even_part); decodedDataStream.Write(decoded, 0, decoded.Length); // then try to recover the odd part by appending "=" to it try { string rest = next_line.Substring(next_line.Length - exc_bytes, exc_bytes); byte[] rest_decoded = Convert.FromBase64String(rest + padding_tails[exc_bytes]); decodedDataStream.Write(decoded, 0, decoded.Length); } catch (System.FormatException) {} } else { byte[] decoded = Convert.FromBase64String(next_line); decodedDataStream.Write(decoded, 0, decoded.Length); } } decodedDataStream.Seek(0, SeekOrigin.Begin); } } m_pStream = stream; m_IsOwner = owner; m_AddLineBreaks = addLineBreaks; m_AccessMode = access; m_pDecodeReminder = new Queue<byte>(); } #endregion #region Methods /// <summary> /// Celans up any resources being used. /// </summary> public new void Dispose() { if (m_IsDisposed) { return; } try { Finish(); } catch {} m_IsDisposed = true; if (m_IsOwner) { m_pStream.Close(); } if (decodedDataStream!=null) { decodedDataStream.Close(); decodedDataStream.Dispose(); } } /// <summary> /// Clears all buffers for this stream and causes any buffered data to be written to the underlying device. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> public override void Flush() { if (m_IsDisposed) { throw new ObjectDisposedException("Base64Stream"); } } /// <summary> /// Sets the position within the current stream. This method is not supported and always throws a NotSupportedException. /// </summary> /// <param name="offset">A byte offset relative to the <b>origin</b> parameter.</param> /// <param name="origin">A value of type SeekOrigin indicating the reference point used to obtain the new position.</param> /// <returns>The new position within the current stream.</returns> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="NotSupportedException">Is raised when this method is accessed.</exception> public override long Seek(long offset, SeekOrigin origin) { if (m_IsDisposed) { throw new ObjectDisposedException("Base64Stream"); } throw new NotSupportedException(); } /// <summary> /// Sets the length of the current stream. This method is not supported and always throws a NotSupportedException. /// </summary> /// <param name="value">The desired length of the current stream in bytes.</param> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="Seek">Is raised when this method is accessed.</exception> public override void SetLength(long value) { if (m_IsDisposed) { throw new ObjectDisposedException("Base64Stream"); } throw new NotSupportedException(); } /// <summary> /// Reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read. /// </summary> /// <param name="buffer">An array of bytes. When this method returns, the buffer contains the specified byte array with the values between offset and (offset + count - 1) replaced by the bytes read from the current source.</param> /// <param name="offset">The zero-based byte offset in buffer at which to begin storing the data read from the current stream.</param> /// <param name="count">The maximum number of bytes to be read from the current stream.</param> /// <returns>The total number of bytes read into the buffer. This can be less than the number of bytes requested if that many bytes are not currently available, or zero (0) if the end of the stream has been reached.</returns> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="ArgumentNullException">Is raised when <b>buffer</b> is null reference.</exception> /// <exception cref="NotSupportedException">Is raised when reading not supported.</exception> public override int Read(byte[] buffer, int offset, int count) { if (m_IsDisposed) { throw new ObjectDisposedException("Base64Stream"); } if (buffer == null) { throw new ArgumentNullException("buffer"); } if ((m_AccessMode & FileAccess.Read) == 0) { throw new NotSupportedException(); } if (decodedDataStream!=null) { //read from it return decodedDataStream.Read(buffer, offset, count); } /* RFC 4648. Base64 is processed from left to right by 4 6-bit byte block, 4 6-bit byte block are converted to 3 8-bit bytes. If base64 4 byte block doesn't have 3 8-bit bytes, missing bytes are marked with =. Value Encoding Value Encoding Value Encoding Value Encoding 0 A 17 R 34 i 51 z 1 B 18 S 35 j 52 0 2 C 19 T 36 k 53 1 3 D 20 U 37 l 54 2 4 E 21 V 38 m 55 3 5 F 22 W 39 n 56 4 6 G 23 X 40 o 57 5 7 H 24 Y 41 p 58 6 8 I 25 Z 42 q 59 7 9 J 26 a 43 r 60 8 10 K 27 b 44 s 61 9 11 L 28 c 45 t 62 + 12 M 29 d 46 u 63 / 13 N 30 e 47 v 14 O 31 f 48 w (pad) = 15 P 32 g 49 x 16 Q 33 h 50 y NOTE: 4 base64 6-bit bytes = 3 8-bit bytes // | 6-bit | 6-bit | 6-bit | 6-bit | // | 1 2 3 4 5 6 | 1 2 3 4 5 6 | 1 2 3 4 5 6 | 1 2 3 4 5 6 | // | 8-bit | 8-bit | 8-bit | */ int storedInBuffer = 0; // If we have decoded-buffered bytes, use them first. while (m_pDecodeReminder.Count > 0) { buffer[offset++] = m_pDecodeReminder.Dequeue(); storedInBuffer++; count--; // We filled whole "buffer", no more room. if (count == 0) { return storedInBuffer; } } // 1) Calculate as much we can decode to "buffer". !!! We need to read as 4x7-bit blocks. int rawBytesToRead = (int) Math.Ceiling(count/3.0)*4; byte[] readBuffer = new byte[rawBytesToRead]; short[] decodeBlock = new short[4]; byte[] decodedBlock = new byte[3]; int decodeBlockOffset = 0; int paddedCount = 0; // Decode while we have room in "buffer". while (storedInBuffer < count) { int readedCount = m_pStream.Read(readBuffer, 0, rawBytesToRead); // We reached end of stream, no more data. if (readedCount == 0) { // We have last block without padding 1 char. if (decodeBlockOffset == 3) { buffer[offset + storedInBuffer++] = (byte) (decodeBlock[0] << 2 | decodeBlock[1] >> 4); // See if "buffer" can accomodate 2 byte. if (storedInBuffer < count) { buffer[offset + storedInBuffer++] = (byte) ((decodeBlock[1] & 0xF) << 4 | decodeBlock[2] >> 2); } else { m_pDecodeReminder.Enqueue( (byte) ((decodeBlock[1] & 0xF) << 4 | decodeBlock[2] >> 2)); } } // We have last block without padding 2 chars. else if (decodeBlockOffset == 2) { buffer[offset + storedInBuffer++] = (byte) (decodeBlock[0] << 2 | decodeBlock[1] >> 4); } // We have invalid base64 data. else if (decodeBlockOffset == 1) { throw new InvalidDataException("Incomplete base64 data.."); } return storedInBuffer; } // Process readed bytes. for (int i = 0; i < readedCount; i++) { byte b = readBuffer[i]; // If padding char. if (b == '=') { decodeBlock[decodeBlockOffset++] = (byte) '='; paddedCount++; rawBytesToRead--; } // If base64 char. else if (BASE64_DECODE_TABLE[b] != -1) { decodeBlock[decodeBlockOffset++] = BASE64_DECODE_TABLE[b]; rawBytesToRead--; } // Non-base64 char, skip it. else {} // Decode block full, decode bytes. if (decodeBlockOffset == 4) { // Decode 3x8-bit block. decodedBlock[0] = (byte) (decodeBlock[0] << 2 | decodeBlock[1] >> 4); decodedBlock[1] = (byte) ((decodeBlock[1] & 0xF) << 4 | decodeBlock[2] >> 2); decodedBlock[2] = (byte) ((decodeBlock[2] & 0x3) << 6 | decodeBlock[3] >> 0); // Invalid base64 data. Base64 final quantum may have max 2 padding chars. if (paddedCount > 2) { throw new InvalidDataException( "Invalid base64 data, more than 2 padding chars(=)."); } for (int n = 0; n < (3 - paddedCount); n++) { // We have room in "buffer", store byte there. if (storedInBuffer < count) { buffer[offset + storedInBuffer++] = decodedBlock[n]; } //No room in "buffer", store reminder. else { m_pDecodeReminder.Enqueue(decodedBlock[n]); } } decodeBlockOffset = 0; paddedCount = 0; } } } return storedInBuffer; } /// <summary> /// Encodes a sequence of bytes, writes to the current stream and advances the current position within this stream by the number of bytes written. /// </summary> /// <param name="buffer">An array of bytes. This method copies count bytes from buffer to the current stream.</param> /// <param name="offset">The zero-based byte offset in buffer at which to begin copying bytes to the current stream.</param> /// <param name="count">The number of bytes to be written to the current stream.</param> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when this.Finish has been called and this method is accessed.</exception> /// <exception cref="ArgumentNullException">Is raised when <b>buffer</b> is null reference.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> /// <exception cref="NotSupportedException">Is raised when reading not supported.</exception> public override void Write(byte[] buffer, int offset, int count) { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (m_IsFinished) { throw new InvalidOperationException("Stream is marked as finished by calling Finish method."); } if (buffer == null) { throw new ArgumentNullException("buffer"); } if (offset < 0 || offset > buffer.Length) { throw new ArgumentException("Invalid argument 'offset' value."); } if (count < 0 || count > (buffer.Length - offset)) { throw new ArgumentException("Invalid argument 'count' value."); } if ((m_AccessMode & FileAccess.Write) == 0) { throw new NotSupportedException(); } /* RFC 4648. Base64 is processed from left to right by 4 6-bit byte block, 4 6-bit byte block are converted to 3 8-bit bytes. If base64 4 byte block doesn't have 3 8-bit bytes, missing bytes are marked with =. Value Encoding Value Encoding Value Encoding Value Encoding 0 A 17 R 34 i 51 z 1 B 18 S 35 j 52 0 2 C 19 T 36 k 53 1 3 D 20 U 37 l 54 2 4 E 21 V 38 m 55 3 5 F 22 W 39 n 56 4 6 G 23 X 40 o 57 5 7 H 24 Y 41 p 58 6 8 I 25 Z 42 q 59 7 9 J 26 a 43 r 60 8 10 K 27 b 44 s 61 9 11 L 28 c 45 t 62 + 12 M 29 d 46 u 63 / 13 N 30 e 47 v 14 O 31 f 48 w (pad) = 15 P 32 g 49 x 16 Q 33 h 50 y NOTE: 4 base64 6-bit bytes = 3 8-bit bytes // | 6-bit | 6-bit | 6-bit | 6-bit | // | 1 2 3 4 5 6 | 1 2 3 4 5 6 | 1 2 3 4 5 6 | 1 2 3 4 5 6 | // | 8-bit | 8-bit | 8-bit | */ int encodeBufSize = m_pEncodeBuffer.Length; // Process all bytes. for (int i = 0; i < count; i++) { m_pEncode3x8Block[m_OffsetInEncode3x8Block++] = buffer[offset + i]; // 3x8-bit encode block is full, encode it. if (m_OffsetInEncode3x8Block == 3) { m_pEncodeBuffer[m_EncodeBufferOffset++] = BASE64_ENCODE_TABLE[m_pEncode3x8Block[0] >> 2]; m_pEncodeBuffer[m_EncodeBufferOffset++] = BASE64_ENCODE_TABLE[(m_pEncode3x8Block[0] & 0x03) << 4 | m_pEncode3x8Block[1] >> 4]; m_pEncodeBuffer[m_EncodeBufferOffset++] = BASE64_ENCODE_TABLE[(m_pEncode3x8Block[1] & 0x0F) << 2 | m_pEncode3x8Block[2] >> 6]; m_pEncodeBuffer[m_EncodeBufferOffset++] = BASE64_ENCODE_TABLE[(m_pEncode3x8Block[2] & 0x3F)]; // Encode buffer is full, write buffer to underlaying stream (we reserved 2 bytes for CRLF). if (m_EncodeBufferOffset >= (encodeBufSize - 2)) { if (m_AddLineBreaks) { m_pEncodeBuffer[m_EncodeBufferOffset++] = (byte) '\r'; m_pEncodeBuffer[m_EncodeBufferOffset++] = (byte) '\n'; } m_pStream.Write(m_pEncodeBuffer, 0, m_EncodeBufferOffset); m_EncodeBufferOffset = 0; } m_OffsetInEncode3x8Block = 0; } } } /// <summary> /// Completes encoding. Call this method if all data has written and no more data. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> public void Finish() { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (m_IsFinished) { return; } m_IsFinished = true; // PADD left-over, if any. Write encode buffer to underlaying stream. if (m_OffsetInEncode3x8Block == 1) { m_pEncodeBuffer[m_EncodeBufferOffset++] = BASE64_ENCODE_TABLE[m_pEncode3x8Block[0] >> 2]; m_pEncodeBuffer[m_EncodeBufferOffset++] = BASE64_ENCODE_TABLE[(m_pEncode3x8Block[0] & 0x03) << 4]; m_pEncodeBuffer[m_EncodeBufferOffset++] = (byte) '='; m_pEncodeBuffer[m_EncodeBufferOffset++] = (byte) '='; } else if (m_OffsetInEncode3x8Block == 2) { m_pEncodeBuffer[m_EncodeBufferOffset++] = BASE64_ENCODE_TABLE[m_pEncode3x8Block[0] >> 2]; m_pEncodeBuffer[m_EncodeBufferOffset++] = BASE64_ENCODE_TABLE[(m_pEncode3x8Block[0] & 0x03) << 4 | m_pEncode3x8Block[1] >> 4]; m_pEncodeBuffer[m_EncodeBufferOffset++] = BASE64_ENCODE_TABLE[(m_pEncode3x8Block[1] & 0x0F) << 2]; m_pEncodeBuffer[m_EncodeBufferOffset++] = (byte) '='; } if (m_EncodeBufferOffset > 0) { m_pStream.Write(m_pEncodeBuffer, 0, m_EncodeBufferOffset); } } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/SIP/Stack/SIP_Hop.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.SIP.Stack { #region usings using System; using System.Net; #endregion /// <summary> /// Implements SIP hop(address,port,transport). Defined in RFC 3261. /// </summary> public class SIP_Hop { #region Members private readonly IPEndPoint m_pEndPoint; private readonly string m_Transport = ""; #endregion #region Properties /// <summary> /// Gets target IP end point. /// </summary> public IPEndPoint EndPoint { get { return m_pEndPoint; } } /// <summary> /// Gets target IP address. /// </summary> public IPAddress IP { get { return m_pEndPoint.Address; } } /// <summary> /// Gets target port. /// </summary> public int Port { get { return m_pEndPoint.Port; } } /// <summary> /// Gets target SIP transport. /// </summary> public string Transport { get { return m_Transport; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="ep">IP end point.</param> /// <param name="transport">SIP transport to use.</param> /// <exception cref="ArgumentNullException">Is raised when <b>ep</b> or <b>transport</b> is null reference.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> public SIP_Hop(IPEndPoint ep, string transport) { if (ep == null) { throw new ArgumentNullException("ep"); } if (transport == null) { throw new ArgumentNullException("transport"); } if (transport == "") { throw new ArgumentException("Argument 'transport' value must be specified."); } m_pEndPoint = ep; m_Transport = transport; } /// <summary> /// Default constructor. /// </summary> /// <param name="ip">IP address.</param> /// <param name="port">Destination port.</param> /// <param name="transport">SIP transport to use.</param> /// <exception cref="ArgumentNullException">Is raised when <b>ip</b> or <b>transport</b> is null reference.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> public SIP_Hop(IPAddress ip, int port, string transport) { if (ip == null) { throw new ArgumentNullException("ip"); } if (port < 1) { throw new ArgumentException("Argument 'port' value must be >= 1."); } if (transport == null) { throw new ArgumentNullException("transport"); } if (transport == "") { throw new ArgumentException("Argument 'transport' value must be specified."); } m_pEndPoint = new IPEndPoint(ip, port); m_Transport = transport; } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/SIP/Stack/SIP_TransactionLayer.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.SIP.Stack { #region usings using System; using System.Collections.Generic; using System.Timers; using Message; #endregion /// <summary> /// Implements SIP transaction layer. Defined in RFC 3261. /// Transaction layer manages client,server transactions and dialogs. /// </summary> public class SIP_TransactionLayer { #region Members private readonly Dictionary<string, SIP_ClientTransaction> m_pClientTransactions; private readonly Dictionary<string, SIP_Dialog> m_pDialogs; private readonly Dictionary<string, SIP_ServerTransaction> m_pServerTransactions; private readonly SIP_Stack m_pStack; private bool m_IsDisposed; private Timer m_pTimer; #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="stack">Reference to SIP stack.</param> /// <exception cref="ArgumentNullException">Is raised when <b>stack</b> is null reference.</exception> internal SIP_TransactionLayer(SIP_Stack stack) { if (stack == null) { throw new ArgumentNullException("stack"); } m_pStack = stack; m_pClientTransactions = new Dictionary<string, SIP_ClientTransaction>(); m_pServerTransactions = new Dictionary<string, SIP_ServerTransaction>(); m_pDialogs = new Dictionary<string, SIP_Dialog>(); m_pTimer = new Timer(20000); m_pTimer.AutoReset = true; m_pTimer.Elapsed += m_pTimer_Elapsed; } #endregion #region Properties /// <summary> /// Gets all available client transactions. This method is thread-safe. /// </summary> public SIP_ClientTransaction[] ClientTransactions { get { lock (m_pClientTransactions) { SIP_ClientTransaction[] retVal = new SIP_ClientTransaction[m_pClientTransactions.Values.Count]; m_pClientTransactions.Values.CopyTo(retVal, 0); return retVal; } } } /// <summary> /// Gets active dialogs. This method is thread-safe. /// </summary> public SIP_Dialog[] Dialogs { get { lock (m_pDialogs) { SIP_Dialog[] retVal = new SIP_Dialog[m_pDialogs.Values.Count]; m_pDialogs.Values.CopyTo(retVal, 0); return retVal; } } } /// <summary> /// Gets all available server transactions. This method is thread-safe. /// </summary> public SIP_ServerTransaction[] ServerTransactions { get { lock (m_pServerTransactions) { SIP_ServerTransaction[] retVal = new SIP_ServerTransaction[m_pServerTransactions.Values.Count]; m_pServerTransactions.Values.CopyTo(retVal, 0); return retVal; } } } #endregion #region Methods /// <summary> /// Creates new client transaction. /// </summary> /// <param name="flow">SIP data flow which is used to send request.</param> /// <param name="request">SIP request that transaction will handle.</param> /// <param name="addVia">If true, transaction will add <b>Via:</b> header, otherwise it's user responsibility.</param> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this method is accessed.</exception> /// <exception cref="ArgumentNullException">Is raised when <b>flow</b> or <b>request</b> is null reference.</exception> /// <returns>Returns created transaction.</returns> public SIP_ClientTransaction CreateClientTransaction(SIP_Flow flow, SIP_Request request, bool addVia) { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (flow == null) { throw new ArgumentNullException("flow"); } if (request == null) { throw new ArgumentNullException("request"); } // Add Via: if (addVia) { SIP_t_ViaParm via = new SIP_t_ViaParm(); via.ProtocolName = "SIP"; via.ProtocolVersion = "2.0"; via.ProtocolTransport = flow.Transport; via.SentBy = new HostEndPoint("transport_layer_will_replace_it", -1); via.Branch = SIP_t_ViaParm.CreateBranch(); via.RPort = 0; request.Via.AddToTop(via.ToStringValue()); } lock (m_pClientTransactions) { SIP_ClientTransaction transaction = new SIP_ClientTransaction(m_pStack, flow, request); m_pClientTransactions.Add(transaction.Key, transaction); transaction.StateChanged += delegate { if (transaction.State == SIP_TransactionState.Terminated) { lock (m_pClientTransactions) { m_pClientTransactions.Remove(transaction.Key); } } }; return transaction; } } /// <summary> /// Creates new SIP server transaction for specified request. /// </summary> /// <param name="flow">SIP data flow which is used to receive request.</param> /// <param name="request">SIP request.</param> /// <returns>Returns added server transaction.</returns> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this method is accessed.</exception> /// <exception cref="ArgumentNullException">Is raised when <b>flow</b> or <b>request</b> is null reference.</exception> public SIP_ServerTransaction CreateServerTransaction(SIP_Flow flow, SIP_Request request) { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (flow == null) { throw new ArgumentNullException("flow"); } if (request == null) { throw new ArgumentNullException("request"); } lock (m_pServerTransactions) { SIP_ServerTransaction transaction = new SIP_ServerTransaction(m_pStack, flow, request); m_pServerTransactions.Add(transaction.Key, transaction); transaction.StateChanged += delegate { if (transaction.State == SIP_TransactionState.Terminated) { lock (m_pClientTransactions) { m_pServerTransactions.Remove(transaction.Key); } } }; return transaction; } } /// <summary> /// Ensures that specified request has matching server transaction. If server transaction doesn't exist, /// it will be created, otherwise existing transaction will be returned. /// </summary> /// <param name="flow">SIP data flow which is used to receive request.</param> /// <param name="request">SIP request.</param> /// <returns>Returns matching transaction.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>flow</b> or <b>request</b> is null.</exception> /// <exception cref="InvalidOperationException">Is raised when request.Method is ACK request.</exception> public SIP_ServerTransaction EnsureServerTransaction(SIP_Flow flow, SIP_Request request) { if (flow == null) { throw new ArgumentNullException("flow"); } if (request == null) { throw new ArgumentNullException("request"); } if (request.RequestLine.Method == SIP_Methods.ACK) { throw new InvalidOperationException( "ACK request is transaction less request, can't create transaction for it."); } /* We use branch and sent-by as indexing key for transaction, the only special what we need to do is to handle CANCEL, because it has same branch as transaction to be canceled. For avoiding key collision, we add branch + '-' + 'sent-by' + CANCEL for cancel index key. ACK has also same branch, but we won't do transaction for ACK, so it isn't problem. */ string key = request.Via.GetTopMostValue().Branch + '-' + request.Via.GetTopMostValue().SentBy; if (request.RequestLine.Method == SIP_Methods.CANCEL) { key += "-CANCEL"; } lock (m_pServerTransactions) { SIP_ServerTransaction retVal = null; m_pServerTransactions.TryGetValue(key, out retVal); // We don't have transaction, create it. if (retVal == null) { retVal = CreateServerTransaction(flow, request); } return retVal; } } /// <summary> /// Matches CANCEL requst to SIP server non-CANCEL transaction. Returns null if no match. /// </summary> /// <param name="cancelRequest">SIP CANCEL request.</param> /// <returns>Returns CANCEL matching server transaction or null if no match.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>cancelTransaction</b> is null.</exception> /// <exception cref="ArgumentException">Is raised when <b>cancelTransaction</b> has invalid.</exception> public SIP_ServerTransaction MatchCancelToTransaction(SIP_Request cancelRequest) { if (cancelRequest == null) { throw new ArgumentNullException("cancelRequest"); } if (cancelRequest.RequestLine.Method != SIP_Methods.CANCEL) { throw new ArgumentException("Argument 'cancelRequest' is not SIP CANCEL request."); } SIP_ServerTransaction retVal = null; // NOTE: There we don't add '-CANCEL' because we want to get CANCEL matching transaction, not CANCEL // transaction itself. string key = cancelRequest.Via.GetTopMostValue().Branch + '-' + cancelRequest.Via.GetTopMostValue().SentBy; lock (m_pServerTransactions) { m_pServerTransactions.TryGetValue(key, out retVal); } return retVal; } /// <summary> /// Gets existing or creates new dialog. /// </summary> /// <param name="transaction">Owner transaction what forces to create dialog.</param> /// <param name="response">Response what forces to create dialog.</param> /// <returns>Returns dialog.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>transaction</b> or <b>response</b> is null.</exception> public SIP_Dialog GetOrCreateDialog(SIP_Transaction transaction, SIP_Response response) { if (transaction == null) { throw new ArgumentNullException("transaction"); } if (response == null) { throw new ArgumentNullException("response"); } string dialogID = ""; if (transaction is SIP_ServerTransaction) { dialogID = response.CallID + "-" + response.To.Tag + "-" + response.From.Tag; } else { dialogID = response.CallID + "-" + response.From.Tag + "-" + response.To.Tag; } lock (m_pDialogs) { SIP_Dialog dialog = null; m_pDialogs.TryGetValue(dialogID, out dialog); // Dialog doesn't exist, create it. if (dialog == null) { if (response.CSeq.RequestMethod.ToUpper() == SIP_Methods.INVITE) { dialog = new SIP_Dialog_Invite(); dialog.Init(m_pStack, transaction, response); dialog.StateChanged += delegate { if (dialog.State == SIP_DialogState.Terminated) { m_pDialogs.Remove(dialog.ID); } }; m_pDialogs.Add(dialog.ID, dialog); } else { throw new ArgumentException("Method '" + response.CSeq.RequestMethod + "' has no dialog handler."); } } return dialog; } } #endregion #region Internal methods /// <summary> /// Cleans up any resources being used. /// </summary> internal void Dispose() { if (m_IsDisposed) { return; } if (m_pTimer != null) { m_pTimer.Dispose(); m_pTimer = null; } foreach (SIP_ClientTransaction tr in ClientTransactions) { try { tr.Dispose(); } catch {} } foreach (SIP_ServerTransaction tr in ServerTransactions) { try { tr.Dispose(); } catch {} } foreach (SIP_Dialog dialog in Dialogs) { try { dialog.Dispose(); } catch {} } m_IsDisposed = true; } /// <summary> /// Matches SIP response to client transaction. If not matching transaction found, returns null. /// </summary> /// <param name="response">SIP response to match.</param> internal SIP_ClientTransaction MatchClientTransaction(SIP_Response response) { /* RFC 3261 17.1.3 Matching Responses to Client Transactions. 1. If the response has the same value of the branch parameter in the top Via header field as the branch parameter in the top Via header field of the request that created the transaction. 2. If the method parameter in the CSeq header field matches the method of the request that created the transaction. The method is needed since a CANCEL request constitutes a different transaction, but shares the same value of the branch parameter. */ SIP_ClientTransaction retVal = null; string transactionID = response.Via.GetTopMostValue().Branch + "-" + response.CSeq.RequestMethod; lock (m_pClientTransactions) { m_pClientTransactions.TryGetValue(transactionID, out retVal); } return retVal; } /// <summary> /// Matches SIP request to server transaction. If not matching transaction found, returns null. /// </summary> /// <param name="request">SIP request to match.</param> /// <returns>Returns matching transaction or null if no match.</returns> internal SIP_ServerTransaction MatchServerTransaction(SIP_Request request) { /* RFC 3261 17.2.3 Matching Requests to Server Transactions. This matching rule applies to both INVITE and non-INVITE transactions. 1. the branch parameter in the request is equal to the one in the top Via header field of the request that created the transaction, and 2. the sent-by value in the top Via of the request is equal to the one in the request that created the transaction, and 3. the method of the request matches the one that created the transaction, except for ACK, where the method of the request that created the transaction is INVITE. Internal implementation notes: Inernally we use branch + '-' + sent-by for non-CANCEL and for CANCEL branch + '-' + sent-by + '-' CANCEL. This is because method matching is actually needed for CANCEL only (CANCEL shares cancelable transaction branch ID). */ SIP_ServerTransaction retVal = null; /* We use branch and sent-by as indexing key for transaction, the only special what we need to do is to handle CANCEL, because it has same branch as transaction to be canceled. For avoiding key collision, we add branch + '-' + 'sent-by' + CANCEL for cancel index key. ACK has also same branch, but we won't do transaction for ACK, so it isn't problem. */ string key = request.Via.GetTopMostValue().Branch + '-' + request.Via.GetTopMostValue().SentBy; if (request.RequestLine.Method == SIP_Methods.CANCEL) { key += "-CANCEL"; } lock (m_pServerTransactions) { m_pServerTransactions.TryGetValue(key, out retVal); } // Don't match ACK for terminated transaction, in that case ACK must be passed to "core". if (retVal != null && request.RequestLine.Method == SIP_Methods.ACK && retVal.State == SIP_TransactionState.Terminated) { retVal = null; } return retVal; } /// <summary> /// Removes specified dialog from dialogs collection. /// </summary> /// <param name="dialog">SIP dialog to remove.</param> internal void RemoveDialog(SIP_Dialog dialog) { lock (m_pDialogs) { m_pDialogs.Remove(dialog.ID); } } /// <summary> /// Matches specified SIP request to SIP dialog. If no matching dialog found, returns null. /// </summary> /// <param name="request">SIP request.</param> /// <returns>Returns matched SIP dialog or null in no match found.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>request</b> is null.</exception> internal SIP_Dialog MatchDialog(SIP_Request request) { if (request == null) { throw new ArgumentNullException("request"); } SIP_Dialog dialog = null; try { string callID = request.CallID; string localTag = request.To.Tag; string remoteTag = request.From.Tag; if (callID != null && localTag != null && remoteTag != null) { string dialogID = callID + "-" + localTag + "-" + remoteTag; lock (m_pDialogs) { m_pDialogs.TryGetValue(dialogID, out dialog); } } } catch {} return dialog; } /// <summary> /// Matches specified SIP response to SIP dialog. If no matching dialog found, returns null. /// </summary> /// <param name="response">SIP response.</param> /// <returns>Returns matched SIP dialog or null in no match found.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>response</b> is null.</exception> internal SIP_Dialog MatchDialog(SIP_Response response) { if (response == null) { throw new ArgumentNullException("response"); } SIP_Dialog dialog = null; try { string callID = response.CallID; string fromTag = response.From.Tag; string toTag = response.To.Tag; if (callID != null && fromTag != null && toTag != null) { string dialogID = callID + "-" + fromTag + "-" + toTag; lock (m_pDialogs) { m_pDialogs.TryGetValue(dialogID, out dialog); } } } catch {} return dialog; } #endregion #region Utility methods private void m_pTimer_Elapsed(object sender, ElapsedEventArgs e) { foreach (SIP_Dialog dialog in Dialogs) { // Terminate early dialog after 5 minutes, normally there must be any, but just in case ... . if (dialog.State == SIP_DialogState.Early) { if (dialog.CreateTime.AddMinutes(5) < DateTime.Now) { dialog.Terminate(); } } // else if (dialog.State == SIP_DialogState.Confirmed) { // TODO: } } } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/SIP/Message/SIP_t_RCValue.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.SIP.Message { #region usings using System; using System.Text; #endregion /// <summary> /// Implements SIP "rc-value" value. Defined in RFC 3841. /// </summary> /// <remarks> /// <code> /// RFC 3841 Syntax: /// rc-value = "*" *(SEMI rc-params) /// rc-params = feature-param / generic-param /// </code> /// </remarks> public class SIP_t_RCValue : SIP_t_ValueWithParams { #region Methods /// <summary> /// Parses "rc-value" from specified value. /// </summary> /// <param name="value">SIP "rc-value" value.</param> /// <exception cref="ArgumentNullException">Raised when <b>value</b> is null.</exception> /// <exception cref="SIP_ParseException">Raised when invalid SIP message.</exception> public void Parse(string value) { if (value == null) { throw new ArgumentNullException("value"); } Parse(new StringReader(value)); } /// <summary> /// Parses "rc-value" from specified reader. /// </summary> /// <param name="reader">Reader from where to parse.</param> /// <exception cref="ArgumentNullException">Raised when <b>reader</b> is null.</exception> /// <exception cref="SIP_ParseException">Raised when invalid SIP message.</exception> public override void Parse(StringReader reader) { /* rc-value = "*" *(SEMI rc-params) rc-params = feature-param / generic-param */ if (reader == null) { throw new ArgumentNullException("reader"); } string word = reader.ReadWord(); if (word == null) { throw new SIP_ParseException("Invalid 'rc-value', '*' is missing !"); } // Parse parameters ParseParameters(reader); } /// <summary> /// Converts this to valid "rc-value" value. /// </summary> /// <returns>Returns "rc-value" value.</returns> public override string ToStringValue() { /* rc-value = "*" *(SEMI rc-params) rc-params = feature-param / generic-param */ StringBuilder retVal = new StringBuilder(); // * retVal.Append("*"); // Add parameters retVal.Append(ParametersToString()); return retVal.ToString(); } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/SIP/Stack/SIP_Stack.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.SIP.Stack { #region usings using System; using System.Collections.Generic; using System.Net; using System.Threading; using AUTH; using Dns.Client; using Log; using Message; #endregion /// <summary> /// Implements SIP stack. /// </summary> public class SIP_Stack { #region Events /// <summary> /// This event is raised by any SIP element when unknown/unhandled error happened. /// </summary> public event EventHandler<ExceptionEventArgs> Error = null; /// <summary> /// This event is raised when new SIP request is received. /// </summary> public event EventHandler<SIP_RequestReceivedEventArgs> RequestReceived = null; /// <summary> /// This event is raised when new stray SIP response is received. /// Stray response means that response doesn't match to any transaction. /// </summary> public event EventHandler<SIP_ResponseReceivedEventArgs> ResponseReceived = null; /// <summary> /// This event is raised when new incoming SIP request is received. You can control incoming requests /// with that event. For example you can require authentication or send what ever error to request maker user. /// </summary> public event EventHandler<SIP_ValidateRequestEventArgs> ValidateRequest = null; #endregion #region Members private readonly List<NetworkCredential> m_pCredentials; private readonly Dns_Client m_pDnsClient; private readonly Logger m_pLogger; private readonly Auth_HttpDigest_NonceManager m_pNonceManager; private readonly List<SIP_Uri> m_pProxyServers; private readonly List<SIP_UA_Registration> m_pRegistrations; private readonly SIP_TransactionLayer m_pTransactionLayer; private readonly SIP_TransportLayer m_pTransportLayer; private readonly SIP_t_CallID m_RegisterCallID; private int m_CSeq = 1; private bool m_IsDisposed; private bool m_IsRunning; private int m_MaxForwards = 70; private int m_MaximumConnections; private int m_MaximumMessageSize = 1000000; private int m_MinExpireTime = 1800; private int m_MinSessionExpires = 90; private string m_Realm = ""; private int m_SessionExpires = 1800; private int MTU = 1400; #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> public SIP_Stack() { m_pTransportLayer = new SIP_TransportLayer(this); m_pTransactionLayer = new SIP_TransactionLayer(this); m_pNonceManager = new Auth_HttpDigest_NonceManager(); m_pProxyServers = new List<SIP_Uri>(); m_pRegistrations = new List<SIP_UA_Registration>(); m_pCredentials = new List<NetworkCredential>(); m_RegisterCallID = SIP_t_CallID.CreateCallID(); m_pLogger = new Logger(); m_pDnsClient = new Dns_Client(); } #endregion #region Properties /// <summary> /// Gets or sets socket bind info. Use this property to specify on which protocol,IP,port server /// listnes and also if connections is SSL. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public IPBindInfo[] BindInfo { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_pTransportLayer.BindInfo; } set { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } m_pTransportLayer.BindInfo = value; } } /// <summary> /// Gets credentials collection. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and and this property is accessed.</exception> public List<NetworkCredential> Credentials { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_pCredentials; } } /// <summary> /// Gets digest authentication nonce manager. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public Auth_HttpDigest_NonceManager DigestNonceManager { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_pNonceManager; } } /// <summary> /// Gets stack DNS client. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public Dns_Client Dns { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_pDnsClient; } } /// <summary> /// Gets or sets if SIP stack is running. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public bool Enabled { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_IsRunning; } set { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (value) { Start(); } else { Stop(); } } } /// <summary> /// Gets if SIP stack has started. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public bool IsRunning { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_IsRunning; } } /// <summary> /// Gets SIP logger. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public Logger Logger { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_pLogger; } } /// <summary> /// Gets or sets maximum forwards SIP request may have. /// </summary> /// <exception cref="ArgumentException">Is raised when value contains invalid value.</exception> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and and this property is accessed.</exception> public int MaxForwards { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_MaxForwards; } set { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (value < 1) { throw new ArgumentException("Value must be > 0."); } m_MaxForwards = value; } } /// <summary> /// Gets or sets how many cunncurent connections allowed. Value 0 means not limited. This is used only for TCP based connections. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public int MaximumConnections { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_MaximumConnections; } set { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (value < 1) { m_MaximumConnections = 0; } else { m_MaximumConnections = value; } } } /// <summary> /// Gets or sets maximum allowed SIP message size in bytes. This is used only for TCP based connections. /// Value 0 means unlimited. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public int MaximumMessageSize { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_MaximumMessageSize; } set { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (value < 1) { m_MaximumMessageSize = 0; } else { m_MaximumMessageSize = value; } } } /// <summary> /// Gets or sets minimum expire time in seconds what server allows. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public int MinimumExpireTime { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_MinExpireTime; } set { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (value < 10) { throw new ArgumentException("Property MinimumExpireTime value must be >= 10 !"); } m_MinExpireTime = value; } } /// <summary> /// Gets or sets minimum session expires value in seconds. NOTE: Minimum value is 90 ! /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> /// <exception cref="ArgumentException">Is raised when invalid value is passed.</exception> public int MinimumSessionExpries { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_MinSessionExpires; } set { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (value < 90) { throw new ArgumentException("Minimum session expires value must be >= 90 !"); } m_MinSessionExpires = value; } } /// <summary> /// Gets SIP outbound proxy servers collection. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and and this property is accessed.</exception> public List<SIP_Uri> ProxyServers { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_pProxyServers; } } /// <summary> /// Gets or sets SIP <b>realm</b> value. Mostly this value is used by <b>digest</b> authentication. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and and this property is accessed.</exception> /// <exception cref="ArgumentNullException">Is raised when null reference is passed.</exception> public string Realm { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_Realm; } set { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (value == null) { throw new ArgumentNullException(); } m_Realm = value; } } /// <summary> /// Gets current registrations. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and and this property is accessed.</exception> public SIP_UA_Registration[] Registrations { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_pRegistrations.ToArray(); } } /// <summary> /// Gets or sets session expires value in seconds. NOTE: This value can't be smaller than MinimumSessionExpries. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> /// <exception cref="ArgumentException">Is raised when invalid value is passed.</exception> public int SessionExpries { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_SessionExpires; } set { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (value < 90) { throw new ArgumentException( "Session expires value can't be < MinimumSessionExpries value !"); } m_SessionExpires = value; } } /// <summary> /// Gets or sets STUN server name or IP address. This value must be filled if SIP stack is running behind a NAT. /// </summary> public string StunServer { get { return m_pTransportLayer.StunServer; } set { m_pTransportLayer.StunServer = value; } } /// <summary> /// Gets transaction layer. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public SIP_TransactionLayer TransactionLayer { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_pTransactionLayer; } } /// <summary> /// Gets transport layer what is used to receive and send requests and responses. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public SIP_TransportLayer TransportLayer { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_pTransportLayer; } } #endregion #region Methods /// <summary> /// Cleans up any resources being used. /// </summary> public void Dispose() { if (m_IsDisposed) { return; } Stop(); m_IsDisposed = true; // TODO: "clean" clean up with disposing state, wait some time transaction/dialogs to die, block new ones. // Release events. RequestReceived = null; ResponseReceived = null; Error = null; if (m_pTransactionLayer != null) { m_pTransactionLayer.Dispose(); } if (m_pTransportLayer != null) { m_pTransportLayer.Dispose(); } if (m_pNonceManager != null) { m_pNonceManager.Dispose(); } if (m_pLogger != null) { m_pLogger.Dispose(); } } /// <summary> /// Starts SIP stack. /// </summary> public void Start() { if (m_IsRunning) { return; } m_IsRunning = true; m_pTransportLayer.Start(); } /// <summary> /// Stops SIP stack. /// </summary> public void Stop() { if (!m_IsRunning) { return; } // Unregister registrations. foreach (SIP_UA_Registration reg in m_pRegistrations.ToArray()) { reg.BeginUnregister(true); } // Wait till all registrations disposed or wait timeout reached. DateTime start = DateTime.Now; while (m_pRegistrations.Count > 0) { Thread.Sleep(500); // Timeout, just kill all UA. if (((DateTime.Now - start)).Seconds > 15) { break; } } m_IsRunning = false; m_pTransportLayer.Stop(); } /// <summary> /// Creates new out-off dialog SIP request. /// </summary> /// <param name="method">SIP request-method.</param> /// <param name="to">Recipient address. For example: sip:<EMAIL></param> /// <param name="from">Senders address. For example: sip:<EMAIL></param> /// <returns>Returns created request.</returns> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and and this method is accessed.</exception> /// <exception cref="ArgumentNullException">Is raised when <b>method</b>,<b>to</b> or <b>from</b> is null.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> public SIP_Request CreateRequest(string method, SIP_t_NameAddress to, SIP_t_NameAddress from) { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (method == null) { throw new ArgumentNullException("method"); } if (method == "") { throw new ArgumentException("Argument 'method' value must be specified."); } if (to == null) { throw new ArgumentNullException("to"); } if (from == null) { throw new ArgumentNullException("from"); } method = method.ToUpper(); /* RFC 3261 8.1.1 Generating the Request A valid SIP request formulated by a UAC MUST, at a minimum, contain the following header fields: To, From, CSeq, Call-ID, Max-Forwards, and Via; all of these header fields are mandatory in all SIP requests. These six header fields are the fundamental building blocks of a SIP message, as they jointly provide for most of the critical message routing services including the addressing of messages, the routing of responses, limiting message propagation, ordering of messages, and the unique identification of transactions. These header fields are in addition to the mandatory request line, which contains the method, Request-URI, and SIP version. */ SIP_Request request = new SIP_Request(method); #region Request-URI (section 8.1.1.1) /* The initial Request-URI of the message SHOULD be set to the value of the URI in the To field. One notable exception is the REGISTER method; behavior for setting the Request-URI of REGISTER is given in Section 10. */ request.RequestLine.Uri = to.Uri; #endregion #region To (section 8.1.1.2) /* The To header field first and foremost specifies the desired "logical" recipient of the request, or the address-of-record of the user or resource that is the target of this request. This may or may not be the ultimate recipient of the request. The To header field MAY contain a SIP or SIPS URI, but it may also make use of other URI schemes (the tel URL (RFC 2806 [9]), for example) when appropriate. */ SIP_t_To t = new SIP_t_To(to); request.To = t; #endregion #region From (section 8.1.1.3) /* The From header field indicates the logical identity of the initiator of the request, possibly the user's address-of-record. Like the To header field, it contains a URI and optionally a display name. It is used by SIP elements to determine which processing rules to apply to a request (for example, automatic call rejection). As such, it is very important that the From URI not contain IP addresses or the FQDN of the host on which the UA is running, since these are not logical names. The From header field allows for a display name. A UAC SHOULD use the display name "Anonymous", along with a syntactically correct, but otherwise meaningless URI (like sip:[email protected]), if the identity of the client is to remain hidden. The From field MUST contain a new "tag" parameter, chosen by the UAC. See Section 19.3 for details on choosing a tag. */ SIP_t_From f = new SIP_t_From(from); f.Tag = SIP_Utils.CreateTag(); request.From = f; #endregion #region CallID (section 8.1.1.4) /* The Call-ID header field acts as a unique identifier to group together a series of messages. It MUST be the same for all requests and responses sent by either UA in a dialog. It SHOULD be the same in each registration from a UA. */ if (method == SIP_Methods.REGISTER) { request.CallID = m_RegisterCallID.ToStringValue(); } else { request.CallID = SIP_t_CallID.CreateCallID().ToStringValue(); } #endregion #region CSeq (section 8.1.1.5) /* The CSeq header field serves as a way to identify and order transactions. It consists of a sequence number and a method. The method MUST match that of the request. For non-REGISTER requests outside of a dialog, the sequence number value is arbitrary. The sequence number value MUST be expressible as a 32-bit unsigned integer and MUST be less than 2**31. As long as it follows the above guidelines, a client may use any mechanism it would like to select CSeq header field values. */ request.CSeq = new SIP_t_CSeq(ConsumeCSeq(), method); #endregion #region Max-Forwards (section 8.1.1.6) request.MaxForwards = m_MaxForwards; #endregion #region Pre-configured route (proxy server) // section 8.1.2 suggests to use pre-configured route for proxy. foreach (SIP_Uri proxy in m_pProxyServers) { request.Route.Add(proxy.ToString()); } #endregion // TODO: RFC 3261 13.2.1 INVITE special headers // INVITE should have // Allow,Supported // TODO: Subscribe special headers. // Expires is mandatory header. return request; } /// <summary> /// Creates SIP request sender for the specified request. /// </summary> /// <param name="request">SIP request.</param> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and and this method is accessed.</exception> /// <exception cref="ArgumentNullException">Is raised when <b>request</b> is null reference.</exception> public SIP_RequestSender CreateRequestSender(SIP_Request request) { return CreateRequestSender(request, null); } /// <summary> /// Consumes current CSeq number and increments it by 1. /// </summary> /// <returns>Returns CSeq number.</returns> public int ConsumeCSeq() { return m_CSeq++; } /// <summary> /// Creates response for the specified request. /// </summary> /// <param name="statusCode_reasonText">Status-code reasontext.</param> /// <param name="request">SIP request.</param> /// <returns>Returns created response.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>statusCode_reasonText</b> or <b>request</b> is null reference.</exception> /// <exception cref="InvalidOperationException">Is raised when request is ACK-request. ACK request is response less.</exception> public SIP_Response CreateResponse(string statusCode_reasonText, SIP_Request request) { return CreateResponse(statusCode_reasonText, request, null); } /// <summary> /// Creates response for the specified request. /// </summary> /// <param name="statusCode_reasonText">Status-code reasontext.</param> /// <param name="request">SIP request.</param> /// <param name="flow">Data flow what sends response. This value is used to construct Contact: header value. /// This value can be null, but then adding Contact: header is response sender responsibility.</param> /// <returns>Returns created response.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>statusCode_reasonText</b> or <b>request</b> is null reference.</exception> /// <exception cref="InvalidOperationException">Is raised when request is ACK-request. ACK request is response less.</exception> public SIP_Response CreateResponse(string statusCode_reasonText, SIP_Request request, SIP_Flow flow) { if (request == null) { throw new ArgumentNullException("request"); } if (request.RequestLine.Method == SIP_Methods.ACK) { throw new InvalidOperationException("ACK is responseless request !"); } /* RFC 3261 8.2.6.1. When a 100 (Trying) response is generated, any Timestamp header field present in the request MUST be copied into this 100 (Trying) response. RFC 3261 8.2.6.2. The From field of the response MUST equal the From header field of the request. The Call-ID header field of the response MUST equal the Call-ID header field of the request. The CSeq header field of the response MUST equal the CSeq field of the request. The Via header field values in the response MUST equal the Via header field values in the request and MUST maintain the same ordering. If a request contained a To tag in the request, the To header field in the response MUST equal that of the request. However, if the To header field in the request did not contain a tag, the URI in the To header field in the response MUST equal the URI in the To header field; additionally, the UAS MUST add a tag to the To header field in the response (with the exception of the 100 (Trying) response, in which a tag MAY be present). This serves to identify the UAS that is responding, possibly resulting in a component of a dialog ID. The same tag MUST be used for all responses to that request, both final and provisional (again excepting the 100 (Trying)). Procedures for the generation of tags are defined in Section 19.3. RFC 3261 12.1.1. When a UAS responds to a request with a response that establishes a dialog (such as a 2xx to INVITE), the UAS MUST copy all Record-Route header field values from the request into the response (including the URIs, URI parameters, and any Record-Route header field parameters, whether they are known or unknown to the UAS) and MUST maintain the order of those values. */ SIP_Response response = new SIP_Response(request); response.StatusCode_ReasonPhrase = statusCode_reasonText; foreach (SIP_t_ViaParm via in request.Via.GetAllValues()) { response.Via.Add(via.ToStringValue()); } response.From = request.From; response.To = request.To; if (request.To.Tag == null) { response.To.Tag = SIP_Utils.CreateTag(); } response.CallID = request.CallID; response.CSeq = request.CSeq; // TODO: Allow: / Supported: if (SIP_Utils.MethodCanEstablishDialog(request.RequestLine.Method)) { foreach (SIP_t_AddressParam route in request.RecordRoute.GetAllValues()) { response.RecordRoute.Add(route.ToStringValue()); } if (response.StatusCodeType == SIP_StatusCodeType.Success && response.Contact.GetTopMostValue() == null && flow != null) { try { string user = ((SIP_Uri) response.To.Address.Uri).User; response.Contact.Add((flow.IsSecure ? "sips:" : "sip:") + user + "@" + TransportLayer.Resolve(flow)); } catch { // TODO: Log } } } return response; } /// <summary> /// Gets target hops(address,port,transport) of the specified URI. /// </summary> /// <param name="uri">Target URI.</param> /// <param name="messageSize">SIP message size.</param> /// <param name="forceTLS">If true only TLS hops are returned.</param> /// <returns>Returns target hops(address,port,transport) of the specified URI.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>uri</b> is null reference.</exception> public SIP_Hop[] GetHops(SIP_Uri uri, int messageSize, bool forceTLS) { if (uri == null) { throw new ArgumentNullException("uri"); } List<SIP_Hop> retVal = new List<SIP_Hop>(); string transport = ""; bool transportSetExplicitly = false; List<DNS_rr_SRV> targetSRV = new List<DNS_rr_SRV>(); #region RFC 3263 4.1 Selecting a Transport Protocol /* 4.1 Selecting a Transport Protocol If the URI specifies a transport protocol in the transport parameter, that transport protocol SHOULD be used. Otherwise, if no transport protocol is specified, but the TARGET is a numeric IP address, the client SHOULD use UDP for a SIP URI, and TCP for a SIPS URI. Similarly, if no transport protocol is specified, and the TARGET is not numeric, but an explicit port is provided, the client SHOULD use UDP for a SIP URI, and TCP for a SIPS URI. This is because UDP is the only mandatory transport in RFC 2543 [6], and thus the only one guaranteed to be interoperable for a SIP URI. It was also specified as the default transport in RFC 2543 when no transport was present in the SIP URI. However, another transport, such as TCP, MAY be used if the guidelines of SIP mandate it for this particular request. That is the case, for example, for requests that exceed the path MTU. Otherwise, if no transport protocol or port is specified, and the target is not a numeric IP address, the client SHOULD perform a NAPTR query for the domain in the URI. The services relevant for the task of transport protocol selection are those with NAPTR service fields with values "SIP+D2X" and "SIPS+D2X", where X is a letter that corresponds to a transport protocol supported by the domain. This specification defines D2U for UDP, D2T for TCP, and D2S for SCTP. We also establish an IANA registry for NAPTR service name to transport protocol mappings. These NAPTR records provide a mapping from a domain to the SRV record for contacting a server with the specific transport protocol in the NAPTR services field. The resource record will contain an empty regular expression and a replacement value, which is the SRV record for that particular transport protocol. If the server supports multiple transport protocols, there will be multiple NAPTR records, each with a different service value. As per RFC 2915 [3], the client discards any records whose services fields are not applicable. For the purposes of this specification, several rules are defined. First, a client resolving a SIPS URI MUST discard any services that do not contain "SIPS" as the protocol in the service field. The converse is not true, however. A client resolving a SIP URI SHOULD retain records with "SIPS" as the protocol, if the client supports TLS. Second, a client MUST discard any service fields that identify a resolution service whose value is not "D2X", for values of X that indicate transport protocols supported by the client. The NAPTR processing as described in RFC 2915 will result in the discovery of the most preferred transport protocol of the server that is supported by the client, as well as an SRV record for the server. It will also allow the client to discover if TLS is available and its preference for its usage. As an example, consider a client that wishes to resolve sip:<EMAIL>. The client performs a NAPTR query for that domain, and the following NAPTR records are returned: ; order pref flags service regexp replacement IN NAPTR 50 50 "s" "SIPS+D2T" "" _sips._tcp.example.com. IN NAPTR 90 50 "s" "SIP+D2T" "" _sip._tcp.example.com IN NAPTR 100 50 "s" "SIP+D2U" "" _sip._udp.example.com. This indicates that the server supports TLS over TCP, TCP, and UDP, in that order of preference. Since the client supports TCP and UDP, TCP will be used, targeted to a host determined by an SRV lookup of _sip._tcp.example.com. That lookup would return: ;; Priority Weight Port Target IN SRV 0 1 5060 server1.example.com IN SRV 0 2 5060 server2.example.com If a SIP proxy, redirect server, or registrar is to be contacted through the lookup of NAPTR records, there MUST be at least three records - one with a "SIP+D2T" service field, one with a "SIP+D2U" service field, and one with a "SIPS+D2T" service field. The records with SIPS as the protocol in the service field SHOULD be preferred (i.e., have a lower value of the order field) above records with SIP as the protocol in the service field. A record with a "SIPS+D2U" service field SHOULD NOT be placed into the DNS, since it is not possible to use TLS over UDP. It is not necessary for the domain suffixes in the NAPTR replacement field to match the domain of the original query (i.e., example.com above). However, for backwards compatibility with RFC 2543, a domain MUST maintain SRV records for the domain of the original query, even if the NAPTR record is in a different domain. As an example, even though the SRV record for TCP is _sip._tcp.school.edu, there MUST also be an SRV record at _sip._tcp.example.com. RFC 2543 will look up the SRV records for the domain directly. If these do not exist because the NAPTR replacement points to a different domain, the client will fail. For NAPTR records with SIPS protocol fields, (if the server is using a site certificate), the domain name in the query and the domain name in the replacement field MUST both be valid based on the site certificate handed out by the server in the TLS exchange. Similarly, the domain name in the SRV query and the domain name in the target in the SRV record MUST both be valid based on the same site certificate. Otherwise, an attacker could modify the DNS records to contain replacement values in a different domain, and the client could not validate that this was the desired behavior or the result of an attack. If no NAPTR records are found, the client constructs SRV queries for those transport protocols it supports, and does a query for each. Queries are done using the service identifier "_sip" for SIP URIs and "_sips" for SIPS URIs. A particular transport is supported if the query is successful. The client MAY use any transport protocol it desires which is supported by the server. This is a change from RFC 2543. It specified that a client would lookup SRV records for all transports it supported, and merge the priority values across those records. Then, it would choose the most preferred record. If no SRV records are found, the client SHOULD use TCP for a SIPS URI, and UDP for a SIP URI. However, another transport protocol, such as TCP, MAY be used if the guidelines of SIP mandate it for this particular request. That is the case, for example, for requests that exceed the path MTU. */ // TLS usage demanded explicitly. if (forceTLS) { transportSetExplicitly = true; transport = SIP_Transport.TLS; } // If the URI specifies a transport protocol in the transport parameter, that transport protocol SHOULD be used. else if (uri.Param_Transport != null) { transportSetExplicitly = true; transport = uri.Param_Transport; } /* If no transport protocol is specified, but the TARGET is a numeric IP address, the client SHOULD use UDP for a SIP URI, and TCP for a SIPS URI. Similarly, if no transport protocol is specified, and the TARGET is not numeric, but an explicit port is provided, the client SHOULD use UDP for a SIP URI, and TCP for a SIPS URI. However, another transport, such as TCP, MAY be used if the guidelines of SIP mandate it for this particular request. That is the case, for example, for requests that exceed the path MTU. */ else if (Net_Utils.IsIPAddress(uri.Host) || uri.Port != -1) { if (uri.IsSecure) { transport = SIP_Transport.TLS; } else if (messageSize > MTU) { transport = SIP_Transport.TCP; } else { transport = SIP_Transport.UDP; } } else { DnsServerResponse response = null; /* DnsServerResponse response = m_pDnsClient.Query(uri.Host,QTYPE.NAPTR); // NAPTR records available. if(response.GetNAPTRRecords().Length > 0){ // TODO: Choose suitable here // 1) If SIPS get SIPS if possible. // 2) If message size > MTU, try to use TCP. // 3) Otherwise use UDP. if(uri.IsSecure){ // Get SIPS+D2T records. } else if(messageSize > MTU){ // Get SIP+D2T records. } else{ // Get SIP+D2U records. } } else{*/ Dictionary<string, DNS_rr_SRV[]> supportedTransports = new Dictionary<string, DNS_rr_SRV[]>(); bool srvRecordsAvailable = false; // Query SRV to see what protocols are supported. response = m_pDnsClient.Query("_sips._tcp." + uri.Host, QTYPE.SRV); if (response.GetSRVRecords().Length > 0) { srvRecordsAvailable = true; supportedTransports.Add(SIP_Transport.TLS, response.GetSRVRecords()); } response = m_pDnsClient.Query("_sip._tcp." + uri.Host, QTYPE.SRV); if (response.GetSRVRecords().Length > 0) { srvRecordsAvailable = true; supportedTransports.Add(SIP_Transport.TCP, response.GetSRVRecords()); } response = m_pDnsClient.Query("_sip._udp." + uri.Host, QTYPE.SRV); if (response.GetSRVRecords().Length > 0) { srvRecordsAvailable = true; supportedTransports.Add(SIP_Transport.UDP, response.GetSRVRecords()); } // SRV records available. if (srvRecordsAvailable) { if (uri.IsSecure) { if (supportedTransports.ContainsKey(SIP_Transport.TLS)) { transport = SIP_Transport.TLS; targetSRV.AddRange(supportedTransports[SIP_Transport.TLS]); } // Target won't support SIPS. else { // TODO: What to do ? } } else if (messageSize > MTU) { if (supportedTransports.ContainsKey(SIP_Transport.TCP)) { transport = SIP_Transport.TCP; targetSRV.AddRange(supportedTransports[SIP_Transport.TCP]); } else if (supportedTransports.ContainsKey(SIP_Transport.TLS)) { transport = SIP_Transport.TLS; targetSRV.AddRange(supportedTransports[SIP_Transport.TLS]); } // Target support UDP only, but TCP is required. else { // TODO: What to do ? } } else { if (supportedTransports.ContainsKey(SIP_Transport.UDP)) { transport = SIP_Transport.UDP; targetSRV.AddRange(supportedTransports[SIP_Transport.UDP]); } else if (supportedTransports.ContainsKey(SIP_Transport.TCP)) { transport = SIP_Transport.TCP; targetSRV.AddRange(supportedTransports[SIP_Transport.TCP]); } else { transport = SIP_Transport.TLS; targetSRV.AddRange(supportedTransports[SIP_Transport.TLS]); } } } /* If no SRV records are found, the client SHOULD use TCP for a SIPS URI, and UDP for a SIP URI. However, another transport protocol, such as TCP, MAY be used if the guidelines of SIP mandate it for this particular request. That is the case, for example, for requests that exceed the path MTU. */ else { if (uri.IsSecure) { transport = SIP_Transport.TLS; } else if (messageSize > MTU) { transport = SIP_Transport.TCP; } else { transport = SIP_Transport.UDP; } } //} } #endregion #region RFC 3263 4.2 Determining Port and IP Address /* 4.2 Determining Port and IP Address If TARGET is a numeric IP address, the client uses that address. If the URI also contains a port, it uses that port. If no port is specified, it uses the default port for the particular transport protocol. If the TARGET was not a numeric IP address, but a port is present in the URI, the client performs an A or AAAA record lookup of the domain name. The result will be a list of IP addresses, each of which can be contacted at the specific port from the URI and transport protocol determined previously. The client SHOULD try the first record. If an attempt should fail, based on the definition of failure in Section 4.3, the next SHOULD be tried, and if that should fail, the next SHOULD be tried, and so on. This is a change from RFC 2543. Previously, if the port was explicit, but with a value of 5060, SRV records were used. Now, A or AAAA records will be used. If the TARGET was not a numeric IP address, and no port was present in the URI, the client performs an SRV query on the record returned from the NAPTR processing of Section 4.1, if such processing was performed. If it was not, because a transport was specified explicitly, the client performs an SRV query for that specific transport, using the service identifier "_sips" for SIPS URIs. For a SIP URI, if the client wishes to use TLS, it also uses the service identifier "_sips" for that specific transport, otherwise, it uses "_sip". If the NAPTR processing was not done because no NAPTR records were found, but an SRV query for a supported transport protocol was successful, those SRV records are selected. Irregardless of how the SRV records were determined, the procedures of RFC 2782, as described in the section titled "Usage rules" are followed, augmented by the additional procedures of Section 4.3 of this document. If no SRV records were found, the client performs an A or AAAA record lookup of the domain name. The result will be a list of IP addresses, each of which can be contacted using the transport protocol determined previously, at the default port for that transport. Processing then proceeds as described above for an explicit port once the A or AAAA records have been looked up. */ if (Net_Utils.IsIPAddress(uri.Host)) { if (uri.Port != -1) { retVal.Add(new SIP_Hop(IPAddress.Parse(uri.Host), uri.Port, transport)); } else if (forceTLS || uri.IsSecure) { retVal.Add(new SIP_Hop(IPAddress.Parse(uri.Host), 5061, transport)); } else { retVal.Add(new SIP_Hop(IPAddress.Parse(uri.Host), 5060, transport)); } } else if (uri.Port != -1) { foreach (IPAddress ip in m_pDnsClient.GetHostAddresses(uri.Host)) { retVal.Add(new SIP_Hop(ip, uri.Port, transport)); } } else { //if(naptrRecords){ // We need to get (IP:Port)'s foreach SRV record. //DnsServerResponse response = m_pDnsClient.Query("??? need NAPTR value here",QTYPE.SRV); //} if (transportSetExplicitly) { DnsServerResponse response = null; if (transport == SIP_Transport.TLS) { response = m_pDnsClient.Query("_sips._tcp." + uri.Host, QTYPE.SRV); } else if (transport == SIP_Transport.TCP) { response = m_pDnsClient.Query("_sip._tcp." + uri.Host, QTYPE.SRV); } else { response = m_pDnsClient.Query("_sip._udp." + uri.Host, QTYPE.SRV); } targetSRV.AddRange(response.GetSRVRecords()); } // We have SRV records, resovle them to (IP:Port)'s. if (targetSRV.Count > 0) { foreach (DNS_rr_SRV record in targetSRV) { if (Net_Utils.IsIPAddress(record.Target)) { retVal.Add(new SIP_Hop(IPAddress.Parse(record.Target), record.Port, transport)); } else { foreach (IPAddress ip in m_pDnsClient.GetHostAddresses(record.Target)) { retVal.Add(new SIP_Hop(ip, record.Port, transport)); } } } } // No SRV recors, just use A and AAAA records. else { int port = 5060; if (transport == SIP_Transport.TLS) { port = 5061; } foreach (IPAddress ip in m_pDnsClient.GetHostAddresses(uri.Host)) { retVal.Add(new SIP_Hop(ip, port, transport)); } } } #endregion return retVal.ToArray(); } /// <summary> /// Creates new registration. /// </summary> /// <param name="server">Registrar server URI. For example: sip:domain.com.</param> /// <param name="aor">Registration address of record. For example: <EMAIL>.</param> /// <param name="contact">Contact URI.</param> /// <param name="expires">Gets after how many seconds reigisration expires.</param> /// <returns>Returns created registration.</returns> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and and this method is accessed.</exception> /// <exception cref="ArgumentNullException">Is raised when <b>server</b>,<b>aor</b> or <b>contact</b> is null reference.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> public SIP_UA_Registration CreateRegistration(SIP_Uri server, string aor, AbsoluteUri contact, int expires) { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (server == null) { throw new ArgumentNullException("server"); } if (aor == null) { throw new ArgumentNullException("aor"); } if (aor == string.Empty) { throw new ArgumentException("Argument 'aor' value must be specified."); } if (contact == null) { throw new ArgumentNullException("contact"); } lock (m_pRegistrations) { SIP_UA_Registration registration = new SIP_UA_Registration(this, server, aor, contact, expires); registration.Disposed += delegate { if (!m_IsDisposed) { m_pRegistrations.Remove(registration); } }; m_pRegistrations.Add(registration); return registration; } } #endregion #region Internal methods /// <summary> /// Creates SIP request sender for the specified request. /// </summary> /// <param name="request">SIP request.</param> /// <param name="flow">Data flow.</param> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and and this method is accessed.</exception> /// <exception cref="ArgumentNullException">Is raised when <b>request</b> is null reference.</exception> internal SIP_RequestSender CreateRequestSender(SIP_Request request, SIP_Flow flow) { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (request == null) { throw new ArgumentNullException("request"); } SIP_RequestSender sender = new SIP_RequestSender(this, request, flow); sender.Credentials.AddRange(m_pCredentials); return sender; } /// <summary> /// Is called by Transport layer when new incoming SIP request is received. /// </summary> /// <param name="request">Incoming SIP request.</param> /// <param name="remoteEndPoint">Request maker IP end point.</param> /// <returns></returns> internal SIP_ValidateRequestEventArgs OnValidateRequest(SIP_Request request, IPEndPoint remoteEndPoint) { SIP_ValidateRequestEventArgs eArgs = new SIP_ValidateRequestEventArgs(request, remoteEndPoint); if (ValidateRequest != null) { ValidateRequest(this, eArgs); } return eArgs; } /// <summary> /// Raises <b>RequestReceived</b> event. /// </summary> /// <param name="e">Event data.</param> internal void OnRequestReceived(SIP_RequestReceivedEventArgs e) { if (RequestReceived != null) { RequestReceived(this, e); } } /// <summary> /// Raises <b>ResponseReceived</b> event. /// </summary> /// <param name="e">Event data.</param> internal void OnResponseReceived(SIP_ResponseReceivedEventArgs e) { if (ResponseReceived != null) { ResponseReceived(this, e); } } /// <summary> /// Is called when ever unknown error happens. /// </summary> /// <param name="x">Exception happened.</param> internal void OnError(Exception x) { if (Error != null) { Error(this, new ExceptionEventArgs(x)); } } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/DNS/Client/DNS_rr_SOA.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.Dns.Client { #region usings using System; #endregion /// <summary> /// SOA record class. /// </summary> [Serializable] public class DNS_rr_SOA : DNS_rr_base { #region Members private readonly string m_AdminEmail = ""; private readonly long m_Expire; private readonly long m_Minimum; private readonly string m_NameServer = ""; private readonly long m_Refresh; private readonly long m_Retry; private readonly long m_Serial; #endregion #region Properties /// <summary> /// Gets name server. /// </summary> public string NameServer { get { return m_NameServer; } } /// <summary> /// Gets zone administrator email. /// </summary> public string AdminEmail { get { return m_AdminEmail; } } /// <summary> /// Gets version number of the original copy of the zone. /// </summary> public long Serial { get { return m_Serial; } } /// <summary> /// Gets time interval(in seconds) before the zone should be refreshed. /// </summary> public long Refresh { get { return m_Refresh; } } /// <summary> /// Gets time interval(in seconds) that should elapse before a failed refresh should be retried. /// </summary> public long Retry { get { return m_Retry; } } /// <summary> /// Gets time value(in seconds) that specifies the upper limit on the time interval that can elapse before the zone is no longer authoritative. /// </summary> public long Expire { get { return m_Expire; } } /// <summary> /// Gets minimum TTL(in seconds) field that should be exported with any RR from this zone. /// </summary> public long Minimum { get { return m_Minimum; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="nameServer">Name server.</param> /// <param name="adminEmail">Zone administrator email.</param> /// <param name="serial">Version number of the original copy of the zone.</param> /// <param name="refresh">Time interval(in seconds) before the zone should be refreshed.</param> /// <param name="retry">Time interval(in seconds) that should elapse before a failed refresh should be retried.</param> /// <param name="expire">Time value(in seconds) that specifies the upper limit on the time interval that can elapse before the zone is no longer authoritative.</param> /// <param name="minimum">Minimum TTL(in seconds) field that should be exported with any RR from this zone.</param> /// <param name="ttl">TTL value.</param> public DNS_rr_SOA(string nameServer, string adminEmail, long serial, long refresh, long retry, long expire, long minimum, int ttl) : base(QTYPE.SOA, ttl) { m_NameServer = nameServer; m_AdminEmail = adminEmail; m_Serial = serial; m_Refresh = refresh; m_Retry = retry; m_Expire = expire; m_Minimum = minimum; } #endregion #region Methods /// <summary> /// Parses resource record from reply data. /// </summary> /// <param name="reply">DNS server reply data.</param> /// <param name="offset">Current offset in reply data.</param> /// <param name="rdLength">Resource record data length.</param> /// <param name="ttl">Time to live in seconds.</param> public static DNS_rr_SOA Parse(byte[] reply, ref int offset, int rdLength, int ttl) { /* RFC 1035 3.3.13. SOA RDATA format +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ / MNAME / / / +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ / RNAME / +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | SERIAL | | | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | REFRESH | | | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | RETRY | | | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | EXPIRE | | | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | MINIMUM | | | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ where: MNAME The <domain-name> of the name server that was the original or primary source of data for this zone. RNAME A <domain-name> which specifies the mailbox of the person responsible for this zone. SERIAL The unsigned 32 bit version number of the original copy of the zone. Zone transfers preserve this value. This value wraps and should be compared using sequence space arithmetic. REFRESH A 32 bit time interval before the zone should be refreshed. RETRY A 32 bit time interval that should elapse before a failed refresh should be retried. EXPIRE A 32 bit time value that specifies the upper limit on the time interval that can elapse before the zone is no longer authoritative. MINIMUM The unsigned 32 bit minimum TTL field that should be exported with any RR from this zone. */ //---- Parse record -------------------------------------------------------------// // MNAME string nameserver = ""; Dns_Client.GetQName(reply, ref offset, ref nameserver); // RNAME string adminMailBox = ""; Dns_Client.GetQName(reply, ref offset, ref adminMailBox); char[] adminMailBoxAr = adminMailBox.ToCharArray(); for (int i = 0; i < adminMailBoxAr.Length; i++) { if (adminMailBoxAr[i] == '.') { adminMailBoxAr[i] = '@'; break; } } adminMailBox = new string(adminMailBoxAr); // SERIAL long serial = reply[offset++] << 24 | reply[offset++] << 16 | reply[offset++] << 8 | reply[offset++]; // REFRESH long refresh = reply[offset++] << 24 | reply[offset++] << 16 | reply[offset++] << 8 | reply[offset++]; // RETRY long retry = reply[offset++] << 24 | reply[offset++] << 16 | reply[offset++] << 8 | reply[offset++]; // EXPIRE long expire = reply[offset++] << 24 | reply[offset++] << 16 | reply[offset++] << 8 | reply[offset++]; // MINIMUM long minimum = reply[offset++] << 24 | reply[offset++] << 16 | reply[offset++] << 8 | reply[offset++]; //--------------------------------------------------------------------------------// return new DNS_rr_SOA(nameserver, adminMailBox, serial, refresh, retry, expire, minimum, ttl); } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/SIP/Stack/SIP_Transaction.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.SIP.Stack { #region usings using System; using System.Collections.Generic; using Message; #endregion /// <summary> /// This is base class for SIP client and server transaction. /// </summary> public abstract class SIP_Transaction : IDisposable { #region Events /// <summary> /// Is raised when transaction is disposed. /// </summary> public event EventHandler Disposed = null; /// <summary> /// Is raised when transaction state has changed. /// </summary> public event EventHandler StateChanged = null; /// <summary> /// Is raised if transaction is timed out. /// </summary> public event EventHandler TimedOut = null; /// <summary> /// Is raised when there is transaction error. For example this is raised when server transaction never /// gets ACK. /// </summary> public event EventHandler TransactionError = null; /// <summary> /// Is raised when there is transport error. /// </summary> public event EventHandler<ExceptionEventArgs> TransportError = null; #endregion #region Members private readonly DateTime m_CreateTime; private readonly string m_ID = ""; private readonly string m_Key = ""; private readonly string m_Method = ""; private readonly object m_pLock = new object(); private readonly List<SIP_Response> m_pResponses; private SIP_Flow m_pFlow; private SIP_Request m_pRequest; private SIP_Stack m_pStack; private SIP_TransactionState m_State; #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="stack">Owner SIP stack.</param> /// <param name="flow">Transaction data flow.</param> /// <param name="request">SIP request that transaction will handle.</param> /// <exception cref="ArgumentNullException">Is raised when <b>stack</b>,<b>flow</b> or <b>request</b> is null reference.</exception> public SIP_Transaction(SIP_Stack stack, SIP_Flow flow, SIP_Request request) { if (stack == null) { throw new ArgumentNullException("stack"); } if (flow == null) { throw new ArgumentNullException("flow"); } if (request == null) { throw new ArgumentNullException("request"); } m_pStack = stack; m_pFlow = flow; m_pRequest = request; m_Method = request.RequestLine.Method; m_CreateTime = DateTime.Now; m_pResponses = new List<SIP_Response>(); // Validate Via: SIP_t_ViaParm via = request.Via.GetTopMostValue(); if (via == null) { throw new ArgumentException("Via: header is missing !"); } if (via.Branch == null) { throw new ArgumentException("Via: header 'branch' parameter is missing !"); } m_ID = via.Branch; if (this is SIP_ServerTransaction) { /* We use branch and sent-by as indexing key for transaction, the only special what we need to do is to handle CANCEL, because it has same branch as transaction to be canceled. For avoiding key collision, we add branch + '-' + 'sent-by' + CANCEL for cancel index key. ACK has also same branch, but we won't do transaction for ACK, so it isn't problem. */ string key = request.Via.GetTopMostValue().Branch + '-' + request.Via.GetTopMostValue().SentBy; if (request.RequestLine.Method == SIP_Methods.CANCEL) { key += "-CANCEL"; } m_Key = key; } else { m_Key = m_ID + "-" + request.RequestLine.Method; } } #endregion #region Properties /// <summary> /// Gets time when this transaction was created. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public DateTime CreateTime { get { if (State == SIP_TransactionState.Disposed) { throw new ObjectDisposedException(GetType().Name); } return m_CreateTime; } } /// <summary> /// Gets transaction related SIP dialog. Returns null if no dialog available. /// </summary> public SIP_Dialog Dialog { // FIX ME: get { return null; } } /// <summary> /// Gets transaction final(2xx - 699) response from responses collection. Returns null if no final responses. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public SIP_Response FinalResponse { get { if (State == SIP_TransactionState.Disposed) { throw new ObjectDisposedException(GetType().Name); } foreach (SIP_Response response in Responses) { if (response.StatusCodeType != SIP_StatusCodeType.Provisional) { return response; } } return null; } } /// <summary> /// Gets transaction data flow. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public SIP_Flow Flow { get { if (State == SIP_TransactionState.Disposed) { throw new ObjectDisposedException(GetType().Name); } return m_pFlow; } } /// <summary> /// Gets if transaction has any provisional(1xx) in responses collection. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public bool HasProvisionalResponse { get { if (State == SIP_TransactionState.Disposed) { throw new ObjectDisposedException(GetType().Name); } foreach (SIP_Response response in m_pResponses) { if (response.StatusCodeType == SIP_StatusCodeType.Provisional) { return true; } } return false; } } /// <summary> /// Gets transaction ID (Via: branch parameter value). /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public string ID { get { if (State == SIP_TransactionState.Disposed) { throw new ObjectDisposedException(GetType().Name); } return m_ID; } } /// <summary> /// Gets if transaction is disposed. /// </summary> public bool IsDisposed { get { return m_State == SIP_TransactionState.Disposed; } } /// <summary> /// Gets transaction final(1xx) response from responses collection. Returns null if no provisional responses. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public SIP_Response LastProvisionalResponse { get { if (State == SIP_TransactionState.Disposed) { throw new ObjectDisposedException(GetType().Name); } for (int i = Responses.Length - 1; i > -1; i--) { if (Responses[i].StatusCodeType == SIP_StatusCodeType.Provisional) { return Responses[i]; } } return null; } } /// <summary> /// Gets request method that transaction handles. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public string Method { get { if (State == SIP_TransactionState.Disposed) { throw new ObjectDisposedException(GetType().Name); } return m_Method; } } /// <summary> /// Gets SIP request what caused this transaction creation. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public SIP_Request Request { get { if (State == SIP_TransactionState.Disposed) { throw new ObjectDisposedException(GetType().Name); } return m_pRequest; } } /// <summary> /// Gets transaction processed responses. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public SIP_Response[] Responses { get { if (State == SIP_TransactionState.Disposed) { throw new ObjectDisposedException(GetType().Name); } return m_pResponses.ToArray(); } } /// <summary> /// Gets owner SIP stack. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public SIP_Stack Stack { get { if (State == SIP_TransactionState.Disposed) { throw new ObjectDisposedException(GetType().Name); } return m_pStack; } } /// <summary> /// Gets current transaction state. /// </summary> public SIP_TransactionState State { get { return m_State; } } /// <summary> /// Gets an object that can be used to synchronize access to the dialog. /// </summary> public object SyncRoot { get { return m_pLock; } } /// <summary> /// Gets or sets user data. /// </summary> public object Tag { get; set; } /// <summary> /// Gets transaction indexing key. /// </summary> internal string Key { get { return m_Key; } } #endregion #region Methods /// <summary> /// Cleans up any resources being used. /// </summary> public virtual void Dispose() { SetState(SIP_TransactionState.Disposed); OnDisposed(); m_pStack = null; m_pFlow = null; m_pRequest = null; StateChanged = null; Disposed = null; TimedOut = null; TransportError = null; } /// <summary> /// Cancels current transaction. /// </summary> public abstract void Cancel(); #endregion #region Utility methods /// <summary> /// Raises event <b>StateChanged</b>. /// </summary> private void OnStateChanged() { if (StateChanged != null) { StateChanged(this, new EventArgs()); } } #endregion /// <summary> /// Changes transaction state. /// </summary> /// <param name="state">New transaction state.</param> protected void SetState(SIP_TransactionState state) { // Log if (Stack.Logger != null) { Stack.Logger.AddText(ID, "Transaction [branch='" + ID + "';method='" + Method + "';IsServer=" + (this is SIP_ServerTransaction) + "] swtiched to '" + state + "' state."); } m_State = state; OnStateChanged(); if (m_State == SIP_TransactionState.Terminated) { Dispose(); } } /// <summary> /// Adds specified response to transaction responses collection. /// </summary> /// <param name="response">SIP response.</param> /// <exception cref="ArgumentNullException">Is raised when <b>response</b> is null reference.</exception> protected void AddResponse(SIP_Response response) { if (response == null) { throw new ArgumentNullException("response"); } // Don't store more than 15 responses, otherwise hacker may try todo buffer overrun with provisional responses. if (m_pResponses.Count < 15 || response.StatusCode >= 200) { m_pResponses.Add(response); } } /// <summary> /// Raises event <b>Disposed</b>. /// </summary> protected void OnDisposed() { if (Disposed != null) { Disposed(this, new EventArgs()); } } /// <summary> /// Raises TimedOut event. /// </summary> protected void OnTimedOut() { if (TimedOut != null) { TimedOut(this, new EventArgs()); } } /// <summary> /// Raises TimedOut event. /// </summary> /// <param name="exception">Transport exception.</param> /// <exception cref="ArgumentNullException">Is raised when <b>exception</b> is null reference.</exception> protected void OnTransportError(Exception exception) { if (exception == null) { throw new ArgumentNullException("exception"); } if (TransportError != null) { TransportError(this, new ExceptionEventArgs(exception)); } } /// <summary> /// Raises TransactionError event. /// </summary> /// <param name="errorText">Text describing error.</param> protected void OnTransactionError(string errorText) { if (TransactionError != null) { TransactionError(this, new EventArgs()); } } } }<file_sep>/common/ASC.Common/Utils/ConfigurationManagerExtension.cs using System.Collections.Concurrent; using System.Collections.Specialized; namespace System.Configuration { //mono:hack public static class ConfigurationManagerExtension { private static ConcurrentDictionary<string, object> Sections { get; set; } static ConfigurationManagerExtension() { Sections = new ConcurrentDictionary<string, object>(); } public static NameValueCollection AppSettings { get { var section = GetSection("appSettings"); if (section == null || !(section is NameValueCollection)) { throw new ConfigurationErrorsException("config exception"); } return (NameValueCollection)section; } } public static object GetSection(string sectionName) { return Sections.GetOrAdd(sectionName, ConfigurationManager.GetSection(sectionName)); } public static ConnectionStringSettingsCollection ConnectionStrings { get { var section = GetSection("connectionStrings"); if (section == null || section.GetType() != typeof(ConnectionStringsSection)) { throw new ConfigurationErrorsException("Config_connectionstrings_declaration_invalid"); } var connectionStringsSection = (ConnectionStringsSection)section; return connectionStringsSection.ConnectionStrings; } } } } <file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/SIP/Message/SIP_ParameterCollection.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.SIP.Message { #region usings using System; using System.Collections; using System.Collections.Generic; #endregion /// <summary> /// This class represents SIP value parameters collection. /// </summary> public class SIP_ParameterCollection : IEnumerable { #region Members private readonly List<SIP_Parameter> m_pCollection; #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> public SIP_ParameterCollection() { m_pCollection = new List<SIP_Parameter>(); } #endregion #region Properties /// <summary> /// Gets parameters count in the collection. /// </summary> public int Count { get { return m_pCollection.Count; } } /// <summary> /// Gets specified parameter from collection. Returns null if parameter with specified name doesn't exist. /// </summary> /// <param name="name">Parameter name.</param> /// <returns>Returns parameter with specified name or null if not found.</returns> public SIP_Parameter this[string name] { get { foreach (SIP_Parameter parameter in m_pCollection) { if (parameter.Name.ToLower() == name.ToLower()) { return parameter; } } return null; } } #endregion #region Methods /// <summary> /// Adds new parameter to the collection. /// </summary> /// <param name="name">Parameter name.</param> /// <param name="value">Parameter value.</param> /// <exception cref="ArgumentNullException">Is raised when <b>name</b> is null.</exception> /// <exception cref="ArgumentException">Is raised when 'name' is '' or parameter with specified name /// already exists in the collection.</exception> public void Add(string name, string value) { if (name == null) { throw new ArgumentNullException("name"); } if (Contains(name)) { throw new ArgumentException( "Prameter '' with specified name already exists in the collection !"); } m_pCollection.Add(new SIP_Parameter(name, value)); } /// <summary> /// Adds or updates specified parameter value. /// </summary> /// <param name="name">Parameter name.</param> /// <param name="value">Parameter value.</param> public void Set(string name, string value) { if (Contains(name)) { this[name].Value = value; } else { Add(name, value); } } /// <summary> /// Removes all parameters from the collection. /// </summary> public void Clear() { m_pCollection.Clear(); } /// <summary> /// Removes specified parameter from the collection. /// </summary> /// <param name="name">Parameter name.</param> public void Remove(string name) { SIP_Parameter parameter = this[name]; if (parameter != null) { m_pCollection.Remove(parameter); } } /// <summary> /// Checks if the collection contains parameter with the specified name. /// </summary> /// <param name="name">Parameter name.</param> /// <returns>Returns true if collection contains specified parameter.</returns> public bool Contains(string name) { SIP_Parameter parameter = this[name]; if (parameter != null) { return true; } else { return false; } } /// <summary> /// Gets enumerator. /// </summary> /// <returns></returns> public IEnumerator GetEnumerator() { return m_pCollection.GetEnumerator(); } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/SIP/Stack/SIP_Flow.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.SIP.Stack { #region usings using System; using System.IO; using System.Net; using System.Threading; using IO; using Mime; using TCP; using UDP; #endregion /// <summary> /// Implements SIP Flow. Defined in draft-ietf-sip-outbound. /// </summary> /// <remarks>A Flow is a network protocol layer (layer 4) association /// between two hosts that is represented by the network address and /// port number of both ends and by the protocol. For TCP, a flow is /// equivalent to a TCP connection. For UDP a flow is a bidirectional /// stream of datagrams between a single pair of IP addresses and /// ports of both peers. /// </remarks> public class SIP_Flow : IDisposable { #region Events /// <summary> /// Is raised when flow is disposing. /// </summary> public event EventHandler IsDisposing = null; #endregion #region Members private readonly DateTime m_CreateTime; private readonly string m_ID = ""; private readonly bool m_IsServer; private readonly IPEndPoint m_pLocalEP; private readonly object m_pLock = new object(); private readonly IPEndPoint m_pRemoteEP; private readonly SIP_Stack m_pStack; private readonly string m_Transport = ""; private long m_BytesWritten; private bool m_IsDisposed; private DateTime m_LastActivity; private bool m_LastCRLF; private TimerEx m_pKeepAliveTimer; private MemoryStream m_pMessage; private TCP_Session m_pTcpSession; #endregion #region Properties /// <summary> /// Gets if this object is disposed. /// </summary> public bool IsDisposed { get { return m_IsDisposed; } } /// <summary> /// Gets if this flow is server flow or client flow. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> public bool IsServer { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_IsServer; } } /// <summary> /// Gets time when flow was created. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> public DateTime CreateTime { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_CreateTime; } } /// <summary> /// Gets flow ID. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> public string ID { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_ID; } } /// <summary> /// Gets flow local IP end point. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> public IPEndPoint LocalEP { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_pLocalEP; } } /// <summary> /// Gets flow remote IP end point. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> public IPEndPoint RemoteEP { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_pRemoteEP; } } /// <summary> /// Gets flow transport. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> public string Transport { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_Transport; } } /// <summary> /// Gets if flow is reliable transport. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> public bool IsReliable { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_Transport != SIP_Transport.UDP; } } /// <summary> /// Gets if this connection is secure. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> public bool IsSecure { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (m_Transport == SIP_Transport.TLS) { return true; } else { return false; } } } /// <summary> /// Gets or sets if flow sends keep-alive packets. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> public bool SendKeepAlives { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_pKeepAliveTimer != null; } set { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (value) { if (m_pKeepAliveTimer == null) { m_pKeepAliveTimer = new TimerEx(15000, true); m_pKeepAliveTimer.Elapsed += delegate { // Log: if (m_pStack.TransportLayer.Stack.Logger != null) { m_pStack.TransportLayer.Stack.Logger.AddWrite ("", null, 2, "Flow [id='" + ID + "'] sent \"ping\"", LocalEP, RemoteEP); } try { SendInternal(new[] { (byte) '\r', (byte) '\n', (byte) '\r', (byte) '\n' }); } catch { // We don't care about errors here. } }; m_pKeepAliveTimer.Enabled = true; } } else { if (m_pKeepAliveTimer != null) { m_pKeepAliveTimer.Dispose(); m_pKeepAliveTimer = null; } } } } /// <summary> /// Gets when flow had last(send or receive) activity. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> public DateTime LastActivity { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (m_Transport == SIP_Transport.TCP || m_Transport == SIP_Transport.TLS) { return m_pTcpSession.LastActivity; } else { return m_LastActivity; } } } // TODO: BytesReaded /// <summary> /// Gets how many bytes this flow has sent to remote party. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> public long BytesWritten { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_BytesWritten; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="stack">Owner stack.</param> /// <param name="isServer">Specifies if flow is server or client flow.</param> /// <param name="localEP">Local IP end point.</param> /// <param name="remoteEP">Remote IP end point.</param> /// <param name="transport">SIP transport.</param> /// <exception cref="ArgumentNullException">Is raised when <b>stack</b>,<b>localEP</b>,<b>remoteEP</b> or <b>transport</b> is null reference.</exception> /// <exception cref="ArgumentException">Is raised whena any of the arguments has invalid value.</exception> internal SIP_Flow(SIP_Stack stack, bool isServer, IPEndPoint localEP, IPEndPoint remoteEP, string transport) { if (stack == null) { throw new ArgumentNullException("stack"); } if (localEP == null) { throw new ArgumentNullException("localEP"); } if (remoteEP == null) { throw new ArgumentNullException("remoteEP"); } if (transport == null) { throw new ArgumentNullException("transport"); } m_pStack = stack; m_IsServer = isServer; m_pLocalEP = localEP; m_pRemoteEP = remoteEP; m_Transport = transport.ToUpper(); m_CreateTime = DateTime.Now; m_LastActivity = DateTime.Now; m_ID = m_pLocalEP + "-" + m_pRemoteEP + "-" + m_Transport; m_pMessage = new MemoryStream(); } /// <summary> /// Server TCP,TLS constructor. /// </summary> /// <param name="stack">Owner stack.</param> /// <param name="session">TCP session.</param> /// <exception cref="ArgumentNullException">Is raised when <b>stack</b> or <b>session</b> is null reference.</exception> internal SIP_Flow(SIP_Stack stack, TCP_Session session) { if (stack == null) { throw new ArgumentNullException("stack"); } if (session == null) { throw new ArgumentNullException("session"); } m_pStack = stack; m_pTcpSession = session; m_IsServer = true; m_pLocalEP = session.LocalEndPoint; m_pRemoteEP = session.RemoteEndPoint; m_Transport = session.IsSecureConnection ? SIP_Transport.TLS : SIP_Transport.TCP; m_CreateTime = DateTime.Now; m_LastActivity = DateTime.Now; m_ID = m_pLocalEP + "-" + m_pRemoteEP + "-" + m_Transport; m_pMessage = new MemoryStream(); BeginReadHeader(); } #endregion #region Methods /// <summary> /// Cleans up any resources being used. /// </summary> public void Dispose() { lock (m_pLock) { if (m_IsDisposed) { return; } OnDisposing(); m_IsDisposed = true; if (m_pTcpSession != null) { m_pTcpSession.Dispose(); m_pTcpSession = null; } m_pMessage = null; if (m_pKeepAliveTimer != null) { m_pKeepAliveTimer.Dispose(); m_pKeepAliveTimer = null; } } } /// <summary> /// Sends specified request to flow remote end point. /// </summary> /// <param name="request">SIP request to send.</param> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="ArgumentNullException">Is raised when <b>request</b> is null reference.</exception> public void Send(SIP_Request request) { lock (m_pLock) { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (request == null) { throw new ArgumentNullException("request"); } SendInternal(request.ToByteData()); } } /// <summary> /// Sends specified response to flow remote end point. /// </summary> /// <param name="response">SIP response to send.</param> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="ArgumentNullException">Is raised when <b>response</b> is null reference.</exception> public void Send(SIP_Response response) { lock (m_pLock) { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (response == null) { throw new ArgumentNullException("response"); } SendInternal(response.ToByteData()); } } #endregion #region Utility methods /// <summary> /// Starts reading SIP message header. /// </summary> private void BeginReadHeader() { // Clear old data. m_pMessage.SetLength(0); // Start reading SIP message header. m_pTcpSession.TcpStream.BeginReadHeader(m_pMessage, m_pStack.TransportLayer.Stack.MaximumMessageSize, SizeExceededAction.JunkAndThrowException, BeginReadHeader_Completed, null); } /// <summary> /// This method is called when SIP message header reading has completed. /// </summary> /// <param name="asyncResult">An IAsyncResult that represents an asynchronous call.</param> private void BeginReadHeader_Completed(IAsyncResult asyncResult) { try { int countStored = m_pTcpSession.TcpStream.EndReadHeader(asyncResult); // We got CRLF(ping or pong). if (countStored == 0) { // We have ping request. if (IsServer) { // We have full ping request. if (m_LastCRLF) { m_LastCRLF = false; m_pStack.TransportLayer.OnMessageReceived(this, new[] { (byte) '\r', (byte) '\n', (byte) '\r', (byte) '\n' }); } // We have first CRLF of ping request. else { m_LastCRLF = true; } } // We got pong to our ping request. else { m_pStack.TransportLayer.OnMessageReceived(this, new[] {(byte) '\r', (byte) '\n'}); } // Wait for new SIP message. BeginReadHeader(); } // We have SIP message header. else { m_LastCRLF = false; // Add header terminator blank line. m_pMessage.Write(new[] {(byte) '\r', (byte) '\n'}, 0, 2); m_pMessage.Position = 0; string contentLengthValue = MimeUtils.ParseHeaderField("Content-Length:", m_pMessage); m_pMessage.Position = m_pMessage.Length; int contentLength = 0; // Read message body. if (contentLengthValue != "") { contentLength = Convert.ToInt32(contentLengthValue); } // Start reading message body. if (contentLength > 0) { // Read body data. m_pTcpSession.TcpStream.BeginReadFixedCount(m_pMessage, contentLength, BeginReadData_Completed, null); } // Message with no body. else { byte[] messageData = m_pMessage.ToArray(); // Wait for new SIP message. BeginReadHeader(); m_pStack.TransportLayer.OnMessageReceived(this, messageData); } } } catch { Dispose(); } } /// <summary> /// This method is called when SIP message data reading has completed. /// </summary> /// <param name="asyncResult">An IAsyncResult that represents an asynchronous call.</param> private void BeginReadData_Completed(IAsyncResult asyncResult) { try { m_pTcpSession.TcpStream.EndReadFixedCount(asyncResult); byte[] messageData = m_pMessage.ToArray(); // Wait for new SIP message. BeginReadHeader(); m_pStack.TransportLayer.OnMessageReceived(this, messageData); } catch { Dispose(); } } /// <summary> /// Raises <b>Disposed</b> event. /// </summary> private void OnDisposing() { if (IsDisposing != null) { IsDisposing(this, new EventArgs()); } } #endregion #region Internal methods /// <summary> /// Starts flow processing. /// </summary> internal void Start() { // Move processing to thread pool. AutoResetEvent startLock = new AutoResetEvent(false); ThreadPool.QueueUserWorkItem(delegate { lock (m_pLock) { startLock.Set(); // TCP / TLS client, connect to remote end point. if (!m_IsServer && m_Transport != SIP_Transport.UDP) { try { TCP_Client client = new TCP_Client(); client.Connect(m_pLocalEP, m_pRemoteEP, m_Transport == SIP_Transport.TLS); m_pTcpSession = client; BeginReadHeader(); } catch { Dispose(); } } } }); startLock.WaitOne(); } /// <summary> /// Sends specified data to the remote end point. /// </summary> /// <param name="data">Data to send.</param> /// <exception cref="ArgumentNullException">Is raised when <b>data</b> is null reference.</exception> internal void SendInternal(byte[] data) { if (data == null) { throw new ArgumentNullException("data"); } try { if (m_Transport == SIP_Transport.UDP) { m_pStack.TransportLayer.UdpServer.SendPacket(m_pLocalEP, data, 0, data.Length, m_pRemoteEP); } else if (m_Transport == SIP_Transport.TCP) { m_pTcpSession.TcpStream.Write(data, 0, data.Length); } else if (m_Transport == SIP_Transport.TLS) { m_pTcpSession.TcpStream.Write(data, 0, data.Length); } m_BytesWritten += data.Length; } catch (IOException x) { Dispose(); throw x; } } /// <summary> /// This method is called when flow gets new UDP packet. /// </summary> /// <param name="e">UDP data.</param> /// <exception cref="ArgumentNullException">Is raised when <b>e</b> is null reference.</exception> internal void OnUdpPacketReceived(UDP_PacketEventArgs e) { if (e == null) { throw new ArgumentNullException("e"); } m_LastActivity = DateTime.Now; m_pStack.TransportLayer.OnMessageReceived(this, e.Data); } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/HTTP/Server/HTTP_Session.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.IO; using System.Collections.Generic; using System.Text; using System.Net; using System.Net.Sockets; namespace LumiSoft.Net.HTTP.Server { /// <summary> /// Default constructor. /// </summary> public class HTTP_Session : SocketServerSession { private HTTP_Server m_pServer = null; /// <summary> /// Default constructor. /// </summary> /// <param name="sessionID">Session ID.</param> /// <param name="socket">Server connected socket.</param> /// <param name="bindInfo">BindInfo what accepted socket.</param> /// <param name="server">Reference to server.</param> internal HTTP_Session(string sessionID,SocketEx socket,BindInfo bindInfo,HTTP_Server server) : base(sessionID,socket,bindInfo,server) { m_pServer = server; StartSession(); } #region method StartSession /// <summary> /// Starts session. /// </summary> private void StartSession() { // Add session to session list m_pServer.AddSession(this); try{ BeginRecieveCmd();/* // Check if ip is allowed to connect this computer if(m_pServer.OnValidate_IpAddress(this.LocalEndPoint,this.RemoteEndPoint)){ //--- Dedicated SSL connection, switch to SSL -----------------------------------// if(this.BindInfo.SSL){ try{ this.Socket.SwitchToSSL(this.BindInfo.SSL_Certificate); if(this.Socket.Logger != null){ this.Socket.Logger.AddTextEntry("SSL negotiation completed successfully."); } } catch(Exception x){ if(this.Socket.Logger != null){ this.Socket.Logger.AddTextEntry("SSL handshake failed ! " + x.Message); EndSession(); return; } } } //-------------------------------------------------------------------------------// BeginRecieveCmd(); } else{ EndSession(); }*/ } catch(Exception x){ OnError(x); } } #endregion #region method EndSession /// <summary> /// Ends session, closes socket. /// </summary> private void EndSession() { try{ // Write logs to log file, if needed if(m_pServer.LogCommands){ this.Socket.Logger.Flush(); } if(this.Socket != null){ this.Socket.Shutdown(SocketShutdown.Both); this.Socket.Disconnect(); //this.Socket = null; } } catch{ // We don't need to check errors here, because they only may be Socket closing errors. } finally{ m_pServer.RemoveSession(this); } } #endregion #region method OnError /// <summary> /// Is called when error occures. /// </summary> /// <param name="x"></param> private void OnError(Exception x) { try{ // We must see InnerException too, SocketException may be as inner exception. SocketException socketException = null; if(x is SocketException){ socketException = (SocketException)x; } else if(x.InnerException != null && x.InnerException is SocketException){ socketException = (SocketException)x.InnerException; } if(socketException != null){ // Client disconnected without shutting down if(socketException.ErrorCode == 10054 || socketException.ErrorCode == 10053){ if(m_pServer.LogCommands){ this.Socket.Logger.AddTextEntry("Client aborted/disconnected"); } EndSession(); // Exception handled, return return; } } m_pServer.OnSysError("",x); } catch(Exception ex){ m_pServer.OnSysError("",ex); } } #endregion #region method BeginRecieveCmd /// <summary> /// Starts recieveing command. /// </summary> private void BeginRecieveCmd() { MemoryStream strm = new MemoryStream(); this.Socket.BeginReadLine(strm,1024,strm,new SocketCallBack(this.EndRecieveCmd)); } #endregion #region method EndRecieveCmd /// <summary> /// Is called if command is recieved. /// </summary> /// <param name="result"></param> /// <param name="exception"></param> /// <param name="count"></param> /// <param name="tag"></param> private void EndRecieveCmd(SocketCallBackResult result,long count,Exception exception,object tag) { try{ switch(result) { case SocketCallBackResult.Ok: MemoryStream strm = (MemoryStream)tag; string cmdLine = System.Text.Encoding.Default.GetString(strm.ToArray()); // Exceute command if(SwitchCommand(cmdLine)){ // Session end, close session EndSession(); } break; case SocketCallBackResult.LengthExceeded: this.Socket.WriteLine("-ERR Line too long."); BeginRecieveCmd(); break; case SocketCallBackResult.SocketClosed: EndSession(); break; case SocketCallBackResult.Exception: OnError(exception); break; } } catch(Exception x){ OnError(x); } } #endregion #region method SwitchCommand /// <summary> /// Parses and executes HTTP commmand. /// </summary> /// <param name="commandLine">Command line.</param> /// <returns>Returns true,if session must be terminated.</returns> private bool SwitchCommand(string commandLine) { /* RFC 2616 5.1 Request-Line The Request-Line begins with a method token, followed by the Request-URI and the protocol version, and ending with CRLF. The elements are separated by SP characters. No CR or LF is allowed except in the final CRLF sequence. Request-Line = Method SP Request-URI SP HTTP-Version CRLF */ string[] parts = TextUtils.SplitQuotedString(commandLine,' '); string method = parts[0].ToUpper(); string uri = parts[1]; string httpVersion = parts[2]; //if(method == "OPTIONS"){ //} if(method == "GET"){ }/* else if(method == "HEAD"){ } else if(method == "POST"){ } else if(method == "PUT"){ } else if(method == "DELETE"){ } else if(method == "TRACE"){ } else if(method == "CONNECT"){ }*/ else{ } return false; } #endregion private void GET() { } } } <file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/_Obsolete/StreamHelper.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.IO { #region usings using System; using System.IO; using System.Text; using Log; #endregion /// <summary> /// This delegate represents callback method for BeginReadLine. /// </summary> /// <param name="e">Method data.</param> public delegate void ReadLineCallback(ReadLine_EventArgs e); /// <summary> /// This delegate represents callback method for BeginReadToEnd,BeginReadHeader,BeginReadPeriodTerminated. /// </summary> /// <param name="e">Method data.</param> public delegate void ReadToStreamCallback(ReadToStream_EventArgs e); /// <summary> /// This delegate represents callback method for BeginWrite. /// </summary> /// <param name="e">Method data.</param> public delegate void WriteCallback(Write_EventArgs e); /// <summary> /// This delegate represents callback method for BeginWrite,BeginWritePeriodTerminated. /// </summary> /// <param name="e">Method data.</param> public delegate void WriteStreamCallback(WriteStream_EventArgs e); /// <summary> /// Stream wrapper class, provides many usefull read and write methods for stream. /// </summary> [Obsolete("Use SmartStream instead.")] public class StreamHelper { #region Nested type: _ToStreamReader /// <summary> /// Asynchronous to stream reader implementation. /// </summary> private class _ToStreamReader { #region Members private readonly SizeExceededAction m_ExceededAction = SizeExceededAction.ThrowException; private readonly int m_MaxSize = Workaround.Definitions.MaxStreamLineLength; private readonly byte[] m_pBuffer; private readonly BufferedStream m_pBufferedStream; private readonly ReadToStreamCallback m_pCallback; private readonly byte[] m_pLineBuffer; private readonly Stream m_pStoreStream; private readonly StreamHelper m_pStreamHelper; private readonly object m_pTag; private int m_CountInBuffer; private int m_CountToRead; private bool m_IsLineSizeExceeded; private int m_TotalReadedCount; #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="streamHelper">Reference to StreamHelper.</param> /// <param name="storeStream">Stream where to store readed data.</param> /// <param name="maxSize">Maximum number of bytes to read.</param> /// <param name="exceededAction">Specifies how this method behaves when maximum size exceeded.</param> /// <param name="callback">Callback what will be called if asynchronous reading compltes.</param> /// <param name="tag">User data.</param> public _ToStreamReader(StreamHelper streamHelper, Stream storeStream, int maxSize, SizeExceededAction exceededAction, ReadToStreamCallback callback, object tag) { m_pStreamHelper = streamHelper; m_pStoreStream = storeStream; m_pBufferedStream = new BufferedStream(m_pStoreStream, Workaround.Definitions.MaxStreamLineLength); m_MaxSize = maxSize; m_ExceededAction = exceededAction; m_pCallback = callback; m_pTag = tag; m_pBuffer = new byte[Workaround.Definitions.MaxStreamLineLength]; m_pLineBuffer = new byte[4096]; } #endregion #region Methods /// <summary> /// Starts reading specified amount of data. /// </summary> /// <param name="count">Number of bytes to read from source stream and store to store stream.</param> public void BeginRead(int count) { m_CountToRead = count; DoRead(); } /// <summary> /// Starts reading period terminated data. /// </summary> public void BeginReadPeriodTerminated() { try { m_pStreamHelper.BeginReadLineInternal(m_pLineBuffer, m_ExceededAction, null, OnReadPeriodTerminated_ReadLine_Completed, false, false); } catch (Exception x) { ReadPeriodTerminatedCompleted(x); } } /// <summary> /// Starts reading header data. /// </summary> public void BeginReadHeader() { try { m_pStreamHelper.BeginReadLineInternal(m_pLineBuffer, m_ExceededAction, null, OnReadHeader_ReadLine_Completed, false, false); } catch (Exception x) { ReadHeaderCompleted(x); } } /// <summary> /// Starts reading all source stream data. /// </summary> public void BeginReadAll() { DoReadAll(); } #endregion #region Utility methods /// <summary> /// Processes all buffer data and gets new buffer if active buffer consumed. /// </summary> private void DoRead() { /* Note: We do own read buffering here, because we cand do buffering here even if * buffering not enabled for StreamHelper. All this because we read all data anyway. * But we need to use StreamHelper read buffer first if there is any data in that buffer. */ try { // We have data in buffer, consume it. if (m_CountInBuffer > 0) { m_TotalReadedCount += m_CountInBuffer; // Write readed data to store stream. m_pStoreStream.Write(m_pBuffer, 0, m_CountInBuffer); m_CountInBuffer = 0; } // We have readed all data that was requested. if (m_TotalReadedCount == m_CountToRead) { OnRead_Completed(null); } else { // There is some data in StreamHelper read buffer, we need to consume it first. if (m_pStreamHelper.m_ReadBufferOffset < m_pStreamHelper.m_ReadBufferEndPos) { int countReadedFromBuffer = Math.Min( m_pStreamHelper.m_ReadBufferEndPos - m_pStreamHelper.m_ReadBufferOffset, m_CountToRead - m_TotalReadedCount); Array.Copy(m_pStreamHelper.m_pReadBuffer, m_pStreamHelper.m_ReadBufferOffset, m_pBuffer, 0, countReadedFromBuffer); m_pStreamHelper.m_ReadBufferOffset += countReadedFromBuffer; } // Start reading new (local)buffer data block. else { m_pStreamHelper.Stream.BeginRead(m_pBuffer, 0, Math.Min(m_pBuffer.Length, m_CountToRead - m_TotalReadedCount), OnRead_ReadBuffer_Completed, null); } } } catch (Exception x) { OnRead_Completed(x); } } /// <summary> /// Is called when asynchrounous data buffer block reading has completed. /// </summary> /// <param name="result"></param> private void OnRead_ReadBuffer_Completed(IAsyncResult result) { try { m_CountInBuffer = m_pStreamHelper.Stream.EndRead(result); // We reached end of stream, no more data. if (m_CountInBuffer == 0) { OnRead_Completed(new IncompleteDataException()); } else { // Continue reading. DoRead(); } } catch (Exception x) { OnRead_Completed(x); } } /// <summary> /// Is called when ReadHeader has completed. /// </summary> /// <param name="x">Exception happened during read or null if operation was successfull.</param> private void OnRead_Completed(Exception x) { // Release read lock. m_pStreamHelper.m_IsReadActive = false; // Log if (m_pStreamHelper.Logger != null) { m_pStreamHelper.Logger.AddRead(m_TotalReadedCount, null); } if (m_pCallback != null) { m_pCallback(new ReadToStream_EventArgs(x, m_pStoreStream, m_TotalReadedCount, m_pTag)); } } /// <summary> /// Is called when asynchrounous line reading has completed. /// </summary> /// <param name="e">Callback data.</param> private void OnReadPeriodTerminated_ReadLine_Completed(ReadLine_EventArgs e) { try { m_TotalReadedCount += e.ReadedCount; // We got error. if (e.Exception != null) { try { m_pBufferedStream.Flush(); m_pStoreStream.Flush(); } catch { // Just skip excpetions here, otherwise we may hide original exception, // if exceptions is thrown by flush. } // Maximum line size exceeded, but junk data wanted. if (m_ExceededAction == SizeExceededAction.JunkAndThrowException && e.Exception is LineSizeExceededException) { m_IsLineSizeExceeded = true; // Start reading next data buffer block. m_pStreamHelper.BeginReadLineInternal(m_pLineBuffer, m_ExceededAction, null, OnReadPeriodTerminated_ReadLine_Completed, false, false); } // Unknown exception or ThrowException, so we are done. else { ReadPeriodTerminatedCompleted(e.Exception); } } // We reached end of stream before got period terminator. else if (e.ReadedCount == 0) { ReadPeriodTerminatedCompleted( new IncompleteDataException( "Source stream was reached end of stream and data is not period terminated !")); } // We got terminator, so we are done now. else if (e.Count == 1 && e.LineBuffer[0] == '.') { m_pBufferedStream.Flush(); m_pStoreStream.Flush(); // LineSizeExceeded. if (m_IsLineSizeExceeded) { ReadPeriodTerminatedCompleted(new LineSizeExceededException()); } // DataSizeExceeded. else if (m_TotalReadedCount > m_MaxSize) { ReadPeriodTerminatedCompleted(new DataSizeExceededException()); } // Completed successfuly. else { ReadPeriodTerminatedCompleted(null); } } // Just append line to store stream and get next line. else { // Maximum allowed data size exceeded. if (m_TotalReadedCount > m_MaxSize) { if (m_ExceededAction == SizeExceededAction.ThrowException) { ReadPeriodTerminatedCompleted(new DataSizeExceededException()); return; } // Junk data. //else{ //} } else { // If line starts with period, first period is removed. if (e.LineBuffer[0] == '.') { m_pBufferedStream.Write(e.LineBuffer, 1, e.Count - 1); } // Normal line. else { m_pBufferedStream.Write(e.LineBuffer, 0, e.Count); } // Add line break. m_pBufferedStream.Write(m_pStreamHelper.m_LineBreak, 0, m_pStreamHelper.m_LineBreak.Length); } // Start getting new data buffer block. m_pStreamHelper.BeginReadLineInternal(m_pLineBuffer, m_ExceededAction, null, OnReadPeriodTerminated_ReadLine_Completed, false, false); } } catch (Exception x) { ReadPeriodTerminatedCompleted(x); } } /// <summary> /// Is called when ReadPeriodTerminated has completd. /// </summary> /// <param name="x">Exeption happened or null if operation completed successfuly.</param> private void ReadPeriodTerminatedCompleted(Exception x) { // Release read lock. m_pStreamHelper.m_IsReadActive = false; // Log if (m_pStreamHelper.Logger != null) { m_pStreamHelper.Logger.AddRead(m_TotalReadedCount, null); } if (m_pCallback != null) { m_pCallback(new ReadToStream_EventArgs(x, m_pStoreStream, m_TotalReadedCount, m_pTag)); } } /// <summary> /// Is called when asynchrounous line reading has completed. /// </summary> /// <param name="e">Callback data.</param> private void OnReadHeader_ReadLine_Completed(ReadLine_EventArgs e) { try { m_TotalReadedCount += e.ReadedCount; // We got error. if (e.Exception != null) { try { m_pBufferedStream.Flush(); m_pStoreStream.Flush(); } catch { // Just skip excpetions here, otherwise we may hide original exception, // if exceptions is thrown by flush. } // Maximum line size exceeded, but junk data wanted. if (m_ExceededAction == SizeExceededAction.JunkAndThrowException && e.Exception is LineSizeExceededException) { m_IsLineSizeExceeded = true; // Start reading next data buffer block. m_pStreamHelper.BeginReadLineInternal(m_pLineBuffer, m_ExceededAction, null, OnReadHeader_ReadLine_Completed, false, false); } // Unknown exception or ThrowException, so we are done. else { ReadHeaderCompleted(e.Exception); } } // We got terminator, so we are done now. else if (e.Count == 0 || e.ReadedCount == 0) { m_pBufferedStream.Flush(); m_pStoreStream.Flush(); // LineSizeExceeded. if (m_IsLineSizeExceeded) { ReadHeaderCompleted(new LineSizeExceededException()); } // DataSizeExceeded. else if (m_TotalReadedCount > m_MaxSize) { ReadHeaderCompleted(new DataSizeExceededException()); } // Completed successfuly. else { ReadHeaderCompleted(null); } } // Just append line to store stream and get next line. else { // Maximum allowed data size exceeded. if (m_TotalReadedCount > m_MaxSize) { if (m_ExceededAction == SizeExceededAction.ThrowException) { ReadHeaderCompleted(new DataSizeExceededException()); return; } // Junk data. //else{ //} } else { m_pBufferedStream.Write(e.LineBuffer, 0, e.Count); m_pBufferedStream.Write(m_pStreamHelper.m_LineBreak, 0, m_pStreamHelper.m_LineBreak.Length); } // Start reading new line. m_pStreamHelper.BeginReadLineInternal(m_pLineBuffer, m_ExceededAction, null, OnReadHeader_ReadLine_Completed, false, false); } } catch (Exception x) { ReadHeaderCompleted(x); } } /// <summary> /// Is called when ReadHeader has completed. /// </summary> /// <param name="x">Exception happened during read or null if operation was successfull.</param> private void ReadHeaderCompleted(Exception x) { // Release read lock. m_pStreamHelper.m_IsReadActive = false; // Log if (m_pStreamHelper.Logger != null) { m_pStreamHelper.Logger.AddRead(m_TotalReadedCount, null); } if (m_pCallback != null) { m_pCallback(new ReadToStream_EventArgs(x, m_pStoreStream, m_TotalReadedCount, m_pTag)); } } /// <summary> /// Processes all buffer data and gets new buffer if active buffer consumed. /// </summary> private void DoReadAll() { /* Note: We do own read buffering here, because we cand do buffering here even if * buffering not enabled for StreamHelper. All this because we read all data anyway. * But we need to use StreamHelper read buffer first if there is any data in that buffer. */ try { // We have data in buffer, consume it. if (m_CountInBuffer > 0) { m_TotalReadedCount += m_CountInBuffer; // Maximum allowed data size exceeded. if (m_TotalReadedCount > m_MaxSize) { if (m_ExceededAction == SizeExceededAction.ThrowException) { ReadAllCompleted(new DataSizeExceededException()); return; } // Junk data. //else{ //} } // Store readed data store stream. else { m_pStoreStream.Write(m_pBuffer, 0, m_CountInBuffer); } m_CountInBuffer = 0; } // There is some data in StreamHelper read buffer, we need to consume it first. if (m_pStreamHelper.m_ReadBufferOffset < m_pStreamHelper.m_ReadBufferEndPos) { Array.Copy(m_pStreamHelper.m_pReadBuffer, m_pStreamHelper.m_ReadBufferOffset, m_pBuffer, 0, m_pStreamHelper.m_ReadBufferEndPos - m_pStreamHelper.m_ReadBufferOffset); m_pStreamHelper.m_ReadBufferOffset = 0; m_pStreamHelper.m_ReadBufferEndPos = 0; } // Start reading new (local)buffer data block. else { m_pStreamHelper.Stream.BeginRead(m_pBuffer, 0, m_pBuffer.Length, OnReadAll_ReadBuffer_Completed, null); } } catch (Exception x) { ReadAllCompleted(x); } } /// <summary> /// Is called when asynchrounous data buffer block reading has completed. /// </summary> /// <param name="result"></param> private void OnReadAll_ReadBuffer_Completed(IAsyncResult result) { try { m_CountInBuffer = m_pStreamHelper.Stream.EndRead(result); // We reached end of stream, no more data. if (m_CountInBuffer == 0) { // Maximum allowed data size exceeded. if (m_TotalReadedCount > m_MaxSize) { ReadAllCompleted(new DataSizeExceededException()); } // ReadToEnd completed successfuly. else { ReadAllCompleted(null); } } else { // Continue reading. DoReadAll(); } } catch (Exception x) { ReadAllCompleted(x); } } /// <summary> /// Is called when ReadToEnd has completed. /// </summary> /// <param name="x">Exception happened during read or null if operation was successfull.</param> private void ReadAllCompleted(Exception x) { // Release read lock. m_pStreamHelper.m_IsReadActive = false; // Log if (m_pStreamHelper.Logger != null) { m_pStreamHelper.Logger.AddRead(m_TotalReadedCount, null); } if (m_pCallback != null) { m_pCallback(new ReadToStream_EventArgs(x, m_pStoreStream, m_TotalReadedCount, m_pTag)); } } #endregion } #endregion #region Members private readonly bool m_IsReadBuffered; private readonly byte[] m_LineBreak = new[] {(byte) '\r', (byte) '\n'}; private readonly int m_MaxLineSize = 4096; private readonly byte[] m_pLineBuffer; private readonly byte[] m_pReadBuffer; private readonly byte[] m_pRLine_ByteBuffer; private readonly ReadLine_EventArgs m_pRLine_EventArgs; private readonly Stream m_pStream; // BeginWrite private int m_BeginWrite_Count; private int m_BeginWrite_Readed; // BeginWriteAll private int m_BeginWriteAll_MaxSize; private int m_BeginWriteAll_Readed; // BeginWritePeriodTerminated private int m_BeginWritePeriodTerminated_MaxSize; private int m_BeginWritePeriodTerminated_Readed; private int m_BeginWritePeriodTerminated_Written; private bool m_IsReadActive; private bool m_IsWriteActive; private byte[] m_pBeginWrite_Buffer; private WriteStreamCallback m_pBeginWrite_Callback; private Stream m_pBeginWrite_Stream; private byte[] m_pBeginWriteAll_Buffer; private WriteStreamCallback m_pBeginWriteAll_Callback; private Stream m_pBeginWriteAll_Stream; private BufferedStream m_pBeginWritePeriodTerminated_BufferedStream; private WriteStreamCallback m_pBeginWritePeriodTerminated_Callback; private Stream m_pBeginWritePeriodTerminated_Stream; private ReadLineCallback m_pRLine_Callback; private byte[] m_pRLine_LineBuffer; private object m_pRLine_Tag; private int m_ReadBufferEndPos; private int m_ReadBufferOffset; private SizeExceededAction m_RLine_ExceedAction = SizeExceededAction.ThrowException; private int m_RLine_LineBufferOffset; private int m_RLine_LineBufferSize; private bool m_RLine_Log; private int m_RLine_TotalReadedCount; private bool m_RLine_UnlockRead = true; #endregion #region Properties /// <summary> /// Gets underlying stream. /// </summary> public Stream Stream { get { return m_pStream; } } /// <summary> /// Gets maximum allowed line size in bytes. /// </summary> public int MaximumLineSize { get { return m_MaxLineSize; } } /// <summary> /// Gets if source stream reads are buffered. /// </summary> public bool IsReadBuffered { get { return m_IsReadBuffered; } } /// <summary> /// Gets or sets logger to use for logging. /// </summary> public Logger Logger { get; set; } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="stream">Source stream.</param> public StreamHelper(Stream stream) : this(stream, 4096, true) {} /// <summary> /// Default constructor. /// </summary> /// <param name="stream">Source stream.</param> /// <param name="maxLineSize">Specifies maximum line size in bytes.</param> /// <param name="bufferRead">Specifies if source stream reads are buffered..</param> public StreamHelper(Stream stream, int maxLineSize, bool bufferRead) { if (stream == null) { throw new ArgumentNullException("stream"); } if (maxLineSize < 1 || maxLineSize > Workaround.Definitions.MaxStreamLineLength) { throw new ArgumentException("Parameter maxLineSize value must be >= 1 and <= Workaround.Definitions.MaxStreamLineLength !"); } m_IsReadBuffered = bufferRead; if (m_IsReadBuffered) { m_pReadBuffer = new byte[Workaround.Definitions.MaxStreamLineLength]; } m_pStream = stream; m_pLineBuffer = new byte[maxLineSize]; m_MaxLineSize = maxLineSize; m_pRLine_EventArgs = new ReadLine_EventArgs(); m_pRLine_ByteBuffer = new byte[1]; } #endregion #region Methods /// <summary> /// Reades byte from source stream. Returns -1 if end of stream reached and no more data. /// </summary> /// <returns>Returns readed byte or -1 if end of stream reached.</returns> public int ReadByte() { if (m_IsReadBuffered) { if (m_ReadBufferOffset >= m_ReadBufferEndPos) { m_ReadBufferEndPos = m_pStream.Read(m_pReadBuffer, 0, Workaround.Definitions.MaxStreamLineLength); m_ReadBufferOffset = 0; // We reached end of stream. if (m_ReadBufferEndPos == 0) { return -1; } } m_ReadBufferOffset++; return m_pReadBuffer[m_ReadBufferOffset - 1]; } else { return m_pStream.ReadByte(); } } /// <summary> /// Starts reading specified amount data and storing to the specified store stream. /// </summary> /// <param name="storeStream">Stream where to store readed data.</param> /// <param name="count">Number of bytes to read from source stream and write to store stream.</param> /// <param name="callback">Callback to be called if asynchronous reading completes.</param> /// <param name="tag">User data.</param> /// <exception cref="ArgumentNullException">Raised when <b>storeStream</b> is null.</exception> /// <exception cref="ArgumentException">Raised when <b>count</b> less than 1.</exception> public void BeginRead(Stream storeStream, int count, ReadToStreamCallback callback, object tag) { if (storeStream == null) { throw new ArgumentNullException("storeStream"); } if (count < 1) { throw new ArgumentException("Parameter count value must be >= 1 !"); } lock (this) { if (m_IsReadActive) { throw new InvalidOperationException( "There is pending read operation, multiple read operations not allowed !"); } m_IsReadActive = true; } _ToStreamReader reader = new _ToStreamReader(this, storeStream, 0, SizeExceededAction.ThrowException, callback, tag); reader.BeginRead(count); } /// <summary> /// Reads specified amount of data from source stream and stores to specified store stream. /// </summary> /// <param name="storeStream">Stream where to store readed data.</param> /// <param name="count">Number of bytes to read from source stream and write to store stream.</param> /// <exception cref="ArgumentNullException">Raised when <b>storeStream</b> is null.</exception> /// <exception cref="ArgumentException">Raised when <b>count</b> less than 1.</exception> /// <exception cref="InvalidOperationException">Raised when there already is pending read operation.</exception> /// <exception cref="IncompleteDataException">Raised source stream has reached end of stream and doesn't have so much data as specified by <b>count</b> argument.</exception> public void Read(Stream storeStream, int count) { if (storeStream == null) { throw new ArgumentNullException("storeStream"); } if (count < 1) { throw new ArgumentException("Parameter count value must be >= 1 !"); } lock (this) { if (m_IsReadActive) { throw new InvalidOperationException( "There is pending read operation, multiple read operations not allowed !"); } m_IsReadActive = true; } try { byte[] buffer = new byte[Workaround.Definitions.MaxStreamLineLength]; int totalReadedCount = 0; int readedCount = 0; while (totalReadedCount < count) { // We have data in read buffer, we must consume it first ! if (m_ReadBufferOffset < m_ReadBufferEndPos) { int countReadedFromBuffer = Math.Min(m_ReadBufferEndPos - m_ReadBufferOffset, count - totalReadedCount); Array.Copy(m_pReadBuffer, m_ReadBufferOffset, buffer, 0, countReadedFromBuffer); m_ReadBufferOffset += countReadedFromBuffer; } // Just get read next data block. else { readedCount = m_pStream.Read(buffer, 0, Math.Min(buffer.Length, count - totalReadedCount)); } // We have reached end of stream, no more data. if (readedCount == 0) { throw new IncompleteDataException( "Underlaying stream don't have so much data than requested, end of stream reached !"); } totalReadedCount += readedCount; // Write readed data to store stream. storeStream.Write(buffer, 0, readedCount); } // Log if (Logger != null) { Logger.AddRead(totalReadedCount, null); } } finally { m_IsReadActive = false; } } /// <summary> /// Starts reading line from source stream. /// </summary> /// <param name="buffer">Buffer where to store line data.</param> /// <param name="tag">User data.</param> /// <param name="callback">Callback to be called whan asynchronous operation completes.</param> /// <exception cref="ArgumentNullException">Raised when <b>buffer</b> is null.</exception> /// <exception cref="InvalidOperationException">Raised when there already is pending read operation.</exception> public void BeginReadLine(byte[] buffer, object tag, ReadLineCallback callback) { BeginReadLine(buffer, SizeExceededAction.ThrowException, tag, callback); } /// <summary> /// Starts reading line from source stream. /// </summary> /// <param name="buffer">Buffer where to store line data.</param> /// <param name="exceededAction">Specifies how this method behaves when maximum line size exceeded.</param> /// <param name="tag">User data.</param> /// <param name="callback">Callback to be called whan asynchronous operation completes.</param> /// <exception cref="ArgumentNullException">Raised when <b>buffer</b> is null.</exception> /// <exception cref="InvalidOperationException">Raised when there already is pending read operation.</exception> public void BeginReadLine(byte[] buffer, SizeExceededAction exceededAction, object tag, ReadLineCallback callback) { if (buffer == null) { throw new ArgumentNullException("buffer"); } lock (this) { if (m_IsReadActive) { throw new InvalidOperationException( "There is pending read operation, multiple read operations not allowed !"); } m_IsReadActive = false; } BeginReadLineInternal(buffer, exceededAction, tag, callback, true, true); } /// <summary> /// Reads line from source stream and stores to specified buffer. This method accepts LF or CRLF lines. /// </summary> /// <param name="buffer">Buffer where to store line data.</param> /// <returns>Returns number of bytes stored to buffer, returns -1 if end of stream reached and no more data.</returns> /// <exception cref="ArgumentNullException">Raised when <b>buffer</b> is null.</exception> /// <exception cref="InvalidOperationException">Raised when there already is pending read operation.</exception> /// <exception cref="LineSizeExceededException">Raised when maximum allowed line size has exceeded.</exception> public int ReadLine(byte[] buffer) { return ReadLine(buffer, SizeExceededAction.ThrowException); } /// <summary> /// Reads line from source stream and stores to specified buffer. This method accepts LF or CRLF lines. /// </summary> /// <param name="buffer">Buffer where to store line data.</param> /// <param name="exceededAction">Specifies how this method behaves when maximum line size exceeded.</param> /// <returns>Returns number of bytes stored to buffer, returns -1 if end of stream reached and no more data.</returns> /// <exception cref="ArgumentNullException">Raised when <b>buffer</b> is null.</exception> /// <exception cref="InvalidOperationException">Raised when there already is pending read operation.</exception> /// <exception cref="LineSizeExceededException">Raised when maximum allowed line size has exceeded.</exception> public int ReadLine(byte[] buffer, SizeExceededAction exceededAction) { if (buffer == null) { throw new ArgumentNullException("buffer"); } lock (this) { if (m_IsReadActive) { throw new InvalidOperationException( "There is pending read operation, multiple read operations not allowed !"); } else { m_IsReadActive = true; } } try { int readedCount = 0; return ReadLineInternal(buffer, exceededAction, out readedCount, true); } finally { m_IsReadActive = false; } } /// <summary> /// Reads line from source stream. /// </summary> /// <param name="encoding">Encoding to use to decode line.</param> /// <returns>Returns readed line with specified encoding or null if end of stream reached and no more data.</returns> /// <exception cref="ArgumentNullException">Raised when <b>encoding</b> is null.</exception> /// <exception cref="InvalidOperationException">Raised when there already is pending read operation.</exception> /// <exception cref="LineSizeExceededException">Raised when maximum allowed line size has exceeded.</exception> public string ReadLine(Encoding encoding) { return ReadLine(encoding, SizeExceededAction.ThrowException); } /// <summary> /// Reads line from source stream. /// </summary> /// <param name="encoding">Encoding to use to decode line.</param> /// <param name="exceededAction">Specifies how this method behaves when maximum line size exceeded.</param> /// <returns>Returns readed line with specified encoding or null if end of stream reached and no more data.</returns> /// <exception cref="ArgumentNullException">Raised when <b>encoding</b> is null.</exception> /// <exception cref="InvalidOperationException">Raised when there already is pending read operation.</exception> /// <exception cref="LineSizeExceededException">Raised when maximum allowed line size has exceeded.</exception> public string ReadLine(Encoding encoding, SizeExceededAction exceededAction) { if (encoding == null) { throw new ArgumentNullException("encoding"); } int readedCount = ReadLine(m_pLineBuffer, exceededAction); if (readedCount == -1) { return null; } else { return encoding.GetString(m_pLineBuffer, 0, readedCount); } } /// <summary> /// Reads line from source stream and stores to specified buffer. This method accepts LF or CRLF lines. /// </summary> /// <param name="buffer">Buffer where to store line data.</param> /// <param name="exceededAction">Specifies how this method behaves when maximum line size exceeded.</param> /// <param name="readedCount">Returns how many bytes this method actually readed form source stream.</param> /// <param name="log">Specifies if read line is logged.</param> /// <returns>Returns number of bytes stored to buffer, returns -1 if end of stream reached and no more data.</returns> /// <exception cref="InvalidOperationException">Raised when there already is pending read operation.</exception> /// <exception cref="LineSizeExceededException">Raised when maximum allowed line size has exceeded.</exception> public int ReadLineInternal(byte[] buffer, SizeExceededAction exceededAction, out int readedCount, bool log) { readedCount = 0; int bufferSize = buffer.Length; int posInBuffer = 0; int currentByte = 0; /* Because performance gain we need todo,2 while, buffered and non buffered read. Each if clause in this while adds about 5% cpu. */ #region Buffered if (m_IsReadBuffered) { while (true) { //--- Read byte ----------------------------------------------------- if (m_ReadBufferOffset >= m_ReadBufferEndPos) { m_ReadBufferEndPos = m_pStream.Read(m_pReadBuffer, 0, Workaround.Definitions.MaxStreamLineLength); m_ReadBufferOffset = 0; // We reached end of stream. if (m_ReadBufferEndPos == 0) { break; } } currentByte = m_pReadBuffer[m_ReadBufferOffset]; m_ReadBufferOffset++; readedCount++; //------------------------------------------------------------------- // We have LF. if (currentByte == '\n') { break; } // We just skip all CR. else if (currentByte == '\r') {} // Maximum allowed line size exceeded. else if (readedCount > bufferSize) { if (exceededAction == SizeExceededAction.ThrowException) { throw new LineSizeExceededException(); } } // Store readed byte. else { buffer[posInBuffer] = (byte) currentByte; posInBuffer++; } } } #endregion #region No-buffered else { while (true) { // Read byte currentByte = m_pStream.ReadByte(); // We reached end of stream, no more data. if (currentByte == -1) { break; } readedCount++; // We have LF. if (currentByte == '\n') { break; } // We just skip all CR. else if (currentByte == '\r') {} // Maximum allowed line size exceeded. else if (readedCount > bufferSize) { if (exceededAction == SizeExceededAction.ThrowException) { throw new LineSizeExceededException(); } } // Store readed byte. else { buffer[posInBuffer] = (byte) currentByte; posInBuffer++; } } } #endregion // We are end of stream, no more data. if (readedCount == 0) { return -1; } // Maximum allowed line size exceeded. if (readedCount > m_MaxLineSize) { throw new LineSizeExceededException(); } // Log if (log && Logger != null) { Logger.AddRead(readedCount, Encoding.Default.GetString(buffer, 0, readedCount)); } return posInBuffer; } /// <summary> /// Starts reading all source stream data. /// </summary> /// <param name="storeStream">Stream where to store data.</param> /// <param name="maxSize">Maximum muber of bytes to read.</param> /// <param name="exceededAction">Specifies how this method behaves when maximum size exceeded.</param> /// <param name="callback">Callback to be called if asynchronous reading completes.</param> /// <param name="tag">User data.</param> /// <exception cref="ArgumentNullException">Raised when <b>storeStream</b> is null.</exception> /// <exception cref="InvalidOperationException">Raised when there already is pending read operation.</exception> public void BeginReadAll(Stream storeStream, int maxSize, SizeExceededAction exceededAction, ReadToStreamCallback callback, object tag) { if (storeStream == null) { throw new ArgumentNullException("storeStream"); } lock (this) { if (m_IsReadActive) { throw new InvalidOperationException( "There is pending read operation, multiple read operations not allowed !"); } m_IsReadActive = false; } _ToStreamReader reader = new _ToStreamReader(this, storeStream, maxSize, exceededAction, callback, tag); reader.BeginReadAll(); } /// <summary> /// Reads all source stream data and stores to the specified store stream. /// </summary> /// <param name="storeStream">Stream where to store readed data.</param> /// <param name="maxSize">Maximum muber of bytes to read.</param> /// <returns>Returns number of bytes written to <b>storeStream</b>.</returns> /// <exception cref="ArgumentNullException">Raised when <b>storeStream</b> is null.</exception> /// <exception cref="ArgumentException">Raised when <b>maxSize</b> less than 1.</exception> /// <exception cref="InvalidOperationException">Raised when there already is pending read operation.</exception> /// <exception cref="DataSizeExceededException">Raised when maximum allowed data size has exceeded.</exception> public int ReadAll(Stream storeStream, int maxSize) { return ReadAll(storeStream, maxSize, SizeExceededAction.ThrowException); } /// <summary> /// Reads all source stream data and stores to the specified store stream. /// </summary> /// <param name="storeStream">Stream where to store readed data.</param> /// <param name="maxSize">Maximum muber of bytes to read.</param> /// <param name="exceededAction">Specifies how this method behaves when maximum size exceeded.</param> /// <returns>Returns number of bytes written to <b>storeStream</b>.</returns> /// <exception cref="ArgumentNullException">Raised when <b>storeStream</b> is null.</exception> /// <exception cref="ArgumentException">Raised when <b>maxSize</b> less than 1.</exception> /// <exception cref="InvalidOperationException">Raised when there already is pending read operation.</exception> /// <exception cref="DataSizeExceededException">Raised when maximum allowed data size has exceeded.</exception> public int ReadAll(Stream storeStream, int maxSize, SizeExceededAction exceededAction) { if (storeStream == null) { throw new ArgumentNullException("storeStream"); } if (maxSize < 1) { throw new ArgumentException("Parameter maxSize value must be >= 1 !"); } lock (this) { if (m_IsReadActive) { throw new InvalidOperationException( "There is pending read operation, multiple read operations not allowed !"); } m_IsReadActive = true; } try { byte[] buffer = new byte[Workaround.Definitions.MaxStreamLineLength]; int totalReadedCount = 0; int readedCount = 0; while (true) { // We have data in read buffer, we must consume it first ! if (m_ReadBufferOffset < m_ReadBufferEndPos) { Array.Copy(m_pLineBuffer, m_ReadBufferOffset, buffer, 0, m_ReadBufferEndPos - m_ReadBufferOffset); m_ReadBufferOffset = 0; m_ReadBufferEndPos = 0; } // Just get read next data block. else { readedCount = m_pStream.Read(buffer, 0, buffer.Length); } // End of stream reached, no more data. if (readedCount == 0) { break; } totalReadedCount += readedCount; // Maximum allowed data size exceeded. if (totalReadedCount > maxSize) { if (exceededAction == SizeExceededAction.ThrowException) { throw new DataSizeExceededException(); } } else { storeStream.Write(buffer, 0, readedCount); } } // Maximum allowed data size exceeded, some data junked. if (totalReadedCount > maxSize) { throw new DataSizeExceededException(); } // Log if (Logger != null) { Logger.AddRead(totalReadedCount, null); } return totalReadedCount; } finally { m_IsReadActive = false; } } /// <summary> /// Starts reading header from source stream. Reads header data while gets blank line, what is /// header terminator. For example this method can be used for reading mail,http,sip, ... headers. /// </summary> /// <param name="storeStream">Stream where to store data.</param> /// <param name="maxSize">Maximum muber of bytes to read.</param> /// <param name="exceededAction">Specifies how this method behaves when maximum size exceeded.</param> /// <param name="callback">Callback to be called if asynchronous reading completes.</param> /// <param name="tag">User data.</param> /// <exception cref="ArgumentNullException">Raised when <b>storeStream</b> is null.</exception> /// <exception cref="InvalidOperationException">Raised when there already is pending read operation.</exception> public void BeginReadHeader(Stream storeStream, int maxSize, SizeExceededAction exceededAction, ReadToStreamCallback callback, object tag) { if (storeStream == null) { throw new ArgumentNullException("storeStream"); } lock (this) { if (m_IsReadActive) { throw new InvalidOperationException( "There is pending read operation, multiple read operations not allowed !"); } m_IsReadActive = false; } _ToStreamReader reader = new _ToStreamReader(this, storeStream, maxSize, exceededAction, callback, tag); reader.BeginReadHeader(); } /// <summary> /// Reads header from source stream and stores to the specified stream. Reads header data while /// gets blank line, what is header terminator. For example this method can be used for reading /// mail,http,sip, ... headers. /// </summary> /// <param name="storeStream">Stream where to store readed data.</param> /// <param name="maxSize">Maximum number of bytes to read.</param> /// <param name="exceededAction">Specifies how this method behaves when maximum line or data size exceeded.</param> /// <returns>Returns number of bytes written to <b>storeStream</b>.</returns> /// <exception cref="ArgumentNullException">Raised when <b>storeStream</b> is null.</exception> /// <exception cref="ArgumentException">Raised when <b>maxSize</b> less than 1.</exception> /// <exception cref="InvalidOperationException">Raised when there already is pending read operation.</exception> /// <exception cref="LineSizeExceededException">Raised when maximum allowed line size has exceeded.</exception> /// <exception cref="DataSizeExceededException">Raised when maximum allowed data size has exceeded.</exception> public int ReadHeader(Stream storeStream, int maxSize, SizeExceededAction exceededAction) { if (storeStream == null) { throw new ArgumentNullException("storeStream"); } lock (this) { if (m_IsReadActive) { throw new InvalidOperationException( "There is pending read operation, multiple read operations not allowed !"); } else { m_IsReadActive = true; } } try { BufferedStream bufferedStoreStream = new BufferedStream(storeStream, Workaround.Definitions.MaxStreamLineLength); bool lineSizeExceeded = false; int totalReadedCount = 0; int readedCount = 0; int rawReadedCount = 0; while (true) { // Read line. readedCount = ReadLineInternal(m_pLineBuffer, SizeExceededAction.ThrowException, out rawReadedCount, false); // We have reached end of stream, no more data. if (rawReadedCount == 0) { break; } totalReadedCount += rawReadedCount; // We got header terminator. if (readedCount == 0) { break; } else { // Maximum allowed data size exceeded. if (totalReadedCount > maxSize) { if (exceededAction == SizeExceededAction.ThrowException) { throw new DataSizeExceededException(); } } // Write readed bytes to store stream. else { bufferedStoreStream.Write(m_pLineBuffer, 0, readedCount); bufferedStoreStream.Write(m_LineBreak, 0, m_LineBreak.Length); } } } bufferedStoreStream.Flush(); // Maximum allowed line size exceeded, some data is junked. if (lineSizeExceeded) { throw new LineSizeExceededException(); } // Maximum allowed data size exceeded, some data is junked. if (totalReadedCount > maxSize) { throw new DataSizeExceededException(); } // Log if (Logger != null) { Logger.AddRead(totalReadedCount, null); } return totalReadedCount; } finally { m_IsReadActive = false; } } /// <summary> /// Begins reading period terminated data from source stream. Reads data while gets single period on line, /// what is data terminator. /// </summary> /// <param name="storeStream">Stream where to store data.</param> /// <param name="maxSize">Maximum muber of bytes to read.</param> /// <param name="exceededAction">Specifies how this method behaves when maximum size exceeded.</param> /// <param name="callback">Callback to be called if asynchronous reading completes.</param> /// <param name="tag">User data.</param> /// <exception cref="ArgumentNullException">Raised when <b>storeStream</b> is null.</exception> /// <exception cref="InvalidOperationException">Raised when there already is pending read operation.</exception> public void BeginReadPeriodTerminated(Stream storeStream, int maxSize, SizeExceededAction exceededAction, ReadToStreamCallback callback, object tag) { if (storeStream == null) { throw new ArgumentNullException("storeStream"); } lock (this) { if (m_IsReadActive) { throw new InvalidOperationException( "There is pending read operation, multiple read operations not allowed !"); } m_IsReadActive = false; } _ToStreamReader reader = new _ToStreamReader(this, storeStream, maxSize, exceededAction, callback, tag); reader.BeginReadPeriodTerminated(); } /// <summary> /// Reads period terminated data from source stream. Reads data while gets single period on line, /// what is data terminator. /// </summary> /// <param name="storeStream">Stream where to store readed data.</param> /// <param name="maxSize">Maximum number of bytes to read.</param> /// <param name="exceededAction">Specifies how this method behaves when maximum size exceeded.</param> /// <returns>Returns number of bytes written to <b>storeStream</b>.</returns> /// <exception cref="ArgumentNullException">Raised when <b>storeStream</b> is null.</exception> /// <exception cref="ArgumentException">Raised when <b>maxSize</b> less than 1.</exception> /// <exception cref="InvalidOperationException">Raised when there already is pending read operation.</exception> /// <exception cref="LineSizeExceededException">Raised when maximum allowed line size has exceeded.</exception> /// <exception cref="DataSizeExceededException">Raised when maximum allowed data size has exceeded.</exception> /// <exception cref="IncompleteDataException">Raised when source stream was reached end of stream and data is not period terminated.</exception> public int ReadPeriodTerminated(Stream storeStream, int maxSize, SizeExceededAction exceededAction) { if (storeStream == null) { throw new ArgumentNullException("storeStream"); } lock (this) { if (m_IsReadActive) { throw new InvalidOperationException( "There is pending read operation, multiple read operations not allowed !"); } else { m_IsReadActive = true; } } try { BufferedStream bufferedStoreStream = new BufferedStream(storeStream, Workaround.Definitions.MaxStreamLineLength); bool lineSizeExceeded = false; bool isPeriodTerminated = false; int totalReadedCount = 0; int readedCount = 0; int rawReadedCount = 0; // Just break reading at once if maximum allowed line or data size exceeded. if (exceededAction == SizeExceededAction.ThrowException) { try { // Read first line. readedCount = ReadLineInternal(m_pLineBuffer, SizeExceededAction.JunkAndThrowException, out rawReadedCount, false); } catch (LineSizeExceededException x) { string dummy = x.Message; lineSizeExceeded = true; } while (rawReadedCount != 0) { totalReadedCount += rawReadedCount; // We have data terminator "<CRLF>.<CRLF>". if (readedCount == 1 && m_pLineBuffer[0] == '.') { isPeriodTerminated = true; break; } // If line starts with period(.), first period is removed. else if (m_pLineBuffer[0] == '.') { // Maximum allowed line or data size exceeded. if (lineSizeExceeded || totalReadedCount > maxSize) { // Junk data } // Write readed line to store stream. else { bufferedStoreStream.Write(m_pLineBuffer, 1, readedCount - 1); bufferedStoreStream.Write(m_LineBreak, 0, m_LineBreak.Length); } } // Normal line. else { // Maximum allowed line or data size exceeded. if (lineSizeExceeded || totalReadedCount > maxSize) { // Junk data } // Write readed line to store stream. else { bufferedStoreStream.Write(m_pLineBuffer, 0, readedCount); bufferedStoreStream.Write(m_LineBreak, 0, m_LineBreak.Length); } } try { // Read next line. readedCount = ReadLineInternal(m_pLineBuffer, SizeExceededAction.JunkAndThrowException, out rawReadedCount, false); } catch (LineSizeExceededException x) { string dummy = x.Message; lineSizeExceeded = true; } } } // Read and junk all data if maximum allowed line or data size exceeded. else { // Read first line. readedCount = ReadLineInternal(m_pLineBuffer, SizeExceededAction.JunkAndThrowException, out rawReadedCount, false); while (rawReadedCount != 0) { totalReadedCount += rawReadedCount; // We have data terminator "<CRLF>.<CRLF>". if (readedCount == 1 && m_pLineBuffer[0] == '.') { isPeriodTerminated = true; break; } // If line starts with period(.), first period is removed. else if (m_pLineBuffer[0] == '.') { // Maximum allowed size exceeded. if (totalReadedCount > maxSize) { throw new DataSizeExceededException(); } // Write readed line to store stream. bufferedStoreStream.Write(m_pLineBuffer, 1, readedCount - 1); bufferedStoreStream.Write(m_LineBreak, 0, m_LineBreak.Length); } // Normal line. else { // Maximum allowed size exceeded. if (totalReadedCount > maxSize) { throw new DataSizeExceededException(); } // Write readed line to store stream. bufferedStoreStream.Write(m_pLineBuffer, 0, readedCount); bufferedStoreStream.Write(m_LineBreak, 0, m_LineBreak.Length); } // Read next line. readedCount = ReadLineInternal(m_pLineBuffer, SizeExceededAction.JunkAndThrowException, out rawReadedCount, false); } } bufferedStoreStream.Flush(); // Log if (Logger != null) { Logger.AddRead(totalReadedCount, null); } if (lineSizeExceeded) { throw new LineSizeExceededException(); } if (!isPeriodTerminated) { throw new IncompleteDataException( "Source stream was reached end of stream and data is not period terminated !"); } if (totalReadedCount > maxSize) { throw new DataSizeExceededException(); } return totalReadedCount; } finally { m_IsReadActive = false; } } /// <summary> /// Starts writing specified data to source stream. /// </summary> /// <param name="data">Data what to write to source stream.</param> /// <param name="callback">Callback to be callled if write completes.</param> /// <exception cref="ArgumentNullException">Raised when <b>data</b> is null.</exception> /// <exception cref="InvalidOperationException">Raised when there already is pending write operation.</exception> public void BeginWrite(byte[] data, WriteCallback callback) { if (data == null) { throw new ArgumentNullException("data"); } BeginWrite(data, 0, data.Length, callback); } /// <summary> /// Starts writing specified data to source stream. /// </summary> /// <param name="data">Data what to write to source stream.</param> /// <param name="offset">The zero-based byte offset in buffer at which to begin copying bytes to the source stream.</param> /// <param name="count">The number of bytes to be written to the source stream.</param> /// <param name="callback">Callback to be callled if write completes.</param> /// <exception cref="ArgumentNullException">Raised when <b>data</b> is null.</exception> /// <exception cref="InvalidOperationException">Raised when there already is pending write operation.</exception> public void BeginWrite(byte[] data, int offset, int count, WriteCallback callback) { if (data == null) { throw new ArgumentNullException("data"); } lock (this) { if (m_IsWriteActive) { throw new InvalidOperationException( "There is pending write operation, multiple write operations not allowed !"); } m_IsWriteActive = true; } // Start writing data block. m_pStream.BeginWrite(data, offset, count, InternalBeginWriteCallback, new object[] {count, callback}); } /// <summary> /// Strats writing specified amount of data from <b>stream</b> to source stream. /// </summary> /// <param name="stream">Stream which data to wite to source stream.</param> /// <param name="count">Number of bytes read from <b>stream</b> and write to source stream.</param> /// <param name="callback">Callback to be called if asynchronous write completes.</param> /// <exception cref="ArgumentNullException">Raised when <b>stream</b> is null.</exception> /// <exception cref="InvalidOperationException">Raised when there already is pending write operation.</exception> public void BeginWrite(Stream stream, int count, WriteStreamCallback callback) { if (stream == null) { throw new ArgumentNullException("stream"); } lock (this) { if (m_IsWriteActive) { throw new InvalidOperationException( "There is pending write operation, multiple write operations not allowed !"); } m_IsWriteActive = true; } m_pBeginWrite_Buffer = new byte[Workaround.Definitions.MaxStreamLineLength]; m_pBeginWrite_Stream = stream; m_BeginWrite_Count = count; m_pBeginWrite_Callback = callback; m_BeginWrite_Readed = 0; // Start reading data block. m_pBeginWrite_Stream.BeginRead(m_pBeginWrite_Buffer, 0, Math.Min(m_pBeginWrite_Buffer.Length, m_BeginWrite_Count), InternalBeginWriteStreamCallback, null); } /// <summary> /// Writes specified buffer data to source stream. /// </summary> /// <param name="data">Data buffer.</param> /// <exception cref="ArgumentNullException">Raised when <b>data</b> is null.</exception> /// <exception cref="InvalidOperationException">Raised when there already is pending write operation.</exception> public void Write(byte[] data) { if (data == null) { throw new ArgumentNullException("data"); } Write(data, 0, data.Length); } /// <summary> /// Writes specified buffer data to source stream. /// </summary> /// <param name="data">Data buffer.</param> /// <param name="offset">The zero-based byte offset in buffer at which to begin copying bytes to the source stream.</param> /// <param name="count">The number of bytes to be written to the source stream.</param> /// <exception cref="ArgumentNullException">Raised when <b>data</b> is null.</exception> /// <exception cref="InvalidOperationException">Raised when there already is pending write operation.</exception> public void Write(byte[] data, int offset, int count) { if (data == null) { throw new ArgumentNullException("data"); } lock (this) { if (m_IsWriteActive) { throw new InvalidOperationException( "There is pending write operation, multiple write operations not allowed !"); } m_IsWriteActive = true; } try { m_pStream.Write(data, offset, count); // Log if (Logger != null) { Logger.AddWrite(count, null); } } finally { m_IsWriteActive = false; } } /// <summary> /// Reads specified amount of data for the specified stream and writes it to source stream. /// </summary> /// <param name="stream">Stream from where to read data.</param> /// <param name="count">Number of bytes to read and write.</param> /// <exception cref="ArgumentNullException">Raised when <b>stream</b> is null.</exception> /// <exception cref="ArgumentException">Raised when argument <b>count</b> is less than 1.</exception> /// <exception cref="InvalidOperationException">Raised when there already is pending write operation.</exception> /// <exception cref="IncompleteDataException">Raised <b>stream</b> has reached end of stream and doesn't have so much data as specified by <b>count</b> argument.</exception> public void Write(Stream stream, int count) { if (stream == null) { throw new ArgumentNullException("stream"); } if (count < 1) { throw new ArgumentException("Parameter count value must be >= 1 !"); } lock (this) { if (m_IsWriteActive) { throw new InvalidOperationException( "There is pending write operation, multiple write operations not allowed !"); } m_IsWriteActive = true; } try { byte[] buffer = new byte[Workaround.Definitions.MaxStreamLineLength]; int totalReadedCount = 0; int readedCount = 0; while (totalReadedCount < count) { // Read data block readedCount = stream.Read(buffer, 0, Math.Min(buffer.Length, count - totalReadedCount)); // We reached end of stream, no more data. That means we didn't get so much data than requested. if (readedCount == 0) { throw new IncompleteDataException( "Stream reached end of stream before we got requested count of data !"); } totalReadedCount += readedCount; // Write readed data to source stream. m_pStream.Write(buffer, 0, readedCount); } m_pStream.Flush(); // Log if (Logger != null) { Logger.AddWrite(count, null); } } finally { m_IsWriteActive = false; } } /// <summary> /// Starts writing all <b>stream</b> data to source stream. /// </summary> /// <param name="stream">Stream which data to write.</param> /// <param name="maxSize">Maximum number of bytes to read from <b>stream</b>.</param> /// <param name="tag">User data.</param> /// <param name="callback">Callback to be called if asynchronous write completes.</param> /// <exception cref="ArgumentNullException">Raised when <b>stream</b> is null.</exception> /// <exception cref="InvalidOperationException">Raised when there already is pending write operation.</exception> public void BeginWriteAll(Stream stream, int maxSize, object tag, WriteStreamCallback callback) { if (stream == null) { throw new ArgumentNullException("stream"); } lock (this) { if (m_IsWriteActive) { throw new InvalidOperationException( "There is pending write operation, multiple write operations not allowed !"); } m_IsWriteActive = true; } m_pBeginWriteAll_Buffer = new byte[Workaround.Definitions.MaxStreamLineLength]; m_pBeginWriteAll_Stream = stream; m_BeginWriteAll_MaxSize = maxSize; m_pBeginWriteAll_Callback = callback; m_BeginWriteAll_Readed = 0; // Start reading data block. m_pBeginWriteAll_Stream.BeginRead(m_pBeginWriteAll_Buffer, 0, m_pBeginWriteAll_Buffer.Length, InternalBeginWriteAllCallback, null); } /// <summary> /// Writes all stream data to source stream. /// </summary> /// <param name="stream">Stream which data to write.</param> /// <returns>Returns number of bytes written to source stream.</returns> /// <exception cref="ArgumentNullException">Raised when <b>stream</b> is null.</exception> /// <exception cref="InvalidOperationException">Raised when there already is pending write operation.</exception> public int WriteAll(Stream stream) { return WriteAll(stream, int.MaxValue); } /// <summary> /// Writes all stream data to source stream. /// </summary> /// <param name="stream">Stream which data to write.</param> /// <param name="maxSize">Maximum muber of bytes to read from <b>stream</b> and write source stream.</param> /// <returns>Returns number of bytes written to source stream.</returns> /// <exception cref="ArgumentNullException">Raised when <b>stream</b> is null.</exception> /// <exception cref="InvalidOperationException">Raised when there already is pending write operation.</exception> /// <exception cref="DataSizeExceededException">Raised when <b>stream</b> stream has more data than specified by <b>maxSize</b>.</exception> public int WriteAll(Stream stream, int maxSize) { if (stream == null) { throw new ArgumentNullException("stream"); } lock (this) { if (m_IsWriteActive) { throw new InvalidOperationException( "There is pending write operation, multiple write operations not allowed !"); } m_IsWriteActive = true; } try { byte[] buffer = new byte[Workaround.Definitions.MaxStreamLineLength]; int totalReadedCount = 0; int readedCount = 0; while (readedCount > 0) { // Read data block readedCount = stream.Read(buffer, 0, buffer.Length); // We reached end of stream, no more data. if (readedCount == 0) { break; } // We have exceeded maximum allowed data size. else if ((totalReadedCount + readedCount) > maxSize) { throw new DataSizeExceededException(); } totalReadedCount += readedCount; // Write readed data to source stream. m_pStream.Write(buffer, 0, readedCount); } // Log if (Logger != null) { Logger.AddWrite(totalReadedCount, null); } return totalReadedCount; } finally { m_IsWriteActive = false; } } /// <summary> /// Starts writing <b>stream</b> data to source stream. Data will be period handled and terminated as needed. /// </summary> /// <param name="stream">Stream which data to write to source stream.</param> /// <param name="maxSize">Maximum muber of bytes to read from <b>stream</b> and write source stream.</param> /// <param name="tag">User data.</param> /// <param name="callback">Callback to be called if asynchronous write completes.</param> /// <exception cref="ArgumentNullException">Raised when <b>stream</b> is null.</exception> /// <exception cref="InvalidOperationException">Raised when there already is pending write operation.</exception> public void BeginWritePeriodTerminated(Stream stream, int maxSize, object tag, WriteStreamCallback callback) { if (stream == null) { throw new ArgumentNullException("stream"); } lock (this) { if (m_IsWriteActive) { throw new InvalidOperationException( "There is pending write operation, multiple write operations not allowed !"); } m_IsWriteActive = true; } m_pBeginWritePeriodTerminated_Stream = stream; m_BeginWritePeriodTerminated_MaxSize = maxSize; m_pBeginWritePeriodTerminated_Callback = callback; m_pBeginWritePeriodTerminated_BufferedStream = new BufferedStream(m_pStream); } /// <summary> /// Reades all data from the specified stream and writes it to source stream. Period handlign and period terminator is added as required. /// </summary> /// <param name="stream">Stream which data to write to source stream.</param> /// <returns>Returns number of bytes written to source stream. Note this value differs from /// <b>stream</b> readed bytes count because of period handling and period terminator. /// </returns> /// <exception cref="ArgumentNullException">Raised when <b>stream</b> is null.</exception> /// <exception cref="InvalidOperationException">Raised when there already is pending write operation.</exception> /// <exception cref="LineSizeExceededException">Raised when <b>stream</b> contains line with bigger line size than allowed.</exception> /// <exception cref="DataSizeExceededException">Raised when <b>stream</b> has more data than <b>maxSize</b> allows..</exception> public int WritePeriodTerminated(Stream stream) { return WritePeriodTerminated(stream, int.MaxValue); } /// <summary> /// Reades all data from the specified stream and writes it to source stream. Period handlign and period terminator is added as required. /// </summary> /// <param name="stream">Stream which data to write to source stream.</param> /// <param name="maxSize">Maximum muber of bytes to read from <b>stream</b> and write source stream.</param> /// <returns>Returns number of bytes written to source stream. Note this value differs from /// <b>stream</b> readed bytes count because of period handling and period terminator. /// </returns> /// <exception cref="ArgumentNullException">Raised when <b>stream</b> is null.</exception> /// <exception cref="InvalidOperationException">Raised when there already is pending write operation.</exception> /// <exception cref="LineSizeExceededException">Raised when <b>stream</b> contains line with bigger line size than allowed.</exception> /// <exception cref="DataSizeExceededException">Raised when <b>stream</b> has more data than <b>maxSize</b> allows..</exception> public int WritePeriodTerminated(Stream stream, int maxSize) { if (stream == null) { throw new ArgumentNullException("stream"); } lock (this) { if (m_IsWriteActive) { throw new InvalidOperationException( "There is pending write operation, multiple write operations not allowed !"); } m_IsWriteActive = true; } try { BufferedStream bufferedStoreStream = new BufferedStream(m_pStream, Workaround.Definitions.MaxStreamLineLength); StreamHelper reader = new StreamHelper(stream); int totalWrittenCount = 0; int readedCount = 0; int rawReadedCount = 0; while (true) { // Read data block. readedCount = ReadLineInternal(m_pLineBuffer, SizeExceededAction.ThrowException, out rawReadedCount, false); // We reached end of stream, no more data. if (readedCount == 0) { break; } // Maximum allowed data size exceeded. if ((totalWrittenCount + rawReadedCount) > maxSize) { throw new DataSizeExceededException(); } // If line starts with period(.), additional period is added. if (m_pLineBuffer[0] == '.') { bufferedStoreStream.WriteByte((byte) '.'); totalWrittenCount++; } // Write readed line to buffered stream. bufferedStoreStream.Write(m_pLineBuffer, 0, readedCount); bufferedStoreStream.Write(m_LineBreak, 0, m_LineBreak.Length); totalWrittenCount += (readedCount + m_LineBreak.Length); } // Write terminator ".<CRLF>". We have start <CRLF> already in stream. bufferedStoreStream.Write(new[] {(byte) '.', (byte) '\r', (byte) '\n'}, 0, 3); bufferedStoreStream.Flush(); m_pStream.Flush(); // Log if (Logger != null) { Logger.AddWrite(totalWrittenCount, null); } return totalWrittenCount; } finally { m_IsWriteActive = false; } } #endregion #region Utility methods /// <summary> /// Starts reading line from source stream. This method does not do any checks and read locks. /// </summary> /// <param name="buffer">Buffer where to store line data.</param> /// <param name="exceededAction">Specifies how this method behaves when maximum line size exceeded.</param> /// <param name="tag">User data.</param> /// <param name="callback">Callback to be called whan asynchronous operation completes.</param> /// <param name="unlockRead">Specifies if read lock is released.</param> /// <param name="log">User data.</param> private void BeginReadLineInternal(byte[] buffer, SizeExceededAction exceededAction, object tag, ReadLineCallback callback, bool unlockRead, bool log) { m_pRLine_LineBuffer = buffer; m_RLine_ExceedAction = exceededAction; m_pRLine_Tag = tag; m_pRLine_Callback = callback; m_RLine_LineBufferOffset = 0; m_RLine_TotalReadedCount = 0; m_RLine_LineBufferSize = buffer.Length; m_RLine_UnlockRead = unlockRead; m_RLine_Log = log; if (IsReadBuffered) { DoReadLine_Buffered(); } else { m_pStream.BeginRead(m_pRLine_ByteBuffer, 0, 1, OnReadByte_Completed, null); } } /// <summary> /// Is called when BeginWrite(byte[] data,int offset,int count) has completed. /// </summary> /// <param name="result"></param> private void InternalBeginWriteCallback(IAsyncResult result) { int count = (int) ((object[]) result.AsyncState)[0]; WriteCallback callback = (WriteCallback) ((object[]) result.AsyncState)[1]; try { m_pStream.EndWrite(result); // Log if (Logger != null) { Logger.AddWrite(count, null); } if (callback != null) { callback(new Write_EventArgs(null)); } } catch (Exception x) { if (callback != null) { callback(new Write_EventArgs(x)); } } finally { m_IsWriteActive = false; } } /// <summary> /// This method is called when BeginWrite has readed new data block. /// </summary> /// <param name="result"></param> private void InternalBeginWriteStreamCallback(IAsyncResult result) { try { int readedCount = m_pBeginWrite_Stream.EndRead(result); // We have reached end of stream, we din't get so much data as requested. if (readedCount == 0) { InternalBeginWriteStreamCompleted( new IncompleteDataException("Read stream didn't have so much data than requested !")); } else { m_BeginWrite_Readed += readedCount; // Write readed bytes to source stream. m_pStream.Write(m_pBeginWrite_Buffer, 0, readedCount); // We have readed all requested data. if (m_BeginWrite_Count == m_BeginWrite_Readed) { InternalBeginWriteStreamCompleted(null); } // We need read more data. else { // Start reading data block. m_pBeginWrite_Stream.BeginRead(m_pBeginWrite_Buffer, 0, Math.Min(m_pBeginWrite_Buffer.Length, m_BeginWrite_Count - m_BeginWrite_Readed), InternalBeginWriteStreamCallback, null); } } } catch (Exception x) { InternalBeginWriteStreamCompleted(x); } } /// <summary> /// Is called when BeginWrite has completed. /// </summary> /// <param name="exception">Exception happened during write or null if operation was successfull.</param> private void InternalBeginWriteStreamCompleted(Exception exception) { // Release write lock. m_IsWriteActive = false; // Log if (Logger != null) { Logger.AddWrite(m_BeginWrite_Readed, null); } if (m_pBeginWrite_Callback != null) { m_pBeginWrite_Callback(new WriteStream_EventArgs(exception, m_pBeginWrite_Stream, m_BeginWrite_Readed, m_BeginWrite_Readed)); } } /// <summary> /// This method is called when BeginWriteAll has readed new data block. /// </summary> /// <param name="result"></param> private void InternalBeginWriteAllCallback(IAsyncResult result) { try { int readedCount = m_pBeginWriteAll_Stream.EndRead(result); // We have reached end of stream, no more data. if (readedCount == 0) { InternalBeginWriteAllCompleted(null); } else { m_BeginWriteAll_Readed += readedCount; // Maximum allowed data size exceeded. if (m_BeginWriteAll_Readed > m_BeginWriteAll_MaxSize) { throw new DataSizeExceededException(); } // Write readed bytes to source stream. m_pStream.Write(m_pBeginWriteAll_Buffer, 0, readedCount); // Start reading next data block. m_pBeginWriteAll_Stream.BeginRead(m_pBeginWriteAll_Buffer, 0, m_pBeginWriteAll_Buffer.Length, InternalBeginWriteAllCallback, null); return; } } catch (Exception x) { InternalBeginWriteAllCompleted(x); } } /// <summary> /// Is called when BeginWriteAll has completed. /// </summary> /// <param name="exception">Exception happened during write or null if operation was successfull.</param> private void InternalBeginWriteAllCompleted(Exception exception) { // Release write lock. m_IsWriteActive = false; // Log if (Logger != null) { Logger.AddWrite(m_BeginWriteAll_Readed, null); } if (m_pBeginWriteAll_Callback != null) { m_pBeginWriteAll_Callback(new WriteStream_EventArgs(exception, m_pBeginWriteAll_Stream, m_BeginWriteAll_Readed, m_BeginWriteAll_Readed)); } } /// <summary> /// Is called when BeginWritePeriodTerminated stream.BeginReadLine has completed. /// </summary> /// <param name="e">Callback data.</param> private void InternalBeginWritePeriodTerminatedReadLineCompleted(ReadLine_EventArgs e) { try { // Error happened during read. if (e.Exception != null) { InternalBeginWritePeriodTerminatedCompleted(e.Exception); } // We reached end of stream, no more data. else if (e.ReadedCount == 0) { InternalBeginWritePeriodTerminatedCompleted(null); } else { m_BeginWritePeriodTerminated_Readed += e.ReadedCount; // Maximum allowed data size exceeded. if (m_BeginWritePeriodTerminated_Readed > m_BeginWritePeriodTerminated_MaxSize) { throw new DataSizeExceededException(); } // If line starts with period, addtional period is added. if (e.LineBuffer[0] == '.') { m_pBeginWritePeriodTerminated_BufferedStream.WriteByte((int) '.'); m_BeginWritePeriodTerminated_Written++; } // Write readed line to buffered stream. m_pBeginWritePeriodTerminated_BufferedStream.Write(e.LineBuffer, 0, e.Count); m_pBeginWritePeriodTerminated_BufferedStream.Write(m_LineBreak, 0, m_LineBreak.Length); m_BeginWritePeriodTerminated_Written += e.Count + m_LineBreak.Length; } } catch (Exception x) { InternalBeginWritePeriodTerminatedCompleted(x); } } /// <summary> /// Is called when asynchronous write period terminated has completed. /// </summary> /// <param name="exception">Exception happened during write or null if operation was successfull.</param> private void InternalBeginWritePeriodTerminatedCompleted(Exception exception) { // Release write lock. m_IsWriteActive = false; // Force to write buffer to source stream, if any. try { m_pBeginWritePeriodTerminated_BufferedStream.Flush(); } catch {} // Log if (Logger != null) { Logger.AddWrite(m_BeginWritePeriodTerminated_Written, null); } if (m_pBeginWritePeriodTerminated_Callback != null) { m_pBeginWritePeriodTerminated_Callback(new WriteStream_EventArgs(exception, m_pBeginWritePeriodTerminated_Stream, m_BeginWritePeriodTerminated_Readed, m_BeginWritePeriodTerminated_Written)); } } /// <summary> /// Is called when asynchronous read byte operation has completed. /// </summary> /// <param name="result"></param> private void OnReadByte_Completed(IAsyncResult result) { try { int readedCount = m_pStream.EndRead(result); if (readedCount == 1) { m_RLine_TotalReadedCount++; // We have LF. if (m_pRLine_ByteBuffer[0] == '\n') { // Line size eceeded and some data junked. if (m_RLine_LineBufferOffset > m_RLine_LineBufferSize) { OnReadLineCompleted(new LineSizeExceededException()); } // Read line completed sucessfully. else { OnReadLineCompleted(null); } return; } // We just skip all CR. else if (m_pRLine_ByteBuffer[0] == '\r') {} else { // Maximum allowed line size exceeded. if (m_RLine_LineBufferOffset >= m_RLine_LineBufferSize) { if (m_RLine_ExceedAction == SizeExceededAction.ThrowException) { OnReadLineCompleted(new LineSizeExceededException()); return; } } // Write readed byte to line buffer. else { m_pRLine_LineBuffer[m_RLine_LineBufferOffset] = m_pRLine_ByteBuffer[0]; m_RLine_LineBufferOffset++; } } // Get next byte. m_pStream.BeginRead(m_pRLine_ByteBuffer, 0, 1, OnReadByte_Completed, null); } // We have no more data. else { // Line size eceeded and some data junked. if (m_RLine_LineBufferOffset >= m_RLine_LineBufferSize) { OnReadLineCompleted(new LineSizeExceededException()); } // Read line completed sucessfully. else { OnReadLineCompleted(null); } } } catch (Exception x) { OnReadLineCompleted(x); } } /// <summary> /// Tries to read line from data buffer, if no line in buffer, new data buffer will be readed(buffered). /// </summary> private void DoReadLine_Buffered() { try { byte currentByte = 0; while (m_ReadBufferOffset < m_ReadBufferEndPos) { currentByte = m_pReadBuffer[m_ReadBufferOffset]; m_ReadBufferOffset++; m_RLine_TotalReadedCount++; // We have LF. if (currentByte == '\n') { // Line size eceeded and some data junked. if (m_RLine_TotalReadedCount > m_RLine_LineBufferSize) { OnReadLineCompleted(new LineSizeExceededException()); } // Read line completed sucessfully. else { OnReadLineCompleted(null); } return; } // We just skip all CR. else if (currentByte == '\r') {} else { // Maximum allowed line size exceeded. if (m_RLine_TotalReadedCount >= m_RLine_LineBufferSize) { if (m_RLine_ExceedAction == SizeExceededAction.ThrowException) { OnReadLineCompleted(new LineSizeExceededException()); return; } } // Write readed byte to line buffer. else { m_pRLine_LineBuffer[m_RLine_LineBufferOffset] = currentByte; m_RLine_LineBufferOffset++; } } } // If we reach here, that means we consumed all read buffer and no line was in it. // Just get new data buffer block. m_pStream.BeginRead(m_pReadBuffer, 0, m_pReadBuffer.Length, OnReadBuffer_Completed, null); } catch (Exception x) { OnReadLineCompleted(x); } } /// <summary> /// Is called when asynchronous data buffering has completed. /// </summary> /// <param name="result"></param> private void OnReadBuffer_Completed(IAsyncResult result) { try { m_ReadBufferEndPos = m_pStream.EndRead(result); m_ReadBufferOffset = 0; // We have reached end of stream, no more data. if (m_ReadBufferEndPos == 0) { // Line size eceeded and some data junked. if (m_RLine_TotalReadedCount > m_RLine_LineBufferSize) { OnReadLineCompleted(new LineSizeExceededException()); } // Read line completed sucessfully. else { OnReadLineCompleted(null); } } // Continue line reading. else { DoReadLine_Buffered(); } } catch (Exception x) { OnReadLineCompleted(x); } } /// <summary> /// Is called when read line has completed. /// </summary> /// <param name="x">Excheption what happened during line reading or null if read line was completed sucessfully.</param> private void OnReadLineCompleted(Exception x) { if (m_RLine_UnlockRead) { // Release reader lock. m_IsReadActive = false; } if (m_RLine_Log && Logger != null) { Logger.AddRead(m_RLine_TotalReadedCount, null); } if (m_pRLine_Callback != null) { m_pRLine_EventArgs.Reuse(x, m_RLine_TotalReadedCount, m_pRLine_LineBuffer, m_RLine_LineBufferOffset, m_pRLine_Tag); m_pRLine_Callback(m_pRLine_EventArgs); } } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/DNS/Client/DnsServerResponse.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.Dns.Client { #region usings using System; using System.Collections.Generic; #endregion /// <summary> /// This class represents dns server response. /// </summary> [Serializable] public class DnsServerResponse { #region Members private readonly List<DNS_rr_base> m_pAdditionalAnswers; private readonly List<DNS_rr_base> m_pAnswers; private readonly List<DNS_rr_base> m_pAuthoritiveAnswers; private readonly RCODE m_RCODE = RCODE.NO_ERROR; private readonly bool m_Success = true; #endregion #region Properties /// <summary> /// Gets if connection to dns server was successful. /// </summary> public bool ConnectionOk { get { return m_Success; } } /// <summary> /// Gets dns server response code. /// </summary> public RCODE ResponseCode { get { return m_RCODE; } } /// <summary> /// Gets all resource records returned by server (answer records section + authority records section + additional records section). /// NOTE: Before using this property ensure that ConnectionOk=true and ResponseCode=RCODE.NO_ERROR. /// </summary> public DNS_rr_base[] AllAnswers { get { List<DNS_rr_base> retVal = new List<DNS_rr_base>(); retVal.AddRange(m_pAnswers.ToArray()); retVal.AddRange(m_pAuthoritiveAnswers.ToArray()); retVal.AddRange(m_pAdditionalAnswers.ToArray()); return retVal.ToArray(); } } /// <summary> /// Gets dns server returned answers. NOTE: Before using this property ensure that ConnectionOk=true and ResponseCode=RCODE.NO_ERROR. /// </summary> /// <code> /// // NOTE: DNS server may return diffrent record types even if you query MX. /// // For example you query lumisoft.ee MX and server may response: /// // 1) MX - mail.lumisoft.ee /// // 2) A - lumisoft.ee /// // /// // Before casting to right record type, see what type record is ! /// /// /// foreach(DnsRecordBase record in Answers){ /// // MX record, cast it to MX_Record /// if(record.RecordType == QTYPE.MX){ /// MX_Record mx = (MX_Record)record; /// } /// } /// </code> public DNS_rr_base[] Answers { get { return m_pAnswers.ToArray(); } } /// <summary> /// Gets name server resource records in the authority records section. NOTE: Before using this property ensure that ConnectionOk=true and ResponseCode=RCODE.NO_ERROR. /// </summary> public DNS_rr_base[] AuthoritiveAnswers { get { return m_pAuthoritiveAnswers.ToArray(); } } /// <summary> /// Gets resource records in the additional records section. NOTE: Before using this property ensure that ConnectionOk=true and ResponseCode=RCODE.NO_ERROR. /// </summary> public DNS_rr_base[] AdditionalAnswers { get { return m_pAdditionalAnswers.ToArray(); } } #endregion #region Constructor internal DnsServerResponse(bool connectionOk, RCODE rcode, List<DNS_rr_base> answers, List<DNS_rr_base> authoritiveAnswers, List<DNS_rr_base> additionalAnswers) { m_Success = connectionOk; m_RCODE = rcode; m_pAnswers = answers; m_pAuthoritiveAnswers = authoritiveAnswers; m_pAdditionalAnswers = additionalAnswers; } #endregion #region Methods /// <summary> /// Gets IPv4 host addess records. /// </summary> /// <returns></returns> public DNS_rr_A[] GetARecords() { List<DNS_rr_A> retVal = new List<DNS_rr_A>(); foreach (DNS_rr_base record in m_pAnswers) { if (record.RecordType == QTYPE.A) { retVal.Add((DNS_rr_A) record); } } return retVal.ToArray(); } /// <summary> /// Gets name server records. /// </summary> /// <returns></returns> public DNS_rr_NS[] GetNSRecords() { List<DNS_rr_NS> retVal = new List<DNS_rr_NS>(); foreach (DNS_rr_base record in m_pAnswers) { if (record.RecordType == QTYPE.NS) { retVal.Add((DNS_rr_NS) record); } } return retVal.ToArray(); } /// <summary> /// Gets CNAME records. /// </summary> /// <returns></returns> public DNS_rr_CNAME[] GetCNAMERecords() { List<DNS_rr_CNAME> retVal = new List<DNS_rr_CNAME>(); foreach (DNS_rr_base record in m_pAnswers) { if (record.RecordType == QTYPE.CNAME) { retVal.Add((DNS_rr_CNAME) record); } } return retVal.ToArray(); } /// <summary> /// Gets SOA records. /// </summary> /// <returns></returns> public DNS_rr_SOA[] GetSOARecords() { List<DNS_rr_SOA> retVal = new List<DNS_rr_SOA>(); foreach (DNS_rr_base record in m_pAnswers) { if (record.RecordType == QTYPE.SOA) { retVal.Add((DNS_rr_SOA) record); } } return retVal.ToArray(); } /// <summary> /// Gets PTR records. /// </summary> /// <returns></returns> public DNS_rr_PTR[] GetPTRRecords() { List<DNS_rr_PTR> retVal = new List<DNS_rr_PTR>(); foreach (DNS_rr_base record in m_pAnswers) { if (record.RecordType == QTYPE.PTR) { retVal.Add((DNS_rr_PTR) record); } } return retVal.ToArray(); } /// <summary> /// Gets HINFO records. /// </summary> /// <returns></returns> public DNS_rr_HINFO[] GetHINFORecords() { List<DNS_rr_HINFO> retVal = new List<DNS_rr_HINFO>(); foreach (DNS_rr_base record in m_pAnswers) { if (record.RecordType == QTYPE.HINFO) { retVal.Add((DNS_rr_HINFO) record); } } return retVal.ToArray(); } /// <summary> /// Gets MX records.(MX records are sorted by preference, lower array element is prefered) /// </summary> /// <returns></returns> public DNS_rr_MX[] GetMXRecords() { List<DNS_rr_MX> mx = new List<DNS_rr_MX>(); foreach (DNS_rr_base record in m_pAnswers) { if (record.RecordType == QTYPE.MX) { mx.Add((DNS_rr_MX) record); } } // Sort MX records by preference. DNS_rr_MX[] retVal = mx.ToArray(); Array.Sort(retVal); return retVal; } /// <summary> /// Gets text records. /// </summary> /// <returns></returns> public DNS_rr_TXT[] GetTXTRecords() { List<DNS_rr_TXT> retVal = new List<DNS_rr_TXT>(); foreach (DNS_rr_base record in m_pAnswers) { if (record.RecordType == QTYPE.TXT) { retVal.Add((DNS_rr_TXT) record); } } return retVal.ToArray(); } /// <summary> /// Gets IPv6 host addess records. /// </summary> /// <returns></returns> public DNS_rr_A[] GetAAAARecords() { List<DNS_rr_A> retVal = new List<DNS_rr_A>(); foreach (DNS_rr_base record in m_pAnswers) { if (record.RecordType == QTYPE.AAAA) { retVal.Add((DNS_rr_A) record); } } return retVal.ToArray(); } /// <summary> /// Gets SRV resource records. /// </summary> /// <returns></returns> public DNS_rr_SRV[] GetSRVRecords() { List<DNS_rr_SRV> retVal = new List<DNS_rr_SRV>(); foreach (DNS_rr_base record in m_pAnswers) { if (record.RecordType == QTYPE.SRV) { retVal.Add((DNS_rr_SRV) record); } } return retVal.ToArray(); } /// <summary> /// Gets NAPTR resource records. /// </summary> /// <returns></returns> public DNS_rr_NAPTR[] GetNAPTRRecords() { List<DNS_rr_NAPTR> retVal = new List<DNS_rr_NAPTR>(); foreach (DNS_rr_base record in m_pAnswers) { if (record.RecordType == QTYPE.NAPTR) { retVal.Add((DNS_rr_NAPTR) record); } } return retVal.ToArray(); } #endregion #region Utility methods /// <summary> /// Filters out specified type of records from answer. /// </summary> /// <param name="answers"></param> /// <param name="type"></param> /// <returns></returns> private List<DNS_rr_base> FilterRecordsX(List<DNS_rr_base> answers, QTYPE type) { List<DNS_rr_base> retVal = new List<DNS_rr_base>(); foreach (DNS_rr_base record in answers) { if (record.RecordType == type) { retVal.Add(record); } } return retVal; } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/_Obsolete/Log_EventArgs.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net { /// <summary> /// Provides data for the SessionLog event. /// </summary> public class Log_EventArgs { #region Members private readonly bool m_FirstLogPart = true; private readonly bool m_LastLogPart; private readonly SocketLogger m_pLoggger; #endregion #region Properties /// <summary> /// Gets log text. /// </summary> public string LogText { get { return SocketLogger.LogEntriesToString(m_pLoggger, m_FirstLogPart, m_LastLogPart); } } /// <summary> /// Gets logger. /// </summary> public SocketLogger Logger { get { return m_pLoggger; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="logger">Socket logger.</param> /// <param name="firstLogPart">Specifies if first log part of multipart log.</param> /// <param name="lastLogPart">Specifies if last log part (logging ended).</param> public Log_EventArgs(SocketLogger logger, bool firstLogPart, bool lastLogPart) { m_pLoggger = logger; m_FirstLogPart = firstLogPart; m_LastLogPart = lastLogPart; } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/SMTP/Relay/Relay_SmartHost.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.SMTP.Relay { #region usings using System; #endregion /// <summary> /// This class holds smart host settings. /// </summary> public class Relay_SmartHost { #region Members private readonly string m_Host = ""; private readonly string m_Password; private readonly int m_Port = 25; private readonly SslMode m_SslMode = SslMode.None; private readonly string m_UserName; #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="host">Smart host name or IP address.</param> /// <param name="port">Smart host port.</param> /// <exception cref="ArgumentNullException">Is raised when <b>host</b> is null.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> public Relay_SmartHost(string host, int port) : this(host, port, SslMode.None, null, null) {} /// <summary> /// Default constructor. /// </summary> /// <param name="host">Smart host name or IP address.</param> /// <param name="port">Smart host port.</param> /// <param name="sslMode">Smart host SSL mode.</param> /// <param name="userName">Smart host user name.</param> /// <param name="password">Smart host password.</param> /// <exception cref="ArgumentNullException">Is raised when <b>host</b> is null.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> public Relay_SmartHost(string host, int port, SslMode sslMode, string userName, string password) { if (host == null) { throw new ArgumentNullException("host"); } if (host == "") { throw new ArgumentException("Argument 'host' value must be specified."); } if (port < 1) { throw new ArgumentException("Argument 'port' value is invalid."); } m_Host = host; m_Port = port; m_SslMode = sslMode; m_UserName = userName; m_Password = <PASSWORD>; } #endregion #region Properties /// <summary> /// Gets smart host name or IP address. /// </summary> public string Host { get { return m_Host; } } /// <summary> /// Gets smart host password. /// </summary> public string Password { get { return m_Password; } } /// <summary> /// Gets smart host port. /// </summary> public int Port { get { return m_Port; } } /// <summary> /// Gets smart host SSL mode. /// </summary> public SslMode SslMode { get { return m_SslMode; } } /// <summary> /// Gets smart host user name. Value null means no authentication used. /// </summary> public string UserName { get { return m_UserName; } } #endregion #region Methods /// <summary> /// Compares the current instance with another object of the same type. /// </summary> /// <param name="obj">An object to compare with this instance.</param> /// <returns>Returns true if two objects are equal.</returns> public override bool Equals(object obj) { if (obj == null) { return false; } if (!(obj is Relay_SmartHost)) { return false; } Relay_SmartHost smartHost = (Relay_SmartHost) obj; if (m_Host != smartHost.Host) { return false; } else if (m_Port != smartHost.Port) { return false; } else if (m_SslMode != smartHost.SslMode) { return false; } else if (m_UserName != smartHost.UserName) { return false; } else if (m_Password != smartHost.Password) { return false; } return true; } /// <summary> /// Returns the hash code. /// </summary> /// <returns>Returns the hash code.</returns> public override int GetHashCode() { return base.GetHashCode(); } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/SMTP/Relay/Relay_Session.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.SMTP.Relay { #region usings using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Security.Principal; using Client; using Dns.Client; using IO; using Log; using TCP; #endregion /// <summary> /// This class implements SMTP relay server session. /// </summary> public class Relay_Session : TCP_Session { #region Members private readonly Relay_Mode m_RelayMode = Relay_Mode.Dns; private readonly DateTime m_SessionCreateTime; private readonly string m_SessionID = ""; private bool m_IsDisposed; private Relay_Target m_pActiveTarget; private IPBindInfo m_pLocalBindInfo; private Relay_QueueItem m_pRelayItem; private Relay_Server m_pServer; private Relay_SmartHost[] m_pSmartHosts; private SMTP_Client m_pSmtpClient; private List<Relay_Target> m_pTargets; #endregion #region Constructor /// <summary> /// Dns relay session constructor. /// </summary> /// <param name="server">Owner relay server.</param> /// <param name="localBindInfo">Local bind info.</param> /// <param name="realyItem">Relay item.</param> /// <exception cref="ArgumentNullException">Is raised when <b>server</b>,<b>localBindInfo</b> or <b>realyItem</b> is null.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> internal Relay_Session(Relay_Server server, IPBindInfo localBindInfo, Relay_QueueItem realyItem) { if (server == null) { throw new ArgumentNullException("server"); } if (localBindInfo == null) { throw new ArgumentNullException("localBindInfo"); } if (realyItem == null) { throw new ArgumentNullException("realyItem"); } m_pServer = server; m_pLocalBindInfo = localBindInfo; m_pRelayItem = realyItem; m_SessionID = Guid.NewGuid().ToString(); m_SessionCreateTime = DateTime.Now; m_pTargets = new List<Relay_Target>(); } /// <summary> /// Smart host relay session constructor. /// </summary> /// <param name="server">Owner relay server.</param> /// <param name="localBindInfo">Local bind info.</param> /// <param name="realyItem">Relay item.</param> /// <param name="smartHosts">Smart hosts.</param> /// <exception cref="ArgumentNullException">Is raised when <b>server</b>,<b>localBindInfo</b>,<b>realyItem</b> or <b>smartHosts</b>is null.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> internal Relay_Session(Relay_Server server, IPBindInfo localBindInfo, Relay_QueueItem realyItem, Relay_SmartHost[] smartHosts) { if (server == null) { throw new ArgumentNullException("server"); } if (localBindInfo == null) { throw new ArgumentNullException("localBindInfo"); } if (realyItem == null) { throw new ArgumentNullException("realyItem"); } if (smartHosts == null) { throw new ArgumentNullException("smartHosts"); } m_pServer = server; m_pLocalBindInfo = localBindInfo; m_pRelayItem = realyItem; m_pSmartHosts = smartHosts; m_RelayMode = Relay_Mode.SmartHost; m_SessionID = Guid.NewGuid().ToString(); m_SessionCreateTime = DateTime.Now; m_pTargets = new List<Relay_Target>(); } #endregion #region Properties /// <summary> /// Gets session authenticated user identity, returns null if not authenticated. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when this property is accessed and relay session is not connected.</exception> public override GenericIdentity AuthenticatedUserIdentity { get { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (!m_pSmtpClient.IsConnected) { throw new InvalidOperationException("You must connect first."); } return m_pSmtpClient.AuthenticatedUserIdentity; } } /// <summary> /// Gets the time when session was connected. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> public override DateTime ConnectTime { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_pSmtpClient.ConnectTime; } } /// <summary> /// Gets how many seconds has left before timout is triggered. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> public int ExpectedTimeout { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return (int) (m_pServer.SessionIdleTimeout - ((DateTime.Now.Ticks - TcpStream.LastActivity.Ticks)/10000)); } } /// <summary> /// Gets from address. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> public string From { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_pRelayItem.From; } } /// <summary> /// Gets session ID. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> public override string ID { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_SessionID; } } /// <summary> /// Gets if session is connected. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> public override bool IsConnected { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_pSmtpClient.IsConnected; } } /// <summary> /// Gets if this object is disposed. /// </summary> public bool IsDisposed { get { return m_IsDisposed; } } /// <summary> /// Gets the last time when data was sent or received. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> public override DateTime LastActivity { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_pSmtpClient.LastActivity; } } /// <summary> /// Gets session local IP end point. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> public override IPEndPoint LocalEndPoint { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_pSmtpClient.LocalEndPoint; } } /// <summary> /// Gets message ID which is being relayed now. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> public string MessageID { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_pRelayItem.MessageID; } } /// <summary> /// Gets message what is being relayed now. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> public Stream MessageStream { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_pRelayItem.MessageStream; } } /// <summary> /// Gets relay queue which session it is. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> public Relay_Queue Queue { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_pRelayItem.Queue; } } /// <summary> /// Gets user data what was procided to Relay_Queue.QueueMessage method. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> public object QueueTag { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_pRelayItem.Tag; } } /// <summary> /// Gets session remote IP end point. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> public override IPEndPoint RemoteEndPoint { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_pSmtpClient.RemoteEndPoint; } } /// <summary> /// Gets time when relay session created. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> public DateTime SessionCreateTime { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_SessionCreateTime; } } /// <summary> /// Gets TCP stream which must be used to send/receive data through this session. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> public override SmartStream TcpStream { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_pSmtpClient.TcpStream; } } /// <summary> /// Gets target recipient. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> public string To { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_pRelayItem.To; } } #endregion #region Methods /// <summary> /// Completes relay session and does clean up. This method is thread-safe. /// </summary> public override void Dispose() { Dispose(new ObjectDisposedException(GetType().Name)); } /// <summary> /// Completes relay session and does clean up. This method is thread-safe. /// </summary> /// <param name="exception">Exception happened or null if relay completed successfully.</param> public void Dispose(Exception exception) { try { lock (this) { if (m_IsDisposed) { return; } try { m_pServer.OnSessionCompleted(this, exception); } catch {} m_pServer.Sessions.Remove(this); m_IsDisposed = true; m_pLocalBindInfo = null; m_pRelayItem = null; m_pSmartHosts = null; if (m_pSmtpClient != null) { m_pSmtpClient.Dispose(); m_pSmtpClient = null; } m_pTargets = null; if (m_pActiveTarget != null) { m_pServer.RemoveIpUsage(m_pActiveTarget.Target.Address); m_pActiveTarget = null; } m_pServer = null; } } catch (Exception x) { if (m_pServer != null) { m_pServer.OnError(x); } } } /// <summary> /// Closes relay connection. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> public override void Disconnect() { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (!IsConnected) { return; } m_pSmtpClient.Disconnect(); } /// <summary> /// Closes relay connection. /// </summary> /// <param name="text">Text to send to the connected host.</param> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> public void Disconnect(string text) { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (!IsConnected) { return; } m_pSmtpClient.TcpStream.WriteLine(text); Disconnect(); } #endregion #region Internal methods /// <summary> /// Start processing relay message. /// </summary> /// <param name="state">User data.</param> internal void Start(object state) { try { m_pSmtpClient = new SMTP_Client(); m_pSmtpClient.LocalHostName = m_pLocalBindInfo.HostName; if (m_pServer.Logger != null) { m_pSmtpClient.Logger = new Logger(); m_pSmtpClient.Logger.WriteLog += SmtpClient_WriteLog; } LogText("Starting to relay message '" + m_pRelayItem.MessageID + "' from '" + m_pRelayItem.From + "' to '" + m_pRelayItem.To + "'."); // Get all possible target hosts for active recipient. List<string> targetHosts = new List<string>(); if (m_RelayMode == Relay_Mode.Dns) { foreach (string host in SMTP_Client.GetDomainHosts(m_pRelayItem.To)) { try { foreach (IPAddress ip in Dns_Client.Resolve(host)) { m_pTargets.Add(new Relay_Target(new IPEndPoint(ip, 25))); } } catch { // Failed to resolve host name. LogText("Failed to resolve host '" + host + "' name."); } } } else if (m_RelayMode == Relay_Mode.SmartHost) { foreach (Relay_SmartHost smartHost in m_pSmartHosts) { try { m_pTargets.Add( new Relay_Target( new IPEndPoint(Dns_Client.Resolve(smartHost.Host)[0], smartHost.Port), smartHost.SslMode, smartHost.UserName, smartHost.Password)); } catch { // Failed to resolve smart host name. LogText("Failed to resolve smart host '" + smartHost.Host + "' name."); } } } BeginConnect(); } catch (Exception x) { Dispose(x); } } #endregion #region Utility methods /// <summary> /// Thsi method is called when SMTP client has new log entry available. /// </summary> /// <param name="sender">Sender.</param> /// <param name="e">Event data.</param> private void SmtpClient_WriteLog(object sender, WriteLogEventArgs e) { try { if (m_pServer.Logger == null) {} else if (e.LogEntry.EntryType == LogEntryType.Read) { m_pServer.Logger.AddRead(m_SessionID, e.LogEntry.UserIdentity, e.LogEntry.Size, e.LogEntry.Text, e.LogEntry.LocalEndPoint, e.LogEntry.RemoteEndPoint); } else if (e.LogEntry.EntryType == LogEntryType.Text) { m_pServer.Logger.AddText(m_SessionID, e.LogEntry.UserIdentity, e.LogEntry.Text, e.LogEntry.LocalEndPoint, e.LogEntry.RemoteEndPoint); } else if (e.LogEntry.EntryType == LogEntryType.Write) { m_pServer.Logger.AddWrite(m_SessionID, e.LogEntry.UserIdentity, e.LogEntry.Size, e.LogEntry.Text, e.LogEntry.LocalEndPoint, e.LogEntry.RemoteEndPoint); } } catch {} } /// <summary> /// Starts connecting to best target. /// </summary> private void BeginConnect() { // No tagets, abort relay. if (m_pTargets.Count == 0) { LogText("No relay target(s) for '" + m_pRelayItem.To + "', aborting."); Dispose(new Exception("No relay target(s) for '" + m_pRelayItem.To + "', aborting.")); return; } // If maximum connections to specified target exceeded and there are more targets, try to get limit free target. if (m_pServer.MaxConnectionsPerIP > 0) { // For DNS or load-balnced smart host relay, search free target if any. if (m_pServer.RelayMode == Relay_Mode.Dns || m_pServer.SmartHostsBalanceMode == BalanceMode.LoadBalance) { foreach (Relay_Target t in m_pTargets) { // We found free target, stop searching. if (m_pServer.TryAddIpUsage(m_pTargets[0].Target.Address)) { m_pActiveTarget = t; m_pTargets.Remove(t); break; } } } // Smart host fail-over mode, just check if it's free. else { // Smart host IP limit not reached. if (m_pServer.TryAddIpUsage(m_pTargets[0].Target.Address)) { m_pActiveTarget = m_pTargets[0]; m_pTargets.RemoveAt(0); } } } // Just get first target. else { m_pActiveTarget = m_pTargets[0]; m_pTargets.RemoveAt(0); } // If all targets has exeeded maximum allowed connection per IP address, end relay session, // next relay cycle will try to relay again. if (m_pActiveTarget == null) { LogText("All targets has exeeded maximum allowed connection per IP address, skip relay."); Dispose( new Exception( "All targets has exeeded maximum allowed connection per IP address, skip relay.")); return; } m_pSmtpClient.BeginConnect(new IPEndPoint(m_pLocalBindInfo.IP, 0), m_pActiveTarget.Target, false, ConnectCallback, null); } /// <summary> /// This method is called when asynchronous Connect method completes. /// </summary> /// <param name="ar">An IAsyncResult that stores state information and any user defined data for this asynchronous operation.</param> private void ConnectCallback(IAsyncResult ar) { try { m_pSmtpClient.EndConnect(ar); // Start TLS requested, start switching to SSL. if (m_pActiveTarget.SslMode == SslMode.TLS) { m_pSmtpClient.BeginStartTLS(StartTlsCallback, null); } // Authentication requested, start authenticating. else if (!string.IsNullOrEmpty(m_pActiveTarget.UserName)) { m_pSmtpClient.BeginAuthenticate(m_pActiveTarget.UserName, m_pActiveTarget.Password, AuthenticateCallback, null); } else { long messageSize = -1; try { messageSize = m_pRelayItem.MessageStream.Length - m_pRelayItem.MessageStream.Position; } catch { // Stream doesn't support seeking. } m_pSmtpClient.BeginMailFrom(From, messageSize, MailFromCallback, null); } } catch (Exception x) { try { // Release IP usage. m_pServer.RemoveIpUsage(m_pActiveTarget.Target.Address); m_pActiveTarget = null; // Connect failed, if there are more target IPs, try next one. if (!IsDisposed && !IsConnected && m_pTargets.Count > 0) { BeginConnect(); } else { Dispose(x); } } catch (Exception xx) { Dispose(xx); } } } /// <summary> /// This method is called when asynchronous <b>StartTLS</b> method completes. /// </summary> /// <param name="ar">An IAsyncResult that stores state information and any user defined data for this asynchronous operation.</param> private void StartTlsCallback(IAsyncResult ar) { try { m_pSmtpClient.EndStartTLS(ar); // Authentication requested, start authenticating. if (!string.IsNullOrEmpty(m_pActiveTarget.UserName)) { m_pSmtpClient.BeginAuthenticate(m_pActiveTarget.UserName, m_pActiveTarget.Password, AuthenticateCallback, null); } else { long messageSize = -1; try { messageSize = m_pRelayItem.MessageStream.Length - m_pRelayItem.MessageStream.Position; } catch { // Stream doesn't support seeking. } m_pSmtpClient.BeginMailFrom(From, messageSize, MailFromCallback, null); } } catch (Exception x) { Dispose(x); } } /// <summary> /// This method is called when asynchronous <b>Authenticate</b> method completes. /// </summary> /// <param name="ar">An IAsyncResult that stores state information and any user defined data for this asynchronous operation.</param> private void AuthenticateCallback(IAsyncResult ar) { try { m_pSmtpClient.EndAuthenticate(ar); long messageSize = -1; try { messageSize = m_pRelayItem.MessageStream.Length - m_pRelayItem.MessageStream.Position; } catch { // Stream doesn't support seeking. } m_pSmtpClient.BeginMailFrom(From, messageSize, MailFromCallback, null); } catch (Exception x) { Dispose(x); } } /// <summary> /// This method is called when asynchronous MailFrom method completes. /// </summary> /// <param name="ar">An IAsyncResult that stores state information and any user defined data for this asynchronous operation.</param> private void MailFromCallback(IAsyncResult ar) { try { m_pSmtpClient.EndMailFrom(ar); m_pSmtpClient.BeginRcptTo(To, RcptToCallback, null); } catch (Exception x) { Dispose(x); } } /// <summary> /// This method is called when asynchronous RcptTo method completes. /// </summary> /// <param name="ar">An IAsyncResult that stores state information and any user defined data for this asynchronous operation.</param> private void RcptToCallback(IAsyncResult ar) { try { m_pSmtpClient.EndRcptTo(ar); m_pSmtpClient.BeginSendMessage(m_pRelayItem.MessageStream, SendMessageCallback, null); } catch (Exception x) { Dispose(x); } } /// <summary> /// This method is called when asynchronous SendMessage method completes. /// </summary> /// <param name="ar">An IAsyncResult that stores state information and any user defined data for this asynchronous operation.</param> private void SendMessageCallback(IAsyncResult ar) { try { m_pSmtpClient.EndSendMessage(ar); // Message relayed successfully. Dispose(null); } catch (Exception x) { Dispose(x); } } /// <summary> /// Logs specified text if logging enabled. /// </summary> /// <param name="text">Text to log.</param> private void LogText(string text) { if (m_pServer.Logger != null) { GenericIdentity identity = null; try { identity = AuthenticatedUserIdentity; } catch {} IPEndPoint localEP = null; IPEndPoint remoteEP = null; try { localEP = m_pSmtpClient.LocalEndPoint; remoteEP = m_pSmtpClient.RemoteEndPoint; } catch {} m_pServer.Logger.AddText(m_SessionID, identity, text, localEP, remoteEP); } } #endregion #region Nested type: Relay_Target /// <summary> /// This class holds relay target information. /// </summary> private class Relay_Target { #region Members private readonly string m_Password; private readonly IPEndPoint m_pTarget; private readonly SslMode m_SslMode = SslMode.None; private readonly string m_UserName; #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="target">Target host IP end point.</param> public Relay_Target(IPEndPoint target) { m_pTarget = target; } /// <summary> /// Default constructor. /// </summary> /// <param name="target">Target host IP end point.</param> /// <param name="sslMode">SSL mode.</param> /// <param name="userName">Target host user name.</param> /// <param name="password">Target host password.</param> public Relay_Target(IPEndPoint target, SslMode sslMode, string userName, string password) { m_pTarget = target; m_SslMode = sslMode; m_UserName = userName; m_Password = <PASSWORD>; } #endregion #region Properties /// <summary> /// Gets target server password. /// </summary> public string Password { get { return m_Password; } } /// <summary> /// Gets target SSL mode. /// </summary> public SslMode SslMode { get { return m_SslMode; } } /// <summary> /// Gets specified target IP end point. /// </summary> public IPEndPoint Target { get { return m_pTarget; } } /// <summary> /// Gets target server user name. /// </summary> public string UserName { get { return m_UserName; } } #endregion } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/AUTH/AUTH_SASL_ServerMechanism_Plain.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.AUTH { #region usings using System; #endregion /// <summary> /// Implements "PLAIN" authenticaiton. Defined in RFC 4616. /// </summary> public class AUTH_SASL_ServerMechanism_Plain : AUTH_SASL_ServerMechanism { #region Events /// <summary> /// Is called when authentication mechanism needs to authenticate specified user. /// </summary> public event EventHandler<AUTH_e_Authenticate> Authenticate = null; #endregion #region Members private readonly bool m_RequireSSL; private bool m_IsAuthenticated; private bool m_IsCompleted; private string m_UserName = ""; #endregion #region Properties /// <summary> /// Gets if the authentication exchange has completed. /// </summary> public override bool IsCompleted { get { return m_IsCompleted; } } /// <summary> /// Gets if user has authenticated sucessfully. /// </summary> public override bool IsAuthenticated { get { return m_IsAuthenticated; } } /// <summary> /// Returns always "PLAIN". /// </summary> public override string Name { get { return "PLAIN"; } } /// <summary> /// Gets if specified SASL mechanism is available only to SSL connection. /// </summary> public override bool RequireSSL { get { return m_RequireSSL; } } /// <summary> /// Gets user login name. /// </summary> public override string UserName { get { return m_UserName; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="requireSSL">Specifies if this mechanism is available to SSL connections only.</param> public AUTH_SASL_ServerMechanism_Plain(bool requireSSL) { m_RequireSSL = requireSSL; } #endregion #region Methods /// <summary> /// Continues authentication process. /// </summary> /// <param name="clientResponse">Client sent SASL response.</param> /// <returns>Retunrns challange response what must be sent to client or null if authentication has completed.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>clientResponse</b> is null reference.</exception> public override string Continue(string clientResponse) { if (clientResponse == null) { throw new ArgumentNullException("clientResponse"); } /* RFC 4616.2. PLAIN SASL Mechanism. The mechanism consists of a single message, a string of [UTF-8] encoded [Unicode] characters, from the client to the server. The client presents the authorization identity (identity to act as), followed by a NUL (U+0000) character, followed by the authentication identity (identity whose password will be used), followed by a NUL (U+0000) character, followed by the clear-text password. As with other SASL mechanisms, the client does not provide an authorization identity when it wishes the server to derive an identity from the credentials and use that as the authorization identity. message = [authzid] UTF8NUL authcid UTF8NUL passwd Example: C: a002 AUTHENTICATE "PLAIN" S: + "" C: {21} C: <NUL>tim<NUL>tanstaaftanstaaf S: a002 OK "Authenticated" */ if (clientResponse == string.Empty) { return ""; } // Parse response else { string[] authzid_authcid_passwd = clientResponse.Split('\0'); if (authzid_authcid_passwd.Length == 3 && !string.IsNullOrEmpty(authzid_authcid_passwd[1])) { m_UserName = authzid_authcid_passwd[1]; AUTH_e_Authenticate result = OnAuthenticate(authzid_authcid_passwd[0], authzid_authcid_passwd[1], authzid_authcid_passwd[2]); m_IsAuthenticated = result.IsAuthenticated; } m_IsCompleted = true; } return null; } #endregion #region Utility methods /// <summary> /// Raises <b>Authenticate</b> event. /// </summary> /// <param name="authorizationID">Authorization ID.</param> /// <param name="userName">User name.</param> /// <param name="password"><PASSWORD>.</param> /// <returns>Returns authentication result.</returns> private AUTH_e_Authenticate OnAuthenticate(string authorizationID, string userName, string password) { AUTH_e_Authenticate retVal = new AUTH_e_Authenticate(authorizationID, userName, password); if (Authenticate != null) { Authenticate(this, retVal); } return retVal; } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Autoreply/ApiRequest.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System.Collections.Generic; using ASC.Core.Tenants; using ASC.Core.Users; using ASC.Mail.Autoreply.ParameterResolvers; namespace ASC.Mail.Autoreply { internal class ApiRequest { public string Method { get; set; } public string Url { get; set; } public List<RequestParameter> Parameters { get; set; } public Tenant Tenant { get; set; } public UserInfo User { get; set; } public List<RequestFileInfo> FilesToPost { get; set; } public ApiRequest(string url) { if (!string.IsNullOrEmpty(url)) { Url = url.Trim('/'); } } public override string ToString() { return string.Format("t:{0}; u:{1}; {2} {3}", Tenant.TenantId, User.ID, Method, Url); } } internal class RequestParameter { public string Name { get; private set; } public object Value { get; set; } public IParameterResolver ValueResolver { get; private set; } public RequestParameter(string name, object value) { Name = name; Value = value; } public RequestParameter(string name, IParameterResolver valueResolver) { Name = name; ValueResolver = valueResolver; } } internal class RequestFileInfo { public byte[] Body { get; set; } public string Name { get; set; } public string ContentType { get; set; } } }<file_sep>/module/ASC.Thrdparty/ASC.Thrdparty/Twitter/TwitterConsumer.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ //----------------------------------------------------------------------- // <copyright file="TwitterConsumer.cs" company="Outercurve Foundation"> // Copyright (c) Outercurve Foundation. All rights reserved. // </copyright> //----------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Globalization; using System.Net; using DotNetOpenAuth.Messaging; using DotNetOpenAuth.OAuth; using DotNetOpenAuth.OAuth.ChannelElements; using Newtonsoft.Json.Linq; namespace ASC.Thrdparty.Twitter { /// <summary> /// A consumer capable of communicating with Twitter. /// </summary> public static class TwitterConsumer { /// <summary> /// The description of Twitter's OAuth protocol URIs for use with their "Sign in with Twitter" feature. /// </summary> public static readonly ServiceProviderDescription SignInWithTwitterServiceDescription = new ServiceProviderDescription { RequestTokenEndpoint = new MessageReceivingEndpoint("https://twitter.com/oauth/request_token", HttpDeliveryMethods.GetRequest | HttpDeliveryMethods.AuthorizationHeaderRequest), UserAuthorizationEndpoint = new MessageReceivingEndpoint("https://twitter.com/oauth/authenticate", HttpDeliveryMethods.GetRequest | HttpDeliveryMethods.AuthorizationHeaderRequest), AccessTokenEndpoint = new MessageReceivingEndpoint("https://twitter.com/oauth/access_token", HttpDeliveryMethods.GetRequest | HttpDeliveryMethods.AuthorizationHeaderRequest), TamperProtectionElements = new ITamperProtectionChannelBindingElement[] { new HmacSha1SigningBindingElement() }, }; /// <summary> /// The URI to get a user's favorites. /// </summary> private static readonly MessageReceivingEndpoint GetFavoritesEndpoint = new MessageReceivingEndpoint("https://twitter.com/favorites.json", HttpDeliveryMethods.GetRequest); private static readonly MessageReceivingEndpoint GetHomeTimeLineEndpoint = new MessageReceivingEndpoint("https://api.twitter.com/1.1/statuses/home_timeline.json", HttpDeliveryMethods.GetRequest | HttpDeliveryMethods.AuthorizationHeaderRequest); private static readonly MessageReceivingEndpoint GetUserTimeLineEndPoint = new MessageReceivingEndpoint("https://api.twitter.com/1.1/statuses/user_timeline.json", HttpDeliveryMethods.GetRequest | HttpDeliveryMethods.AuthorizationHeaderRequest); public static JArray GetUserTimeLine(WebConsumer consumer, String accessToken, int userId, String screenName, bool includeRetweets, int count) { var parameters = new Dictionary<String, string> { { "count", count.ToString(CultureInfo.InvariantCulture) }, { "include_rts", includeRetweets.ToString() } }; if (!String.IsNullOrEmpty(screenName)) parameters.Add("screen_name", screenName); if (userId > 0) parameters.Add("user_id", userId.ToString(CultureInfo.InvariantCulture)); var request = consumer.PrepareAuthorizedRequest(GetUserTimeLineEndPoint, accessToken, parameters); var response = consumer.Channel.WebRequestHandler.GetResponse(request); using (var responseReader = response.GetResponseReader()) { var result = responseReader.ReadToEnd(); return JArray.Parse(result); } } public static JArray GetHomeTimeLine(WebConsumer consumer, String accessToken, bool includeRetweets, int count) { var parameters = new Dictionary<String, string> { { "count", count.ToString(CultureInfo.InvariantCulture) }, { "include_rts", includeRetweets.ToString() } }; var request = consumer.PrepareAuthorizedRequest(GetHomeTimeLineEndpoint, accessToken, parameters); var response = consumer.Channel.WebRequestHandler.GetResponse(request); using (var responseReader = response.GetResponseReader()) { var result = responseReader.ReadToEnd(); return JArray.Parse(result); } } public static JObject GetUserInfo(WebConsumer consumer, int userid, String screenName, string accessToken) { const string baseUri = "https://api.twitter.com/1.1/users/show.json"; var uri = String.Empty; if (userid > 0 && String.IsNullOrEmpty(screenName)) uri = String.Concat(baseUri, "?user_id=", userid); if (userid == 0 && !String.IsNullOrEmpty(screenName)) uri = String.Concat(baseUri, "?screen_name=", screenName); var endpoint = new MessageReceivingEndpoint(uri, HttpDeliveryMethods.GetRequest | HttpDeliveryMethods.AuthorizationHeaderRequest); var response = consumer.PrepareAuthorizedRequestAndSend(endpoint, accessToken); using (var responseReader = response.GetResponseReader()) { var result = responseReader.ReadToEnd(); return JObject.Parse(result); } } public static JArray SearchUsers(WebConsumer consumer, String search, string accessToken) { var endpoint = new MessageReceivingEndpoint("https://api.twitter.com/1.1/users/search.json?q=" + Uri.EscapeDataString(search), HttpDeliveryMethods.GetRequest | HttpDeliveryMethods.AuthorizationHeaderRequest); var response = consumer.PrepareAuthorizedRequestAndSend(endpoint, accessToken); using (var responseReader = response.GetResponseReader()) { var result = responseReader.ReadToEnd(); return JArray.Parse(result); } } /// <summary> /// Initializes static members of the <see cref="TwitterConsumer"/> class. /// </summary> static TwitterConsumer() { // Twitter can't handle the Expect 100 Continue HTTP header. ServicePointManager.FindServicePoint(GetFavoritesEndpoint.Location).Expect100Continue = false; } } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/MIME/MIME_b.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.MIME { #region usings using System; using System.IO; using System.Text; using IO; #endregion /// <summary> /// This class is base class for MIME entity bodies. /// </summary> public abstract class MIME_b { #region Members private readonly MIME_h_ContentType m_pContentType; private MIME_Entity m_pEntity; #endregion #region Properties /// <summary> /// Gets if body has modified. /// </summary> public abstract bool IsModified { get; } /// <summary> /// Gets body owner entity. Returns null if body not bounded to any entity yet. /// </summary> public MIME_Entity Entity { get { return m_pEntity; } } /// <summary> /// Gets MIME entity body content type. /// </summary> public MIME_h_ContentType ContentType { get { return m_pContentType; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="contentType">Content type.</param> /// <exception cref="ArgumentNullException">Is raised when <b>contentType</b> is null reference.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> public MIME_b(MIME_h_ContentType contentType) { if (contentType == null) { throw new ArgumentNullException("contentType"); } m_pContentType = contentType; } #endregion #region Abstract methods /// <summary> /// Stores MIME entity body to the specified stream. /// </summary> /// <param name="stream">Stream where to store body data.</param> /// <param name="headerWordEncoder">Header 8-bit words ecnoder. Value null means that words are not encoded.</param> /// <param name="headerParmetersCharset">Charset to use to encode 8-bit header parameters. Value null means parameters not encoded.</param> /// <exception cref="ArgumentNullException">Is raised when <b>stream</b> is null reference.</exception> protected internal abstract void ToStream(Stream stream, MIME_Encoding_EncodedWord headerWordEncoder, Encoding headerParmetersCharset); #endregion #region Internal methods /// <summary> /// Sets body parent. /// </summary> /// <param name="entity">Owner entity.</param> internal void SetParent(MIME_Entity entity) { m_pEntity = entity; } #endregion /// <summary> /// Parses body from the specified stream /// </summary> /// <param name="owner">Owner MIME entity.</param> /// <param name="mediaType">MIME media type. For example: text/plain.</param> /// <param name="stream">Stream from where to read body.</param> /// <returns>Returns parsed body.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>stream</b>, <b>mediaType</b> or <b>stream</b> is null reference.</exception> /// <exception cref="ParseException">Is raised when any parsing errors.</exception> protected static MIME_b Parse(MIME_Entity owner, string mediaType, SmartStream stream) { if (owner == null) { throw new ArgumentNullException("owner"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } if (stream == null) { throw new ArgumentNullException("stream"); } throw new NotImplementedException("Body provider class does not implement required Parse method."); } } }<file_sep>/common/ASC.Data.Storage/ChunkedUploader/CommonChunkedUploadSession.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections.Generic; using System.IO; using System.Runtime.Serialization.Formatters.Binary; namespace ASC.Core.ChunkedUploader { [Serializable] public class CommonChunkedUploadSession : ICloneable { public string Id { get; set; } public DateTime Created { get; set; } public DateTime Expired { get; set; } public string Location { get; set; } public long BytesUploaded { get; set; } public long BytesTotal { get; set; } public int TenantId { get; set; } public Guid UserId { get; set; } public bool UseChunks { get; set; } public string CultureName { get; set; } public readonly Dictionary<string, object> Items = new Dictionary<string, object>(); private const string TempPathKey = "TempPath"; public string TempPath { get { return GetItemOrDefault<string>(TempPathKey); } set { Items[TempPathKey] = value; } } private const string UploadIdKey = "UploadId"; public string UploadId { get { return GetItemOrDefault<string>(UploadIdKey); } set { Items[UploadIdKey] = value; } } private const string ChunksBufferKey = "ChunksBuffer"; public string ChunksBuffer { get { return GetItemOrDefault<string>(ChunksBufferKey); } set { Items[ChunksBufferKey] = value; } } public CommonChunkedUploadSession(long bytesTotal) { Id = Guid.NewGuid().ToString("N"); Created = DateTime.UtcNow; BytesUploaded = 0; BytesTotal = bytesTotal; UseChunks = true; } public T GetItemOrDefault<T>(string key) { return Items.ContainsKey(key) && Items[key] is T ? (T)Items[key] : default(T); } public Stream Serialize() { var stream = new MemoryStream(); new BinaryFormatter().Serialize(stream, this); return stream; } public static CommonChunkedUploadSession Deserialize(Stream stream) { return (CommonChunkedUploadSession)new BinaryFormatter().Deserialize(stream); } public virtual object Clone() { return (CommonChunkedUploadSession) MemberwiseClone(); } } } <file_sep>/common/ASC.Core.Common/Core/AzRecord.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using ASC.Common.Security; using ASC.Common.Security.Authorizing; using System; namespace ASC.Core { [Serializable] public class AzRecord { public Guid SubjectId { get; set; } public Guid ActionId { get; set; } public string ObjectId { get; set; } public AceType Reaction { get; set; } public int Tenant { get; set; } public AzRecord() { } public AzRecord(Guid subjectId, Guid actionId, AceType reaction) : this(subjectId, actionId, reaction, default(string)) { } public AzRecord(Guid subjectId, Guid actionId, AceType reaction, ISecurityObjectId objectId) : this(subjectId, actionId, reaction, AzObjectIdHelper.GetFullObjectId(objectId)) { } internal AzRecord(Guid subjectId, Guid actionId, AceType reaction, string objectId) { SubjectId = subjectId; ActionId = actionId; Reaction = reaction; ObjectId = objectId; } public override bool Equals(object obj) { var r = obj as AzRecord; return r != null && r.Tenant == Tenant && r.SubjectId == SubjectId && r.ActionId == ActionId && r.ObjectId == ObjectId && r.Reaction == Reaction; } public override int GetHashCode() { return Tenant.GetHashCode() ^ SubjectId.GetHashCode() ^ ActionId.GetHashCode() ^ (ObjectId ?? string.Empty).GetHashCode() ^ Reaction.GetHashCode(); } } } <file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/IMAP/Server/Folder_EventArgs.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.IMAP.Server { /// <summary> /// Provides data for IMAP events. /// </summary> public class Mailbox_EventArgs { #region Members private readonly string m_Folder = ""; private readonly string m_NewFolder = ""; #endregion #region Properties /// <summary> /// Gets folder. /// </summary> public string Folder { get { return m_Folder; } } /// <summary> /// Gets new folder name, this is available for rename only. /// </summary> public string NewFolder { get { return m_NewFolder; } } /// <summary> /// Gets or sets custom error text, which is returned to client. /// </summary> public string ErrorText { get; set; } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="folder"></param> public Mailbox_EventArgs(string folder) { m_Folder = folder; } /// <summary> /// Folder rename constructor. /// </summary> /// <param name="folder"></param> /// <param name="newFolder"></param> public Mailbox_EventArgs(string folder, string newFolder) { m_Folder = folder; m_NewFolder = newFolder; } #endregion } }<file_sep>/module/ASC.Socket.IO/app/controllers/chat.js module.exports = (chat) => { const router = require('express').Router(); router .post("/send", (req, res) => { chat.send(req.body); res.end(); }) .post("/sendInvite", (req, res) => { chat.sendInvite(req.body); res.end(); }) .post("/setState", (req, res) => { chat.setState(req.body); res.end(); }) .post("/sendOfflineMessages", (req, res) => { chat.sendOfflineMessages(req.body); res.end(); }); return router; }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/RTP/RTCP_Packet_SDES.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.RTP { #region usings using System; using System.Collections.Generic; #endregion /// <summary> /// This class represents SDES: Source Description RTCP Packet. /// </summary> public class RTCP_Packet_SDES : RTCP_Packet { #region Members private readonly List<RTCP_Packet_SDES_Chunk> m_pChunks; private int m_Version = 2; #endregion #region Properties /// <summary> /// Gets RTCP version. /// </summary> public override int Version { get { return m_Version; } } /// <summary> /// Gets RTCP packet type. /// </summary> public override int Type { get { return RTCP_PacketType.SDES; } } /// <summary> /// Gets session description(SDES) chunks. /// </summary> public List<RTCP_Packet_SDES_Chunk> Chunks { get { return m_pChunks; } } /// <summary> /// Gets number of bytes needed for this packet. /// </summary> public override int Size { get { int size = 4; foreach (RTCP_Packet_SDES_Chunk chunk in m_pChunks) { size += chunk.Size; } return size; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> internal RTCP_Packet_SDES() { m_pChunks = new List<RTCP_Packet_SDES_Chunk>(); } #endregion #region Methods /// <summary> /// Stores SDES packet to the specified buffer. /// </summary> /// <param name="buffer">Buffer where to store SDES packet.</param> /// <param name="offset">Offset in buffer.</param> public override void ToByte(byte[] buffer, ref int offset) { /* RFC 3550 6.5 SDES: Source Description RTCP Packet. 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ header |V=2|P| SC | PT=SDES=202 | length | +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ chunk | SSRC/CSRC_1 | 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | SDES items | | ... | +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ chunk | SSRC/CSRC_2 | 2 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | SDES items | | ... | +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ */ // V=2 P SC buffer[offset++] = (byte) (2 << 6 | 0 << 5 | m_pChunks.Count & 0x1F); // PT=SDES=202 buffer[offset++] = 202; // length int lengthOffset = offset; buffer[offset++] = 0; // We fill it at last, when length is known. buffer[offset++] = 0; // We fill it at last, when length is known. int chunksStartOffset = offset; // Add chunks. foreach (RTCP_Packet_SDES_Chunk chunk in m_pChunks) { chunk.ToByte(buffer, ref offset); } // NOTE: Size in 32-bit boundary, header not included. int length = (offset - chunksStartOffset)/4; // length buffer[lengthOffset] = (byte) ((length >> 8) & 0xFF); buffer[lengthOffset + 1] = (byte) ((length) & 0xFF); } #endregion #region Overrides /// <summary> /// Parses Source Description(SDES) packet from data buffer. /// </summary> /// <param name="buffer">Buffer what contains SDES packet.</param> /// <param name="offset">Offset in buffer.</param> protected override void ParseInternal(byte[] buffer, ref int offset) { /* RFC 3550 6.5 SDES: Source Description RTCP Packet. 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ header |V=2|P| SC | PT=SDES=202 | length | +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ chunk | SSRC/CSRC_1 | 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | SDES items | | ... | +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ chunk | SSRC/CSRC_2 | 2 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | SDES items | | ... | +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ */ m_Version = buffer[offset] >> 6; bool isPadded = Convert.ToBoolean((buffer[offset] >> 5) & 0x1); int sourceCount = buffer[offset++] & 0x1F; int type = buffer[offset++]; int length = buffer[offset++] << 8 | buffer[offset++]; if (isPadded) { PaddBytesCount = buffer[offset + length]; } // Read chunks for (int i = 0; i < sourceCount; i++) { RTCP_Packet_SDES_Chunk chunk = new RTCP_Packet_SDES_Chunk(); chunk.Parse(buffer, ref offset); m_pChunks.Add(chunk); } } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/ABNF/ABNF_Rule.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.ABNF { #region usings using System; using System.IO; #endregion /// <summary> /// This class represents ABNF "rule". Defined in RFC 5234 2.2. /// </summary> public class ABNF_Rule { #region Members private readonly string m_Name; private readonly ABNF_Alternation m_pElements; #endregion #region Properties /// <summary> /// Gets rule name. /// </summary> public string Name { get { return m_Name; } } /// <summary> /// Gets rule elements. /// </summary> public ABNF_Alternation Elements { get { return m_pElements; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="name">Rule name.</param> /// <param name="elements">Alternation elements.</param> /// <exception cref="ArgumentNullException">Is raised when <b>name</b> or <b>elements</b> is null reference.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> public ABNF_Rule(string name, ABNF_Alternation elements) { if (name == null) { throw new ArgumentNullException("name"); } if (name == string.Empty) { throw new ArgumentException("Argument 'name' value must be specified."); } if (!ValidateName(name)) { throw new ArgumentException( "Invalid argument 'name' value. Value must be 'rulename = ALPHA *(ALPHA / DIGIT / \"-\")'."); } if (elements == null) { throw new ArgumentNullException("elements"); } m_Name = name; m_pElements = elements; } #endregion #region Methods /// <summary> /// /// </summary> /// <param name="value"></param> /// <returns></returns> public static ABNF_Rule Parse(string value) { if (value == null) { throw new ArgumentNullException("value"); } string[] name_value = value.Split(new[] {'='}, 2); if (name_value.Length != 2) { throw new ParseException("Invalid ABNF rule '" + value + "'."); } ABNF_Rule retVal = new ABNF_Rule(name_value[0].Trim(), ABNF_Alternation.Parse(new StringReader(name_value[1]))); return retVal; } #endregion #region Utility methods /// <summary> /// Validates 'rulename' value. /// </summary> /// <param name="name">Rule name.</param> /// <returns>Returns true if rule name is valid, otherwise false.</returns> private bool ValidateName(string name) { if (name == null) { return false; } if (name == string.Empty) { return false; } // RFC 5234 4. // rulename = ALPHA *(ALPHA / DIGIT / "-") if (!char.IsLetter(name[0])) { return false; } for (int i = 1; i < name.Length; i++) { char c = name[i]; if (!(char.IsLetter(c) | char.IsDigit(c) | c == '-')) { return false; } } return true; } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/POP3/Server/POP3_Message_EventArgs.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.POP3.Server { #region usings using System.Net.Sockets; #endregion /// <summary> /// Provides data for the GetMailEvent,DeleteMessage,GetTopLines event. /// </summary> public class POP3_Message_EventArgs { #region Members private readonly int m_Lines; private readonly POP3_Message m_pMessage; private readonly POP3_Session m_pSession; private Socket m_pSocket; #endregion #region Properties /// <summary> /// Gets reference to pop3 session. /// </summary> public POP3_Session Session { get { return m_pSession; } } /// <summary> /// Gets reference to message, which to get. /// </summary> public POP3_Message Message { get { return m_pMessage; } } /// <summary> /// ID of message which to retrieve. /// </summary> public string MessageID { get { return m_pMessage.ID; } } /// <summary> /// UID of message which to retrieve. /// </summary> public string MessageUID { get { return m_pMessage.UID; } } /* /// <summary> /// Gets direct access to connected socket. /// This is meant for advanced users only. /// Just write message to this socket. /// NOTE: Message must be period handled and doesn't(MAY NOT) contain message terminator at end. /// </summary> public Socket ConnectedSocket { get{ return m_pSocket; } } */ /// <summary> /// Mail message which is delivered to user. NOTE: may be full message or top lines of message. /// </summary> public byte[] MessageData { get; set; } /// <summary> /// Number of lines to get. /// </summary> public int Lines { get { return m_Lines; } } /// <summary> /// User Name. /// </summary> public string UserName { get { return m_pSession.UserName; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="session">Reference to pop3 session.</param> /// <param name="message">Message which to get.</param> /// <param name="socket">Connected socket.</param> public POP3_Message_EventArgs(POP3_Session session, POP3_Message message, Socket socket) { m_pSession = session; m_pMessage = message; m_pSocket = socket; } /// <summary> /// TopLines constructor. /// </summary> /// <param name="session">Reference to pop3 session.</param> /// <param name="message">Message which to get.</param> /// <param name="socket">Connected socket.</param> /// <param name="nLines">Number of lines to get.</param> public POP3_Message_EventArgs(POP3_Session session, POP3_Message message, Socket socket, int nLines) { m_pSession = session; m_pMessage = message; m_pSocket = socket; m_Lines = nLines; } #endregion } }<file_sep>/web/studio/ASC.Web.Studio/Products/Community/Modules/Wiki/WikiUC/fckeditor/editor/plugins/asccut/lang/ru.js  FCKLang.AscCut = "Скрыть для предпросмотра"; FCKLang.AscCutContents = "Введите содержимое врезки";<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/SIP/Message/SIP_t_CSeq.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.SIP.Message { #region usings using System; #endregion /// <summary> /// Implements SIP "Cseq" value. Defined in RFC 3261. /// A CSeq in a request contains a single decimal sequence number and /// the request method. The method part of CSeq is case-sensitive. The CSeq header /// field serves to order transactions within a dialog, to provide a means to uniquely /// identify transactions, and to differentiate between new requests and request retransmissions. /// </summary> /// <remarks> /// <code> /// RFC 3261 Syntax: /// CSeq = 1*DIGIT LWS Method /// </code> /// </remarks> public class SIP_t_CSeq : SIP_t_Value { #region Members private string m_RequestMethod = ""; private int m_SequenceNumber = 1; #endregion #region Properties /// <summary> /// Gets or sets sequence number. /// </summary> public int SequenceNumber { get { return m_SequenceNumber; } set { if (value < 1) { throw new ArgumentException("Property SequenceNumber value must be >= 1 !"); } m_SequenceNumber = value; } } /// <summary> /// Gets or sets request method. Note: this value is case-sensitive ! /// </summary> public string RequestMethod { get { return m_RequestMethod; } set { if (string.IsNullOrEmpty(value)) { throw new ArgumentException("Property RequestMethod value can't be null or empty !"); } m_RequestMethod = value; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="value">CSeq: header field value.</param> public SIP_t_CSeq(string value) { Parse(new StringReader(value)); } /// <summary> /// Default constructor. /// </summary> /// <param name="sequenceNumber">Command sequence number.</param> /// <param name="requestMethod">Request method.</param> public SIP_t_CSeq(int sequenceNumber, string requestMethod) { m_SequenceNumber = sequenceNumber; m_RequestMethod = requestMethod; } #endregion #region Methods /// <summary> /// Parses "CSeq" from specified value. /// </summary> /// <param name="value">SIP "CSeq" value.</param> /// <exception cref="ArgumentNullException">Raised when <b>value</b> is null.</exception> /// <exception cref="SIP_ParseException">Raised when invalid SIP message.</exception> public void Parse(string value) { if (value == null) { throw new ArgumentNullException("value"); } Parse(new StringReader(value)); } /// <summary> /// Parses "CSeq" from specified reader. /// </summary> /// <param name="reader">Reader from where to parse.</param> /// <exception cref="ArgumentNullException">Raised when <b>reader</b> is null.</exception> /// <exception cref="SIP_ParseException">Raised when invalid SIP message.</exception> public override void Parse(StringReader reader) { // CSeq = 1*DIGIT LWS Method if (reader == null) { throw new ArgumentNullException("reader"); } // Get sequence number string word = reader.ReadWord(); if (word == null) { throw new SIP_ParseException("Invalid 'CSeq' value, sequence number is missing !"); } try { m_SequenceNumber = Convert.ToInt32(word); } catch { throw new SIP_ParseException("Invalid CSeq 'sequence number' value !"); } // Get request method word = reader.ReadWord(); if (word == null) { throw new SIP_ParseException("Invalid 'CSeq' value, request method is missing !"); } m_RequestMethod = word; } /// <summary> /// Converts this to valid "CSeq" value. /// </summary> /// <returns>Returns "CSeq" value.</returns> public override string ToStringValue() { return m_SequenceNumber + " " + m_RequestMethod; } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/IMAP/Server/IMAP_Message.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.IMAP.Server { #region usings using System; #endregion /// <summary> /// IMAP message info. /// </summary> public class IMAP_Message:IDisposable { #region Members private readonly string m_ID = ""; private readonly DateTime m_InternalDate = DateTime.Now; private readonly IMAP_MessageCollection m_pOwner; private readonly long m_Size; private readonly long m_UID; private IMAP_MessageFlags m_Flags = IMAP_MessageFlags.None; #endregion #region Properties /// <summary> /// Gets message 1 based sequence number in the collection. This property is slow, use with care, never use in big for loops ! /// </summary> public int SequenceNo { get { return m_pOwner.IndexOf(this) + 1; } } /// <summary> /// Gets message ID. /// </summary> public string ID { get { return m_ID; } } /// <summary> /// Gets message IMAP UID value. /// </summary> public long UID { get { return m_UID; } } /// <summary> /// Gets message store date. /// </summary> public DateTime InternalDate { get { return m_InternalDate; } } /// <summary> /// Gets message size in bytes. /// </summary> public long Size { get { return m_Size; } } /// <summary> /// Gets message flags. /// </summary> public IMAP_MessageFlags Flags { get { return m_Flags; } } /// <summary> /// Gets message flags string. For example: "\DELETES \SEEN". /// </summary> public string FlagsString { get { return IMAP_Utils.MessageFlagsToString(m_Flags); } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="onwer">Owner collection.</param> /// <param name="id">Message ID.</param> /// <param name="uid">Message IMAP UID value.</param> /// <param name="internalDate">Message store date.</param> /// <param name="size">Message size in bytes.</param> /// <param name="flags">Message flags.</param> internal IMAP_Message(IMAP_MessageCollection onwer, string id, long uid, DateTime internalDate, long size, IMAP_MessageFlags flags) { m_pOwner = onwer; m_ID = id; m_UID = uid; m_InternalDate = internalDate; m_Size = size; m_Flags = flags; } #endregion #region Internal methods /// <summary> /// Sets message flags. /// </summary> /// <param name="flags">Message flags.</param> internal void SetFlags(IMAP_MessageFlags flags) { m_Flags = flags; } #endregion public void Dispose() { } } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Autoreply/AutoreplyService.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Reflection; using System.Text.RegularExpressions; using ASC.Common.Web; using ASC.Core; using ASC.Core.Users; using ASC.Mail.Autoreply.AddressParsers; using ASC.Mail.Net; using ASC.Mail.Net.MIME; using ASC.Mail.Net.Mail; using ASC.Mail.Net.SMTP.Server; using ASC.Mail.Net.TCP; using log4net; namespace ASC.Mail.Autoreply { internal class AutoreplyService : IDisposable { private readonly ILog _log = LogManager.GetLogger(typeof(AutoreplyService)); private readonly List<IAddressParser> _addressParsers = new List<IAddressParser>(); private readonly SMTP_Server _smtpServer; private readonly ApiService _apiService; private readonly CooldownInspector _cooldownInspector; private readonly bool _storeIncomingMail; private readonly string _mailFolder; public AutoreplyService(AutoreplyServiceConfiguration configuration = null) { configuration = configuration ?? AutoreplyServiceConfiguration.GetSection(); _storeIncomingMail = configuration.IsDebug; _mailFolder = Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), configuration.MailFolder); if (!Directory.Exists(_mailFolder)) Directory.CreateDirectory(_mailFolder); _smtpServer = new SMTP_Server { MaxBadCommands = configuration.SmtpConfiguration.MaxBadCommands, MaxTransactions = configuration.SmtpConfiguration.MaxTransactions, MaxMessageSize = configuration.SmtpConfiguration.MaxMessageSize, MaxRecipients = configuration.SmtpConfiguration.MaxRecipients, MaxConnectionsPerIP = configuration.SmtpConfiguration.MaxConnectionsPerIP, MaxConnections = configuration.SmtpConfiguration.MaxConnections, Bindings = new[] {new IPBindInfo("localhost", IPAddress.Any, configuration.SmtpConfiguration.Port, SslMode.None, null)}, }; _smtpServer.Error += OnSmtpError; _smtpServer.SessionCreated += OnSmtpSessionCreated; _cooldownInspector = new CooldownInspector(configuration.CooldownConfiguration); _apiService = new ApiService(configuration.Https); } public void Start() { _smtpServer.Start(); _apiService.Start(); _cooldownInspector.Start(); } public void Stop() { _smtpServer.Stop(); _apiService.Stop(); _cooldownInspector.Stop(); } public void Dispose() { Stop(); _smtpServer.Dispose(); } public void RegisterAddressParser(IAddressParser addressHandler) { _addressParsers.Add(addressHandler); } private void OnSmtpSessionCreated(object sender, TCP_ServerSessionEventArgs<SMTP_Session> e) { e.Session.Started += (sndr, args) => _log.DebugFormat("session started: {0}", e.Session); e.Session.MailFrom += OnSessionMailFrom; e.Session.RcptTo += OnSessionRcptTo; e.Session.GetMessageStream += OnSessionGetMessageStream; e.Session.MessageStoringCanceled += OnSessionMessageStoringCancelled; e.Session.MessageStoringCompleted += OnSessionMessageStoringCompleted; } private void OnSmtpError(object sender, Error_EventArgs e) { _log.WarnFormat("smtp error: {0}", e.Exception); } private void OnSessionMailFrom(object sender, SMTP_e_MailFrom e) { e.Session.Tag = Regex.Replace(e.MailFrom.Mailbox, "^prvs=[0-9a-zA-Z]+=", "", RegexOptions.Compiled); //Set session mailbox } private void OnSessionRcptTo(object sender, SMTP_e_RcptTo e) { _log.Debug("start processing rcpt to event"); var addressTo = e.RcptTo.Mailbox; var addressFrom = (string)e.Session.Tag; var requestInfo = _addressParsers.Select(routeParser => routeParser.ParseRequestInfo(addressTo)) .FirstOrDefault(rInfo => rInfo != null); if (requestInfo == null) { _log.WarnFormat("could not create request from the address {0}", addressTo); e.Reply = new SMTP_Reply(501, "Could not create request from the address " + addressTo); return; } CoreContext.TenantManager.SetCurrentTenant(requestInfo.Tenant); UserInfo user = CoreContext.UserManager.GetUserByEmail(addressFrom); if (user.Equals(Constants.LostUser)) { e.Reply = new SMTP_Reply(501, "Could not find user by email address " + addressFrom); return; } if (_cooldownInspector != null) { var cooldownMinutes = Math.Ceiling(_cooldownInspector.GetCooldownRemainigTime(user.ID).TotalMinutes); if (cooldownMinutes > 0) { e.Reply = new SMTP_Reply(554, string.Format("User {0} can not use the autoreply service for another {1} minutes", addressFrom, cooldownMinutes)); return; } _cooldownInspector.RegisterServiceUsage(user.ID); } requestInfo.User = user; _log.DebugFormat("created request info {0}", requestInfo); e.Session.Tags.Add(e.RcptTo.Mailbox, requestInfo); _log.Debug("complete processing rcpt to event"); } private void OnSessionGetMessageStream(object sender, SMTP_e_Message e) { try { var messageFileName = Path.Combine(_mailFolder, DateTime.UtcNow.ToString("yyyy'-'MM'-'dd HH'-'mm'-'ss'Z'") + ".eml"); e.Stream = new FileStream(messageFileName, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite, 8096, _storeIncomingMail ? FileOptions.None : FileOptions.DeleteOnClose); } catch (Exception error) { _log.Error("error while allocating temporary stream for the message", error); } } private void OnSessionMessageStoringCancelled(object sender, SMTP_e_MessageStored e) { try { e.Stream.Close(); } catch (Exception error) { _log.Error("error while closing message stream", error); } } private void OnSessionMessageStoringCompleted(object sender, SMTP_e_MessageStored e) { _log.Debug("begin processing message storing completed event"); try { e.Stream.Flush(); e.Stream.Seek(0, SeekOrigin.Begin); Mail_Message message = Mail_Message.ParseFromStream(e.Stream); message.Subject = Regex.Replace(message.Subject, @"\t", ""); foreach (var requestInfo in e.Session.To .Where(x => e.Session.Tags.ContainsKey(x.Mailbox)) .Select(x => (ApiRequest)e.Session.Tags[x.Mailbox])) { try { _log.Debug("begin process request (" + requestInfo + ")"); CoreContext.TenantManager.SetCurrentTenant(requestInfo.Tenant); if (requestInfo.Parameters != null) { foreach (var parameter in requestInfo.Parameters.Where(x => x.ValueResolver != null)) { parameter.Value = parameter.ValueResolver.ResolveParameterValue(message); } } if (requestInfo.FilesToPost != null) { requestInfo.FilesToPost = message.AllEntities.Where(IsAttachment).Select(GetAsAttachment).ToList(); } if (requestInfo.FilesToPost == null || requestInfo.FilesToPost.Count > 0) { _apiService.EnqueueRequest(requestInfo); } _log.Debug("end process request (" + requestInfo + ")"); } catch (Exception ex) { _log.Error("error while processing request info", ex); } } } catch (Exception error) { _log.Error("error while processing message storing completed event", error); } finally { e.Stream.Close(); } _log.Debug("complete processing message storing completed event"); } private static bool IsAttachment(MIME_Entity entity) { return entity.Body.ContentType != null && entity.Body.ContentType.TypeWithSubype != null && entity.ContentDisposition != null && entity.ContentDisposition.DispositionType == MIME_DispositionTypes.Attachment && (!string.IsNullOrEmpty(entity.ContentDisposition.Param_FileName) || !string.IsNullOrEmpty(entity.ContentType.Param_Name)) && entity.Body is MIME_b_SinglepartBase; } private static RequestFileInfo GetAsAttachment(MIME_Entity entity) { var attachment = new RequestFileInfo { Body = ((MIME_b_SinglepartBase)entity.Body).Data }; if (!string.IsNullOrEmpty(entity.ContentDisposition.Param_FileName)) { attachment.Name = entity.ContentDisposition.Param_FileName; } else if (!string.IsNullOrEmpty(entity.ContentType.Param_Name)) { attachment.Name = entity.ContentType.Param_Name; } attachment.ContentType = MimeMapping.GetMimeMapping(attachment.Name); return attachment; } } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/DNS/Client/DNS_rr_HINFO.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.Dns.Client { /// <summary> /// HINFO record. /// </summary> public class DNS_rr_HINFO : DNS_rr_base { #region Members private readonly string m_CPU = ""; private readonly string m_OS = ""; #endregion #region Properties /// <summary> /// Gets host's CPU. /// </summary> public string CPU { get { return m_CPU; } } /// <summary> /// Gets host's OS. /// </summary> public string OS { get { return m_OS; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="cpu">Host CPU.</param> /// <param name="os">Host OS.</param> /// <param name="ttl">TTL value.</param> public DNS_rr_HINFO(string cpu, string os, int ttl) : base(QTYPE.HINFO, ttl) { m_CPU = cpu; m_OS = os; } #endregion #region Methods /// <summary> /// Parses resource record from reply data. /// </summary> /// <param name="reply">DNS server reply data.</param> /// <param name="offset">Current offset in reply data.</param> /// <param name="rdLength">Resource record data length.</param> /// <param name="ttl">Time to live in seconds.</param> public static DNS_rr_HINFO Parse(byte[] reply, ref int offset, int rdLength, int ttl) { /* RFC 1035 3.3.2. HINFO RDATA format +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ / CPU / +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ / OS / +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ CPU A <character-string> which specifies the CPU type. OS A <character-string> which specifies the operating system type. Standard values for CPU and OS can be found in [RFC-1010]. */ // CPU string cpu = Dns_Client.ReadCharacterString(reply, ref offset); // OS string os = Dns_Client.ReadCharacterString(reply, ref offset); return new DNS_rr_HINFO(cpu, os, ttl); } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/POP3/Server/AuthUser_EventArgs.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.POP3.Server { public class AuthUser_EventArgsBase { protected AuthType m_AuthType; protected string m_Data = ""; protected string m_PasswData = ""; protected string m_UserName = ""; private string m_ReturnData = ""; private bool m_Validated = true; /// <summary> /// User name. /// </summary> public string UserName { get { return m_UserName; } } /// <summary> /// Password data. eg. for AUTH=PLAIN it's password and for AUTH=APOP it's md5HexHash. /// </summary> public string PasswData { get { return m_PasswData; } } /// <summary> /// Authentication specific data(as tag). /// </summary> public string AuthData { get { return m_Data; } } /// <summary> /// Authentication type. /// </summary> public AuthType AuthType { get { return m_AuthType; } } /// <summary> /// Gets or sets if user is valid. /// </summary> public bool Validated { get { return m_Validated; } set { m_Validated = value; } } /// <summary> /// Gets or sets authentication data what must be returned for connected client. /// </summary> public string ReturnData { get { return m_ReturnData; } set { m_ReturnData = value; } } /// <summary> /// Gets or sets error text returned to connected client. /// </summary> public string ErrorText { get; set; } } /// <summary> /// Provides data for the AuthUser event for POP3_Server. /// </summary> public class AuthUser_EventArgs : AuthUser_EventArgsBase { #region Members private readonly POP3_Session m_pSession; #endregion #region Properties /// <summary> /// Gets reference to pop3 session. /// </summary> public POP3_Session Session { get { return m_pSession; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="session">Reference to pop3 session.</param> /// <param name="userName">Username.</param> /// <param name="passwData">Password data.</param> /// <param name="data">Authentication specific data(as tag).</param> /// <param name="authType">Authentication type.</param> public AuthUser_EventArgs(POP3_Session session, string userName, string passwData, string data, AuthType authType) { m_pSession = session; m_UserName = userName; m_PasswData = <PASSWORD>; m_Data = data; m_AuthType = authType; } #endregion } }<file_sep>/module/ASC.Api/ASC.Api.Portal/PortalApi.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Globalization; using System.Linq; using System.Net; using System.Security; using System.Threading; using System.Web; using ASC.Api.Attributes; using ASC.Api.Collections; using ASC.Api.Impl; using ASC.Api.Interfaces; using ASC.Common.Logging; using ASC.Core; using ASC.Core.Billing; using ASC.Core.Common.Contracts; using ASC.Core.Common.Notify.Jabber; using ASC.Core.Common.Notify.Push; using ASC.Core.Notify.Jabber; using ASC.Core.Tenants; using ASC.Core.Users; using ASC.ElasticSearch; using ASC.ElasticSearch.Core; using ASC.Geolocation; using ASC.MessagingSystem; using ASC.Security.Cryptography; using ASC.Web.Core; using ASC.Web.Core.Helpers; using ASC.Web.Core.Mobile; using ASC.Web.Core.Utility; using ASC.Web.Core.Utility.Settings; using ASC.Web.Studio.Core; using ASC.Web.Studio.Core.Backup; using ASC.Web.Studio.Core.Notify; using ASC.Web.Studio.Core.SMS; using ASC.Web.Studio.Core.TFA; using ASC.Web.Studio.PublicResources; using ASC.Web.Studio.UserControls.FirstTime; using ASC.Web.Studio.UserControls.Statistics; using ASC.Web.Studio.Utility; using Resources; using SecurityContext = ASC.Core.SecurityContext; using UrlShortener = ASC.Web.Core.Utility.UrlShortener; namespace ASC.Api.Portal { ///<summary> /// Portal info access ///</summary> public class PortalApi : IApiEntryPoint { private readonly IMobileAppInstallRegistrator mobileAppRegistrator; private readonly BackupAjaxHandler backupHandler = new BackupAjaxHandler(); ///<summary> /// Api name entry ///</summary> public string Name { get { return "portal"; } } private static HttpRequest Request { get { return HttpContext.Current.Request; } } public PortalApi(ApiContext context) { mobileAppRegistrator = new CachedMobileAppInstallRegistrator(new MobileAppInstallRegistrator()); } ///<summary> ///Returns the current portal ///</summary> ///<short> ///Current portal ///</short> ///<returns>Portal</returns> [Read("")] public Tenant Get() { return CoreContext.TenantManager.GetCurrentTenant(); } ///<summary> ///Returns the user with specified userID from the current portal ///</summary> ///<short> ///User with specified userID ///</short> /// <category>Users</category> ///<returns>User</returns> [Read("users/{userID}")] public UserInfo GetUser(Guid userID) { return CoreContext.UserManager.GetUsers(userID); } ///<summary> /// Returns invitational link to the portal ///</summary> ///<short> /// Returns invitational link to the portal ///</short> /// <param name="employeeType"> /// User or Visitor /// </param> ///<category>Users</category> ///<returns> /// Invite link ///</returns> [Read("users/invite/{employeeType}")] public string GeInviteLink(EmployeeType employeeType) { if (!CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID).IsAdmin() && !WebItemSecurity.IsProductAdministrator(WebItemManager.PeopleProductID, SecurityContext.CurrentAccount.ID)) throw new SecurityException("Method not available"); return CommonLinkUtility.GetConfirmationUrl(string.Empty, ConfirmType.LinkInvite, (int)employeeType, SecurityContext.CurrentAccount.ID) + String.Format("&emplType={0}", (int)employeeType); } /// <summary> /// Returns shorten link /// </summary> /// <param name="link">Link for shortening</param> ///<returns>link</returns> ///<visible>false</visible> [Update("getshortenlink")] public String GetShortenLink(string link) { try { return UrlShortener.Instance.GetShortenLink(link); } catch (Exception ex) { LogManager.GetLogger("ASC.Web").Error("getshortenlink", ex); return link; } } ///<summary> ///Returns the used space of the current portal ///</summary> ///<short> ///Used space of the current portal ///</short> /// <category>Quota</category> ///<returns>Used space</returns> [Read("usedspace")] public double GetUsedSpace() { return Math.Round( CoreContext.TenantManager.FindTenantQuotaRows(new TenantQuotaRowQuery(CoreContext.TenantManager.GetCurrentTenant().TenantId)) .Where(q => !string.IsNullOrEmpty(q.Tag) && new Guid(q.Tag) != Guid.Empty) .Sum(q => q.Counter) / 1024f / 1024f / 1024f, 2); } ///<summary> ///Returns the users count of the current portal ///</summary> ///<short> ///Users count of the current portal ///</short> /// <category>Users</category> ///<returns>Users count</returns> [Read("userscount")] public long GetUsersCount() { return CoreContext.UserManager.GetUserNames(EmployeeStatus.Active).Count(); } ///<visible>false</visible> [Create("uploadlicense")] public FileUploadResult UploadLicense(IEnumerable<HttpPostedFileBase> attachments) { if (!CoreContext.Configuration.Standalone) throw new NotSupportedException(); var license = attachments.FirstOrDefault(); if (license == null) throw new Exception(Resource.ErrorEmptyUploadFileSelected); var result = new FileUploadResult(); try { var dueDate = LicenseReader.SaveLicenseTemp(license.InputStream); result.Message = dueDate >= DateTime.UtcNow.Date ? Resource.LicenseUploaded : string.Format(Resource.LicenseUploadedOverdue, string.Empty, string.Empty, dueDate.Date.ToLongDateString()); result.Success = true; } catch (LicenseExpiredException ex) { LogManager.GetLogger("ASC").Error("License upload", ex); result.Message = Resource.LicenseErrorExpired; } catch (LicenseQuotaException ex) { LogManager.GetLogger("ASC").Error("License upload", ex); result.Message = Resource.LicenseErrorQuota; } catch (LicensePortalException ex) { LogManager.GetLogger("ASC").Error("License upload", ex); result.Message = Resource.LicenseErrorPortal; } catch (Exception ex) { LogManager.GetLogger("ASC").Error("License upload", ex); result.Message = Resource.LicenseError; } return result; } ///<visible>false</visible> [Create("activatelicense")] public FileUploadResult ActivateLicense() { if (!CoreContext.Configuration.Standalone) throw new NotSupportedException(); var result = new FileUploadResult(); try { LicenseReader.RefreshLicense(); Web.Studio.UserControls.Management.TariffSettings.LicenseAccept = true; MessageService.Send(HttpContext.Current.Request, MessageAction.LicenseKeyUploaded); result.Success = true; } catch (BillingNotFoundException ex) { LogManager.GetLogger("ASC").Error("License activate", ex); result.Message = UserControlsCommonResource.LicenseKeyNotFound; } catch (BillingNotConfiguredException ex) { LogManager.GetLogger("ASC").Error("License activate", ex); result.Message = UserControlsCommonResource.LicenseKeyNotCorrect; } catch (BillingException ex) { LogManager.GetLogger("ASC").Error("License activate", ex); result.Message = UserControlsCommonResource.LicenseException; } catch (Exception ex) { LogManager.GetLogger("ASC").Error("License activate", ex); result.Message = ex.Message; } return result; } ///<visible>false</visible> [Create("activatetrial")] public bool ActivateTrial() { if (!CoreContext.Configuration.Standalone) throw new NotSupportedException(); if (!CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID).IsAdmin()) throw new SecurityException(); var curQuota = TenantExtra.GetTenantQuota(); if (curQuota.Id != Tenant.DEFAULT_TENANT) return false; if (curQuota.Trial) return false; var curTariff = TenantExtra.GetCurrentTariff(); if (curTariff.DueDate.Date != DateTime.MaxValue.Date) return false; var quota = new TenantQuota(-1000) { Name = "apirequest", ActiveUsers = curQuota.ActiveUsers, MaxFileSize = curQuota.MaxFileSize, MaxTotalSize = curQuota.MaxTotalSize, Features = curQuota.Features }; quota.Trial = true; CoreContext.TenantManager.SaveTenantQuota(quota); var DEFAULT_TRIAL_PERIOD = 30; var tariff = new Tariff { QuotaId = quota.Id, DueDate = DateTime.Today.AddDays(DEFAULT_TRIAL_PERIOD) }; CoreContext.PaymentManager.SetTariff(-1, tariff); MessageService.Send(HttpContext.Current.Request, MessageAction.LicenseKeyUploaded); return true; } ///<visible>false</visible> [Read("tenantextra")] public object GetTenantExtra() { return new { opensource = TenantExtra.Opensource, enterprise = TenantExtra.Enterprise, tariff = TenantExtra.GetCurrentTariff(), quota = TenantExtra.GetTenantQuota(), notPaid = TenantStatisticsProvider.IsNotPaid(), licenseAccept = Web.Studio.UserControls.Management.TariffSettings.LicenseAccept }; } ///<summary> ///Returns the current tariff of the current portal ///</summary> ///<short> ///Tariff of the current portal ///</short> /// <category>Quota</category> ///<returns>Tariff</returns> [Read("tariff")] public Tariff GetTariff() { return CoreContext.PaymentManager.GetTariff(CoreContext.TenantManager.GetCurrentTenant().TenantId); } ///<summary> ///Returns the current quota of the current portal ///</summary> ///<short> ///Quota of the current portal ///</short> /// <category>Quota</category> ///<returns>Quota</returns> [Read("quota")] public TenantQuota GetQuota() { return CoreContext.TenantManager.GetTenantQuota(CoreContext.TenantManager.GetCurrentTenant().TenantId); } ///<summary> ///Returns the recommended quota of the current portal ///</summary> ///<short> ///Quota of the current portal ///</short> /// <category>Quota</category> ///<returns>Quota</returns> [Read("quota/right")] public TenantQuota GetRightQuota() { var usedSpace = GetUsedSpace(); var needUsersCount = GetUsersCount(); return CoreContext.TenantManager.GetTenantQuotas().OrderBy(r => r.Price) .FirstOrDefault(quota => quota.ActiveUsers > needUsersCount && quota.MaxTotalSize > usedSpace && !quota.Year); } ///<summary> ///Returns path ///</summary> ///<short> ///path ///</short> ///<returns>path</returns> ///<visible>false</visible> [Read("path")] public string GetFullAbsolutePath(string virtualPath) { return CommonLinkUtility.GetFullAbsolutePath(virtualPath); } ///<visible>false</visible> [Read("talk/unreadmessages")] public int GetMessageCount() { try { return new JabberServiceClient().GetNewMessagesCount(); } catch { } return 0; } ///<visible>false</visible> [Delete("talk/connection")] public int RemoveXmppConnection(string connectionId) { try { return new JabberServiceClient().RemoveXmppConnection(connectionId); } catch { } return 0; } ///<visible>false</visible> [Create("talk/connection")] public byte AddXmppConnection(string connectionId, byte state) { try { return new JabberServiceClient().AddXmppConnection(connectionId, state); } catch { } return 0; } ///<visible>false</visible> [Read("talk/state")] public int GetState(string userName) { try { return new JabberServiceClient().GetState(userName); } catch { } return 0; } ///<visible>false</visible> [Create("talk/state")] public byte SendState(byte state) { try { return new JabberServiceClient().SendState(state); } catch { } return 4; } ///<visible>false</visible> [Create("talk/message")] public void SendMessage(string to, string text, string subject) { try { var username = CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID).UserName; new JabberServiceClient().SendMessage(TenantProvider.CurrentTenantID, username, to, text, subject); } catch { } } ///<visible>false</visible> [Read("talk/states")] public Dictionary<string, byte> GetAllStates() { try { return new JabberServiceClient().GetAllStates(); } catch { } return new Dictionary<string, byte>(); } ///<visible>false</visible> [Read("talk/recentMessages")] public MessageClass[] GetRecentMessages(string calleeUserName, int id) { try { var userName = CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID).UserName; var recentMessages = new JabberServiceClient().GetRecentMessages(calleeUserName, id); if (recentMessages == null) return null; foreach (var mc in recentMessages) { mc.DateTime = TenantUtil.DateTimeFromUtc(mc.DateTime.AddMilliseconds(1)); if (mc.UserName == null || string.Equals(mc.UserName, calleeUserName, StringComparison.InvariantCultureIgnoreCase)) { mc.UserName = calleeUserName; } else { mc.UserName = userName; } } return recentMessages; } catch { } return new MessageClass[0]; } ///<visible>false</visible> [Create("talk/ping")] public void Ping(byte state) { try { new JabberServiceClient().Ping(state); } catch { } } ///<visible>false</visible> [Create("mobile/registration")] public void RegisterMobileAppInstall(MobileAppType type) { var currentUser = CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID); mobileAppRegistrator.RegisterInstall(currentUser.Email, type); } /// <summary> /// Returns the backup schedule of the current portal /// </summary> /// <category>Backup</category> /// <returns>Backup Schedule</returns> [Read("getbackupschedule")] public BackupAjaxHandler.Schedule GetBackupSchedule() { if (CoreContext.Configuration.Standalone) { TenantExtra.DemandControlPanelPermission(); } return backupHandler.GetSchedule(); } /// <summary> /// Create the backup schedule of the current portal /// </summary> /// <param name="storageType">Storage type</param> /// <param name="storageParams">Storage parameters</param> /// <param name="backupsStored">Max of the backup's stored copies</param> /// <param name="cronParams">Cron parameters</param> /// <param name="backupMail">Include mail in the backup</param> /// <category>Backup</category> [Create("createbackupschedule")] public void CreateBackupSchedule(BackupStorageType storageType, IEnumerable<ItemKeyValuePair<string, string>> storageParams, int backupsStored, BackupAjaxHandler.CronParams cronParams, bool backupMail) { if (CoreContext.Configuration.Standalone) { TenantExtra.DemandControlPanelPermission(); } backupHandler.CreateSchedule(storageType, storageParams.ToDictionary(r=> r.Key, r=> r.Value), backupsStored, cronParams, backupMail); } /// <summary> /// Delete the backup schedule of the current portal /// </summary> /// <category>Backup</category> [Delete("deletebackupschedule")] public void DeleteBackupSchedule() { if (CoreContext.Configuration.Standalone) { TenantExtra.DemandControlPanelPermission(); } backupHandler.DeleteSchedule(); } /// <summary> /// Start a backup of the current portal /// </summary> /// <param name="storageType">Storage Type</param> /// <param name="storageParams">Storage Params</param> /// <param name="backupMail">Include mail in the backup</param> /// <category>Backup</category> /// <returns>Backup Progress</returns> [Create("startbackup")] public BackupProgress StartBackup(BackupStorageType storageType, IEnumerable<ItemKeyValuePair<string, string>> storageParams, bool backupMail) { if (CoreContext.Configuration.Standalone) { TenantExtra.DemandControlPanelPermission(); } return backupHandler.StartBackup(storageType, storageParams.ToDictionary(r=> r.Key, r=> r.Value), backupMail); } /// <summary> /// Returns the progress of the started backup /// </summary> /// <category>Backup</category> /// <returns>Backup Progress</returns> [Read("getbackupprogress")] public BackupProgress GetBackupProgress() { if (CoreContext.Configuration.Standalone) { TenantExtra.DemandControlPanelPermission(); } return backupHandler.GetBackupProgress(); } /// <summary> /// Returns the backup history of the started backup /// </summary> /// <category>Backup</category> /// <returns>Backup History</returns> [Read("getbackuphistory")] public List<BackupHistoryRecord> GetBackupHistory() { if (CoreContext.Configuration.Standalone) { TenantExtra.DemandControlPanelPermission(); } return backupHandler.GetBackupHistory(); } /// <summary> /// Delete the backup with the specified id /// </summary> /// <category>Backup</category> [Delete("deletebackup/{id}")] public void DeleteBackup(Guid id) { if (CoreContext.Configuration.Standalone) { TenantExtra.DemandControlPanelPermission(); } backupHandler.DeleteBackup(id); } /// <summary> /// Delete all backups of the current portal /// </summary> /// <category>Backup</category> /// <returns>Backup History</returns> [Delete("deletebackuphistory")] public void DeleteBackupHistory() { if (CoreContext.Configuration.Standalone) { TenantExtra.DemandControlPanelPermission(); } backupHandler.DeleteAllBackups(); } /// <summary> /// Start a data restore of the current portal /// </summary> /// <param name="backupId">Backup Id</param> /// <param name="storageType">Storage Type</param> /// <param name="storageParams">Storage Params</param> /// <param name="notify">Notify about backup to users</param> /// <category>Backup</category> /// <returns>Restore Progress</returns> [Create("startrestore")] public BackupProgress StartBackupRestore(string backupId, BackupStorageType storageType, IEnumerable<ItemKeyValuePair<string, string>> storageParams, bool notify) { if (CoreContext.Configuration.Standalone) { TenantExtra.DemandControlPanelPermission(); } return backupHandler.StartRestore(backupId, storageType, storageParams.ToDictionary(r => r.Key, r => r.Value), notify); } /// <summary> /// Returns the progress of the started restore /// </summary> /// <category>Backup</category> /// <returns>Restore Progress</returns> [Read("getrestoreprogress", true, false)] //NOTE: this method doesn't check payment!!! public BackupProgress GetRestoreProgress() { if (CoreContext.Configuration.Standalone) { TenantExtra.DemandControlPanelPermission(); } return backupHandler.GetRestoreProgress(); } ///<visible>false</visible> [Read("backuptmp")] public string GetTempPath(string alias) { if (CoreContext.Configuration.Standalone) { TenantExtra.DemandControlPanelPermission(); } return backupHandler.GetTmpFolder(); } ///<visible>false</visible> [Update("portalrename")] public object UpdatePortalName(string alias) { var enabled = SetupInfo.IsVisibleSettings("PortalRename"); if (!enabled) throw new SecurityException(Resource.PortalAccessSettingsTariffException); if (CoreContext.Configuration.Personal) throw new Exception(Resource.ErrorAccessDenied); SecurityContext.DemandPermissions(SecutiryConstants.EditPortalSettings); if (String.IsNullOrEmpty(alias)) throw new ArgumentException(); var tenant = CoreContext.TenantManager.GetCurrentTenant(); var user = CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID); var localhost = CoreContext.Configuration.BaseDomain == "localhost" || tenant.TenantAlias == "localhost"; var newAlias = alias.ToLowerInvariant(); var oldAlias = tenant.TenantAlias; var oldVirtualRootPath = CommonLinkUtility.GetFullAbsolutePath("~").TrimEnd('/'); if (!String.Equals(newAlias, oldAlias, StringComparison.InvariantCultureIgnoreCase)) { if (!String.IsNullOrEmpty(ApiSystemHelper.ApiSystemUrl)) { ApiSystemHelper.ValidatePortalName(newAlias); } else { CoreContext.TenantManager.CheckTenantAddress(newAlias.Trim()); } if (!String.IsNullOrEmpty(ApiSystemHelper.ApiCacheUrl)) { ApiSystemHelper.AddTenantToCache(newAlias); } tenant.TenantAlias = alias; tenant = CoreContext.TenantManager.SaveTenant(tenant); if (!String.IsNullOrEmpty(ApiSystemHelper.ApiCacheUrl)) { ApiSystemHelper.RemoveTenantFromCache(oldAlias); } if (!localhost || string.IsNullOrEmpty(tenant.MappedDomain)) { StudioNotifyService.Instance.PortalRenameNotify(oldVirtualRootPath); } } else { throw new Exception(ResourceJS.ErrorPortalNameWasNotChanged); } var reference = CreateReference(Request, tenant.TenantDomain, tenant.TenantId, user.Email); return new { message = Resource.SuccessfullyPortalRenameMessage, reference = reference }; } ///<visible>false</visible> [Update("portalanalytics")] public bool UpdatePortalAnalytics(bool enable) { SecurityContext.DemandPermissions(SecutiryConstants.EditPortalSettings); if (!(TenantExtra.Opensource || (TenantExtra.Saas && SetupInfo.CustomScripts.Length != 0)) || CoreContext.Configuration.CustomMode) throw new SecurityException(); if (TenantExtra.Opensource) { var wizardSettings = WizardSettings.Load(); wizardSettings.Analytics = enable; wizardSettings.Save(); } else if (TenantExtra.Saas) { var analyticsSettings = TenantAnalyticsSettings.Load(); analyticsSettings.Analytics = enable; analyticsSettings.Save(); } return enable; } #region create reference for auth on renamed tenant private static string CreateReference(HttpRequest request, string tenantDomain, int tenantId, string email) { return String.Format("{0}{1}{2}/{3}", request != null && request.UrlReferrer != null ? request.UrlReferrer.Scheme : Uri.UriSchemeHttp, Uri.SchemeDelimiter, tenantDomain, CommonLinkUtility.GetConfirmationUrlRelative(tenantId, email, ConfirmType.Auth) ); } #endregion ///<visible>false</visible> [Create("sendcongratulations", false)] //NOTE: this method doesn't requires auth!!! public void SendCongratulations(Guid userid, string key) { var authInterval = TimeSpan.FromHours(1); var checkKeyResult = EmailValidationKeyProvider.ValidateEmailKey(userid.ToString() + ConfirmType.Auth, key, authInterval); switch (checkKeyResult) { case EmailValidationKeyProvider.ValidationResult.Ok: var currentUser = CoreContext.UserManager.GetUsers(userid); StudioNotifyService.Instance.SendCongratulations(currentUser); StudioNotifyService.Instance.SendRegData(currentUser); FirstTimeTenantSettings.SendInstallInfo(currentUser); if (!SetupInfo.IsSecretEmail(currentUser.Email)) { if (SetupInfo.TfaRegistration == "sms") { StudioSmsNotificationSettings.Enable = true; } else if (SetupInfo.TfaRegistration == "code") { TfaAppAuthSettings.Enable = true; } } break; default: throw new SecurityException("Access Denied."); } } ///<visible>false</visible> [Update("fcke/comment/removecomplete")] public object RemoveCommentComplete(string commentid, string domain) { try { CommonControlsConfigurer.FCKUploadsRemoveForItem(domain, commentid); return 1; } catch { return 0; } } ///<visible>false</visible> [Update("fcke/comment/cancelcomplete")] public object CancelCommentComplete(string commentid, string domain, bool isedit) { try { if (isedit) CommonControlsConfigurer.FCKEditingCancel(domain, commentid); else CommonControlsConfigurer.FCKEditingCancel(domain); return 1; } catch { return 0; } } ///<visible>false</visible> [Update("fcke/comment/editcomplete")] public object EditCommentComplete(string commentid, string domain, string html, bool isedit) { try { CommonControlsConfigurer.FCKEditingComplete(domain, commentid, html, isedit); return 1; } catch { return 0; } } ///<visible>false</visible> [Read("bar/promotions")] public string GetBarPromotions(string domain, string page, bool desktop) { try { var showPromotions = PromotionsSettings.Load().Show; if (!showPromotions) return null; var tenant = CoreContext.TenantManager.GetCurrentTenant(); var user = CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID); var uriBuilder = new UriBuilder(SetupInfo.NotifyAddress + "promotions/Get"); var query = HttpUtility.ParseQueryString(uriBuilder.Query); if (string.IsNullOrEmpty(domain)) { domain = Request.UrlReferrer != null ? Request.UrlReferrer.Host : string.Empty; } if (string.IsNullOrEmpty(page)) { page = Request.UrlReferrer != null ? Request.UrlReferrer.PathAndQuery : string.Empty; } query["userId"] = user.ID.ToString(); query["language"] = Thread.CurrentThread.CurrentCulture.Name.ToLowerInvariant(); query["version"] = tenant.Version.ToString(CultureInfo.InvariantCulture); query["tariff"] = TenantExtra.GetTenantQuota().Id.ToString(CultureInfo.InvariantCulture); query["admin"] = user.IsAdmin().ToString(); query["userCreated"] = user.CreateDate.ToString(CultureInfo.InvariantCulture); query["promo"] = true.ToString(); query["domain"] = domain; query["page"] = page; query["agent"] = Request.UserAgent ?? Request.Headers["User-Agent"]; query["desktop"] = desktop.ToString(); uriBuilder.Query = query.ToString(); using (var client = new WebClient()) { client.Encoding = System.Text.Encoding.UTF8; return client.DownloadString(uriBuilder.Uri); } } catch (Exception ex) { LogManager.GetLogger("ASC.Web").Error("GetBarTips", ex); return null; } } ///<visible>false</visible> [Create("bar/promotions/mark/{id}")] public void MarkBarPromotion(string id) { try { var url = string.Format("{0}promotions/Complete", SetupInfo.NotifyAddress); using (var client = new WebClient()) { client.UploadValues(url, "POST", new NameValueCollection { {"id", id}, {"userId", SecurityContext.CurrentAccount.ID.ToString()} }); } } catch (Exception ex) { LogManager.GetLogger("ASC.Web").Error("MarkBarPromotion", ex); } } ///<visible>false</visible> [Read("bar/tips")] public string GetBarTips(string page, bool productAdmin, bool desktop) { try { if (string.IsNullOrEmpty(page)) return null; if (!TipsSettings.LoadForCurrentUser().Show) return null; var tenant = CoreContext.TenantManager.GetCurrentTenant(); var user = CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID); var uriBuilder = new UriBuilder(SetupInfo.TipsAddress + "tips/Get"); var query = HttpUtility.ParseQueryString(uriBuilder.Query); query["userId"] = user.ID.ToString(); query["tenantId"] = tenant.TenantId.ToString(CultureInfo.InvariantCulture); query["page"] = page; query["language"] = Thread.CurrentThread.CurrentCulture.Name.ToLowerInvariant(); query["admin"] = user.IsAdmin().ToString(); query["productAdmin"] = productAdmin.ToString(); query["visitor"] = user.IsVisitor().ToString(); query["userCreatedDate"] = user.CreateDate.ToString(CultureInfo.InvariantCulture); query["tenantCreatedDate"] = tenant.CreatedDateTime.ToString(CultureInfo.InvariantCulture); query["desktop"] = desktop.ToString(); uriBuilder.Query = query.ToString(); using (var client = new WebClient()) { client.Encoding = System.Text.Encoding.UTF8; return client.DownloadString(uriBuilder.Uri); } } catch (Exception ex) { LogManager.GetLogger("ASC.Web").Error("GetBarTips", ex); return null; } } ///<visible>false</visible> [Create("bar/tips/mark/{id}")] public void MarkBarTip(string id) { try { var url = string.Format("{0}tips/MarkRead", SetupInfo.TipsAddress); using (var client = new WebClient()) { client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded"; client.UploadValues(url, "POST", new NameValueCollection { {"id", id}, {"userId", SecurityContext.CurrentAccount.ID.ToString()}, {"tenantId", CoreContext.TenantManager.GetCurrentTenant().TenantId.ToString(CultureInfo.InvariantCulture)} }); } } catch (Exception ex) { LogManager.GetLogger("ASC.Web").Error("MarkBarTip", ex); } } ///<visible>false</visible> [Delete("bar/tips")] public void DeleteBarTips() { try { var url = string.Format("{0}tips/DeleteReaded", SetupInfo.TipsAddress); using (var client = new WebClient()) { client.UploadValues(url, "POST", new NameValueCollection { {"userId", SecurityContext.CurrentAccount.ID.ToString()}, {"tenantId", CoreContext.TenantManager.GetCurrentTenant().TenantId.ToString(CultureInfo.InvariantCulture)} }); } } catch (Exception ex) { LogManager.GetLogger("ASC.Web").Error("DeleteBarTips", ex); } } [Read("search")] public IEnumerable<object> GetSearchSettings() { TenantExtra.DemandControlPanelPermission(); return SearchSettings.GetAllItems().Select(r => new { id =r.ID, title = r.Title, enabled = r.Enabled }); } [Read("search/state")] public object CheckSearchAvailable() { TenantExtra.DemandControlPanelPermission(); return FactoryIndexer.GetState(); } [Create("search/reindex")] public object Reindex(string name) { TenantExtra.DemandControlPanelPermission(); FactoryIndexer.Reindex(name); return CheckSearchAvailable(); } [Create("search")] public void SetSearchSettings(List<SearchSettingsItem> items) { TenantExtra.DemandControlPanelPermission(); SearchSettings.Set(items); } /// <summary> /// Get random password /// </summary> /// <short>Get random password</short> ///<visible>false</visible> [Read(@"randompwd")] public string GetRandomPassword() { var Noise = "1234567890mnbasdflkjqwerpoiqweyuvcxnzhdkqpsdk_-()="; var ps = PasswordSettings.Load(); var maxLength = PasswordSettings.MaxLength - (ps.Digits ? 1 : 0) - (ps.UpperCase ? 1 : 0) - (ps.SpecSymbols ? 1 : 0); var minLength = Math.Min(ps.MinLength, maxLength); var password = String.Format("{0}{1}{2}{3}", GeneratePassword(minLength, minLength, Noise.Substring(0, Noise.Length - 4)), ps.Digits ? GeneratePassword(1, 1, Noise.Substring(0, 10)) : String.Empty, ps.UpperCase ? GeneratePassword(1, 1, Noise.Substring(10, 20).ToUpper()) : String.Empty, ps.SpecSymbols ? GeneratePassword(1, 1, Noise.Substring(Noise.Length - 4, 4).ToUpper()) : String.Empty); return password; } private static readonly Random Rnd = new Random(); private static string GeneratePassword(int minLength, int maxLength, string noise) { var length = Rnd.Next(minLength, maxLength + 1); var pwd = string.Empty; while (length-- > 0) { pwd += noise.Substring(Rnd.Next(noise.Length - 1), 1); } return pwd; } /// <summary> /// Get information by IP address /// </summary> /// <short>Get information by IP address</short> ///<visible>false</visible> [Read("ip/{ipAddress}")] public object GetIPInformation(string ipAddress) { GeolocationHelper helper = new GeolocationHelper("teamlabsite"); return helper.GetIPGeolocation(ipAddress); } ///<visible>false</visible> [Create("gift/mark")] public void MarkGiftAsReaded() { try { var settings = OpensourceGiftSettings.LoadForCurrentUser(); settings.Readed = true; settings.SaveForCurrentUser(); } catch (Exception ex) { LogManager.GetLogger("ASC.Web").Error("MarkGiftAsReaded", ex); } } } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/RTP/RTP_Source.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.RTP { #region usings using System; using System.Net; #endregion /// <summary> /// This class represents RTP source. /// </summary> /// <remarks>Source indicates an entity sending packets, either RTP and/or RTCP. /// Sources what send RTP packets are called "active", only RTCP sending ones are "passive". /// Source can be local(we send RTP and/or RTCP remote party) or remote(remote party sends RTP and/or RTCP to us). /// </remarks> public abstract class RTP_Source { #region Events /// <summary> /// Is raised when source is closed (by BYE). /// </summary> public event EventHandler Closed = null; /// <summary> /// Is raised when source is disposing. /// </summary> public event EventHandler Disposing = null; /// <summary> /// Is raised when source state has changed. /// </summary> public event EventHandler StateChanged = null; #endregion #region Members private readonly DateTime m_LastRRTime = DateTime.MinValue; private string m_CloseReason; private DateTime m_LastActivity = DateTime.Now; private DateTime m_LastRtcpPacket = DateTime.MinValue; private DateTime m_LastRtpPacket = DateTime.MinValue; private IPEndPoint m_pRtcpEP; private IPEndPoint m_pRtpEP; private RTP_Session m_pSession; private uint m_SSRC; private RTP_SourceState m_State = RTP_SourceState.Passive; #endregion #region Properties /// <summary> /// Gets source state. /// </summary> public RTP_SourceState State { get { return m_State; } } /// <summary> /// Gets owner RTP session. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public RTP_Session Session { get { if (m_State == RTP_SourceState.Disposed) { throw new ObjectDisposedException(GetType().Name); } return m_pSession; } } /// <summary> /// Gets synchronization source ID. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public uint SSRC { get { if (m_State == RTP_SourceState.Disposed) { throw new ObjectDisposedException(GetType().Name); } return m_SSRC; } } /// <summary> /// Gets source RTCP end point. Value null means source haven't sent any RTCP packet. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public IPEndPoint RtcpEP { get { if (m_State == RTP_SourceState.Disposed) { throw new ObjectDisposedException(GetType().Name); } return m_pRtcpEP; } } /// <summary> /// Gets source RTP end point. Value null means source haven't sent any RTCP packet. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public IPEndPoint RtpEP { get { if (m_State == RTP_SourceState.Disposed) { throw new ObjectDisposedException(GetType().Name); } return m_pRtpEP; } } /// <summary> /// Gets if source is local or remote source. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public abstract bool IsLocal { get; } /// <summary> /// Gets last time when source sent RTP or RCTP packet. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public DateTime LastActivity { get { if (m_State == RTP_SourceState.Disposed) { throw new ObjectDisposedException(GetType().Name); } return m_LastActivity; } } /// <summary> /// Gets last time when source sent RTCP packet. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public DateTime LastRtcpPacket { get { if (m_State == RTP_SourceState.Disposed) { throw new ObjectDisposedException(GetType().Name); } return m_LastRtcpPacket; } } /// <summary> /// Gets last time when source sent RTP packet. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public DateTime LastRtpPacket { get { if (m_State == RTP_SourceState.Disposed) { throw new ObjectDisposedException(GetType().Name); } return m_LastRtpPacket; } } /// <summary> /// Gets last time when source sent RTCP RR report. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public DateTime LastRRTime { get { if (m_State == RTP_SourceState.Disposed) { throw new ObjectDisposedException(GetType().Name); } return m_LastRRTime; } } /// <summary> /// Gets source closing reason. Value null means not specified. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public string CloseReason { get { if (m_State == RTP_SourceState.Disposed) { throw new ObjectDisposedException(GetType().Name); } return m_CloseReason; } } /// <summary> /// Gets or sets user data. /// </summary> public object Tag { get; set; } /// <summary> /// Gets source CNAME. Value null means that source not binded to participant. /// </summary> internal abstract string CName { get; } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="session">Owner RTP session.</param> /// <param name="ssrc">Synchronization source ID.</param> /// <exception cref="ArgumentNullException">Is raised when <b>session</b> is null reference.</exception> internal RTP_Source(RTP_Session session, uint ssrc) { if (session == null) { throw new ArgumentNullException("session"); } m_pSession = session; m_SSRC = ssrc; } #endregion #region Virtual methods /// <summary> /// Cleans up any resources being used. /// </summary> internal virtual void Dispose() { if (m_State == RTP_SourceState.Disposed) { return; } OnDisposing(); SetState(RTP_SourceState.Disposed); m_pSession = null; m_pRtcpEP = null; m_pRtpEP = null; Closed = null; Disposing = null; StateChanged = null; } /// <summary> /// Closes specified source. /// </summary> /// <param name="closeReason">Closing reason. Value null means not specified.</param> internal virtual void Close(string closeReason) { m_CloseReason = closeReason; OnClosed(); Dispose(); } #endregion #region Utility methods /// <summary> /// Raises <b>Closed</b> event. /// </summary> private void OnClosed() { if (Closed != null) { Closed(this, new EventArgs()); } } /// <summary> /// Raises <b>Disposing</b> event. /// </summary> private void OnDisposing() { if (Disposing != null) { Disposing(this, new EventArgs()); } } /// <summary> /// Raises <b>StateChanged</b> event. /// </summary> private void OnStateChaged() { if (StateChanged != null) { StateChanged(this, new EventArgs()); } } #endregion #region Internal methods /// <summary> /// Sets property <b>RtcpEP</b> value. /// </summary> /// <param name="ep">IP end point.</param> internal void SetRtcpEP(IPEndPoint ep) { m_pRtcpEP = ep; } /// <summary> /// Sets property <b>RtpEP</b> value. /// </summary> /// <param name="ep">IP end point.</param> internal void SetRtpEP(IPEndPoint ep) { m_pRtpEP = ep; } /// <summary> /// Sets source active/passive state. /// </summary> /// <param name="active">If true, source switches to active, otherwise to passive.</param> internal void SetActivePassive(bool active) { if (active) {} else {} // TODO: } /// <summary> /// Sets <b>LastRtcpPacket</b> property value. /// </summary> /// <param name="time">Time.</param> internal void SetLastRtcpPacket(DateTime time) { m_LastRtcpPacket = time; m_LastActivity = time; } /// <summary> /// Sets <b>LastRtpPacket</b> property value. /// </summary> /// <param name="time">Time.</param> internal void SetLastRtpPacket(DateTime time) { m_LastRtpPacket = time; m_LastActivity = time; } /// <summary> /// Sets property LastRR value. /// </summary> /// <param name="rr">RTCP RR report.</param> /// <exception cref="ArgumentNullException">Is raised when <b>rr</b> is null reference.</exception> internal void SetRR(RTCP_Packet_ReportBlock rr) { if (rr == null) { throw new ArgumentNullException("rr"); } } /// <summary> /// Generates new SSRC value. This must be called only if SSRC collision of local source. /// </summary> internal void GenerateNewSSRC() { m_SSRC = RTP_Utils.GenerateSSRC(); } #endregion /// <summary> /// Sets source state. /// </summary> /// <param name="state">New source state.</param> protected void SetState(RTP_SourceState state) { if (m_State == RTP_SourceState.Disposed) { return; } if (m_State != state) { m_State = state; OnStateChaged(); } } } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/SIP/UA/SIP_UA_CallState.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.SIP.UA { /// <summary> /// This enum specifies SIP UA call states. /// </summary> public enum SIP_UA_CallState { /// <summary> /// Outgoing call waits to be started. /// </summary> WaitingForStart, /// <summary> /// Outgoing calling is in progress. /// </summary> Calling, /// <summary> /// Outgoing call remote end party is ringing. /// </summary> Ringing, /// <summary> /// Outgoing call remote end pary queued a call. /// </summary> Queued, /// <summary> /// Incoming call waits to be accepted. /// </summary> WaitingToAccept, /// <summary> /// Call is active. /// </summary> Active, /// <summary> /// Call is terminating. /// </summary> Terminating, /// <summary> /// Call is terminated. /// </summary> Terminated, /// <summary> /// Call has disposed. /// </summary> Disposed } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/Mail/Mail_t_Group.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.Mail { #region usings using System.Collections.Generic; using System.Text; using MIME; #endregion /// <summary> /// Defined in RFC 2822 3.4. /// </summary> public class Mail_t_Group : Mail_t_Address { #region Members private readonly List<Mail_t_Mailbox> m_pList; private string m_DisplayName; #endregion #region Properties /// <summary> /// Gets or sets diplay name. Value null means not specified. /// </summary> public string DisplayName { get { return m_DisplayName; } set { m_DisplayName = value; } } /// <summary> /// Gets groiup address members collection. /// </summary> public List<Mail_t_Mailbox> Members { get { return m_pList; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="displayName">Display name. Value null means not specified.</param> public Mail_t_Group(string displayName) { m_DisplayName = displayName; m_pList = new List<Mail_t_Mailbox>(); } #endregion #region Methods /// <summary> /// Returns mailbox as string. /// </summary> /// <returns>Returns mailbox as string.</returns> public override string ToString() { return ToString(null); } /// <summary> /// Returns address as string value. /// </summary> /// <param name="wordEncoder">8-bit words ecnoder. Value null means that words are not encoded.</param> /// <returns>Returns address as string value.</returns> public override string ToString(MIME_Encoding_EncodedWord wordEncoder) { StringBuilder retVal = new StringBuilder(); if (string.IsNullOrEmpty(m_DisplayName)) { retVal.Append(":"); } else { if (MIME_Encoding_EncodedWord.MustEncode(m_DisplayName)) { retVal.Append(wordEncoder.Encode(m_DisplayName) + ":"); } else { retVal.Append(TextUtils.QuoteString(m_DisplayName) + ":"); } } for (int i = 0; i < m_pList.Count; i++) { retVal.Append(m_pList[i].ToString(wordEncoder)); if (i < (m_pList.Count - 1)) { retVal.Append(","); } } retVal.Append(";"); return retVal.ToString(); } #endregion } }<file_sep>/redistributable/Twitterizer2/Twitterizer2/Methods/Tweets/Entities/TwitterEntityCollection.cs //----------------------------------------------------------------------- // <copyright file="TwitterEntityCollection.cs" company="Patrick 'Ricky' Smith"> // This file is part of the Twitterizer library (http://www.twitterizer.net) // // Copyright (c) 2010, Patrick "Ricky" Smith (<EMAIL>) // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, are // permitted provided that the following conditions are met: // // - Redistributions of source code must retain the above copyright notice, this list // of conditions and the following disclaimer. // - Redistributions in binary form must reproduce the above copyright notice, this list // of conditions and the following disclaimer in the documentation and/or other // materials provided with the distribution. // - Neither the name of the Twitterizer nor the names of its contributors may be // used to endorse or promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. // IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, // INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT // NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // </copyright> // <author><NAME></author> // <summary>The twitter entity collection class</summary> //----------------------------------------------------------------------- using System.Collections.Generic; namespace Twitterizer.Entities { using System; using System.Linq; using System.Collections.ObjectModel; using Newtonsoft.Json; using System.Linq.Expressions; using System.Reflection; using System.Globalization; /// <summary> /// Represents multiple <see cref="Twitterizer.Entities.TwitterEntity"/> objects. /// </summary> #if !SILVERLIGHT [Serializable] #endif public class TwitterEntityCollection : Collection<TwitterEntity> { /// <summary> /// The Json converter for <see cref="TwitterEntityCollection"/> data. /// </summary> #if !SILVERLIGHT internal class Converter : JsonConverter #else public class Converter : JsonConverter #endif { /// <summary> /// Determines whether this instance can convert the specified object type. /// </summary> /// <param name="objectType">Type of the object.</param> /// <returns> /// <c>true</c> if this instance can convert the specified object type; otherwise, <c>false</c>. /// </returns> public override bool CanConvert(Type objectType) { return objectType == typeof(TwitterEntityCollection); } /// <summary> /// Reads the JSON representation of the object. /// </summary> /// <param name="reader">The <see cref="T:Newtonsoft.Json.JsonReader"/> to read from.</param> /// <param name="objectType">Type of the object.</param> /// <param name="existingValue">The existing value of object being read.</param> /// <param name="serializer">The calling serializer.</param> /// <returns>The object value.</returns> public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { TwitterEntityCollection result = existingValue as TwitterEntityCollection; if (result == null) result = new TwitterEntityCollection(); int startDepth = reader.Depth; string entityType = string.Empty; TwitterEntity entity = null; try { if (reader.TokenType == JsonToken.StartArray) reader.Read(); while (reader.Read() && reader.Depth > startDepth) { if (reader.TokenType == JsonToken.PropertyName && reader.Depth == startDepth + 1) { entityType = (string)reader.Value; continue; } switch (entityType) { case "urls": if (reader.TokenType == JsonToken.StartObject) entity = new TwitterUrlEntity(); TwitterUrlEntity tue = entity as TwitterUrlEntity; if (tue != null) { ReadFieldValue(reader, "url", entity, () => tue.Url); ReadFieldValue(reader, "display_url", entity, () => tue.DisplayUrl); ReadFieldValue(reader, "expanded_url", entity, () => tue.ExpandedUrl); } break; case "user_mentions": if (reader.TokenType == JsonToken.StartObject) entity = new TwitterMentionEntity(); TwitterMentionEntity tme = entity as TwitterMentionEntity; if (tme != null) { ReadFieldValue(reader, "screen_name", entity, () => tme.ScreenName); ReadFieldValue(reader, "name", entity, () => tme.Name); ReadFieldValue(reader, "id", entity, () => tme.UserId); } break; case "hashtags": if (reader.TokenType == JsonToken.StartObject) entity = new TwitterHashTagEntity(); TwitterHashTagEntity the = entity as TwitterHashTagEntity; if (the != null) { ReadFieldValue(reader, "text", entity, () => the.Text); } break; case "media": // Move to object start and parse the entity reader.Read(); entity = parseMediaEntity(reader); break; } // Read the indicies (for all entities except Media) if (reader.TokenType == JsonToken.PropertyName && (string)reader.Value == "indices" && entity != null) { reader.Read(); reader.Read(); entity.StartIndex = Convert.ToInt32((long)reader.Value); reader.Read(); entity.EndIndex = Convert.ToInt32((long)reader.Value); } if ((reader.TokenType == JsonToken.EndObject && entity != null) || entity is TwitterMediaEntity) { result.Add(entity); entity = null; } } } catch { } return result; } /// <summary> /// Writes the JSON representation of the object. /// </summary> /// <param name="writer">The <see cref="T:Newtonsoft.Json.JsonWriter"/> to write to.</param> /// <param name="value">The value.</param> /// <param name="serializer">The calling serializer.</param> /// <remarks>This is a best attempt to recreate the structure created by the Twitter API.</remarks> public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { TwitterEntityCollection entities = (TwitterEntityCollection)value; writer.WriteStartObject(); { WriteEntity(writer, entities.OfType<TwitterHashTagEntity>().ToList(), "hashtags", (w, e) => { w.WritePropertyName("text"); w.WriteValue(e.Text); }); WriteEntity(writer, entities.OfType<TwitterMentionEntity>().ToList(), "user_mentions", (w, e) => { w.WritePropertyName("screen_name"); w.WriteValue(e.ScreenName); w.WritePropertyName("name"); w.WriteValue(e.Name); w.WritePropertyName("id"); w.WriteValue(e.UserId); }); WriteEntity(writer, entities.OfType<TwitterUrlEntity>().ToList(), "urls", (w, e) => { w.WritePropertyName("url"); w.WriteValue(e.Url); w.WritePropertyName("display_url"); w.WriteValue(e.DisplayUrl); w.WritePropertyName("expanded_url"); w.WriteValue(e.ExpandedUrl); }); WriteEntity(writer, entities.OfType<TwitterMediaEntity>().ToList(), "media", WriteMediaEntity); writer.WriteEndObject(); } } /// <summary> /// Writes the media entity. /// </summary> /// <param name="w">The w.</param> /// <param name="e">The e.</param> private static void WriteMediaEntity(JsonWriter w, TwitterMediaEntity e) { w.WritePropertyName("type"); switch (e.MediaType) { case TwitterMediaEntity.MediaTypes.Unknown: w.WriteNull(); break; case TwitterMediaEntity.MediaTypes.Photo: w.WriteValue("photo"); break; default: break; } w.WritePropertyName("sizes"); w.WriteStartObject(); { foreach (var item in e.Sizes) { w.WritePropertyName(item.Size.ToString().ToLower()); w.WriteStartObject(); { w.WritePropertyName("h"); w.WriteValue(item.Height); w.WritePropertyName("w"); w.WriteValue(item.Width); w.WritePropertyName("resize"); w.WriteValue(item.Resize == TwitterMediaEntity.MediaSize.MediaSizeResizes.Fit ? "fit" : "crop"); w.WriteEndObject(); } } w.WriteEndObject(); } w.WritePropertyName("id"); w.WriteValue(e.Id); w.WritePropertyName("id_str"); w.WriteValue(e.IdString); w.WritePropertyName("media_url"); w.WriteValue(e.MediaUrl); w.WritePropertyName("media_url_https"); w.WriteValue(e.MediaUrlSecure); w.WritePropertyName("url"); w.WriteValue(e.Url); w.WritePropertyName("display_url"); w.WriteValue(e.DisplayUrl); w.WritePropertyName("expanded_url"); w.WriteValue(e.ExpandedUrl); } /// <summary> /// Writes an entity. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="writer">The writer.</param> /// <param name="entities">The entities.</param> /// <param name="entityName">Name of the entity.</param> /// <param name="detailsAction">The details action.</param> private static void WriteEntity<T>(JsonWriter writer, IEnumerable<T> entities, string entityName, Action<JsonWriter, T> detailsAction) where T : TwitterEntity { // Note to people reading this code: Extra brackets exist to group code by json hierarchy. You're welcome. writer.WritePropertyName(entityName); writer.WriteStartArray(); { foreach (var item in entities) { writer.WriteStartObject(); { writer.WritePropertyName("indices"); writer.WriteStartArray(); { writer.WriteValue(item.StartIndex); writer.WriteValue(item.EndIndex); writer.WriteEndArray(); } detailsAction(writer, item); writer.WriteEndObject(); } } writer.WriteEndArray(); } } /// <summary> /// Parses the media entity. /// </summary> /// <param name="reader">The reader.</param> /// <returns></returns> public TwitterMediaEntity parseMediaEntity(JsonReader reader) { try { if (reader.TokenType != JsonToken.StartObject) return null; TwitterMediaEntity entity = new TwitterMediaEntity(); int startDepth = reader.Depth; // Start looping through all of the child nodes while (reader.Read() && reader.Depth >= startDepth) { // If the current node isn't a property, skip it if (reader.TokenType != JsonToken.PropertyName) { continue; } string fieldName = reader.Value as string; if (string.IsNullOrEmpty(fieldName)) { continue; } switch (fieldName) { case "type": entity.MediaType = string.IsNullOrEmpty((string)reader.Value) ? TwitterMediaEntity.MediaTypes.Unknown : TwitterMediaEntity.MediaTypes.Photo; break; case "sizes": entity.Sizes = new List<TwitterMediaEntity.MediaSize>(); break; case "large": case "medium": case "small": case "thumb": if (reader.TokenType != JsonToken.PropertyName) { break; } TwitterMediaEntity.MediaSize newSize = new TwitterMediaEntity.MediaSize(); switch ((string)reader.Value) { case "large": newSize.Size = TwitterMediaEntity.MediaSize.MediaSizes.Large; break; case "medium": newSize.Size = TwitterMediaEntity.MediaSize.MediaSizes.Medium; break; case "small": newSize.Size = TwitterMediaEntity.MediaSize.MediaSizes.Small; break; case "thumb": newSize.Size = TwitterMediaEntity.MediaSize.MediaSizes.Thumb; break; default: break; } int sizeDepth = reader.Depth; // Loop through all of the properties of the size and read their values while (reader.Read() && sizeDepth < reader.Depth) { if (reader.TokenType != JsonToken.PropertyName) { continue; } ReadFieldValue(reader, "h", newSize, () => newSize.Height); ReadFieldValue(reader, "w", newSize, () => newSize.Width); if (reader.TokenType == JsonToken.PropertyName && (string)reader.Value == "resize") { reader.Read(); newSize.Resize = string.IsNullOrEmpty((string)reader.Value) ? TwitterMediaEntity.MediaSize.MediaSizeResizes.Unknown : ((string)reader.Value == "fit" ? TwitterMediaEntity.MediaSize.MediaSizeResizes.Fit : TwitterMediaEntity.MediaSize.MediaSizeResizes.Crop); } } entity.Sizes.Add(newSize); break; case "indices": reader.Read(); reader.Read(); entity.StartIndex = Convert.ToInt32((long)reader.Value); reader.Read(); entity.EndIndex = Convert.ToInt32((long)reader.Value); break; default: break; } ReadFieldValue(reader, "id", entity, () => entity.Id); ReadFieldValue(reader, "id_str", entity, () => entity.IdString); ReadFieldValue(reader, "media_url", entity, () => entity.MediaUrl); ReadFieldValue(reader, "media_url_https", entity, () => entity.MediaUrlSecure); ReadFieldValue(reader, "url", entity, () => entity.Url); ReadFieldValue(reader, "display_url", entity, () => entity.DisplayUrl); ReadFieldValue(reader, "expanded_url", entity, () => entity.ExpandedUrl); } return entity; } catch { return null; } } private bool ReadFieldValue<T>(JsonReader reader, string fieldName, ref T result) { try { if (reader.TokenType != JsonToken.PropertyName) return false; if ((string)reader.Value != fieldName) return false; reader.Read(); if (reader.ValueType == typeof(T)) { result = (T)reader.Value; } else { #if !SILVERLIGHT result = (T)Convert.ChangeType(reader.Value, typeof(T)); #endif #if SILVERLIGHT result = (T)Convert.ChangeType(reader.Value, typeof(T), CultureInfo.InvariantCulture); #endif } return true; } catch { return false; } } private void ReadFieldValue<TSource, TProperty>(JsonReader reader, string fieldName, TSource source, Expression<Func<TProperty>> property) where TSource : class { try { if (reader == null || source == null) { return /*false*/; } var expr = (MemberExpression)property.Body; var prop = (PropertyInfo)expr.Member; TProperty value = (TProperty)prop.GetValue(source, null); if (ReadFieldValue(reader, fieldName, ref value)) { prop.SetValue(source, value, null); return /*true*/; } return /*false*/; } catch { return /*false*/; } } } } } <file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/SMTP/Server/SMTP_Reply.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.SMTP.Server { #region usings using System; using System.Text; #endregion /// <summary> /// This class implements SMTP server reply. /// </summary> public class SMTP_Reply { #region Members private readonly string[] m_pReplyLines; private readonly int m_ReplyCode; #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="replyCode">SMTP server reply code.</param> /// <param name="replyLine">SMTP server reply line.</param> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> /// <exception cref="ArgumentNullException">Is raised when <b>replyLine</b> is null reference.</exception> public SMTP_Reply(int replyCode, string replyLine) : this(replyCode, new[] {replyLine}) { if (replyLine == null) { throw new ArgumentNullException("replyLine"); } } /// <summary> /// Default constructor. /// </summary> /// <param name="replyCode">SMTP server reply code.</param> /// <param name="replyLines">SMTP server reply line(s).</param> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> /// <exception cref="ArgumentNullException">Is raised when <b>replyLines</b> is null reference.</exception> public SMTP_Reply(int replyCode, string[] replyLines) { if (replyCode < 200 || replyCode > 599) { throw new ArgumentException("Argument 'replyCode' value must be >= 200 and <= 599.", "replyCode"); } if (replyLines == null) { throw new ArgumentNullException("replyLines"); } if (replyLines.Length == 0) { throw new ArgumentException("Argument 'replyLines' must conatin at least one line.", "replyLines"); } m_ReplyCode = replyCode; m_pReplyLines = replyLines; } #endregion #region Properties /// <summary> /// Gets SMTP server reply code. /// </summary> public int ReplyCode { get { return m_ReplyCode; } } /// <summary> /// Gets SMTP server reply lines. /// </summary> public string[] ReplyLines { get { return m_pReplyLines; } } #endregion #region Methods /// <summary> /// Returns SMTP server reply as string. /// </summary> /// <returns>Returns SMTP server reply as string.</returns> public override string ToString() { StringBuilder retVal = new StringBuilder(); for (int i = 0; i < m_pReplyLines.Length; i++) { // Last line. if (i == (m_pReplyLines.Length - 1)) { retVal.Append(m_ReplyCode + " " + m_pReplyLines[i] + "\r\n"); } else { retVal.Append(m_ReplyCode + "-" + m_pReplyLines[i] + "\r\n"); } } return retVal.ToString(); } #endregion } }<file_sep>/module/ASC.Api/ASC.Api.Community/Forums/ForumApi.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Security; using ASC.Api.Attributes; using ASC.Api.Collections; using ASC.Api.Forums; using ASC.Api.Utils; using ASC.Core; using ASC.Forum; using System; using ASC.Web.Community.Forum; using ASC.Web.Community.Forum.Resources; using ASC.Web.Studio.Utility; namespace ASC.Api.Community { //TODO: Add html decoding to some fields!!! public partial class CommunityApi { private int TenantId { get { return CoreContext.TenantManager.GetCurrentTenant().TenantId; } } private const int DefaultItemsPerPage = 100; private int CurrentPage { get { return (int)(_context.StartIndex / Count); } } private int Count { get { return (int)(_context.Count == 0 ? DefaultItemsPerPage : _context.Count); } } ///<summary> ///Returns the list of all forums created on the portal with the topic/thread titles, date of creation and update, post text and author ID and display name ///</summary> ///<short> ///Forum list ///</short> ///<returns>List of forums</returns> ///<category>Forums</category> [Read("forum")] public ForumWrapper GetForums() { List<ThreadCategory> categories; List<Thread> threads; Forum.ForumDataProvider.GetThreadCategories(TenantId, false, out categories, out threads); return new ForumWrapper(categories, threads); } ///<summary> ///Returns the number of all forums created on the portal ///</summary> ///<short> ///Forums count ///</short> ///<returns>Number of forums</returns> ///<visible>false</visible> ///<category>Forums</category> [Read("forum/count")] public int GetForumsCount() { return Forum.ForumDataProvider.GetThreadCategoriesCount(TenantId); } ///<summary> ///Returns the list of all thread topics in the forums on the portal with the thread title, date of creation and update, post text and author id and display name ///</summary> ///<short> ///Thread topics ///</short> ///<param name="threadid">Thread ID</param> ///<returns>List of topics in thread</returns> ///<category>Forums</category> [Read("forum/{threadid}")] public ForumThreadWrapperFull GetThreadTopics(int threadid) { var topicsIds = ForumDataProvider.GetTopicIDs(TenantId, threadid).Skip((int)_context.StartIndex); if (_context.Count > 0) { topicsIds = topicsIds.Take((int)_context.Count); } _context.SetDataPaginated(); return new ForumThreadWrapperFull(ForumDataProvider.GetThreadByID(TenantId, threadid).NotFoundIfNull(), ForumDataProvider.GetTopicsByIDs(TenantId, topicsIds.ToList(), true)); } ///<summary> ///Returns the list of all recently updated topics in the forums on the portal with the topic title, date of creation and update, post text and author ///</summary> ///<short> ///Last updated topics ///</short> ///<returns></returns> ///<category>Forums</category> [Read("forum/topic/recent")] public IEnumerable<ForumTopicWrapper> GetLastTopics() { var result = ForumDataProvider.GetLastUpdateTopics(TenantId, (int)_context.StartIndex, (int)_context.Count); _context.SetDataPaginated(); return result.Select(x => new ForumTopicWrapper(x)).ToSmartList(); } ///<summary> ///Returns the list of all posts in a selected thread in the forums on the portal with the thread title, date of creation and update, post text and author ID and display name ///</summary> ///<short> ///Posts ///</short> ///<param name="topicid">Topic ID</param> ///<returns>List of posts in topic</returns> ///<category>Forums</category> [Read("forum/topic/{topicid}")] public ForumTopicWrapperFull GetTopicPosts(int topicid) { //TODO: Deal with polls var postIds = ForumDataProvider.GetPostIDs(TenantId, topicid).Skip((int)_context.StartIndex); if (_context.Count > 0) { postIds = postIds.Take((int)_context.Count); } _context.SetDataPaginated(); return new ForumTopicWrapperFull(ForumDataProvider.GetTopicByID(TenantId, topicid).NotFoundIfNull(), ForumDataProvider.GetPostsByIDs(TenantId, postIds.ToList())); } ///<summary> /// Add thread to category ///</summary> ///<short> /// Add thread to category ///</short> /// <param name="categoryId">Category ID (-1 for new category)</param> /// <param name="categoryName">Category name</param> /// <param name="threadName">Thread name</param> /// <param name="threadDescription">Thread description</param> ///<returns>Added thread</returns> ///<category>Forums</category> [Create("forum")] public ForumThreadWrapper AddThreadToCategory(int categoryId, string categoryName, string threadName, string threadDescription) { categoryName = categoryName.Trim(); threadName = threadName.Trim(); threadDescription = threadDescription.Trim(); if (!ForumManager.Instance.ValidateAccessSecurityAction(ForumAction.GetAccessForumEditor, null)) { throw new Exception("Error access denied"); } if (String.IsNullOrEmpty(threadName)) { throw new Exception("Error empty thread name"); } var thread = new Thread { Title = threadName, Description = threadDescription, SortOrder = 100, CategoryID = categoryId }; if (thread.CategoryID == -1) { if (String.IsNullOrEmpty(categoryName)) { throw new Exception("Error empty category name"); } thread.CategoryID = ForumDataProvider.CreateThreadCategory(TenantId, categoryName, String.Empty, 100); } var threadId = ForumDataProvider.CreateThread(TenantId, thread.CategoryID, thread.Title, thread.Description, thread.SortOrder); thread = ForumDataProvider.GetThreadByID(TenantId, threadId); return new ForumThreadWrapper(thread); } ///<summary> /// Adds a new topic to an existing thread with a subject, content and topic type specified ///</summary> ///<short> /// Add topic to thread ///</short> /// <param name="subject">Topic subject</param> /// <param name="threadid">ID of thread to add to</param> /// <param name="content">Topic text</param> /// <param name="topicType">Type of topic</param> ///<returns>Added topic</returns> ///<category>Forums</category> [Create("forum/{threadid}")] public ForumTopicWrapperFull AddTopic(int threadid, string subject, string content, TopicType topicType) { var id = ForumDataProvider.CreateTopic(TenantId, threadid, subject, topicType); ForumDataProvider.CreatePost(TenantId, id, 0, subject, content, true, PostTextFormatter.BBCode); return GetTopicPosts(id); } ///<summary> /// Updates a topic in an existing thread changing the thread subject, making it sticky or closing it ///</summary> ///<short> /// Update topic in thread ///</short> /// <param name="topicid">ID of topic to update</param> /// <param name="subject">Subject</param> /// <param name="sticky">Is sticky</param> /// <param name="closed">Close topic</param> ///<returns>Updated topic</returns> ///<category>Forums</category> [Update("forum/topic/{topicid}")] public ForumTopicWrapperFull UpdateTopic(int topicid, string subject, bool sticky, bool closed) { ForumDataProvider.UpdateTopic(TenantId, topicid, subject, sticky, closed); return GetTopicPosts(topicid); } ///<summary> /// Adds a post to an existing topic with a post subject and content specified in the request ///</summary> ///<short> /// Add post to topic ///</short> ///<param name="topicid">Topic ID</param> ///<param name="parentPostId">Parent post ID</param> ///<param name="subject">Post subject (required)</param> ///<param name="content">Post text</param> ///<returns>New post</returns> ///<category>Forums</category> [Create("forum/topic/{topicid}")] public ForumTopicPostWrapper AddTopicPosts(int topicid, int parentPostId, string subject, string content) { var id = ForumDataProvider.CreatePost(TenantId, topicid, parentPostId, subject, content, true, PostTextFormatter.BBCode); return new ForumTopicPostWrapper(ForumDataProvider.GetPostByID(TenantId, id)); } ///<summary> /// Updates a post in an existing topic changing the post subject or/and content ///</summary> ///<short> /// Update post in topic ///</short> ///<param name="topicid">Topic ID</param> ///<param name="postid">ID of post to update</param> ///<param name="subject">Post subject (required)</param> ///<param name="content">Post text</param> ///<returns>Updated post</returns> ///<category>Forums</category> [Update("forum/topic/{topicid}/{postid}")] public ForumTopicPostWrapper UpdateTopicPosts(int topicid, int postid, string subject, string content) { ForumDataProvider.UpdatePost(TenantId, postid, subject, content, PostTextFormatter.BBCode); return new ForumTopicPostWrapper(ForumDataProvider.GetPostByID(TenantId, postid)); } ///<summary> ///Returns a list of topics matching the search query with the topic title, date of creation and update, post text and author ///</summary> ///<short> ///Search ///</short> ///<param name="query">Search query</param> ///<returns>list of topics</returns> ///<category>Forums</category> [Read("forum/@search/{query}")] public IEnumerable<ForumTopicWrapper> SearchTopics(string query) { int count; var topics = ForumDataProvider.SearchTopicsByText(TenantId, query, 0, -1, out count); return topics.Select(x => new ForumTopicWrapper(x)).ToSmartList(); } ///<summary> /// Deletes a selected post ///</summary> ///<short> /// Delete post ///</short> ///<param name="postid">Post ID</param> ///<returns></returns> ///<category>Forums</category> [Delete("forum/post/{postid}")] public ForumTopicPostWrapper DeletePost(int postid) { var post = ForumDataProvider.GetPostByID(TenantId, postid); if (post == null || !ForumManager.Settings.ForumManager.ValidateAccessSecurityAction(ForumAction.PostDelete, post)) { throw new SecurityException(ForumResource.ErrorAccessDenied); } var result = RemoveDataHelper.RemovePost(post); if(result != DeletePostResult.Successfully) throw new Exception("DeletePostResult: " + result); return new ForumTopicPostWrapper(post); } ///<summary> /// Deletes a selected topic ///</summary> ///<short> /// Delete topic ///</short> ///<param name="topicid">Topic ID</param> ///<returns></returns> ///<category>Forums</category> [Delete("forum/topic/{topicid}")] public ForumTopicWrapper DeleteTopic(int topicid) { var topic = ForumDataProvider.GetTopicByID(TenantProvider.CurrentTenantID, topicid); if (topic == null || !ForumManager.Settings.ForumManager.ValidateAccessSecurityAction(ForumAction.TopicDelete, topic)) { throw new SecurityException(ForumResource.ErrorAccessDenied); } RemoveDataHelper.RemoveTopic(topic); return new ForumTopicWrapper(topic); } ///<summary> /// Deletes a selected thread ///</summary> ///<short> /// Delete thread ///</short> ///<param name="threadid">Thread ID</param> ///<returns></returns> ///<category>Forums</category> [Delete("forum/thread/{threadid}")] public ForumThreadWrapper DeleteThread(int threadid) { var thread = ForumDataProvider.GetThreadByID(TenantProvider.CurrentTenantID, threadid); if (thread == null || !ForumManager.Instance.ValidateAccessSecurityAction(ForumAction.GetAccessForumEditor, null)) { throw new SecurityException(ForumResource.ErrorAccessDenied); } RemoveDataHelper.RemoveThread(thread); return new ForumThreadWrapper(thread); } ///<summary> /// Deletes a selected thread category ///</summary> ///<short> /// Delete category ///</short> ///<param name="categoryid">Category ID</param> ///<returns></returns> ///<category>Forums</category> [Delete("forum/category/{categoryid}")] public ForumCategoryWrapper DeleteThreadCategory(int categoryid) { List<Thread> threads; var category = ForumDataProvider.GetCategoryByID(TenantProvider.CurrentTenantID, categoryid, out threads); if (category == null || !ForumManager.Instance.ValidateAccessSecurityAction(ForumAction.GetAccessForumEditor, null)) { throw new SecurityException(ForumResource.ErrorAccessDenied); } RemoveDataHelper.RemoveThreadCategory(category); return new ForumCategoryWrapper(category, threads); } } } <file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/SIP/SIP_ValidateRequestEventArgs.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.SIP.Stack { #region usings using System; using System.Net; #endregion /// <summary> /// This class provides data for SIP_Stack.ValidateRequest event. /// </summary> public class SIP_ValidateRequestEventArgs : EventArgs { #region Members private readonly IPEndPoint m_pRemoteEndPoint; private readonly SIP_Request m_pRequest; #endregion #region Properties /// <summary> /// Gets incoming SIP request. /// </summary> public SIP_Request Request { get { return m_pRequest; } } /// <summary> /// Gets IP end point what made request. /// </summary> public IPEndPoint RemoteEndPoint { get { return m_pRemoteEndPoint; } } /// <summary> /// Gets or sets response code. Value null means SIP stack will handle it. /// </summary> public string ResponseCode { get; set; } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="request">Incoming SIP request.</param> /// <param name="remoteEndpoint">IP end point what made request.</param> public SIP_ValidateRequestEventArgs(SIP_Request request, IPEndPoint remoteEndpoint) { m_pRequest = request; m_pRemoteEndPoint = remoteEndpoint; } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/SIP/SIP_Utils.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.SIP { #region usings using System; using AUTH; using Message; using MIME; using Stack; #endregion /// <summary> /// SIP helper methods. /// </summary> public class SIP_Utils { #region Methods /// <summary> /// Parses address from SIP To: header field. /// </summary> /// <param name="to">SIP header To: value.</param> /// <returns></returns> public static string ParseAddress(string to) { try { string retVal = to; if (to.IndexOf('<') > -1 && to.IndexOf('<') < to.IndexOf('>')) { retVal = to.Substring(to.IndexOf('<') + 1, to.IndexOf('>') - to.IndexOf('<') - 1); } // Remove sip: if (retVal.IndexOf(':') > -1) { retVal = retVal.Substring(retVal.IndexOf(':') + 1).Split(':')[0]; } return retVal; } catch { throw new ArgumentException("Invalid SIP header To: '" + to + "' value !"); } } /// <summary> /// Converts URI to Request-URI by removing all not allowed Request-URI parameters from URI. /// </summary> /// <param name="uri">URI value.</param> /// <returns>Returns valid Request-URI value.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>uri</b> is null reference.</exception> public static AbsoluteUri UriToRequestUri(AbsoluteUri uri) { if (uri == null) { throw new ArgumentNullException("uri"); } if (uri is SIP_Uri) { // RFC 3261 19.1.2.(Table) // We need to strip off "method-param" and "header" URI parameters". // Currently we do it for sip or sips uri, do we need todo it for others too ? SIP_Uri sUri = (SIP_Uri) uri; sUri.Parameters.Remove("method"); sUri.Header = null; return sUri; } else { return uri; } } /// <summary> /// Gets if specified value is SIP or SIPS URI. /// </summary> /// <param name="value">Value to check.</param> /// <returns>Returns true if specified value is SIP or SIPS URI, otherwise false.</returns> public static bool IsSipOrSipsUri(string value) { try { SIP_Uri.Parse(value); return true; } catch {} return false; } /// <summary> /// Gets if specified URI is tel: or sip tel URI. There is special case when SIP URI can be tel:, /// sip:+xxxx and sip:xxx;user=phone. /// </summary> /// <param name="uri">URI to check.</param> /// <returns>Returns true if specified URI is tel: URI.</returns> public static bool IsTelUri(string uri) { uri = uri.ToLower(); try { if (uri.StartsWith("tel:")) { return true; } else if (IsSipOrSipsUri(uri)) { SIP_Uri sipUri = SIP_Uri.Parse(uri); // RFC 3398 12. If user part starts with +, it's tel: URI. if (sipUri.User.StartsWith("+")) { return true; } // RFC 3398 12. else if (sipUri.Param_User != null && sipUri.Param_User.ToLower() == "phone") { return true; } } } catch {} return false; } /// <summary> /// Gets specified realm SIP proxy credentials. Returns null if none exists for specified realm. /// </summary> /// <param name="request">SIP reques.</param> /// <param name="realm">Realm(domain).</param> /// <returns>Returns specified realm credentials or null if none.</returns> public static SIP_t_Credentials GetCredentials(SIP_Request request, string realm) { foreach ( SIP_SingleValueHF<SIP_t_Credentials> authorization in request.ProxyAuthorization.HeaderFields) { if (authorization.ValueX.Method.ToLower() == "digest") { Auth_HttpDigest authDigest = new Auth_HttpDigest(authorization.ValueX.AuthData, request.RequestLine.Method); if (authDigest.Realm.ToLower() == realm.ToLower()) { return authorization.ValueX; } } } return null; } /// <summary> /// Gets is specified option tags constains specified option tag. /// </summary> /// <param name="tags">Option tags.</param> /// <param name="tag">Option tag to check.</param> /// <returns>Returns true if specified option tag exists.</returns> public static bool ContainsOptionTag(SIP_t_OptionTag[] tags, string tag) { foreach (SIP_t_OptionTag t in tags) { if (t.OptionTag.ToLower() == tag) { return true; } } return false; } /// <summary> /// Gets if specified method can establish dialog. /// </summary> /// <param name="method">SIP method.</param> /// <returns>Returns true if specified SIP method can establish dialog, otherwise false.</returns> /// <exception cref="ArgumentException">Is raised when invalid value is passed.</exception> public static bool MethodCanEstablishDialog(string method) { if (string.IsNullOrEmpty(method)) { throw new ArgumentException("Argument 'method' value can't be null or empty !"); } method = method.ToUpper(); if (method == SIP_Methods.INVITE) { return true; } else if (method == SIP_Methods.SUBSCRIBE) { return true; } else if (method == SIP_Methods.REFER) { return true; } return false; } /// <summary> /// Creates tag for tag header filed. For example From:/To: tag value. /// </summary> /// <returns>Returns tag string.</returns> public static string CreateTag() { return Guid.NewGuid().ToString().Replace("-", "").Substring(8); } /// <summary> /// Gets if the specified transport is reliable transport. /// </summary> /// <param name="transport">SIP transport.</param> /// <returns>Returns if specified transport is reliable.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>transport</b> is null reference.</exception> public static bool IsReliableTransport(string transport) { if (transport == null) { throw new ArgumentNullException("transport"); } if (transport.ToUpper() == SIP_Transport.TCP) { return true; } else if (transport.ToUpper() == SIP_Transport.TLS) { return true; } else { return false; } } /// <summary> /// Gets if the specified value is "token". /// </summary> /// <param name="value">Value to check.</param> /// <returns>Returns true if specified valu is token, otherwise false.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>value</b> is null reference.</exception> public static bool IsToken(string value) { if (value == null) { throw new ArgumentNullException("value"); } return MIME_Reader.IsToken(value); } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/SMTP/Server/old/ValidateMailboxSize_EventArgs.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; namespace LumiSoft.Net.SMTP.Server { /// <summary> /// Provides data for the ValidateMailboxSize event. /// </summary> public class ValidateMailboxSize_EventArgs { private SMTP_Session m_pSession = null; private string m_eAddress = ""; private long m_MsgSize = 0; private bool m_IsValid = true; /// <summary> /// Default constructor. /// </summary> /// <param name="session">Reference to smtp session.</param> /// <param name="eAddress">Email address of recipient.</param> /// <param name="messageSize">Message size.</param> public ValidateMailboxSize_EventArgs(SMTP_Session session,string eAddress,long messageSize) { m_pSession = session; m_eAddress = eAddress; m_MsgSize = messageSize; } #region Properties Implementation /// <summary> /// Gets reference to smtp session. /// </summary> public SMTP_Session Session { get{ return m_pSession; } } /// <summary> /// Email address which mailbox size to check. /// </summary> public string eAddress { get{ return m_eAddress; } } /// <summary> /// Message size.NOTE: value 0 means that size is unknown. /// </summary> public long MessageSize { get{ return m_MsgSize; } } /// <summary> /// Gets or sets if mailbox size is valid. /// </summary> public bool IsValid { get{ return m_IsValid; } set{ m_IsValid = value; } } // public SMTP_Session aa // { // get{ return null; } // } #endregion } } <file_sep>/web/studio/ASC.Web.Studio/UserControls/Management/SingleSignOnSettings/SingleSignOnSettings.ascx.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Web; using System.Web.UI; using AjaxPro; using ASC.Core; using ASC.Web.Studio.Core; using ASC.Web.Studio.Utility; namespace ASC.Web.Studio.UserControls.Management.SingleSignOnSettings { //TODO: Remove this or re-write like in Control Panel? [ManagementControl(ManagementType.PortalSecurity, ManagementType.SingleSignOnSettings, Location, SortOrder = 100)] [AjaxNamespace("SsoSettingsController")] public partial class SingleSignOnSettings : UserControl { protected SsoSettingsV2 Settings { get; private set; } protected const string Location = "~/UserControls/Management/SingleSignOnSettings/SingleSignOnSettings.ascx"; protected string HelpLink { get; set; } protected void Page_Load(object sender, EventArgs e) { if (CoreContext.Configuration.Standalone || !SetupInfo.IsVisibleSettings(ManagementType.SingleSignOnSettings.ToString())) { Response.Redirect(CommonLinkUtility.GetDefault(), true); return; } AjaxPro.Utility.RegisterTypeForAjax(typeof(SingleSignOnSettings), Page); Page.RegisterBodyScripts("~/UserControls/Management/SingleSignOnSettings/js/singlesignonsettings.js"); Settings = SsoSettingsV2.Load(); HelpLink = CommonLinkUtility.GetHelpLink(); } } }<file_sep>/module/ASC.Socket.IO/app/controllers/index.js module.exports = (counters, chat, voip, files) => { const router = require('express').Router(), bodyParser = require('body-parser'), authService = require('../middleware/authService.js')(); router.use(bodyParser.json()); router.use(bodyParser.urlencoded({ extended: false })); router.use(require('cookie-parser')()); router.use((req, res, next) => { if (!authService(req)) { res.sendStatus(403); return; } next(); }); router .use("/counters", require(`./counters.js`)(counters)) .use("/mail", require(`./mail.js`)(counters)) .use("/chat", require(`./chat.js`)(chat)) .use("/voip", require(`./voip.js`)(voip)) .use("/files", require(`./files.js`)(files)); return router; }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/ServersCore/commonDelegates.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net { /// <summary> /// Represent the method what will handle Error event. /// </summary> /// <param name="sender">Delegate caller.</param> /// <param name="e">Event data.</param> public delegate void ErrorEventHandler(object sender, Error_EventArgs e); /// <summary> /// To be supplied. /// </summary> public delegate void LogEventHandler(object sender, Log_EventArgs e); /// <summary> /// Represents the method that will handle the <see href="LumiSoftMailServerSMTPSMTP_ServerValidateIPAddressFieldOrEvent.html">SMTP_Server.ValidateIPAddress</see> and <see href="LumiSoftMailServerPOP3POP3_ServerValidateIPAddressFieldOrEvent.html">POP3_Server.ValidateIPAddress</see>event. /// </summary> /// <param name="sender">The source of the event. </param> /// <param name="e">A <see href="LumiSoftMailServerValidateIP_EventArgs.html">ValidateIP_EventArgs</see> that contains the event data.</param> public delegate void ValidateIPHandler(object sender, ValidateIP_EventArgs e); }<file_sep>/web/studio/ASC.Web.Studio/UserControls/Management/TariffSettings/TariffUsage.ascx.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections.Generic; using System.Configuration; using System.Globalization; using System.Linq; using System.Threading; using System.Web; using System.Web.UI; using AjaxPro; using ASC.Common.Logging; using ASC.Core; using ASC.Core.Billing; using ASC.Core.Tenants; using ASC.Geolocation; using ASC.Web.Core; using ASC.Web.Studio.Core; using ASC.Web.Studio.Core.Notify; using ASC.Web.Studio.UserControls.Statistics; using ASC.Web.Studio.Utility; using PhoneNumbers; using Resources; namespace ASC.Web.Studio.UserControls.Management { [AjaxNamespace("TariffUsageController")] public partial class TariffUsage : UserControl { public static string Location { get { return "~/UserControls/Management/TariffSettings/TariffUsage.ascx"; } } protected Dictionary<string, bool> ListStarRemark = new Dictionary<string, bool>(); protected int UsersCount; protected long UsedSize; protected Tariff CurrentTariff; protected TenantQuota CurrentQuota; protected bool MonthIsDisable; protected bool YearIsDisable; protected int MinActiveUser; protected RegionInfo RegionDefault = new RegionInfo("US"); protected RegionInfo CurrentRegion; protected string PhoneCountry = "US"; protected List<RegionInfo> Regions = new List<RegionInfo>(); protected bool InRuble { get { return "RU".Equals(CurrentRegion.Name); } } protected bool InEuro { get { return "EUR".Equals(CurrentRegion.ISOCurrencySymbol); } } protected decimal[] PricesPerUser { get { return InEuro ? new[] { 4.25m, 2.40m, 1.60m } : new[] { 5.0m, 3.0m, 2.0m }; } } protected decimal[] FakePrices { get { return InEuro ? new[] { 9.0m, 18.0m } : new[] { 10.0m, 20.0m }; } } private string _currencyFormat = "{currency}{price}"; private IDictionary<string, IEnumerable<Tuple<string, decimal>>> _priceInfo; private IEnumerable<TenantQuota> _quotaList; protected List<TenantQuota> QuotasYear; private TenantQuota _quotaForDisplay; protected TenantQuota QuotaForDisplay { get { if (_quotaForDisplay != null) return _quotaForDisplay; TenantQuota quota = null; if (CurrentQuota.Trial || CurrentQuota.Free || !CurrentQuota.Visible) { var rightQuotaId = TenantExtra.GetRightQuotaId(); quota = _quotaList.FirstOrDefault(q => q.Id == rightQuotaId); } _quotaForDisplay = quota ?? CurrentQuota; return _quotaForDisplay; } } protected bool PeopleModuleAvailable { get { var peopleProduct = WebItemManager.Instance[WebItemManager.PeopleProductID]; return peopleProduct != null && !peopleProduct.IsDisabled(); } } protected void Page_Load(object sender, EventArgs e) { Page .RegisterBodyScripts("~/UserControls/Management/TariffSettings/js/tariffusage.js", "~/js/asc/plugins/countries.js", "~/js/asc/plugins/phonecontroller.js") .RegisterStyle( "~/skins/default/phonecontroller.css", "~/UserControls/Management/TariffSettings/css/tariff.less", "~/UserControls/Management/TariffSettings/css/tariffusage.less") .RegisterClientScript(new CountriesResources()); CurrentRegion = RegionDefault; Regions.Add(CurrentRegion); UsersCount = TenantStatisticsProvider.GetUsersCount(); UsedSize = TenantStatisticsProvider.GetUsedSize(); CurrentTariff = TenantExtra.GetCurrentTariff(); CurrentQuota = TenantExtra.GetTenantQuota(); if (_quotaList == null || !_quotaList.Any()) { _quotaList = TenantExtra.GetTenantQuotas(); } else if (!CurrentQuota.Trial) { CurrentQuota = _quotaList.FirstOrDefault(q => q.Id == CurrentQuota.Id) ?? CurrentQuota; } _quotaList = _quotaList.OrderBy(r => r.ActiveUsers).ToList().Where(r => !r.Trial); QuotasYear = _quotaList.Where(r => r.Year).ToList(); MonthIsDisable = !CurrentQuota.Free && (CurrentQuota.Year || CurrentQuota.Year3) && CurrentTariff.State == TariffState.Paid; YearIsDisable = !CurrentQuota.Free && CurrentQuota.Year3 && CurrentTariff.State == TariffState.Paid; var minYearQuota = QuotasYear.FirstOrDefault(q => q.ActiveUsers >= UsersCount && q.MaxTotalSize >= UsedSize); MinActiveUser = minYearQuota != null ? minYearQuota.ActiveUsers : (QuotasYear.Count > 0 ? QuotasYear.Last().ActiveUsers : 0 + 1); downgradeInfoContainer.Options.IsPopup = true; AjaxPro.Utility.RegisterTypeForAjax(GetType()); CurrencyCheck(); } private void CurrencyCheck() { var findRegion = FindRegionInfo(); CurrentRegion = findRegion ?? CurrentRegion; PhoneCountry = (findRegion ?? new RegionInfo(Thread.CurrentThread.CurrentCulture.LCID)).TwoLetterISORegionName; if (!CurrentRegion.Equals(RegionDefault)) { Regions.Add(CurrentRegion); } var requestCur = Request["cur"]; if (!string.IsNullOrEmpty(requestCur)) { try { CurrentRegion = new RegionInfo(requestCur); if (!Regions.Contains(CurrentRegion)) { Regions.Add(CurrentRegion); } } catch { } } _priceInfo = CoreContext.TenantManager.GetProductPriceInfo(false); if (!_priceInfo.Values.Any(value => value.Any(item => item.Item1 == CurrentRegion.ISOCurrencySymbol))) { Regions.Remove(CurrentRegion); CurrentRegion = RegionDefault; } if (InRuble) { _currencyFormat = "{price}{currency}"; SetStar(string.Format(Resource.TariffsCurrencyRu, SetupInfo.ExchangeRateRuble)); } } private static RegionInfo FindRegionInfo() { RegionInfo ri = null; var ownerId = CoreContext.TenantManager.GetCurrentTenant().OwnerId; var owner = CoreContext.UserManager.GetUsers(ownerId); if (!string.IsNullOrEmpty(owner.MobilePhone)) { try { var phoneUtil = PhoneNumberUtil.GetInstance(); var number = phoneUtil.Parse("+" + owner.MobilePhone.TrimStart('+'), "en-US"); var regionCode = phoneUtil.GetRegionCodeForNumber(number); if (!string.IsNullOrEmpty(regionCode)) { ri = new RegionInfo(regionCode); } } catch (Exception err) { LogManager.GetLogger("ASC.Web.Tariff").WarnFormat("Can not find country by phone {0}: {1}", owner.MobilePhone, err); } } if (ri == null) { var geoinfo = new GeolocationHelper("teamlabsite").GetIPGeolocationFromHttpContext(); if (!string.IsNullOrEmpty(geoinfo.Key)) { try { ri = new RegionInfo(geoinfo.Key); } catch (Exception) { // ignore } } } return ri; } protected string TariffDescription() { if (CurrentQuota.Trial) { if (CurrentTariff.State == TariffState.Trial) { return "<b>" + Resource.TariffTrial + "</b> " + (CurrentTariff.DueDate.Date != DateTime.MaxValue.Date ? string.Format(Resource.TariffExpiredDate, CurrentTariff.DueDate.Date.ToLongDateString()) : "") + "<br />" + Resource.TariffChooseLabel; } return String.Format(Resource.TariffTrialOverdue.HtmlEncode(), "<span class='tarifff-marked'>", "</span>", "<br />", string.Empty, string.Empty); } if (CurrentQuota.Free) { return "<b>" + Resource.TariffFree + "</b><br />" + Resource.TariffChooseLabel; } if (CurrentTariff.State == TariffState.Paid && CurrentTariff.DueDate.Date >= DateTime.Today) { if (CurrentQuota.NonProfit) { return "<b>" + UserControlsCommonResource.TariffNonProfit + "</b>"; } var str = "<b>" + String.Format(UserControlsCommonResource.TariffPaidPlan, TenantExtra.GetPrevUsersCount(CurrentQuota), CurrentQuota.ActiveUsers) + "</b> "; if (CurrentTariff.DueDate.Date != DateTime.MaxValue.Date) str += string.Format(Resource.TariffExpiredDate, CurrentTariff.DueDate.Date.ToLongDateString()); if (CurrentTariff.Autorenewal) return str; str += "<br />" + Resource.TariffCanProlong; return str; } return String.Format(UserControlsCommonResource.TariffOverduePlan.HtmlEncode(), TenantExtra.GetPrevUsersCount(CurrentQuota), CurrentQuota.ActiveUsers, "<span class='tariff-marked'>", "</span>", "<br />"); } protected TenantQuota GetQuotaMonth(TenantQuota quota) { return _quotaList.FirstOrDefault(r => r.ActiveUsers == quota.ActiveUsers && (!r.Year || quota.Free) && !r.Year3); } protected TenantQuota GetQuotaYear3(TenantQuota quota) { return _quotaList.FirstOrDefault(r => r.ActiveUsers == quota.ActiveUsers && r.Year3); } protected Tuple<string, string, string> GetBuyAttr(TenantQuota quota) { var cssList = new List<string>(); var getHref = true; var text = Resource.TariffButtonBuy; if (quota != null) { cssList.Add(CurrentTariff.State >= TariffState.NotPaid ? "red" : "blue"); if (quota.ActiveUsers < UsersCount || quota.MaxTotalSize < UsedSize) { cssList.Add("disable"); getHref = false; } else if (Equals(quota.Id, CurrentQuota.Id)) { text = Resource.TariffButtonExtend; if (!CurrentTariff.Prolongable) { cssList.Add("disable"); getHref = false; } else if (CurrentTariff.Autorenewal) { cssList.Add("disable"); getHref = false; text = Resource.TariffEnabledAutorenew + SetStar(Resource.TariffRemarkProlongEnable); } } else if (CurrentTariff.Prolongable) { text = Resource.TariffButtonBuy + SetStar(Resource.TariffRemarkProlongDisable); } else if (CurrentTariff.State == TariffState.Paid && quota.ActiveUsers < CurrentQuota.ActiveUsers) { cssList.Add("disable"); getHref = false; text = Resource.TariffButtonBuy + SetStar(CurrentQuota.Year3 ? Resource.TariffRemarkDisabledYear : Resource.TariffRemarkDisabledMonth); } if (!quota.Year3) { if (quota.Year && YearIsDisable || !quota.Year && MonthIsDisable) { cssList.Add("disable"); getHref = false; text = Resource.TariffButtonBuy; } } } else { cssList.Add("disable"); getHref = false; } var href = getHref ? GetShoppingUri(quota) : string.Empty; var cssClass = string.Join(" ", cssList.Distinct()); var result = new Tuple<string, string, string>(cssClass, href, text); return result; } private string GetShoppingUri(TenantQuota quota) { var uri = string.Empty; if (quota != null) { var ownerId = CoreContext.TenantManager.GetCurrentTenant().OwnerId.ToString(); var link = CoreContext.PaymentManager.GetShoppingUri(quota.Id, true, null, CurrentRegion.ISOCurrencySymbol, Thread.CurrentThread.CurrentCulture.TwoLetterISOLanguageName, ownerId); if (link == null) { LogManager.GetLogger("ASC.Web.Billing").Error(string.Format("GetShoppingUri return null for tenant {0} and quota {1}", TenantProvider.CurrentTenantID, quota.Id)); } else { uri = link.ToString(); } } return uri; } protected string SetStar(string starType, bool withHighlight = false) { if (!ListStarRemark.Keys.Contains(starType)) { ListStarRemark.Add(starType, withHighlight); } return GetStar(starType); } protected string GetStar(string starType) { if (!ListStarRemark.Keys.Contains(starType)) { return null; } var result = string.Empty; for (var i = 0; i < ListStarRemark.Keys.ToList().IndexOf(starType) + 1; i++) { result += "*"; } return result; } protected string GetRemarks() { var result = string.Empty; if (QuotasYear.Count == 0) return result; foreach (var starType in ListStarRemark) { if (!string.IsNullOrEmpty(result)) result += "<br />"; if (starType.Value) result += "<span class=\"tariff-remark-highlight\">"; result += GetStar(starType.Key) + " "; result += starType.Key; if (starType.Value) result += "</span>"; } return result; } protected string GetSaleDate() { DateTime date; if (!DateTime.TryParse(ConfigurationManagerExtension.AppSettings["web.payment-sale"], out date)) { date = new DateTime(DateTime.UtcNow.Year, DateTime.UtcNow.Month, 1).AddMonths(1).AddDays(-1); } return date.ToString(Thread.CurrentThread.CurrentCulture.DateTimeFormat.MonthDayPattern); } protected string GetPriceString(decimal price, bool rubleRate = true, string currencySymbol = null) { if (rubleRate && InRuble) { price = price * SetupInfo.ExchangeRateRuble; } var priceString = InEuro && Math.Truncate(price) != price ? price.ToString(CultureInfo.InvariantCulture) : ((int)price).ToString(CultureInfo.InvariantCulture); return _currencyFormat .Replace("{currency}", "<span class='tariff-price-cur'>" + (currencySymbol ?? CurrentRegion.CurrencySymbol) + "</span>") .Replace("{price}", priceString); } protected string GetPriceString(TenantQuota quota) { if (!string.IsNullOrEmpty(quota.AvangateId) && _priceInfo.ContainsKey(quota.AvangateId)) { var prices = _priceInfo[quota.AvangateId]; var price = prices.FirstOrDefault(p => p.Item1 == CurrentRegion.ISOCurrencySymbol); if (price != null) { return GetPriceString(price.Item2, false); } return GetPriceString(quota.Price, false, RegionDefault.CurrencySymbol); } return GetPriceString(quota.Price); } protected decimal GetPrice(TenantQuota quota) { if (!string.IsNullOrEmpty(quota.AvangateId) && _priceInfo.ContainsKey(quota.AvangateId)) { var prices = _priceInfo[quota.AvangateId]; var price = prices.FirstOrDefault(p => p.Item1 == CurrentRegion.ISOCurrencySymbol); if (price != null) { return price.Item2; } return quota.Price; } return quota.Price; } protected decimal GetSaleValue(decimal priceMonth, TenantQuota quota) { var price = GetPrice(quota); var period = quota.Year ? 12 : 36; return priceMonth * period - price; } protected string GetPerUserPrice(TenantQuota quota) { var price = PricesPerUser[quota == null ? 0 : quota.Year ? 1 : quota.Year3 ? 2 : 0]; return GetPriceString(price, InRuble); } [AjaxMethod] public void RequestTariff(string fname, string lname, string title, string email, string phone, string ctitle, string csize, string site, string message) { var key = HttpContext.Current.Request.UserHostAddress + "requesttariff"; var count = Convert.ToInt32(HttpContext.Current.Cache[key]); if (2 < count) { throw new ArgumentOutOfRangeException("Messages count", "Rate limit exceeded."); } HttpContext.Current.Cache.Insert(key, ++count, null, System.Web.Caching.Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(2)); StudioNotifyService.Instance.SendRequestTariff(false, fname, lname, title, email, phone, ctitle, csize, site, message); } } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/MIME/MIME_Utils.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.MIME { #region usings using System; using System.Globalization; #endregion /// <summary> /// Provides MIME related utility methods. /// </summary> public class MIME_Utils { #region Methods /// <summary> /// Converts date to RFC 2822 date time string. /// </summary> /// <param name="dateTime">Date time value to convert..</param> /// <returns>Returns RFC 2822 date time string.</returns> public static string DateTimeToRfc2822(DateTime dateTime) { return dateTime.ToString("ddd, dd MMM yyyy HH':'mm':'ss ", DateTimeFormatInfo.InvariantInfo) + dateTime.ToString("zzz").Replace(":", ""); } /// <summary> /// Parses RFC 2822 date-time from the specified value. /// </summary> /// <param name="value">RFC 2822 date-time string value.</param> /// <returns>Returns parsed datetime value.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>value</b> is null.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> public static DateTime ParseRfc2822DateTime(string value) { if (value == null) { throw new ArgumentNullException(value); } //Try parse dt DateTime parsedTime; if (DateTime.TryParse(value, out parsedTime)) { return parsedTime; } /* RFC 2822 3. * date-time = [ day-of-week "," ] date FWS time [CFWS] * day-of-week = ([FWS] day-name) / obs-day-of-week * day-name = "Mon" / "Tue" / "Wed" / "Thu" / "Fri" / "Sat" / "Sun" * date = day month year * year = 4*DIGIT / obs-year * month = (FWS month-name FWS) / obs-month * month-name = "Jan" / "Feb" / "Mar" / "Apr" / "May" / "Jun" / "Jul" / "Aug" / "Sep" / "Oct" / "Nov" / "Dec" * day = ([FWS] 1*2DIGIT) / obs-day * time = time-of-day FWS zone * time-of-day = hour ":" minute [ ":" second ] * hour = 2DIGIT / obs-hour * minute = 2DIGIT / obs-minute * second = 2DIGIT / obs-second * zone = (( "+" / "-" ) 4DIGIT) / obs-zone * * The date and time-of-day SHOULD express local time. */ try { MIME_Reader r = new MIME_Reader(value); string v = r.Atom(); // Skip optional [ day-of-week "," ] and read "day". if (v.Length == 3) { r.Char(true); v = r.Atom(); } int day = Convert.ToInt32(v); v = r.Atom().ToLower(); int month = 1; if (v == "jan") { month = 1; } else if (v == "feb") { month = 2; } else if (v == "mar") { month = 3; } else if (v == "apr") { month = 4; } else if (v == "may") { month = 5; } else if (v == "jun") { month = 6; } else if (v == "jul") { month = 7; } else if (v == "aug") { month = 8; } else if (v == "sep") { month = 9; } else if (v == "oct") { month = 10; } else if (v == "nov") { month = 11; } else if (v == "dec") { month = 12; } else { throw new ArgumentException("Invalid month-name value '" + value + "'."); } int year = Convert.ToInt32(r.Atom()); int hour = Convert.ToInt32(r.Atom()); r.Char(true); int minute = Convert.ToInt32(r.Atom()); int second = 0; // We have optional "second". if (r.Peek(true) == ':') { r.Char(true); second = Convert.ToInt32(r.Atom()); } int timeZoneMinutes = 0; v = r.Atom(); // We have RFC 2822 date. For example: +2000. if (v[0] == '+' || v[0] == '-') { if (v[0] == '+') { timeZoneMinutes = (Convert.ToInt32(v.Substring(1, 2))*60 + Convert.ToInt32(v.Substring(3, 2))); } else { timeZoneMinutes = -(Convert.ToInt32(v.Substring(1, 2))*60 + Convert.ToInt32(v.Substring(3, 2))); } } // We have RFC 822 date with abbrevated time zone name. For example: GMT. else { v = v.ToUpper(); #region time zones // Alpha Time Zone (military). if (v == "A") { timeZoneMinutes = ((01*60) + 00); } // Australian Central Daylight Time. else if (v == "ACDT") { timeZoneMinutes = ((10*60) + 30); } // Australian Central Standard Time. else if (v == "ACST") { timeZoneMinutes = ((09*60) + 30); } // Atlantic Daylight Time. else if (v == "ADT") { timeZoneMinutes = -((03*60) + 00); } // Australian Eastern Daylight Time. else if (v == "AEDT") { timeZoneMinutes = ((11*60) + 00); } // Australian Eastern Standard Time. else if (v == "AEST") { timeZoneMinutes = ((10*60) + 00); } // Alaska Daylight Time. else if (v == "AKDT") { timeZoneMinutes = -((08*60) + 00); } // Alaska Standard Time. else if (v == "AKST") { timeZoneMinutes = -((09*60) + 00); } // Atlantic Standard Time. else if (v == "AST") { timeZoneMinutes = -((04*60) + 00); } // Australian Western Daylight Time. else if (v == "AWDT") { timeZoneMinutes = ((09*60) + 00); } // Australian Western Standard Time. else if (v == "AWST") { timeZoneMinutes = ((08*60) + 00); } // Bravo Time Zone (millitary). else if (v == "B") { timeZoneMinutes = ((02*60) + 00); } // British Summer Time. else if (v == "BST") { timeZoneMinutes = ((01*60) + 00); } // Charlie Time Zone (millitary). else if (v == "C") { timeZoneMinutes = ((03*60) + 00); } // Central Daylight Time. else if (v == "CDT") { timeZoneMinutes = -((05*60) + 00); } // Central European Daylight Time. else if (v == "CEDT") { timeZoneMinutes = ((02*60) + 00); } // Central European Summer Time. else if (v == "CEST") { timeZoneMinutes = ((02*60) + 00); } // Central European Time. else if (v == "CET") { timeZoneMinutes = ((01*60) + 00); } // Central Standard Time. else if (v == "CST") { timeZoneMinutes = -((06*60) + 00); } // Christmas Island Time. else if (v == "CXT") { timeZoneMinutes = ((01*60) + 00); } // Delta Time Zone (military). else if (v == "D") { timeZoneMinutes = ((04*60) + 00); } // Echo Time Zone (military). else if (v == "E") { timeZoneMinutes = ((05*60) + 00); } // Eastern Daylight Time. else if (v == "EDT") { timeZoneMinutes = -((04*60) + 00); } // Eastern European Daylight Time. else if (v == "EEDT") { timeZoneMinutes = ((03*60) + 00); } // Eastern European Summer Time. else if (v == "EEST") { timeZoneMinutes = ((03*60) + 00); } // Eastern European Time. else if (v == "EET") { timeZoneMinutes = ((02*60) + 00); } // Eastern Standard Time. else if (v == "EST") { timeZoneMinutes = -((05*60) + 00); } // Foxtrot Time Zone (military). else if (v == "F") { timeZoneMinutes = (06*60 + 00); } // Golf Time Zone (military). else if (v == "G") { timeZoneMinutes = ((07*60) + 00); } // Greenwich Mean Time. else if (v == "GMT") { timeZoneMinutes = 0000; } // Hotel Time Zone (military). else if (v == "H") { timeZoneMinutes = ((08*60) + 00); } // India Time Zone (military). else if (v == "I") { timeZoneMinutes = ((09*60) + 00); } // Irish Summer Time. else if (v == "IST") { timeZoneMinutes = ((01*60) + 00); } // Kilo Time Zone (millitary). else if (v == "K") { timeZoneMinutes = ((10*60) + 00); } // Lima Time Zone (millitary). else if (v == "L") { timeZoneMinutes = ((11*60) + 00); } // Mike Time Zone (millitary). else if (v == "M") { timeZoneMinutes = ((12*60) + 00); } // Mountain Daylight Time. else if (v == "MDT") { timeZoneMinutes = -((06*60) + 00); } // Mountain Standard Time. else if (v == "MST") { timeZoneMinutes = -((07*60) + 00); } // November Time Zone (military). else if (v == "N") { timeZoneMinutes = -((01*60) + 00); } // Newfoundland Daylight Time. else if (v == "NDT") { timeZoneMinutes = -((02*60) + 30); } // Norfolk (Island) Time. else if (v == "NFT") { timeZoneMinutes = ((11*60) + 30); } // Newfoundland Standard Time. else if (v == "NST") { timeZoneMinutes = -((03*60) + 30); } // Oscar Time Zone (military). else if (v == "O") { timeZoneMinutes = -((02*60) + 00); } // Papa Time Zone (military). else if (v == "P") { timeZoneMinutes = -((03*60) + 00); } // Pacific Daylight Time. else if (v == "PDT") { timeZoneMinutes = -((07*60) + 00); } // Pacific Standard Time. else if (v == "PST") { timeZoneMinutes = -((08*60) + 00); } // Quebec Time Zone (military). else if (v == "Q") { timeZoneMinutes = -((04*60) + 00); } // Romeo Time Zone (military). else if (v == "R") { timeZoneMinutes = -((05*60) + 00); } // Sierra Time Zone (military). else if (v == "S") { timeZoneMinutes = -((06*60) + 00); } // Tango Time Zone (military). else if (v == "T") { timeZoneMinutes = -((07*60) + 00); } // Uniform Time Zone (military). else if (v == "") { timeZoneMinutes = -((08*60) + 00); } // Coordinated Universal Time. else if (v == "UTC") { timeZoneMinutes = 0000; } // Victor Time Zone (militray). else if (v == "V") { timeZoneMinutes = -((09*60) + 00); } // Whiskey Time Zone (military). else if (v == "W") { timeZoneMinutes = -((10*60) + 00); } // Western European Daylight Time. else if (v == "WEDT") { timeZoneMinutes = ((01*60) + 00); } // Western European Summer Time. else if (v == "WEST") { timeZoneMinutes = ((01*60) + 00); } // Western European Time. else if (v == "WET") { timeZoneMinutes = 0000; } // Western Standard Time. else if (v == "WST") { timeZoneMinutes = ((08*60) + 00); } // X-ray Time Zone (military). else if (v == "X") { timeZoneMinutes = -((11*60) + 00); } // Yankee Time Zone (military). else if (v == "Y") { timeZoneMinutes = -((12*60) + 00); } // Zulu Time Zone (military). else if (v == "Z") { timeZoneMinutes = 0000; } #endregion } // Convert time to UTC and then back to local. DateTime timeUTC = new DateTime(year, month, day, hour, minute, second).AddMinutes(-(timeZoneMinutes)); return new DateTime(timeUTC.Year, timeUTC.Month, timeUTC.Day, timeUTC.Hour, timeUTC.Minute, timeUTC.Second, DateTimeKind.Utc).ToLocalTime(); } catch (Exception x) { string dymmy = x.Message; throw new ArgumentException("Argumnet 'value' value '" + value + "' is not valid RFC 822/2822 date-time string."); } } /// <summary> /// Unfolds folded header field. /// </summary> /// <param name="value">Header field.</param> /// <returns>Returns unfolded header field.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>value</b> is null reference.</exception> public static string UnfoldHeader(string value) { if (value == null) { throw new ArgumentNullException("value"); } /* RFC 2822 2.2.3 Long Header Fields. The process of moving from this folded multiple-line representation of a header field to its single line representation is called "unfolding". Unfolding is accomplished by simply removing any CRLF that is immediately followed by WSP. */ return value.Replace("\r\n", ""); } /// <summary> /// Creates Rfc 2822 3.6.4 message-id. Syntax: '&lt;' id-left '@' id-right '&gt;'. /// </summary> /// <returns></returns> public static string CreateMessageID() { return "<" + Guid.NewGuid().ToString().Replace("-", "").Substring(16) + "@" + Guid.NewGuid().ToString().Replace("-", "").Substring(16) + ">"; } #endregion } }<file_sep>/module/ASC.Thrdparty/ASC.FederatedLogin/LoginProviders/YahooLoginProvider.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections.Generic; using System.Web; using ASC.FederatedLogin.Profile; namespace ASC.FederatedLogin.LoginProviders { public class YahooLoginProvider : BaseLoginProvider<YahooLoginProvider> { public const string YahooUrlUserGuid = "https://social.yahooapis.com/v1/me/guid"; public const string YahooUrlContactsFormat = "https://social.yahooapis.com/v1/user/{0}/contacts"; public override string CodeUrl { get { return "https://api.login.yahoo.com/oauth2/request_auth"; } } public override string AccessTokenUrl { get { return "https://api.login.yahoo.com/oauth2/get_token"; } } public override string RedirectUri { get { return this["yahooRedirectUrl"]; } } public override string ClientID { get { return this["yahooClientId"]; } } public override string ClientSecret { get { return this["yahooClientSecret"]; } } public override string Scopes { get { return "sdct-r"; } } public YahooLoginProvider() { } public YahooLoginProvider(string name, int order, Dictionary<string, string> props, Dictionary<string, string> additional = null) : base(name, order, props, additional) { } public OAuth20Token Auth(HttpContext context) { return Auth(context, Scopes); } public override LoginProfile GetLoginProfile(string accessToken) { throw new NotImplementedException(); } } } <file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/SIP/Message/SIP_WarningCodes.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.SIP.Message { /// <summary> /// SIP Warning Codes. Defined in RFC 3261 27.2. /// </summary> public class SIP_WarningCodes { #region Members /// <summary> /// One or more network protocols contained in the session description are not available. /// </summary> public const int x300_Incompatible_network_protocol = 300; /// <summary> /// One or more network address formats contained in the session description are not available. /// </summary> public const int x301_Incompatible_network_address_formats = 301; /// <summary> /// One or more transport protocols described in the session description are not available. /// </summary> public const int x302_Incompatible_network_address_formats = 302; /// <summary> /// One or more bandwidth measurement units contained in the session description were not understood. /// </summary> public const int x303_Incompatible_bandwidth_units = 303; /// <summary> /// One or more media types contained in the session description are not available. /// </summary> public const int x304_Media_type_not_available = 304; /// <summary> /// One or more media formats contained in the session description are not available. /// </summary> public const int x305_Incompatible_media_format = 305; /// <summary> /// One or more of the media attributes in the session description are not supported. /// </summary> public const int x306_Attribute_not_understood = 306; /// <summary> /// A parameter other than those listed above was not understood. /// </summary> public const int x307_Session_description_parameter_not_understood = 307; /// <summary> /// The site where the user is located does not support multicast. /// </summary> public const int x330_Multicast_not_available = 330; /// <summary> /// The site where the user is located does not support unicast communication /// (usually due to the presence of a firewall). /// </summary> public const int x331_Unicast_not_available = 331; /// <summary> /// The bandwidth specified in the session description or defined by the media /// exceeds that known to be available. /// </summary> public const int x370_Insufficient_bandwidth = 370; /// <summary> /// The warning text can include arbitrary information to be presented to a human user or logged. /// A system receiving this warning MUST NOT take any automated action. /// </summary> public const int x399_Miscellaneous_warning = 399; #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/IMAP/Client/IMAP_Acl.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.IMAP.Client { #region usings using Server; #endregion /// <summary> /// IMAP ACL entry. Defined in RFC 2086. /// </summary> public class IMAP_Acl { #region Members private readonly string m_Name = ""; private readonly IMAP_ACL_Flags m_Rights = IMAP_ACL_Flags.None; #endregion #region Properties /// <summary> /// Gets authentication identifier name. Normally this is user or group name. /// </summary> public string Name { get { return m_Name; } } /// <summary> /// Gets the rights associated with this ACL entry. /// </summary> public IMAP_ACL_Flags Rights { get { return m_Rights; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="name">Authentication identifier name. Normally this is user or group name.</param> /// <param name="rights">Rights associated with this ACL entry.</param> public IMAP_Acl(string name, IMAP_ACL_Flags rights) { m_Name = name; m_Rights = rights; } #endregion #region Internal methods /// <summary> /// Parses ACL entry from IMAP ACL response string. /// </summary> /// <param name="aclResponseString">IMAP ACL response string.</param> /// <returns></returns> internal static IMAP_Acl Parse(string aclResponseString) { string[] args = TextUtils.SplitQuotedString(aclResponseString, ' ', true); return new IMAP_Acl(args[1], IMAP_Utils.ACL_From_String(args[2])); } #endregion } }<file_sep>/web/studio/ASC.Web.Studio/UserControls/FirstTime/FirstTimeTenantSettings.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections.Specialized; using System.Configuration; using System.Net; using ASC.Common.Logging; using ASC.Common.Utils; using ASC.Core; using ASC.Core.Users; using ASC.Web.Core.Utility.Settings; using ASC.Web.Studio.Utility; namespace ASC.Web.Studio.UserControls.FirstTime { public static class FirstTimeTenantSettings { public static void SendInstallInfo(UserInfo user) { if (!TenantExtra.Opensource) return; if (!WizardSettings.Load().Analytics) return; try { var url = ConfigurationManagerExtension.AppSettings["web.install-url"]; if (string.IsNullOrEmpty(url)) return; var tenant = CoreContext.TenantManager.GetCurrentTenant(); var q = new MailQuery { Email = user.Email, Id = CoreContext.Configuration.GetKey(tenant.TenantId), Alias = tenant.TenantDomain, }; var index = url.IndexOf("?v=", StringComparison.InvariantCultureIgnoreCase); if (0 < index) { q.Version = url.Substring(index + 3) + Environment.OSVersion; url = url.Substring(0, index); } using (var webClient = new WebClient()) { var values = new NameValueCollection { {"query", Signature.Create(q, "4be71393-0c90-41bf-b641-a8d9523fba5c")} }; webClient.UploadValues(url, values); } } catch (Exception error) { LogManager.GetLogger("ASC.Web").Error(error); } } private class MailQuery { public string Email { get; set; } public string Version { get; set; } public string Id { get; set; } public string Alias { get; set; } } } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/POP3/Server/POP3_Server.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using ASC.Mail.Net.TCP; namespace ASC.Mail.Net.POP3.Server { #region usings using System; using System.Net; using System.Net.Sockets; using System.Text; using AUTH; #endregion #region Event delegates /// <summary> /// Represents the method that will handle the AuthUser event for POP3_Server. /// </summary> /// <param name="sender">The source of the event. </param> /// <param name="e">A AuthUser_EventArgs that contains the event data.</param> public delegate void AuthUserEventHandler(object sender, AuthUser_EventArgs e); /// <summary> /// Represents the method that will handle the GetMessgesList event for POP3_Server. /// </summary> /// <param name="sender">The source of the event. </param> /// <param name="e">A GetMessagesInfo_EventArgs that contains the event data.</param> public delegate void GetMessagesInfoHandler(object sender, GetMessagesInfo_EventArgs e); /// <summary> /// Represents the method that will handle the GetMessage,DeleteMessage,GetTopLines event for POP3_Server. /// </summary> /// <param name="sender">The source of the event. </param> /// <param name="e">A GetMessage_EventArgs that contains the event data.</param> public delegate void MessageHandler(object sender, POP3_Message_EventArgs e); /// <summary> /// Represents the method that will handle the GetMessageStream event for POP3_Server. /// </summary> /// <param name="sender">The source of the event. </param> /// <param name="e">Event data.</param> public delegate void GetMessageStreamHandler(object sender, POP3_eArgs_GetMessageStream e); #endregion /// <summary> /// POP3 server component. /// </summary> public class POP3_Server : TCP_Server<POP3_Session> { #region Events /// <summary> /// Occurs when connected user tryes to authenticate. /// </summary> public event AuthUserEventHandler AuthUser = null; /// <summary> /// Occurs when user requests delete message. /// </summary> public event MessageHandler DeleteMessage = null; /// <summary> /// Occurs when user requests to get specified message. /// </summary> public event GetMessageStreamHandler GetMessageStream = null; /// <summary> /// Occurs when server needs to know logged in user's maibox messages. /// </summary> public event GetMessagesInfoHandler GetMessgesList = null; /// <summary> /// Occurs when user requests specified message TOP lines. /// </summary> public event MessageHandler GetTopLines = null; /// <summary> /// Occurs user session ends. This is place for clean up. /// </summary> public event EventHandler SessionEnd = null; /// <summary> /// Occurs when POP3 session has finished and session log is available. /// </summary> public event LogEventHandler SessionLog = null; /// <summary> /// Occurs user session resetted. Messages marked for deletion are unmarked. /// </summary> public event EventHandler SessionResetted = null; /// <summary> /// Occurs when new computer connected to POP3 server. /// </summary> public event ValidateIPHandler ValidateIPAddress = null; #endregion #region Members private string m_GreetingText = ""; private int m_MaxConnectionsPerIP; private SaslAuthTypes m_SupportedAuth = SaslAuthTypes.All; #endregion #region Properties /// <summary> /// Gets or sets server supported authentication types. /// </summary> public SaslAuthTypes SupportedAuthentications { get { return m_SupportedAuth; } set { m_SupportedAuth = value; } } /// <summary> /// Gets or sets server greeting text. /// </summary> public string GreetingText { get { return m_GreetingText; } set { m_GreetingText = value; } } /// <summary> /// Gets or sets maximum allowed conncurent connections from 1 IP address. Value 0 means unlimited connections. /// </summary> public new int MaxConnectionsPerIP { get { return m_MaxConnectionsPerIP; } set { m_MaxConnectionsPerIP = value; } } public int MaxBadCommands { get; set; } #endregion #region Constructor /// <summary> /// Defalut constructor. /// </summary> public POP3_Server() { } #endregion #region Overrides #endregion #region Virtual methods protected override void OnMaxConnectionsPerIPExceeded(POP3_Session session) { base.OnMaxConnectionsPerIPExceeded(session); session.TcpStream.WriteLine("-ERR Maximum connections from your IP address is exceeded, try again later!"); } protected override void OnMaxConnectionsExceeded(POP3_Session session) { session.TcpStream.WriteLine("-ERR Maximum connections exceeded, try again later!"); } /// <summary> /// Raises event ValidateIP event. /// </summary> /// <param name="localEndPoint">Server IP.</param> /// <param name="remoteEndPoint">Connected client IP.</param> /// <returns>Returns true if connection allowed.</returns> internal virtual bool OnValidate_IpAddress(IPEndPoint localEndPoint, IPEndPoint remoteEndPoint) { ValidateIP_EventArgs oArg = new ValidateIP_EventArgs(localEndPoint, remoteEndPoint); if (ValidateIPAddress != null) { ValidateIPAddress(this, oArg); } return oArg.Validated; } /// <summary> /// Authenticates user. /// </summary> /// <param name="session">Reference to current pop3 session.</param> /// <param name="userName">User name.</param> /// <param name="<PASSWORD>wData"></param> /// <param name="data"></param> /// <param name="authType"></param> /// <returns></returns> internal virtual AuthUser_EventArgs OnAuthUser(POP3_Session session, string userName, string passwData, string data, AuthType authType) { AuthUser_EventArgs oArg = new AuthUser_EventArgs(session, userName, passwData, data, authType); if (AuthUser != null) { AuthUser(this, oArg); } return oArg; } /// <summary> /// Gest pop3 messages info. /// </summary> /// <param name="session"></param> /// <param name="messages"></param> internal virtual void OnGetMessagesInfo(POP3_Session session, POP3_MessageCollection messages) { GetMessagesInfo_EventArgs oArg = new GetMessagesInfo_EventArgs(session, messages, session.UserName); if (GetMessgesList != null) { GetMessgesList(this, oArg); } } /// <summary> /// Raises delete message event. /// </summary> /// <param name="session"></param> /// <param name="message">Message which to delete.</param> /// <returns></returns> internal virtual bool OnDeleteMessage(POP3_Session session, POP3_Message message) { POP3_Message_EventArgs oArg = new POP3_Message_EventArgs(session, message, null); if (DeleteMessage != null) { DeleteMessage(this, oArg); } return true; } #endregion #region Internal methods /// <summary> /// Checks if user is logged in. /// </summary> /// <param name="userName">User name.</param> /// <returns></returns> internal bool IsUserLoggedIn(string userName) { lock (Sessions) { foreach (POP3_Session sess in Sessions) { if (sess.AuthenticatedUserIdentity!=null && sess.AuthenticatedUserIdentity.Name.ToLower() == userName.ToLower()) { return true; } } } return false; } /// <summary> /// Raises event 'GetMessageStream'. /// </summary> /// <param name="session">Reference to POP3 session.</param> /// <param name="messageInfo">Message info what message stream to get.</param> /// <returns></returns> internal POP3_eArgs_GetMessageStream OnGetMessageStream(POP3_Session session, POP3_Message messageInfo) { POP3_eArgs_GetMessageStream eArgs = new POP3_eArgs_GetMessageStream(session, messageInfo); if (GetMessageStream != null) { GetMessageStream(this, eArgs); } return eArgs; } /// <summary> /// Raises event GetTopLines. /// </summary> /// <param name="session"></param> /// <param name="message">Message wich top lines to get.</param> /// <param name="nLines">Header + number of body lines to get.</param> /// <returns></returns> internal byte[] OnGetTopLines(POP3_Session session, POP3_Message message, int nLines) { POP3_Message_EventArgs oArgs = new POP3_Message_EventArgs(session, message, null, nLines); if (GetTopLines != null) { GetTopLines(this, oArgs); } return oArgs.MessageData; } /// <summary> /// Raises SessionEnd event. /// </summary> /// <param name="session">Session which is ended.</param> internal void OnSessionEnd(object session) { if (SessionEnd != null) { SessionEnd(session, new EventArgs()); } } /// <summary> /// Raises SessionResetted event. /// </summary> /// <param name="session">Session which is resetted.</param> internal void OnSessionResetted(object session) { if (SessionResetted != null) { SessionResetted(session, new EventArgs()); } } #endregion public void OnSysError(string s, Exception exception) { OnError(exception); } } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/POP3/POP3_ExtendedCapabilities.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections.Generic; using System.Text; namespace LumiSoft.Net.POP3 { /// <summary> /// This class holds known POP3 extended capabilities. Defined in http://www.iana.org/assignments/pop3-extension-mechanism. /// </summary> public class POP3_ExtendedCapabilities { /// <summary> /// The TOP capability indicates the optional TOP command is available. Defined in RFC 2449. /// </summary> public static readonly string TOP = "TOP"; /// <summary> /// The USER capability indicates that the USER and PASS commands are supported. Defined in RFC 2449. /// </summary> public static readonly string USER = "USER"; /// <summary> /// The SASL capability indicates that the AUTH command is available and that it supports an optional base64 /// encoded second argument for an initial client response as described in the SASL specification. Defined in RFC 2449. /// </summary> public static readonly string SASL = "SASL"; /// <summary> /// The RESP-CODES capability indicates that any response text issued by this server which begins with an open /// square bracket ("[") is an extended response code. Defined in RFC 2449. /// </summary> public static readonly string RESP_CODES = "RESP-CODES"; /// <summary> /// LOGIN-DELAY capability. Defined in RFC 2449. /// </summary> public static readonly string LOGIN_DELAY = "LOGIN-DELAY"; /// <summary> /// The PIPELINING capability indicates the server is capable of accepting multiple commands at a time; /// the client does not have to wait for the response to a command before issuing a subsequent command. /// Defined in RFC 2449. /// </summary> public static readonly string PIPELINING = "PIPELINING"; /// <summary> /// EXPIRE capability. Defined in RFC 2449. /// </summary> public static readonly string EXPIRE = "EXPIRE"; /// <summary> /// UIDL command is supported. Defined in RFC 2449. /// </summary> public static readonly string UIDL = "UIDL"; /// <summary> /// STLS(start TLS) command supported. Defined in RFC 2449. /// </summary> public static readonly string STLS = "STLS"; } } <file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/IMAP/Server/IMAP_Folders.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.IMAP.Server { #region usings using System.Collections; #endregion /// <summary> /// IMAP folders collection. /// </summary> public class IMAP_Folders { #region Members private readonly string m_Mailbox = ""; private readonly ArrayList m_Mailboxes; private readonly IMAP_Session m_pSession; private readonly string m_RefName = ""; #endregion #region Properties /// <summary> /// Gets current IMAP session. /// </summary> public IMAP_Session Session { get { return m_pSession; } } /// <summary> /// Gest list of IMAP folders. /// </summary> public IMAP_Folder[] Folders { get { IMAP_Folder[] retVal = new IMAP_Folder[m_Mailboxes.Count]; m_Mailboxes.CopyTo(retVal); return retVal; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="session">Owner IMAP session.</param> /// <param name="referenceName">Folder Path. Eg. Inbox\.</param> /// <param name="folder">Folder name.</param> public IMAP_Folders(IMAP_Session session, string referenceName, string folder) { m_pSession = session; m_Mailboxes = new ArrayList(); m_RefName = referenceName; m_Mailbox = folder.Replace("\\", "/"); } #endregion #region Methods /// <summary> /// Adds folder to folders list. /// </summary> /// <param name="folder">Full path to folder, path separator = '/'. Eg. Inbox/myFolder .</param> /// <param name="selectable">Gets or sets if folder is selectable(SELECT command can select this folder).</param> public void Add(string folder, bool selectable) { folder = folder.Replace("\\", "/"); string folderPattern = m_RefName + m_Mailbox; if (m_RefName != "" && !m_RefName.EndsWith("/") && !m_Mailbox.StartsWith("/")) { folderPattern = m_RefName + "/" + m_Mailbox; } if (FolderMatches(folderPattern, Core.Decode_IMAP_UTF7_String(folder))) { m_Mailboxes.Add(new IMAP_Folder(folder, selectable)); } } // TODO: move to some global utility method /// <summary> /// Checks if specified text matches to specified asteric pattern. /// </summary> /// <param name="pattern">Asteric pattern. Foe example: *xxx,*xxx*,xx*aa*xx, ... .</param> /// <param name="text">Text to match.</param> /// <returns></returns> public bool AstericMatch(string pattern, string text) { pattern = pattern.ToLower(); text = text.ToLower(); if (pattern == "") { pattern = "*"; } while (pattern.Length > 0) { // *xxx[*xxx...] if (pattern.StartsWith("*")) { // *xxx*xxx if (pattern.IndexOf("*", 1) > -1) { string indexOfPart = pattern.Substring(1, pattern.IndexOf("*", 1) - 1); if (text.IndexOf(indexOfPart) == -1) { return false; } text = text.Substring(text.IndexOf(indexOfPart) + indexOfPart.Length + 1); pattern = pattern.Substring(pattern.IndexOf("*", 1) + 1); } // *xxx This is last pattern else { return text.EndsWith(pattern.Substring(1)); } } // xxx*[xxx...] else if (pattern.IndexOfAny(new[] {'*'}) > -1) { string startPart = pattern.Substring(0, pattern.IndexOfAny(new[] {'*'})); // Text must startwith if (!text.StartsWith(startPart)) { return false; } text = text.Substring(text.IndexOf(startPart) + startPart.Length); pattern = pattern.Substring(pattern.IndexOfAny(new[] {'*'})); } // xxx else { return text == pattern; } } return true; } #endregion #region Utility methods /// <summary> /// Gets if folder matches to specified folder pattern. /// </summary> /// <param name="folderPattern">Folder pattern. * and % between path separators have same meaning (asteric pattern). /// If % is at the end, then matches only last folder child folders and not child folder child folders.</param> /// <param name="folder">Folder name with full path.</param> /// <returns></returns> private bool FolderMatches(string folderPattern, string folder) { folderPattern = folderPattern.ToLower(); folder = folder.ToLower(); string[] folderParts = folder.Split('/'); string[] patternParts = folderPattern.Split('/'); // pattern is more nested than folder if (folderParts.Length < patternParts.Length) { return false; } // This can happen only if * at end else if (folderParts.Length > patternParts.Length && !folderPattern.EndsWith("*")) { return false; } else { // Loop patterns for (int i = 0; i < patternParts.Length; i++) { string patternPart = patternParts[i].Replace("%", "*"); // This is asteric pattern if (patternPart.IndexOf('*') > -1) { if (!AstericMatch(patternPart, folderParts[i])) { return false; } // else process next pattern } // No *, this must be exact match else { if (folderParts[i] != patternPart) { return false; } } } } return true; } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/SIP/Stack/SIP_TimerConstants.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.SIP.Stack { /// <summary> /// This class holds known SIP timer constant values. /// </summary> internal class SIP_TimerConstants { #region Constants public const int T1 = 500; public const int T2 = 4000; public const int T4 = 5000; #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/_Obsolete/ReadToStream_EventArgs.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.IO { #region usings using System; using System.IO; using System.Text; #endregion /// <summary> /// This class provides data to asynchronous read to stream methods callback. /// </summary> public class ReadToStream_EventArgs { #region Members private readonly int m_Count; private readonly Exception m_pException; private readonly Stream m_pStream; #endregion #region Properties /// <summary> /// Gets exception what happened while reading data. Returns null if data reading completed sucessfully. /// </summary> public Exception Exception { get { return m_pException; } } /// <summary> /// Gets stream where data is stored. /// </summary> public Stream Stream { get { return m_pStream; } } /// <summary> /// Gets number of bytes readed and written to <b>Stream</b>. /// </summary> public int Count { get { return m_Count; } } /// <summary> /// Gets readed data. NOTE: This property is available only is Stream supports seeking ! /// </summary> public byte[] Data { get { if (!m_pStream.CanSeek) { throw new InvalidOperationException("Underlaying stream won't support seeking !"); } long currentPos = m_pStream.Position; m_pStream.Position = 0; byte[] data = new byte[m_pStream.Length]; m_pStream.Read(data, 0, data.Length); return data; } } /// <summary> /// Gets readed line data as string with system <b>default</b> encoding. /// NOTE: This property is available only is Stream supports seeking ! /// </summary> public string DataStringDefault { get { return DataToString(Encoding.Default); } } /// <summary> /// Gets readed line data as string with <b>ASCII</b> encoding. /// NOTE: This property is available only is Stream supports seeking ! /// </summary> public string DataStringAscii { get { return DataToString(Encoding.ASCII); } } /// <summary> /// Gets readed line data as string with <b>UTF8</b> encoding. /// NOTE: This property is available only is Stream supports seeking ! /// </summary> public string DataStringUtf8 { get { return DataToString(Encoding.UTF8); } } /// <summary> /// Gets or stes user data. /// </summary> public object Tag { get; set; } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="exception">Exception what happened while reading data or null if data reading was successfull.</param> /// <param name="stream">Stream where data was stored.</param> /// <param name="count">Number of bytes readed.</param> /// <param name="tag">User data.</param> public ReadToStream_EventArgs(Exception exception, Stream stream, int count, object tag) { m_pException = exception; m_pStream = stream; m_Count = count; Tag = tag; } #endregion #region Methods /// <summary> /// Converts byte[] line data to the specified encoding string. /// </summary> /// <param name="encoding">Encoding to use for convert.</param> /// <returns>Returns line data as string.</returns> public string DataToString(Encoding encoding) { if (encoding == null) { throw new ArgumentNullException("encoding"); } if (Data == null) { return null; } else { return encoding.GetString(Data); } } #endregion } }<file_sep>/web/studio/ASC.Web.Studio/UserControls/Statistics/ProductQuotes/ProductQuotes.ascx.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using ASC.Core; using ASC.Core.Billing; using ASC.Web.Core; using ASC.Web.Studio.Core; using ASC.Web.Studio.Utility; namespace ASC.Web.Studio.UserControls.Statistics { [ManagementControl(ManagementType.Statistic, Location)] public partial class ProductQuotes : UserControl { public const string Location = "~/UserControls/Statistics/ProductQuotes/ProductQuotes.ascx"; private long MaxTotalSpace { get; set; } private long UsedSpace { get; set; } protected void Page_Load(object sender, EventArgs e) { Page .RegisterStyle("~/UserControls/Statistics/ProductQuotes/css/productquotes_style.less") .RegisterBodyScripts("~/UserControls/Statistics/ProductQuotes/js/product_quotes.js"); MaxTotalSpace = TenantExtra.GetTenantQuota().MaxTotalSize; UsedSpace = TenantStatisticsProvider.GetUsedSize(); } protected IEnumerable<IWebItem> GetWebItems() { return WebItemManager.Instance.GetItems(Web.Core.WebZones.WebZoneType.All, ItemAvailableState.All) .Where(item => item != null && item.Visible && item.Context != null && item.Context.SpaceUsageStatManager != null); } protected String RenderCreatedDate() { return String.Format("{0}", CoreContext.TenantManager.GetCurrentTenant().CreatedDateTime.ToShortDateString()); } protected string RenderUsersTotal() { var result = TenantStatisticsProvider.GetUsersCount().ToString(); var maxActiveUsers = TenantExtra.GetTenantQuota().ActiveUsers; if (!CoreContext.Configuration.Standalone || maxActiveUsers != LicenseReader.MaxUserCount) { result += " / " + maxActiveUsers; } return result; } protected String RenderMaxTotalSpace() { return FileSizeComment.FilesSizeToString(MaxTotalSpace); } protected String RenderUsedSpace() { return FileSizeComment.FilesSizeToString(UsedSpace); } protected String RenderUsedSpaceClass() { return !CoreContext.Configuration.Standalone && UsedSpace > MaxTotalSpace*9/10 ? "red-text" : string.Empty; } } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/SIP/Message/SIP_t_SubscriptionState.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.SIP.Message { #region usings using System; using System.Text; #endregion /// <summary> /// Implements SIP "Subscription-State" value. Defined in RFC 3265. /// </summary> /// <remarks> /// <code> /// RFC 3265 Syntax: /// Subscription-State = substate-value *( SEMI subexp-params ) /// substate-value = "active" / "pending" / "terminated" / extension-substate /// extension-substate = token /// subexp-params = ("reason" EQUAL event-reason-value) /// / ("expires" EQUAL delta-seconds) /// / ("retry-after" EQUAL delta-seconds) /// / generic-param /// event-reason-value = "deactivated" / "probation" / "rejected" / "timeout" / "giveup" /// / "noresource" / event-reason-extension /// event-reason-extension = token /// </code> /// </remarks> public class SIP_t_SubscriptionState : SIP_t_ValueWithParams { #region Nested type: EventReason /// <summary> /// This class holds 'event-reason-value' values. /// </summary> public class EventReason { #region Members /// <summary> /// The subscription has been terminated, but the subscriber SHOULD retry immediately /// with a new subscription. One primary use of such a status code is to allow migration of /// subscriptions between nodes. The "retry-after" parameter has no semantics for "deactivated". /// </summary> public const string deactivated = "deactivated"; /// <summary> /// The subscription has been terminated because the notifier could not obtain authorization in a /// timely fashion. If a "retry-after" parameter is also present, the client SHOULD wait at least /// the number of seconds specified by that parameter before attempting to re-subscribe; otherwise, /// the client MAY retry immediately, but will likely get put back into pending state. /// </summary> public const string giveup = "giveup"; /// <summary> /// The subscription has been terminated because the resource state which was being monitored /// no longer exists. Clients SHOULD NOT attempt to re-subscribe. The "retry-after" parameter /// has no semantics for "noresource". /// </summary> public const string noresource = "noresource"; /// <summary> /// The subscription has been terminated, but the client SHOULD retry at some later time. /// If a "retry-after" parameter is also present, the client SHOULD wait at least the number of /// seconds specified by that parameter before attempting to re-subscribe. /// </summary> public const string probation = "probation"; /// <summary> /// The subscription has been terminated due to change in authorization policy. /// Clients SHOULD NOT attempt to re-subscribe. The "retry-after" parameter has no /// semantics for "rejected". /// </summary> public const string rejected = "rejected"; /// <summary> /// The subscription has been terminated because it was not refreshed before it expired. /// Clients MAY re-subscribe immediately. The "retry-after" parameter has no semantics for "timeout". /// </summary> public const string timeout = "timeout"; #endregion } #endregion #region Nested type: SubscriptionState /// <summary> /// This class holds 'substate-value' values. /// </summary> public class SubscriptionState { #region Members /// <summary> /// The subscription has been accepted and (in general) has been authorized. /// </summary> public const string active = "active"; /// <summary> /// The subscription has been received by the notifier, but there is insufficient policy /// information to grant or deny the subscription yet. /// </summary> public const string pending = "pending"; /// <summary> /// The subscriber should consider the subscription terminated. /// </summary> public const string terminated = "terminated"; #endregion } #endregion #region Members private string m_Value = ""; #endregion #region Properties /// <summary> /// Gets or sets subscription state value. Known values are defined in SubscriptionState class. /// </summary> /// <exception cref="ArgumentNullException">Is raised when null value passed.</exception> /// <exception cref="ArgumentException">Is raised when empty string is passed or value is not token.</exception> public string Value { get { return m_Value; } set { if (value == null) { throw new ArgumentNullException("Value"); } if (value == "") { throw new ArgumentException("Property 'Value' value may not be '' !"); } if (!TextUtils.IsToken(value)) { throw new ArgumentException("Property 'Value' value must be 'token' !"); } m_Value = value; } } /// <summary> /// Gets or sets 'reason' parameter value. Known reason values are defined in EventReason class. /// Value null means not specified. /// </summary> public string Reason { get { SIP_Parameter parameter = Parameters["reason"]; if (parameter != null) { return parameter.Value; } else { return null; } } set { if (string.IsNullOrEmpty(value)) { Parameters.Remove("reason"); } else { Parameters.Set("reason", value); } } } /// <summary> /// Gets or sets 'expires' parameter value. Value -1 means not specified. /// </summary> /// <exception cref="ArgumentException">Is raised when negative value(except -1) is passed.</exception> public int Expires { get { SIP_Parameter parameter = Parameters["expires"]; if (parameter != null) { return Convert.ToInt32(parameter.Value); } else { return -1; } } set { if (value == -1) { Parameters.Remove("expires"); } else { if (value < 0) { throw new ArgumentException("Property 'Expires' value must >= 0 !"); } Parameters.Set("expires", value.ToString()); } } } /// <summary> /// Gets or sets 'expires' parameter value. Value -1 means not specified. /// </summary> /// <exception cref="ArgumentException">Is raised when negative value(except -1) is passed.</exception> public int RetryAfter { get { SIP_Parameter parameter = Parameters["retry-after"]; if (parameter != null) { return Convert.ToInt32(parameter.Value); } else { return -1; } } set { if (value == -1) { Parameters.Remove("retry-after"); } else { if (value < 0) { throw new ArgumentException("Property 'RetryAfter' value must >= 0 !"); } Parameters.Set("retry-after", value.ToString()); } } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="value"></param> public SIP_t_SubscriptionState(string value) { Parse(value); } #endregion #region Methods /// <summary> /// Parses "Subscription-State" from specified value. /// </summary> /// <param name="value">SIP "Subscription-State" value.</param> /// <exception cref="ArgumentNullException">Raised when <b>value</b> is null.</exception> /// <exception cref="SIP_ParseException">Raised when invalid SIP message.</exception> public void Parse(string value) { if (value == null) { throw new ArgumentNullException("value"); } Parse(new StringReader(value)); } /// <summary> /// Parses "Subscription-State" from specified reader. /// </summary> /// <param name="reader">Reader from where to parse.</param> /// <exception cref="ArgumentNullException">Raised when <b>reader</b> is null.</exception> /// <exception cref="SIP_ParseException">Raised when invalid SIP message.</exception> public override void Parse(StringReader reader) { /* Subscription-State = substate-value *( SEMI subexp-params ) substate-value = "active" / "pending" / "terminated" / extension-substate extension-substate = token subexp-params = ("reason" EQUAL event-reason-value) / ("expires" EQUAL delta-seconds) / ("retry-after" EQUAL delta-seconds) / generic-param event-reason-value = "deactivated" / "probation" / "rejected" / "timeout" / "giveup" / "noresource" / event-reason-extension event-reason-extension = token */ if (reader == null) { throw new ArgumentNullException("reader"); } // substate-value string word = reader.ReadWord(); if (word == null) { throw new SIP_ParseException("SIP Event 'substate-value' value is missing !"); } m_Value = word; // Parse parameters ParseParameters(reader); } /// <summary> /// Converts this to valid "Subscription-State" value. /// </summary> /// <returns>Returns "Subscription-State" value.</returns> public override string ToStringValue() { /* Subscription-State = substate-value *( SEMI subexp-params ) substate-value = "active" / "pending" / "terminated" / extension-substate extension-substate = token subexp-params = ("reason" EQUAL event-reason-value) / ("expires" EQUAL delta-seconds) / ("retry-after" EQUAL delta-seconds) / generic-param event-reason-value = "deactivated" / "probation" / "rejected" / "timeout" / "giveup" / "noresource" / event-reason-extension event-reason-extension = token */ StringBuilder retVal = new StringBuilder(); // substate-value retVal.Append(m_Value); // Add parameters retVal.Append(ParametersToString()); return retVal.ToString(); } #endregion } }<file_sep>/module/ASC.Api/ASC.Api.Projects/ProjectApi.Tags.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections.Generic; using System.Linq; using ASC.Api.Attributes; using ASC.Api.Projects.Wrappers; using ASC.Projects.Core.Domain; using ASC.Projects.Engine; namespace ASC.Api.Projects { public partial class ProjectApi { ///<summary> ///Returns the list of all available project tags ///</summary> ///<short> ///Project tags ///</short> ///<category>Tags</category> ///<returns>List of tags</returns> [Read(@"tag")] public IEnumerable<ObjectWrapperBase> GetAllTags() { return EngineFactory.TagEngine.GetTags().Select(x => new ObjectWrapperBase {Id = x.Key, Title = x.Value}); } ///<summary> ///Creates new tag ///</summary> ///<short> ///Tag ///</short> ///<category>Tags</category> ///<returns>Created tag</returns> [Create(@"tag")] public ObjectWrapperBase CreateNewTag(string data) { if (string.IsNullOrEmpty(data)) throw new ArgumentException("data"); ProjectSecurity.DemandCreate<Project>(null); var result = EngineFactory.TagEngine.Create(data); return new ObjectWrapperBase {Id = result.Key, Title = result.Value}; } ///<summary> ///Returns the detailed list of all projects with the specified tag ///</summary> ///<short> ///Project by tag ///</short> ///<category>Tags</category> ///<param name="tag">Tag name</param> ///<returns>List of projects</returns> [Read(@"tag/{tag}")] public IEnumerable<ProjectWrapper> GetProjectsByTags(string tag) { var projectsTagged = EngineFactory.TagEngine.GetTagProjects(tag); return EngineFactory.ProjectEngine.GetByID(projectsTagged).Select(ProjectWrapperSelector).ToList(); } ///<summary> ///Returns the list of all tags like the specified tag name ///</summary> ///<short> ///Tags by tag name ///</short> ///<category>Tags</category> ///<param name="tagName">Tag name</param> ///<returns>List of tags</returns> [Read(@"tag/search")] public string[] GetTagsByName(string tagName) { return !string.IsNullOrEmpty(tagName) && tagName.Trim() != string.Empty ? EngineFactory.TagEngine.GetTags(tagName.Trim()).Select(r => r.Value).ToArray() : new string[0]; } } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/SIP/Message/SIP_Message.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.SIP.Message { #region usings using System; using System.Globalization; using System.IO; using System.Text; #endregion /// <summary> /// Implements SIP message. This is base class for SIP_Request and SIP_Response. Defined in RFC 3261. /// </summary> public abstract class SIP_Message { #region Members private readonly SIP_HeaderFieldCollection m_pHeader; private byte[] m_Data; #endregion #region Properties /// <summary> /// Gets direct access to header. /// </summary> public SIP_HeaderFieldCollection Header { get { return m_pHeader; } } /// <summary> /// Gets or sets what features end point supports. /// </summary> public SIP_MVGroupHFCollection<SIP_t_AcceptRange> Accept { get { return new SIP_MVGroupHFCollection<SIP_t_AcceptRange>(this, "Accept:"); } } /// <summary> /// Gets or sets Accept-Contact header value. Defined in RFC 3841. /// </summary> public SIP_MVGroupHFCollection<SIP_t_ACValue> AcceptContact { get { return new SIP_MVGroupHFCollection<SIP_t_ACValue>(this, "Accept-Contact:"); } } /// <summary> /// Gets encodings what end point supports. Example: Accept-Encoding: gzip. /// </summary> public SIP_MVGroupHFCollection<SIP_t_Encoding> AcceptEncoding { get { return new SIP_MVGroupHFCollection<SIP_t_Encoding>(this, "Accept-Encoding:"); } } /// <summary> /// Gets preferred languages for reason phrases, session descriptions, or /// status responses carried as message bodies in the response. If no Accept-Language /// header field is present, the server SHOULD assume all languages are acceptable to the client. /// </summary> public SIP_MVGroupHFCollection<SIP_t_Language> AcceptLanguage { get { return new SIP_MVGroupHFCollection<SIP_t_Language>(this, "Accept-Language:"); } } /// <summary> /// Gets Accept-Resource-Priority headers. Defined in RFC 4412. /// </summary> public SIP_MVGroupHFCollection<SIP_t_RValue> AcceptResourcePriority { get { return new SIP_MVGroupHFCollection<SIP_t_RValue>(this, "Accept-Resource-Priority:"); } } /// <summary> /// Gets AlertInfo values collection. When present in an INVITE request, the Alert-Info header /// field specifies an alternative ring tone to the UAS. When present in a 180 (Ringing) response, /// the Alert-Info header field specifies an alternative ringback tone to the UAC. /// </summary> public SIP_MVGroupHFCollection<SIP_t_AlertParam> AlertInfo { get { return new SIP_MVGroupHFCollection<SIP_t_AlertParam>(this, "Alert-Info:"); } } /// <summary> /// Gets methods collection which is supported by the UA which generated the message. /// </summary> public SIP_MVGroupHFCollection<SIP_t_Method> Allow { get { return new SIP_MVGroupHFCollection<SIP_t_Method>(this, "Allow:"); } } /// <summary> /// Gets Allow-Events header which indicates the event packages supported by the client. Defined in rfc 3265. /// </summary> public SIP_MVGroupHFCollection<SIP_t_EventType> AllowEvents { get { return new SIP_MVGroupHFCollection<SIP_t_EventType>(this, "Allow-Events:"); } } /// <summary> /// Gets the Authentication-Info header fields which provides for mutual authentication /// with HTTP Digest. /// </summary> public SIP_SVGroupHFCollection<SIP_t_AuthenticationInfo> AuthenticationInfo { get { return new SIP_SVGroupHFCollection<SIP_t_AuthenticationInfo>(this, "Authentication-Info:"); } } /// <summary> /// Gets the Authorization header fields which contains authentication credentials of a UA. /// </summary> public SIP_SVGroupHFCollection<SIP_t_Credentials> Authorization { get { return new SIP_SVGroupHFCollection<SIP_t_Credentials>(this, "Authorization:"); } } /// <summary> /// Gets or sets the Call-ID header field which uniquely identifies a particular invitation or all /// registrations of a particular client. /// Value null means not specified. /// </summary> public string CallID { get { SIP_HeaderField h = m_pHeader.GetFirst("Call-ID:"); if (h != null) { return h.Value; } else { return null; } } set { if (value == null) { m_pHeader.RemoveFirst("Call-ID:"); } else { m_pHeader.Set("Call-ID:", value); } } } /// <summary> /// Gets the Call-Info header field which provides additional information about the /// caller or callee, depending on whether it is found in a request or response. /// </summary> public SIP_MVGroupHFCollection<SIP_t_Info> CallInfo { get { return new SIP_MVGroupHFCollection<SIP_t_Info>(this, "Call-Info:"); } } /// <summary> /// Gets contact header fields. The Contact header field provides a SIP or SIPS URI that can be used /// to contact that specific instance of the UA for subsequent requests. /// </summary> public SIP_MVGroupHFCollection<SIP_t_ContactParam> Contact { get { return new SIP_MVGroupHFCollection<SIP_t_ContactParam>(this, "Contact:"); } } /// <summary> /// Gets or sets the Content-Disposition header field which describes how the message body /// or, for multipart messages, a message body part is to be interpreted by the UAC or UAS. /// Value null means not specified. /// </summary> public SIP_t_ContentDisposition ContentDisposition { get { SIP_HeaderField h = m_pHeader.GetFirst("Content-Disposition:"); if (h != null) { return ((SIP_SingleValueHF<SIP_t_ContentDisposition>) h).ValueX; } else { return null; } } set { if (value == null) { m_pHeader.RemoveFirst("Content-Disposition:"); } else { m_pHeader.Set("Content-Disposition:", value.ToStringValue()); } } } /// <summary> /// Gets the Content-Encodings which is used as a modifier to the "media-type". When present, /// its value indicates what additional content codings have been applied to the entity-body, /// and thus what decoding mechanisms MUST be applied in order to obtain the media-type referenced /// by the Content-Type header field. /// </summary> public SIP_MVGroupHFCollection<SIP_t_ContentCoding> ContentEncoding { get { return new SIP_MVGroupHFCollection<SIP_t_ContentCoding>(this, "Content-Encoding:"); } } /// <summary> /// Gets content languages. /// </summary> public SIP_MVGroupHFCollection<SIP_t_LanguageTag> ContentLanguage { get { return new SIP_MVGroupHFCollection<SIP_t_LanguageTag>(this, "Content-Language:"); } } /// <summary> /// Gets SIP request content data size in bytes. /// </summary> public int ContentLength { get { if (m_Data == null) { return 0; } else { return m_Data.Length; } } } /// <summary> /// Gets or sets the Content-Type header field which indicates the media type of the /// message-body sent to the recipient. /// Value null means not specified. /// </summary> public string ContentType { get { SIP_HeaderField h = m_pHeader.GetFirst("Content-Type:"); if (h != null) { return h.Value; } else { return null; } } set { if (value == null) { m_pHeader.RemoveFirst("Content-Type:"); } else { m_pHeader.Set("Content-Type:", value); } } } /// <summary> /// Gets or sets command sequence number and the request method. /// Value null means not specified. /// </summary> public SIP_t_CSeq CSeq { get { SIP_HeaderField h = m_pHeader.GetFirst("CSeq:"); if (h != null) { return ((SIP_SingleValueHF<SIP_t_CSeq>) h).ValueX; } else { return null; } } set { if (value == null) { m_pHeader.RemoveFirst("CSeq:"); } else { m_pHeader.Set("CSeq:", value.ToStringValue()); } } } /// <summary> /// Gets or sets date and time. Value DateTime.MinValue means that value not specified. /// </summary> public DateTime Date { get { SIP_HeaderField h = m_pHeader.GetFirst("Date:"); if (h != null) { return DateTime.ParseExact(h.Value, "r", DateTimeFormatInfo.InvariantInfo); } else { return DateTime.MinValue; } } set { if (value == DateTime.MinValue) { m_pHeader.RemoveFirst("Date:"); } else { m_pHeader.Set("Date:", value.ToString("r")); } } } /// <summary> /// Gets the Error-Info header field which provides a pointer to additional /// information about the error status response. /// </summary> public SIP_MVGroupHFCollection<SIP_t_ErrorUri> ErrorInfo { get { return new SIP_MVGroupHFCollection<SIP_t_ErrorUri>(this, "Error-Info:"); } } /// <summary> /// Gets or sets Event header. Defined in RFC 3265. /// </summary> public SIP_t_Event Event { get { SIP_HeaderField h = m_pHeader.GetFirst("Event:"); if (h != null) { return ((SIP_SingleValueHF<SIP_t_Event>) h).ValueX; } else { return null; } } set { if (value == null) { m_pHeader.RemoveFirst("Event:"); } else { m_pHeader.Set("Event:", value.ToStringValue()); } } } /// <summary> /// Gets or sets relative time after which the message (or content) expires. /// Value -1 means that value not specified. /// </summary> public int Expires { get { SIP_HeaderField h = m_pHeader.GetFirst("Expires:"); if (h != null) { return Convert.ToInt32(h.Value); } else { return -1; } } set { if (value < 0) { m_pHeader.RemoveFirst("Expires:"); } else { m_pHeader.Set("Expires:", value.ToString()); } } } /// <summary> /// Gets or sets initiator of the request. /// Value null means not specified. /// </summary> public SIP_t_From From { get { SIP_HeaderField h = m_pHeader.GetFirst("From:"); if (h != null) { return ((SIP_SingleValueHF<SIP_t_From>) h).ValueX; } else { return null; } } set { if (value == null) { m_pHeader.RemoveFirst("From:"); } else { m_pHeader.Add(new SIP_SingleValueHF<SIP_t_From>("From:", value)); } } } /// <summary> /// Gets History-Info headers. Defined in RFC 4244. /// </summary> public SIP_MVGroupHFCollection<SIP_t_HiEntry> HistoryInfo { get { return new SIP_MVGroupHFCollection<SIP_t_HiEntry>(this, "History-Info:"); } } /// <summary> /// Identity header value. Value null means not specified. Defined in RFC 4474. /// </summary> public string Identity { get { SIP_HeaderField h = m_pHeader.GetFirst("Identity:"); if (h != null) { return h.Value; } else { return null; } } set { if (value == null) { m_pHeader.RemoveFirst("Identity:"); } else { m_pHeader.Set("Identity:", value); } } } /// <summary> /// Gets or sets Identity-Info header value. Value null means not specified. /// Defined in RFC 4474. /// </summary> public SIP_t_IdentityInfo IdentityInfo { get { SIP_HeaderField h = m_pHeader.GetFirst("Identity-Info:"); if (h != null) { return ((SIP_SingleValueHF<SIP_t_IdentityInfo>) h).ValueX; } else { return null; } } set { if (value == null) { m_pHeader.RemoveFirst("Identity-Info:"); } else { m_pHeader.Add(new SIP_SingleValueHF<SIP_t_IdentityInfo>("Identity-Info:", value)); } } } /// <summary> /// Gets the In-Reply-To header fields which enumerates the Call-IDs that this call /// references or returns. /// </summary> public SIP_MVGroupHFCollection<SIP_t_CallID> InReplyTo { get { return new SIP_MVGroupHFCollection<SIP_t_CallID>(this, "In-Reply-To:"); } } /// <summary> /// Gets or sets Join header which indicates that a new dialog (created by the INVITE in which /// the Join header field in contained) should be joined with a dialog identified by the header /// field, and any associated dialogs or conferences. Defined in 3911. Value null means not specified. /// </summary> public SIP_t_Join Join { get { SIP_HeaderField h = m_pHeader.GetFirst("Join:"); if (h != null) { return ((SIP_SingleValueHF<SIP_t_Join>) h).ValueX; } else { return null; } } set { if (value == null) { m_pHeader.RemoveFirst("Join:"); } else { m_pHeader.Add(new SIP_SingleValueHF<SIP_t_Join>("Join:", value)); } } } /// <summary> /// Gets or sets limit the number of proxies or gateways that can forward the request /// to the next downstream server. /// Value -1 means that value not specified. /// </summary> public int MaxForwards { get { SIP_HeaderField h = m_pHeader.GetFirst("Max-Forwards:"); if (h != null) { return Convert.ToInt32(h.Value); } else { return -1; } } set { if (value < 0) { m_pHeader.RemoveFirst("Max-Forwards:"); } else { m_pHeader.Set("Max-Forwards:", value.ToString()); } } } /// <summary> /// Gets or sets mime version. Currently 1.0 is only defined value. /// Value null means not specified. /// </summary> public string MimeVersion { get { SIP_HeaderField h = m_pHeader.GetFirst("Mime-Version:"); if (h != null) { return h.Value; } else { return null; } } set { if (value == null) { m_pHeader.RemoveFirst("Mime-Version:"); } else { m_pHeader.Set("Mime-Version:", value); } } } /// <summary> /// Gets or sets minimum refresh interval supported for soft-state elements managed by that server. /// Value -1 means that value not specified. /// </summary> public int MinExpires { get { SIP_HeaderField h = m_pHeader.GetFirst("Min-Expires:"); if (h != null) { return Convert.ToInt32(h.Value); } else { return -1; } } set { if (value < 0) { m_pHeader.RemoveFirst("Min-Expires:"); } else { m_pHeader.Set("Min-Expires:", value.ToString()); } } } /// <summary> /// Gets or sets Min-SE header which indicates the minimum value for the session interval, /// in units of delta-seconds. Defined in 4028. Value null means not specified. /// </summary> public SIP_t_MinSE MinSE { get { SIP_HeaderField h = m_pHeader.GetFirst("Min-SE:"); if (h != null) { return ((SIP_SingleValueHF<SIP_t_MinSE>) h).ValueX; } else { return null; } } set { if (value == null) { m_pHeader.RemoveFirst("Min-SE:"); } else { m_pHeader.Set("Min-SE:", value.ToStringValue()); } } } /// <summary> /// Gets or sets organization name which the SIP element issuing the request or response belongs. /// Value null means not specified. /// </summary> public string Organization { get { SIP_HeaderField h = m_pHeader.GetFirst("Organization:"); if (h != null) { return h.Value; } else { return null; } } set { if (value == null) { m_pHeader.RemoveFirst("Organization:"); } else { m_pHeader.Set("Organization:", value); } } } /// <summary> /// Gets an Path header. It is used in conjunction with SIP REGISTER requests and with 200 /// class messages in response to REGISTER (REGISTER responses). Defined in rfc 3327. /// </summary> public SIP_SVGroupHFCollection<SIP_t_AddressParam> Path { get { return new SIP_SVGroupHFCollection<SIP_t_AddressParam>(this, "Path:"); } } /// <summary> /// Gest or sets priority that the SIP request should have to the receiving human or its agent. /// Value null means not specified. /// </summary> public string Priority { get { SIP_HeaderField h = m_pHeader.GetFirst("Priority:"); if (h != null) { return h.Value; } else { return null; } } set { if (value == null) { m_pHeader.RemoveFirst("Priority:"); } else { m_pHeader.Set("Priority:", value); } } } // Privacy [RFC3323] /// <summary> /// Gets an proxy authentication challenge. /// </summary> public SIP_SVGroupHFCollection<SIP_t_Challenge> ProxyAuthenticate { get { return new SIP_SVGroupHFCollection<SIP_t_Challenge>(this, "Proxy-Authenticate:"); } } /// <summary> /// Gest credentials containing the authentication information of the user agent /// for the proxy and/or realm of the resource being requested. /// </summary> public SIP_SVGroupHFCollection<SIP_t_Credentials> ProxyAuthorization { get { return new SIP_SVGroupHFCollection<SIP_t_Credentials>(this, "Proxy-Authorization:"); } } /// <summary> /// Gets proxy-sensitive features that must be supported by the proxy. /// </summary> public SIP_MVGroupHFCollection<SIP_t_OptionTag> ProxyRequire { get { return new SIP_MVGroupHFCollection<SIP_t_OptionTag>(this, "Proxy-Require:"); } } /// <summary> /// Gets or sets RAck header. Defined in 3262. Value null means not specified. /// </summary> public SIP_t_RAck RAck { get { SIP_HeaderField h = m_pHeader.GetFirst("RAck:"); if (h != null) { return ((SIP_SingleValueHF<SIP_t_RAck>) h).ValueX; } else { return null; } } set { if (value == null) { m_pHeader.RemoveFirst("RAck:"); } else { m_pHeader.Set("RAck:", value.ToStringValue()); } } } /// <summary> /// Gets the Reason header. Defined in rfc 3326. /// </summary> public SIP_MVGroupHFCollection<SIP_t_ReasonValue> Reason { get { return new SIP_MVGroupHFCollection<SIP_t_ReasonValue>(this, "Reason:"); } } /// <summary> /// Gets the Record-Route header fields what is inserted by proxies in a request to /// force future requests in the dialog to be routed through the proxy. /// </summary> public SIP_MVGroupHFCollection<SIP_t_AddressParam> RecordRoute { get { return new SIP_MVGroupHFCollection<SIP_t_AddressParam>(this, "Record-Route:"); } } /// <summary> /// Gets or sets Refer-Sub header. Defined in rfc 4488. Value null means not specified. /// </summary> public SIP_t_ReferSub ReferSub { get { SIP_HeaderField h = m_pHeader.GetFirst("Refer-Sub:"); if (h != null) { return ((SIP_SingleValueHF<SIP_t_ReferSub>) h).ValueX; } else { return null; } } set { if (value == null) { m_pHeader.RemoveFirst("Refer-Sub:"); } else { m_pHeader.Add(new SIP_SingleValueHF<SIP_t_ReferSub>("Refer-Sub:", value)); } } } /// <summary> /// Gets or sets Refer-To header. Defined in rfc 3515. Value null means not specified. /// </summary> public SIP_t_AddressParam ReferTo { get { SIP_HeaderField h = m_pHeader.GetFirst("Refer-To:"); if (h != null) { return ((SIP_SingleValueHF<SIP_t_AddressParam>) h).ValueX; } else { return null; } } set { if (value == null) { m_pHeader.RemoveFirst("Refer-To:"); } else { m_pHeader.Add(new SIP_SingleValueHF<SIP_t_AddressParam>("Refer-To:", value)); } } } /// <summary> /// Gets or sets Referred-By header. Defined in rfc 3892. Value null means not specified. /// </summary> public SIP_t_ReferredBy ReferredBy { get { SIP_HeaderField h = m_pHeader.GetFirst("Referred-By:"); if (h != null) { return ((SIP_SingleValueHF<SIP_t_ReferredBy>) h).ValueX; } else { return null; } } set { if (value == null) { m_pHeader.RemoveFirst("Referred-By:"); } else { m_pHeader.Add(new SIP_SingleValueHF<SIP_t_ReferredBy>("Referred-By:", value)); } } } /// <summary> /// Gets Reject-Contact headers. Defined in RFC 3841. /// </summary> public SIP_MVGroupHFCollection<SIP_t_RCValue> RejectContact { get { return new SIP_MVGroupHFCollection<SIP_t_RCValue>(this, "Reject-Contact:"); } } /// <summary> /// Gets or sets Replaces header. Defined in rfc 3891. Value null means not specified. /// </summary> public SIP_t_Replaces Replaces { get { SIP_HeaderField h = m_pHeader.GetFirst("Replaces:"); if (h != null) { return ((SIP_SingleValueHF<SIP_t_Replaces>) h).ValueX; } else { return null; } } set { if (value == null) { m_pHeader.RemoveFirst("Replaces:"); } else { m_pHeader.Add(new SIP_SingleValueHF<SIP_t_Replaces>("Replaces:", value)); } } } /// <summary> /// Gets logical return URI that may be different from the From header field. /// </summary> public SIP_MVGroupHFCollection<SIP_t_AddressParam> ReplyTo { get { return new SIP_MVGroupHFCollection<SIP_t_AddressParam>(this, "Reply-To:"); } } /// <summary> /// Gets or sets Request-Disposition header. The Request-Disposition header field specifies caller preferences for /// how a server should process a request. Defined in rfc 3841. /// </summary> public SIP_MVGroupHFCollection<SIP_t_Directive> RequestDisposition { get { return new SIP_MVGroupHFCollection<SIP_t_Directive>(this, "Request-Disposition:"); } } /// <summary> /// Gets options that the UAC expects the UAS to support in order to process the request. /// </summary> public SIP_MVGroupHFCollection<SIP_t_OptionTag> Require { get { return new SIP_MVGroupHFCollection<SIP_t_OptionTag>(this, "Require:"); } } /// <summary> /// Gets Resource-Priority headers. Defined in RFC 4412. /// </summary> public SIP_MVGroupHFCollection<SIP_t_RValue> ResourcePriority { get { return new SIP_MVGroupHFCollection<SIP_t_RValue>(this, "Resource-Priority:"); } } /// <summary> /// Gets or sets how many seconds the service is expected to be unavailable to the requesting client. /// Value null means that value not specified. /// </summary> public SIP_t_RetryAfter RetryAfter { get { SIP_HeaderField h = m_pHeader.GetFirst("Retry-After:"); if (h != null) { return ((SIP_SingleValueHF<SIP_t_RetryAfter>) h).ValueX; } else { return null; } } set { if (value == null) { m_pHeader.RemoveFirst("Retry-After:"); } else { m_pHeader.Add(new SIP_SingleValueHF<SIP_t_RetryAfter>("Retry-After:", value)); } } } /// <summary> /// Gets force routing for a request through the listed set of proxies. /// </summary> public SIP_MVGroupHFCollection<SIP_t_AddressParam> Route { get { return new SIP_MVGroupHFCollection<SIP_t_AddressParam>(this, "Route:"); } } /// <summary> /// Gets or sets RSeq header. Value -1 means that value not specified. Defined in rfc 3262. /// </summary> public int RSeq { get { SIP_HeaderField h = m_pHeader.GetFirst("RSeq:"); if (h != null) { return Convert.ToInt32(h.Value); } else { return -1; } } set { if (value < 0) { m_pHeader.RemoveFirst("RSeq:"); } else { m_pHeader.Set("RSeq:", value.ToString()); } } } /// <summary> /// Gets Security-Client headers. Defined in RFC 3329. /// </summary> public SIP_MVGroupHFCollection<SIP_t_SecMechanism> SecurityClient { get { return new SIP_MVGroupHFCollection<SIP_t_SecMechanism>(this, "Security-Client:"); } } /// <summary> /// Gets Security-Server headers. Defined in RFC 3329. /// </summary> public SIP_MVGroupHFCollection<SIP_t_SecMechanism> SecurityServer { get { return new SIP_MVGroupHFCollection<SIP_t_SecMechanism>(this, "Security-Server:"); } } /// <summary> /// Gets Security-Verify headers. Defined in RFC 3329. /// </summary> public SIP_MVGroupHFCollection<SIP_t_SecMechanism> SecurityVerify { get { return new SIP_MVGroupHFCollection<SIP_t_SecMechanism>(this, "Security-Verify:"); } } /// <summary> /// Gets or sets the software used by the UAS to handle the request. /// Value null means not specified. /// </summary> public string Server { get { SIP_HeaderField h = m_pHeader.GetFirst("Server:"); if (h != null) { return h.Value; } else { return null; } } set { if (value == null) { m_pHeader.RemoveFirst("Server:"); } else { m_pHeader.Set("Server:", value); } } } /// <summary> /// Gets the Service-Route header. Defined in rfc 3608. /// </summary> public SIP_MVGroupHFCollection<SIP_t_AddressParam> ServiceRoute { get { return new SIP_MVGroupHFCollection<SIP_t_AddressParam>(this, "Service-Route:"); } } /// <summary> /// Gets or sets Session-Expires expires header. Value null means that value not specified. /// Defined in rfc 4028. /// </summary> public SIP_t_SessionExpires SessionExpires { get { SIP_HeaderField h = m_pHeader.GetFirst("Session-Expires:"); if (h != null) { return ((SIP_SingleValueHF<SIP_t_SessionExpires>) h).ValueX; } else { return null; } } set { if (value == null) { m_pHeader.RemoveFirst("Session-Expires:"); } else { m_pHeader.Set("Session-Expires:", value.ToStringValue()); } } } /// <summary> /// Gets or sets SIP-ETag header value. Value null means not specified. Defined in RFC 3903. /// </summary> public string SIPETag { get { SIP_HeaderField h = m_pHeader.GetFirst("SIP-ETag:"); if (h != null) { return h.Value; } else { return null; } } set { if (value == null) { m_pHeader.RemoveFirst("SIP-ETag:"); } else { m_pHeader.Set("SIP-ETag:", value); } } } /// <summary> /// Gets or sets SIP-ETag header value. Value null means not specified. Defined in RFC 3903. /// </summary> public string SIPIfMatch { get { SIP_HeaderField h = m_pHeader.GetFirst("SIP-If-Match:"); if (h != null) { return h.Value; } else { return null; } } set { if (value == null) { m_pHeader.RemoveFirst("SIP-If-Match:"); } else { m_pHeader.Set("SIP-If-Match:", value); } } } /// <summary> /// Gets or sets call subject text. /// Value null means not specified. /// </summary> public string Subject { get { SIP_HeaderField h = m_pHeader.GetFirst("Subject:"); if (h != null) { return h.Value; } else { return null; } } set { if (value == null) { m_pHeader.RemoveFirst("Subject:"); } else { m_pHeader.Set("Subject:", value); } } } /// <summary> /// Gets or sets Subscription-State header value. Value null means that value not specified. /// Defined in RFC 3265. /// </summary> public SIP_t_SubscriptionState SubscriptionState { get { SIP_HeaderField h = m_pHeader.GetFirst("Subscription-State:"); if (h != null) { return ((SIP_SingleValueHF<SIP_t_SubscriptionState>) h).ValueX; } else { return null; } } set { if (value == null) { m_pHeader.RemoveFirst("Subscription-State:"); } else { m_pHeader.Add(new SIP_SingleValueHF<SIP_t_SubscriptionState>("Subscription-State:", value)); } } } /// <summary> /// Gets extensions supported by the UAC or UAS. Known values are defined in SIP_OptionTags class. /// </summary> public SIP_MVGroupHFCollection<SIP_t_OptionTag> Supported { get { return new SIP_MVGroupHFCollection<SIP_t_OptionTag>(this, "Supported:"); } } /// <summary> /// Gets or sets Target-Dialog header value. Value null means that value not specified. /// Defined in RFC 4538. /// </summary> public SIP_t_TargetDialog TargetDialog { get { SIP_HeaderField h = m_pHeader.GetFirst("Target-Dialog:"); if (h != null) { return ((SIP_SingleValueHF<SIP_t_TargetDialog>) h).ValueX; } else { return null; } } set { if (value == null) { m_pHeader.RemoveFirst("Target-Dialog:"); } else { m_pHeader.Add(new SIP_SingleValueHF<SIP_t_TargetDialog>("Target-Dialog:", value)); } } } /// <summary> /// Gets or sets when the UAC sent the request to the UAS. /// Value null means that value not specified. /// </summary> public SIP_t_Timestamp Timestamp { get { SIP_HeaderField h = m_pHeader.GetFirst("Timestamp:"); if (h != null) { return ((SIP_SingleValueHF<SIP_t_Timestamp>) h).ValueX; } else { return null; } } set { if (value == null) { m_pHeader.RemoveFirst("Timestamp:"); } else { m_pHeader.Add(new SIP_SingleValueHF<SIP_t_Timestamp>("Timestamp:", value)); } } } /// <summary> /// Gets or sets logical recipient of the request. /// Value null means not specified. /// </summary> public SIP_t_To To { get { SIP_HeaderField h = m_pHeader.GetFirst("To:"); if (h != null) { return ((SIP_SingleValueHF<SIP_t_To>) h).ValueX; } else { return null; } } set { if (value == null) { m_pHeader.RemoveFirst("To:"); } else { m_pHeader.Add(new SIP_SingleValueHF<SIP_t_To>("To:", value)); } } } /// <summary> /// Gets features not supported by the UAS. /// </summary> public SIP_MVGroupHFCollection<SIP_t_OptionTag> Unsupported { get { return new SIP_MVGroupHFCollection<SIP_t_OptionTag>(this, "Unsupported:"); } } /// <summary> /// Gets or sets information about the UAC originating the request. /// Value null means not specified. /// </summary> public string UserAgent { get { SIP_HeaderField h = m_pHeader.GetFirst("User-Agent:"); if (h != null) { return h.Value; } else { return null; } } set { if (value == null) { m_pHeader.RemoveFirst("User-Agent:"); } else { m_pHeader.Set("User-Agent:", value); } } } /// <summary> /// Gets Via header fields.The Via header field indicates the transport used for the transaction /// and identifies the location where the response is to be sent. /// </summary> public SIP_MVGroupHFCollection<SIP_t_ViaParm> Via { get { return new SIP_MVGroupHFCollection<SIP_t_ViaParm>(this, "Via:"); } } /// <summary> /// Gets additional information about the status of a response. /// </summary> public SIP_MVGroupHFCollection<SIP_t_WarningValue> Warning { get { return new SIP_MVGroupHFCollection<SIP_t_WarningValue>(this, "Warning:"); } } /// <summary> /// Gets or authentication challenge. /// </summary> public SIP_SVGroupHFCollection<SIP_t_Challenge> WWWAuthenticate { get { return new SIP_SVGroupHFCollection<SIP_t_Challenge>(this, "WWW-Authenticate:"); } } /// <summary> /// Gets or sets content data. /// </summary> public byte[] Data { get { return m_Data; } set { m_Data = value; } } #endregion #region Constructor /// <summary> /// Default constuctor. /// </summary> public SIP_Message() { m_pHeader = new SIP_HeaderFieldCollection(); } #endregion /// <summary> /// Parses SIP message from specified byte array. /// </summary> /// <param name="data">SIP message data.</param> protected void InternalParse(byte[] data) { InternalParse(new MemoryStream(data)); } /// <summary> /// Parses SIP message from specified stream. /// </summary> /// <param name="stream">SIP message stream.</param> protected void InternalParse(Stream stream) { /* SIP message syntax: header-line<CRFL> .... <CRFL> data size of Content-Length header field. */ // Parse header Header.Parse(stream); // Parse data int contentLength = 0; try { contentLength = Convert.ToInt32(m_pHeader.GetFirst("Content-Length:").Value); } catch {} if (contentLength > 0) { byte[] data = new byte[contentLength]; stream.Read(data, 0, data.Length); Data = data; } } /// <summary> /// Stores SIP_Message to specified stream. /// </summary> /// <param name="stream">Stream where to store SIP_Message.</param> protected void InternalToStream(Stream stream) { // Ensure that we add right Contnet-Length. m_pHeader.RemoveAll("Content-Length:"); if (m_Data != null) { m_pHeader.Add("Content-Length:", Convert.ToString(m_Data.Length)); } else { m_pHeader.Add("Content-Length:", Convert.ToString(0)); } // Store header byte[] header = Encoding.UTF8.GetBytes(m_pHeader.ToHeaderString()); stream.Write(header, 0, header.Length); // Store data if (m_Data != null && m_Data.Length > 0) { stream.Write(m_Data, 0, m_Data.Length); } } } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/Multilang/IMLangConvertCharset.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace MultiLanguage { using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Security; [ComImport, Guid("D66D6F98-CDAA-11D0-B822-00C04FC9B31F"), InterfaceType((short) 1)] public interface IMLangConvertCharset { [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void Initialize([In] uint uiSrcCodePage, [In] uint uiDstCodePage, [In] uint dwProperty); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetSourceCodePage(out uint puiSrcCodePage); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetDestinationCodePage(out uint puiDstCodePage); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetProperty(out uint pdwProperty); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void DoConversion([In] ref byte pSrcStr, [In, Out] ref uint pcSrcSize, [In] ref byte pDstStr, [In, Out] ref uint pcDstSize); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void DoConversionToUnicode([In] ref sbyte pSrcStr, [In, Out] ref uint pcSrcSize, [In] ref ushort pDstStr, [In, Out] ref uint pcDstSize); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void DoConversionFromUnicode([In] ref ushort pSrcStr, [In, Out] ref uint pcSrcSize, [In] ref sbyte pDstStr, [In, Out] ref uint pcDstSize); } } <file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/MIME/O/MIME_MultipartBody.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.IO; using System.Collections.Generic; using System.Text; using LumiSoft.Net.IO; namespace LumiSoft.Net.MIME { /// <summary> /// Represents MIME entity multipart/... body. Defined in RFC 2045. /// </summary> public class MIME_MultipartBody : MIME_Body { #region class _MIME_MultipartReader /// <summary> /// This class implements mulitpart/xxx body parts reader. /// </summary> internal class _MIME_MultipartReader : LineReader { #region enum State /// <summary> /// Specifies reader state. /// </summary> private enum State { /// <summary> /// Body reading pending, the whole body isn't readed yet. /// </summary> InBody, /// <summary> /// First "body part" start must be searched. /// </summary> SeekFirst, /// <summary> /// Multipart "body part" reading has completed, next "body part" reading is pending. /// </summary> NextWaited, /// <summary> /// All "body parts" readed. /// </summary> Finished, } #endregion private LineReader m_pReader = null; private string m_Boundary = ""; private State m_State = State.SeekFirst; /// <summary> /// Default constructor. /// </summary> /// <param name="reader">Line reader.</param> /// <param name="boundary">Boundary ID.</param> public _MIME_MultipartReader(LineReader reader,string boundary) : base(reader.Stream,false,32000) { m_pReader = reader; m_Boundary = boundary; if(reader.CanSyncStream){ reader.SyncStream(); } } #region method Next /// <summary> /// Moves to next "body part". Returns true if moved to next "body part" or false if there are no more parts. /// </summary> /// <returns>Returns true if moved to next "body part" or false if there are no more parts.</returns> public bool Next() { // Seek first. if(m_State == State.SeekFirst){ while(true){ string line = m_pReader.ReadLine(); // We reached end of stream, no more data. if(line == null){ m_State = State.Finished; return false; } else if(line == "--" + m_Boundary){ m_State = State.InBody; return true; } } } else if(m_State != State.NextWaited){ return false; } else{ m_State = State.InBody; return true; } } #endregion #region method override ReadLine /// <summary> /// Reads binary line and stores it to the specified buffer. /// </summary> /// <param name="buffer">Buffer where to store line data.</param> /// <param name="offset">Start offset in the buffer.</param> /// <param name="count">Maximum number of bytes store to the buffer.</param> /// <param name="exceededAction">Specifies how reader acts when line buffer too small.</param> /// <param name="rawBytesReaded">Gets raw number of bytes readed from source.</param> /// <returns>Returns number of bytes stored to <b>buffer</b> or -1 if end of stream reached.</returns> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="ArgumentNullException">Is raised when <b>buffer</b> is null.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> /// <exception cref="LineSizeExceededException">Is raised when line is bigger than <b>buffer</b> can store.</exception> public override int ReadLine(byte[] buffer,int offset,int count,SizeExceededAction exceededAction,out int rawBytesReaded) { rawBytesReaded = 0; // We are at the end of body or "body part". if(m_State == State.Finished || m_State == State.NextWaited){ return -1; } // Read next line. else{ int readedCount = m_pReader.ReadLine(buffer,offset,count,exceededAction,out rawBytesReaded); // End of stream reached, no more data. if(readedCount == -1){ m_State = State.Finished; return -1; } // For multipart we must check boundary tags. else if(!string.IsNullOrEmpty(m_Boundary) && readedCount > 2 && buffer[0] == '-'){ string line = Encoding.Default.GetString(buffer,0,readedCount); // Boundray end-tag reached, no more "body parts". if(line == "--" + m_Boundary + "--"){ m_State = State.Finished; return -1; } // Boundary start-tag reached, wait for this.Next() call. else if(line == "--" + m_Boundary){ m_State = State.NextWaited; return -1; } } return readedCount; } } #endregion #region method SyncStream /// <summary> /// Sets stream position to the place we have consumed from stream and clears buffer data. /// For example if we have 10 byets in buffer, stream position is actually +10 bigger than /// we readed, the result is that stream.Position -= 10 and buffer is cleared. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when source stream won't support seeking.</exception> public override void SyncStream() { m_pReader.SyncStream(); } #endregion #region Properties Implementation #endregion } #endregion private string m_Boundary = ""; private MIME_EntityCollection m_pParts = null; /// <summary> /// Default constructor. /// </summary> /// <param name="owner">Owner MIME entity.</param> /// <exception cref="ArgumentNullException">Is raised when <b>owner</b> is null.</exception> internal MIME_MultipartBody(MIME_Entity owner) : base(owner) { m_Boundary = owner.ContentType.Param_Boundary; m_pParts = new MIME_EntityCollection(); } #region override method ToStream /// <summary> /// Stores MIME entity body data to the specified stream /// </summary> /// <param name="stream">Stream where to store body. Storing starts from stream current position.</param> /// <param name="encoded">If true, encoded data is stored, if false, decoded data will be stored.</param> /// <exception cref="ArgumentNullException">Is raised when <b>stream</b> is null.</exception> public override void ToStream(Stream stream,bool encoded) { } #endregion #region override method ParseFromReader /// <summary> /// Parses MIME entity body from the specified reader. /// </summary> /// <param name="reader">Body reader from where to parse body.</param> /// <param name="owner">Specifies if body will be stream owner.</param> /// <returns>Returns true if this is last boundary in the message or in multipart "body parts".</returns> internal override void ParseFromReader(LineReader reader,bool owner) { // For multipart we need todo new limiting(limits to specified boundary) reader. _MIME_MultipartReader r = new _MIME_MultipartReader(reader,m_Boundary); while(r.Next()){ MIME_Entity bodyPart = new MIME_Entity(); bodyPart.Parse(r,owner); m_pParts.Add(bodyPart); } } #endregion #region Properties Implementation /// <summary> /// Gets boundary ID. /// </summary> public string Boundary { get{ return m_Boundary; } } /// <summary> /// Gets body parts collection. /// </summary> public MIME_EntityCollection BodyParts { get{ return m_pParts; } } #endregion } } <file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/_Obsolete/SaslAuthTypes.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.AUTH { /// <summary> /// SASL authentications /// </summary> public enum SaslAuthTypes { /// <summary> /// Non authentication /// </summary> None = 0, /// <summary> /// Plain text authentication. For POP3 USER/PASS commands, for IMAP LOGIN command. /// </summary> Plain = 1, /// <summary> /// LOGIN. /// </summary> Login = 2, /// <summary> /// CRAM-MD5 /// </summary> Cram_md5 = 4, /// <summary> /// DIGEST-MD5. /// </summary> Digest_md5 = 8, /// <summary> /// All authentications. /// </summary> All = 0xF, } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/SMTP/SMTP_ServiceExtensions.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.SMTP { /// <summary> /// This class holds known SMTP service extensions. Defined in http://www.iana.org/assignments/mail-parameters. /// </summary> public class SMTP_ServiceExtensions { #region Members /// <summary> /// Use 8-bit data. Defined in RFC 1652. /// </summary> public static readonly string _8BITMIME = "8BITMIME"; /// <summary> /// Authenticated TURN. Defined in RFC 2645. /// </summary> public static readonly string ATRN = "ATRN"; /// <summary> /// Authentication. Defined in RFC 4954. /// </summary> public static readonly string AUTH = "AUTH"; /// <summary> /// Binary MIME. Defined in RFC 3030. /// </summary> public static readonly string BINARYMIME = "BINARYMIME"; /// <summary> /// Remote Content. Defined in RFC 4468. /// </summary> public static readonly string BURL = "BURL"; /// <summary> /// Checkpoint/Restart. Defined in RFC 1845. /// </summary> public static readonly string CHECKPOINT = "CHECKPOINT"; /// <summary> /// Chunking. Defined in RFC 3030. /// </summary> public static readonly string CHUNKING = "CHUNKING"; /// <summary> /// Delivery Status Notification. Defined in RFC 1891. /// </summary> public static readonly string DSN = "DSN"; /// <summary> /// Enhanced Status Codes. Defined in RFC 2034. /// </summary> public static readonly string ENHANCEDSTATUSCODES = "ENHANCEDSTATUSCODES"; /// <summary> /// Extended Turn. Defined in RFC 1985. /// </summary> public static readonly string ETRN = "ETRN"; /// <summary> /// Expand the mailing list. Defined in RFC 821, /// </summary> public static readonly string EXPN = "EXPN"; /// <summary> /// Future Message Release. Defined in RFC 4865. /// </summary> public static readonly string FUTURERELEASE = "FUTURERELEASE"; /// <summary> /// Supply helpful information. Defined in RFC 821. /// </summary> public static readonly string HELP = "HELP"; /// <summary> /// Message Tracking. Defined in RFC 3885. /// </summary> public static readonly string MTRK = "MTRK"; /// <summary> /// Notification of no soliciting. Defined in RFC 3865. /// </summary> public static readonly string NO_SOLICITING = "NO-SOLICITING"; /// <summary> /// Command Pipelining. Defined in RFC 2920. /// </summary> public static readonly string PIPELINING = "PIPELINING"; /// <summary> /// Send as mail and terminal. Defined in RFC 821. /// </summary> public static readonly string SAML = "SAML"; /// <summary> /// Send as mail. Defined in RFC RFC 821. /// </summary> public static readonly string SEND = "SEND"; /// <summary> /// Message size declaration. Defined in RFC 1870. /// </summary> public static readonly string SIZE = "SIZE"; /// <summary> /// Send as mail or terminal. Defined in RFC 821. /// </summary> public static readonly string SOML = "SOML"; /// <summary> /// Start TLS. Defined in RFC 3207. /// </summary> public static readonly string STARTTLS = "STARTTLS"; /// <summary> /// SMTP Responsible Submitter. Defined in RFC 4405. /// </summary> public static readonly string SUBMITTER = "SUBMITTER"; /// <summary> /// Turn the operation around. Defined in RFC 821. /// </summary> public static readonly string TURN = "TURN"; #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/SIP/Message/SIP_t_NameAddress.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.SIP.Message { #region usings using System; #endregion /// <summary> /// Implements SIP "name-addr" value. Defined in RFC 3261. /// </summary> /// <remarks> /// <code> /// RFC 3261 Syntax: /// name-addr = [ display-name ] LAQUOT addr-spec RAQUOT /// addr-spec = SIP-URI / SIPS-URI / absoluteURI /// </code> /// </remarks> public class SIP_t_NameAddress { #region Members private string m_DisplayName = ""; private AbsoluteUri m_pUri; #endregion #region Properties /// <summary> /// Gets or sets display name. /// </summary> public string DisplayName { get { return m_DisplayName; } set { if (value == null) { value = ""; } m_DisplayName = value; } } /// <summary> /// Gets or sets URI. This can be SIP-URI / SIPS-URI / absoluteURI. /// Examples: sip:<EMAIL>,sips:<EMAIL>,mailto:<EMAIL>, .... . /// </summary> /// <exception cref="ArgumentNullException">Is raised when null reference passed.</exception> public AbsoluteUri Uri { get { return m_pUri; } set { if (value == null) { throw new ArgumentNullException("value"); } m_pUri = value; } } /// <summary> /// Gets if current URI is sip or sips URI. /// </summary> public bool IsSipOrSipsUri { get { return IsSipUri || IsSecureSipUri; } } /// <summary> /// Gets if current URI is SIP uri. /// </summary> public bool IsSipUri { get { if (m_pUri.Scheme == UriSchemes.sip) { return true; } return false; } } /// <summary> /// Gets if current URI is SIPS uri. /// </summary> public bool IsSecureSipUri { get { if (m_pUri.Scheme == UriSchemes.sips) { return true; } return false; } } /// <summary> /// Gets if current URI is MAILTO uri. /// </summary> public bool IsMailToUri { get { if (m_pUri.Scheme == UriSchemes.mailto) { return true; } return false; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> public SIP_t_NameAddress() {} /// <summary> /// Default constructor. /// </summary> /// <param name="value">SIP <b>name-addr</b> value.</param> /// <exception cref="ArgumentNullException">Raised when <b>reader</b> is null.</exception> /// <exception cref="SIP_ParseException">Raised when invalid SIP message.</exception> public SIP_t_NameAddress(string value) { Parse(value); } /// <summary> /// Default constructor. /// </summary> /// <param name="displayName">Display name.</param> /// <param name="uri">Uri.</param> /// <exception cref="ArgumentNullException">Is raised when <b>uri</b> is null reference.</exception> public SIP_t_NameAddress(string displayName, AbsoluteUri uri) { if (uri == null) { throw new ArgumentNullException("uri"); } DisplayName = displayName; Uri = uri; } #endregion #region Methods /// <summary> /// Parses "name-addr" or "addr-spec" from specified value. /// </summary> /// <param name="value">SIP "name-addr" or "addr-spec" value.</param> /// <exception cref="ArgumentNullException">Raised when <b>reader</b> is null.</exception> /// <exception cref="SIP_ParseException">Raised when invalid SIP message.</exception> public void Parse(string value) { if (value == null) { throw new ArgumentNullException("reader"); } Parse(new StringReader(value)); } /// <summary> /// Parses "name-addr" or "addr-spec" from specified reader. /// </summary> /// <param name="reader">Reader from where to parse.</param> /// <exception cref="ArgumentNullException">Raised when <b>reader</b> is null.</exception> /// <exception cref="SIP_ParseException">Raised when invalid SIP message.</exception> public void Parse(StringReader reader) { /* RFC 3261. name-addr = [ display-name ] LAQUOT addr-spec RAQUOT addr-spec = SIP-URI / SIPS-URI / absoluteURI */ if (reader == null) { throw new ArgumentNullException("reader"); } reader.ReadToFirstChar(); // LAQUOT addr-spec RAQUOT if (reader.StartsWith("<")) { m_pUri = AbsoluteUri.Parse(reader.ReadParenthesized()); } else { string word = reader.ReadWord(); if (word == null) { throw new SIP_ParseException("Invalid 'name-addr' or 'addr-spec' value !"); } reader.ReadToFirstChar(); // name-addr if (reader.StartsWith("<")) { m_DisplayName = word; m_pUri = AbsoluteUri.Parse(reader.ReadParenthesized()); } // addr-spec else { m_pUri = AbsoluteUri.Parse(word); } } } /// <summary> /// Converts this to valid name-addr or addr-spec string as needed. /// </summary> /// <returns>Returns name-addr or addr-spec string.</returns> public string ToStringValue() { /* RFC 3261. name-addr = [ display-name ] LAQUOT addr-spec RAQUOT addr-spec = SIP-URI / SIPS-URI / absoluteURI */ // addr-spec if (string.IsNullOrEmpty(m_DisplayName)) { return "<" + m_pUri + ">"; } // name-addr else { return TextUtils.QuoteString(m_DisplayName) + " <" + m_pUri + ">"; } } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/Log/Logger.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.Log { #region usings using System; using System.Net; using System.Security.Principal; #endregion /// <summary> /// General logging module. /// </summary> public class Logger : IDisposable { #region Events /// <summary> /// Is raised when new log entry is available. /// </summary> public event EventHandler<WriteLogEventArgs> WriteLog = null; #endregion #region Methods /// <summary> /// Cleans up any resources being used. /// </summary> public void Dispose() {} /// <summary> /// Adds read log entry. /// </summary> /// <param name="size">Readed data size in bytes.</param> /// <param name="text">Log text.</param> public void AddRead(long size, string text) { OnWriteLog(new LogEntry(LogEntryType.Read, "", size, text)); } /// <summary> /// Adds read log entry. /// </summary> /// <param name="id">Log entry ID.</param> /// <param name="size">Readed data size in bytes.</param> /// <param name="text">Log text.</param> /// <param name="userIdentity">Authenticated user identity.</param> /// <param name="localEP">Local IP endpoint.</param> /// <param name="remoteEP">Remote IP endpoint.</param> public void AddRead(string id, GenericIdentity userIdentity, long size, string text, IPEndPoint localEP, IPEndPoint remoteEP) { OnWriteLog(new LogEntry(LogEntryType.Read, id, userIdentity, size, text, localEP, remoteEP, (byte[]) null)); } /// <summary> /// Adds read log entry. /// </summary> /// <param name="id">Log entry ID.</param> /// <param name="size">Readed data size in bytes.</param> /// <param name="text">Log text.</param> /// <param name="userIdentity">Authenticated user identity.</param> /// <param name="localEP">Local IP endpoint.</param> /// <param name="remoteEP">Remote IP endpoint.</param> /// <param name="data">Log data.</param> public void AddRead(string id, GenericIdentity userIdentity, long size, string text, IPEndPoint localEP, IPEndPoint remoteEP, byte[] data) { OnWriteLog(new LogEntry(LogEntryType.Read, id, userIdentity, size, text, localEP, remoteEP, data)); } /// <summary> /// Add write log entry. /// </summary> /// <param name="size">Written data size in bytes.</param> /// <param name="text">Log text.</param> public void AddWrite(long size, string text) { OnWriteLog(new LogEntry(LogEntryType.Write, "", size, text)); } /// <summary> /// Add write log entry. /// </summary> /// <param name="id">Log entry ID.</param> /// <param name="size">Written data size in bytes.</param> /// <param name="text">Log text.</param> /// <param name="userIdentity">Authenticated user identity.</param> /// <param name="localEP">Local IP endpoint.</param> /// <param name="remoteEP">Remote IP endpoint.</param> public void AddWrite(string id, GenericIdentity userIdentity, long size, string text, IPEndPoint localEP, IPEndPoint remoteEP) { OnWriteLog(new LogEntry(LogEntryType.Write, id, userIdentity, size, text, localEP, remoteEP, (byte[]) null)); } /// <summary> /// Add write log entry. /// </summary> /// <param name="id">Log entry ID.</param> /// <param name="size">Written data size in bytes.</param> /// <param name="text">Log text.</param> /// <param name="userIdentity">Authenticated user identity.</param> /// <param name="localEP">Local IP endpoint.</param> /// <param name="remoteEP">Remote IP endpoint.</param> /// <param name="data">Log data.</param> public void AddWrite(string id, GenericIdentity userIdentity, long size, string text, IPEndPoint localEP, IPEndPoint remoteEP, byte[] data) { OnWriteLog(new LogEntry(LogEntryType.Write, id, userIdentity, size, text, localEP, remoteEP, data)); } /// <summary> /// Adds text entry. /// </summary> /// <param name="text">Log text.</param> public void AddText(string text) { OnWriteLog(new LogEntry(LogEntryType.Text, "", 0, text)); } /// <summary> /// Adds text entry. /// </summary> /// <param name="id">Log entry ID.</param> /// <param name="text">Log text.</param> public void AddText(string id, string text) { OnWriteLog(new LogEntry(LogEntryType.Text, id, 0, text)); } /// <summary> /// Adds text entry. /// </summary> /// <param name="id">Log entry ID.</param> /// <param name="text">Log text.</param> /// <param name="userIdentity">Authenticated user identity.</param> /// <param name="localEP">Local IP endpoint.</param> /// <param name="remoteEP">Remote IP endpoint.</param> public void AddText(string id, GenericIdentity userIdentity, string text, IPEndPoint localEP, IPEndPoint remoteEP) { OnWriteLog(new LogEntry(LogEntryType.Read, id, userIdentity, 0, text, localEP, remoteEP, (byte[]) null)); } /// <summary> /// Adds exception entry. /// </summary> /// <param name="id">Log entry ID.</param> /// <param name="text">Log text.</param> /// <param name="userIdentity">Authenticated user identity.</param> /// <param name="localEP">Local IP endpoint.</param> /// <param name="remoteEP">Remote IP endpoint.</param> /// <param name="exception">Exception happened.</param> public void AddException(string id, GenericIdentity userIdentity, string text, IPEndPoint localEP, IPEndPoint remoteEP, Exception exception) { OnWriteLog(new LogEntry(LogEntryType.Exception, id, userIdentity, 0, text, localEP, remoteEP, exception)); } #endregion #region Utility methods /// <summary> /// Raises WriteLog event. /// </summary> /// <param name="entry">Log entry.</param> private void OnWriteLog(LogEntry entry) { if (WriteLog != null) { WriteLog(this, new WriteLogEventArgs(entry)); } } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/DNS/Client/DNS_rr_base.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.Dns.Client { /// <summary> /// Base class for DNS records. /// </summary> public abstract class DNS_rr_base { #region Members private readonly int m_TTL = -1; private readonly QTYPE m_Type = QTYPE.A; #endregion #region Properties /// <summary> /// Gets record type (A,MX,...). /// </summary> public QTYPE RecordType { get { return m_Type; } } /// <summary> /// Gets TTL (time to live) value in seconds. /// </summary> public int TTL { get { return m_TTL; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="recordType">Record type (A,MX, ...).</param> /// <param name="ttl">TTL (time to live) value in seconds.</param> public DNS_rr_base(QTYPE recordType, int ttl) { m_Type = recordType; m_TTL = ttl; } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/IPBindInfo.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net { #region usings using System; using System.Net; using System.Security.Cryptography.X509Certificates; #endregion /// <summary> /// Holds IP bind info. /// </summary> public class IPBindInfo { #region Members private readonly string m_HostName = ""; private readonly X509Certificate2 m_pCertificate; private readonly IPEndPoint m_pEndPoint; private readonly BindInfoProtocol m_Protocol = BindInfoProtocol.TCP; private readonly SslMode m_SslMode = SslMode.None; #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="hostName">Host name.</param> /// <param name="protocol">Bind protocol.</param> /// <param name="ip">IP address to listen.</param> /// <param name="port">Port to listen.</param> /// <exception cref="ArgumentNullException">Is raised when <b>ip</b> is null.</exception> public IPBindInfo(string hostName, BindInfoProtocol protocol, IPAddress ip, int port) { if (ip == null) { throw new ArgumentNullException("ip"); } m_HostName = hostName; m_Protocol = protocol; m_pEndPoint = new IPEndPoint(ip, port); } /// <summary> /// Default constructor. /// </summary> /// <param name="hostName">Host name.</param> /// <param name="ip">IP address to listen.</param> /// <param name="port">Port to listen.</param> /// <param name="sslMode">Specifies SSL mode.</param> /// <param name="sslCertificate">Certificate to use for SSL connections.</param> /// <exception cref="ArgumentNullException">Is raised when <b>ip</b> is null.</exception> public IPBindInfo(string hostName, IPAddress ip, int port, SslMode sslMode, X509Certificate2 sslCertificate) : this(hostName, BindInfoProtocol.TCP, ip, port, sslMode, sslCertificate) {} /// <summary> /// Default constructor. /// </summary> /// <param name="hostName">Host name.</param> /// <param name="protocol">Bind protocol.</param> /// <param name="ip">IP address to listen.</param> /// <param name="port">Port to listen.</param> /// <param name="sslMode">Specifies SSL mode.</param> /// <param name="sslCertificate">Certificate to use for SSL connections.</param> /// <exception cref="ArgumentNullException">Is raised when <b>ip</b> is null.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> public IPBindInfo(string hostName, BindInfoProtocol protocol, IPAddress ip, int port, SslMode sslMode, X509Certificate2 sslCertificate) { if (ip == null) { throw new ArgumentNullException("ip"); } m_HostName = hostName; m_Protocol = protocol; m_pEndPoint = new IPEndPoint(ip, port); m_SslMode = sslMode; m_pCertificate = sslCertificate; if ((sslMode == SslMode.SSL || sslMode == SslMode.TLS) && sslCertificate == null) { throw new ArgumentException("SSL requested, but argument 'sslCertificate' is not provided."); } } #endregion #region Properties /// <summary> /// Gets SSL certificate. /// </summary> public X509Certificate2 Certificate { get { return m_pCertificate; } } /// <summary> /// Gets IP end point. /// </summary> public IPEndPoint EndPoint { get { return m_pEndPoint; } } /// <summary> /// Gets host name. /// </summary> public string HostName { get { return m_HostName; } } /// <summary> /// Gets IP address. /// </summary> public IPAddress IP { get { return m_pEndPoint.Address; } } /// <summary> /// Gets port. /// </summary> public int Port { get { return m_pEndPoint.Port; } } /// <summary> /// Gets protocol. /// </summary> public BindInfoProtocol Protocol { get { return m_Protocol; } } /// <summary> /// Gets SSL certificate. /// </summary> [Obsolete("Use property Certificate instead.")] public X509Certificate2 SSL_Certificate { get { return m_pCertificate; } } /// <summary> /// Gets SSL mode. /// </summary> public SslMode SslMode { get { return m_SslMode; } } /// <summary> /// Gets or sets user data. This is used internally don't use it !!!. /// </summary> public object Tag { get; set; } #endregion #region Methods /// <summary> /// Compares the current instance with another object of the same type. /// </summary> /// <param name="obj">An object to compare with this instance.</param> /// <returns>Returns true if two objects are equal.</returns> public override bool Equals(object obj) { if (obj == null) { return false; } if (!(obj is IPBindInfo)) { return false; } IPBindInfo bInfo = (IPBindInfo) obj; if (bInfo.HostName != m_HostName) { return false; } if (bInfo.Protocol != m_Protocol) { return false; } if (!bInfo.EndPoint.Equals(m_pEndPoint)) { return false; } if (bInfo.SslMode != m_SslMode) { return false; } if (!Equals(bInfo.Certificate, m_pCertificate)) { return false; } return true; } /// <summary> /// Returns the hash code. /// </summary> /// <returns>Returns the hash code.</returns> public override int GetHashCode() { return base.GetHashCode(); } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/MIME/MIME_b_Multipart.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.MIME { #region usings using System; using System.IO; using System.Text; using IO; #endregion /// <summary> /// This class represents MIME application/xxx bodies. Defined in RFC 2046 5.1. /// </summary> /// <remarks> /// The "multipart" represents single MIME body containing multiple child MIME entities. /// The "multipart" body must contain at least 1 MIME entity. /// </remarks> public class MIME_b_Multipart : MIME_b { #region Nested type: _MultipartReader /// <summary> /// Implements multipart "body parts" reader. /// </summary> public class _MultipartReader : Stream { #region Nested type: State /// <summary> /// This enum specified multipart reader sate. /// </summary> private enum State { /// <summary> /// First boundary must be seeked. /// </summary> SeekFirst = 0, /// <summary> /// Read next boundary. /// </summary> ReadNext = 1, /// <summary> /// All boundraies readed. /// </summary> Done = 2, } #endregion #region Members private readonly string m_Boundary = ""; private readonly SmartStream.ReadLineAsyncOP m_pReadLineOP; private readonly SmartStream m_pStream; private readonly StringBuilder m_pTextEpilogue; private readonly StringBuilder m_pTextPreamble; private State m_State = State.SeekFirst; #endregion #region Properties /// <summary> /// Gets a value indicating whether the current stream supports reading. /// </summary> public override bool CanRead { get { return true; } } /// <summary> /// Gets a value indicating whether the current stream supports seeking. /// </summary> public override bool CanSeek { get { return false; } } /// <summary> /// Gets a value indicating whether the current stream supports writing. /// </summary> public override bool CanWrite { get { return false; } } /// <summary> /// Gets the length in bytes of the stream. This method is not supported and always throws a NotSupportedException. /// </summary> /// <exception cref="NotSupportedException">Is raised when this property is accessed.</exception> public override long Length { get { throw new NotSupportedException(); } } /// <summary> /// Gets or sets the position within the current stream. This method is not supported and always throws a NotSupportedException. /// </summary> /// <exception cref="NotSupportedException">Is raised when this property is accessed.</exception> public override long Position { get { throw new NotSupportedException(); } set { throw new NotSupportedException(); } } /// <summary> /// Gets "preamble" text. Defined in RFC 2046 5.1.1. /// </summary> /// <remarks>Preamble text is text between MIME entiy headers and first boundary.</remarks> public string TextPreamble { get { return m_pTextPreamble.ToString(); } } /// <summary> /// Gets "epilogue" text. Defined in RFC 2046 5.1.1. /// </summary> /// <remarks>Epilogue text is text after last boundary end.</remarks> public string TextEpilogue { get { return m_pTextEpilogue.ToString(); } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="stream">Stream from where to read body part.</param> /// <param name="boundary">Boundry ID what separates body parts.</param> /// <exception cref="ArgumentNullException">Is raised when <b>stream</b> or <b>boundary</b> is null reference.</exception> public _MultipartReader(SmartStream stream, string boundary) { if (stream == null) { throw new ArgumentNullException("stream"); } if (boundary == null) { throw new ArgumentNullException("boundary"); } m_pStream = stream; m_Boundary = boundary; m_pReadLineOP = new SmartStream.ReadLineAsyncOP(new byte[Workaround.Definitions.MaxStreamLineLength], SizeExceededAction.ThrowException); m_pTextPreamble = new StringBuilder(); m_pTextEpilogue = new StringBuilder(); } #endregion #region Methods /// <summary> /// Moves to next "body part". Returns true if moved to next "body part" or false if there are no more parts. /// </summary> /// <returns>Returns true if moved to next "body part" or false if there are no more body parts.</returns> public bool Next() { if (m_State == State.Done) { return false; } else if (m_State == State.SeekFirst) { while (true) { m_pStream.ReadLine(m_pReadLineOP, false); if (m_pReadLineOP.Error != null) { throw m_pReadLineOP.Error; } // We reached end of stream. Bad boundary: boundary end tag missing. else if (m_pReadLineOP.BytesInBuffer == 0) { m_State = State.Done; return false; } else { // Check if we have boundary start/end. if (m_pReadLineOP.Buffer[0] == '-') { string boundary = m_pReadLineOP.LineUtf8; // We have readed all MIME entity body parts. if ("--" + m_Boundary + "--" == boundary) { m_State = State.Done; return false; } // We have next boundary. else if ("--" + m_Boundary == boundary) { m_State = State.ReadNext; return true; } // Not boundary or not boundary we want. //else{ } m_pTextPreamble.Append(m_pReadLineOP.LineUtf8 + "\r\n"); } } } else if (m_State == State.ReadNext) { return true; } return false; } /// <summary> /// Clears all buffers for this stream and causes any buffered data to be written to the underlying device. /// </summary> public override void Flush() {} /// <summary> /// Sets the position within the current stream. This method is not supported and always throws a NotSupportedException. /// </summary> /// <param name="offset">A byte offset relative to the <b>origin</b> parameter.</param> /// <param name="origin">A value of type SeekOrigin indicating the reference point used to obtain the new position.</param> /// <returns>The new position within the current stream.</returns> /// <exception cref="NotSupportedException">Is raised when this method is accessed.</exception> public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(); } /// <summary> /// Sets the length of the current stream. This method is not supported and always throws a NotSupportedException. /// </summary> /// <param name="value">The desired length of the current stream in bytes.</param> /// <exception cref="Seek">Is raised when this method is accessed.</exception> public override void SetLength(long value) { throw new NotSupportedException(); } /// <summary> /// Reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read. /// </summary> /// <param name="buffer">An array of bytes. When this method returns, the buffer contains the specified byte array with the values between offset and (offset + count - 1) replaced by the bytes read from the current source.</param> /// <param name="offset">The zero-based byte offset in buffer at which to begin storing the data read from the current stream.</param> /// <param name="count">The maximum number of bytes to be read from the current stream.</param> /// <returns>The total number of bytes read into the buffer. This can be less than the number of bytes requested if that many bytes are not currently available, or zero (0) if the end of the stream has been reached.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>buffer</b> is null reference.</exception> public override int Read(byte[] buffer, int offset, int count) { if (buffer == null) { throw new ArgumentNullException("buffer"); } if (m_State == State.Done) { return 0; } m_pStream.ReadLine(m_pReadLineOP, false); if (m_pReadLineOP.Error != null) { throw m_pReadLineOP.Error; } // We reached end of stream. Bad boundary: boundary end tag missing. else if (m_pReadLineOP.BytesInBuffer == 0) { m_State = State.Done; return 0; } else { // Check if we have boundary start/end. if (m_pReadLineOP.Buffer[0] == '-') { string boundary = m_pReadLineOP.LineUtf8; // We have readed all MIME entity body parts. if ("--" + m_Boundary + "--" == boundary) { m_State = State.Done; // Read "epilogoue" if any. while (true) { m_pStream.ReadLine(m_pReadLineOP, false); if (m_pReadLineOP.Error != null) { throw m_pReadLineOP.Error; } // We reached end of stream. Epilogue reading completed. else if (m_pReadLineOP.BytesInBuffer == 0) { break; } else { m_pTextEpilogue.Append(m_pReadLineOP.LineUtf8 + "\r\n"); } } return 0; } // We have next boundary. else if ("--" + m_Boundary == boundary) { return 0; } // Not boundary or not boundary we want. //else{ } // We have body part data line //else{ if (count < m_pReadLineOP.BytesInBuffer) { //throw new ArgumentException("Argument 'buffer' is to small. This should never happen."); } Array.Copy(m_pReadLineOP.Buffer, 0, buffer, offset, m_pReadLineOP.BytesInBuffer); return m_pReadLineOP.BytesInBuffer; } } /// <summary> /// Writes sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written. /// </summary> /// <param name="buffer">An array of bytes. This method copies count bytes from buffer to the current stream.</param> /// <param name="offset">The zero-based byte offset in buffer at which to begin copying bytes to the current stream.</param> /// <param name="count">The number of bytes to be written to the current stream.</param> /// <exception cref="NotSupportedException">Is raised when this method is accessed.</exception> public override void Write(byte[] buffer, int offset, int count) { throw new NotSupportedException(); } #endregion } #endregion #region Members private readonly MIME_EntityCollection m_pBodyParts; private string m_TextEpilogue = ""; private string m_TextPreamble = ""; #endregion #region Properties /// <summary> /// Gets if body has modified. /// </summary> public override bool IsModified { get { return m_pBodyParts.IsModified; } } /// <summary> /// Gets default body part Content-Type. For more info see RFC 2046 5.1. /// </summary> public virtual MIME_h_ContentType DefaultBodyPartContentType { /* RFC 2026 5.1. The absence of a Content-Type header usually indicates that the corresponding body has a content-type of "text/plain; charset=US-ASCII". */ get { MIME_h_ContentType retVal = new MIME_h_ContentType("text/plain"); retVal.Param_Charset = "US-ASCII"; return retVal; } } /// <summary> /// Gets multipart body body-parts collection. /// </summary> /// <remarks>Multipart entity child entities are called "body parts" in RFC 2045.</remarks> public MIME_EntityCollection BodyParts { get { return m_pBodyParts; } } /// <summary> /// Gets or sets "preamble" text. Defined in RFC 2046 5.1.1. /// </summary> /// <remarks>Preamble text is text between MIME entiy headers and first boundary.</remarks> public string TextPreamble { get { return m_TextPreamble; } set { m_TextPreamble = value; } } /// <summary> /// Gets or sets "epilogue" text. Defined in RFC 2046 5.1.1. /// </summary> /// <remarks>Epilogue text is text after last boundary end.</remarks> public string TextEpilogue { get { return m_TextEpilogue; } set { m_TextEpilogue = value; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="contentType">Content type.</param> /// <exception cref="ArgumentNullException">Is raised when <b>contentType</b> is null reference.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> public MIME_b_Multipart(MIME_h_ContentType contentType) : base(contentType) { if (contentType == null) { throw new ArgumentNullException("contentType"); } if (string.IsNullOrEmpty(contentType.Param_Boundary)) { throw new ArgumentException( "Argument 'contentType' doesn't contain required boundary parameter."); } m_pBodyParts = new MIME_EntityCollection(); } #endregion #region Overrides /// <summary> /// Stores MIME entity body to the specified stream. /// </summary> /// <param name="stream">Stream where to store body data.</param> /// <param name="headerWordEncoder">Header 8-bit words ecnoder. Value null means that words are not encoded.</param> /// <param name="headerParmetersCharset">Charset to use to encode 8-bit header parameters. Value null means parameters not encoded.</param> /// <exception cref="ArgumentNullException">Is raised when <b>stream</b> is null reference.</exception> protected internal override void ToStream(Stream stream, MIME_Encoding_EncodedWord headerWordEncoder, Encoding headerParmetersCharset) { if (stream == null) { throw new ArgumentNullException("stream"); } // Set "preamble" text if any. if (!string.IsNullOrEmpty(m_TextPreamble)) { byte[] preableBytes = null; if (m_TextPreamble.EndsWith("\r\n")) { preableBytes = Encoding.UTF8.GetBytes(m_TextPreamble); } else { preableBytes = Encoding.UTF8.GetBytes(m_TextPreamble + "\r\n"); } stream.Write(preableBytes, 0, preableBytes.Length); } for (int i = 0; i < m_pBodyParts.Count; i++) { MIME_Entity bodyPart = m_pBodyParts[i]; // Start new body part. byte[] bStart = Encoding.UTF8.GetBytes("--" + ContentType.Param_Boundary + "\r\n"); stream.Write(bStart, 0, bStart.Length); bodyPart.ToStream(stream, headerWordEncoder, headerParmetersCharset); // Last body part, close boundary. if (i == (m_pBodyParts.Count - 1)) { byte[] bEnd = Encoding.UTF8.GetBytes("--" + ContentType.Param_Boundary + "--\r\n"); stream.Write(bEnd, 0, bEnd.Length); } } // Set "epilogoue" text if any. if (!string.IsNullOrEmpty(m_TextEpilogue)) { byte[] epilogoueBytes = null; if (m_TextEpilogue.EndsWith("\r\n")) { epilogoueBytes = Encoding.UTF8.GetBytes(m_TextEpilogue); } else { epilogoueBytes = Encoding.UTF8.GetBytes(m_TextEpilogue + "\r\n"); } stream.Write(epilogoueBytes, 0, epilogoueBytes.Length); } } #endregion /// <summary> /// Parses body from the specified stream /// </summary> /// <param name="owner">Owner MIME entity.</param> /// <param name="mediaType">MIME media type. For example: text/plain.</param> /// <param name="stream">Stream from where to read body.</param> /// <returns>Returns parsed body.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>stream</b>, <b>mediaType</b> or <b>stream</b> is null reference.</exception> /// <exception cref="ParseException">Is raised when any parsing errors.</exception> protected new static MIME_b Parse(MIME_Entity owner, string mediaType, SmartStream stream) { if (owner == null) { throw new ArgumentNullException("owner"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } if (stream == null) { throw new ArgumentNullException("stream"); } if (owner.ContentType == null || owner.ContentType.Param_Boundary == null) { throw new ParseException("Multipart entity has not required 'boundary' paramter."); } MIME_b_Multipart retVal = new MIME_b_Multipart(owner.ContentType); ParseInternal(owner, mediaType, stream, retVal); return retVal; } /// <summary> /// Internal body parsing. /// </summary> /// <param name="owner">Owner MIME entity.</param> /// <param name="mediaType">MIME media type. For example: text/plain.</param> /// <param name="stream">Stream from where to read body.</param> /// <param name="body">Multipart body instance.</param> /// <exception cref="ArgumentNullException">Is raised when <b>stream</b>, <b>mediaType</b>, <b>stream</b> or <b>body</b> is null reference.</exception> /// <exception cref="ParseException">Is raised when any parsing errors.</exception> protected static void ParseInternal(MIME_Entity owner, string mediaType, SmartStream stream, MIME_b_Multipart body) { if (owner == null) { throw new ArgumentNullException("owner"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } if (stream == null) { throw new ArgumentNullException("stream"); } if (owner.ContentType == null || owner.ContentType.Param_Boundary == null) { throw new ParseException("Multipart entity has not required 'boundary' parameter."); } if (body == null) { throw new ArgumentNullException("body"); } _MultipartReader multipartReader = new _MultipartReader(stream, owner.ContentType.Param_Boundary); while (multipartReader.Next()) { MIME_Entity entity = new MIME_Entity(); entity.Parse(new SmartStream(multipartReader, false), body.DefaultBodyPartContentType); body.m_pBodyParts.Add(entity); entity.SetParent(owner); } body.m_TextPreamble = multipartReader.TextPreamble; body.m_TextEpilogue = multipartReader.TextEpilogue; } } }<file_sep>/module/ASC.AuditTrail/Mappers/DocumentsActionMapper.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System.Collections.Generic; using ASC.MessagingSystem; namespace ASC.AuditTrail.Mappers { internal class DocumentsActionMapper { public static Dictionary<MessageAction, MessageMaps> GetMaps() { return new Dictionary<MessageAction, MessageMaps> { { MessageAction.FileCreated, new MessageMaps { ActionTypeTextResourceName = "CreateActionType", ActionTextResourceName = "FileCreated", ProductResourceName = "DocumentsProduct", ModuleResourceName = "FilesModule" } }, { MessageAction.FileRenamed, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "FileRenamed", ProductResourceName = "DocumentsProduct", ModuleResourceName = "FilesModule" } }, { MessageAction.FileUpdated, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "FileUpdated", ProductResourceName = "DocumentsProduct", ModuleResourceName = "FilesModule" } }, { MessageAction.UserFileUpdated, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "UserFileUpdated", ProductResourceName = "DocumentsProduct", ModuleResourceName = "FilesModule" } }, { MessageAction.FileCreatedVersion, new MessageMaps { ActionTypeTextResourceName = "CreateActionType", ActionTextResourceName = "FileCreatedVersion", ProductResourceName = "DocumentsProduct", ModuleResourceName = "FilesModule" } }, { MessageAction.FileDeletedVersion, new MessageMaps { ActionTypeTextResourceName = "DeleteActionType", ActionTextResourceName = "FileDeletedVersion", ProductResourceName = "DocumentsProduct", ModuleResourceName = "FilesModule" } }, { MessageAction.FileRestoreVersion, new MessageMaps { ActionTypeTextResourceName = "CreateActionType", ActionTextResourceName = "FileRestoreVersion", ProductResourceName = "DocumentsProduct", ModuleResourceName = "FilesModule" } }, { MessageAction.FileUpdatedRevisionComment, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "FileUpdatedRevisionComment", ProductResourceName = "DocumentsProduct", ModuleResourceName = "FilesModule" } }, { MessageAction.FileLocked, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "FileLocked", ProductResourceName = "DocumentsProduct", ModuleResourceName = "FilesModule" } }, { MessageAction.FileUnlocked, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "FileUnlocked", ProductResourceName = "DocumentsProduct", ModuleResourceName = "FilesModule" } }, { MessageAction.FileUpdatedAccess, new MessageMaps { ActionTypeTextResourceName = "UpdateAccessActionType", ActionTextResourceName = "FileUpdatedAccess", ProductResourceName = "DocumentsProduct", ModuleResourceName = "FilesModule" } }, { MessageAction.FileDownloaded, new MessageMaps { ActionTypeTextResourceName = "DownloadActionType", ActionTextResourceName = "FileDownloaded", ProductResourceName = "DocumentsProduct", ModuleResourceName = "FilesModule" } }, { MessageAction.FileDownloadedAs, new MessageMaps { ActionTypeTextResourceName = "DownloadActionType", ActionTextResourceName = "FileDownloadedAs", ProductResourceName = "DocumentsProduct", ModuleResourceName = "FilesModule" } }, { MessageAction.FileUploaded, new MessageMaps { ActionTypeTextResourceName = "UploadActionType", ActionTextResourceName = "FileUploaded", ProductResourceName = "DocumentsProduct", ModuleResourceName = "FilesModule" } }, { MessageAction.FileImported, new MessageMaps { ActionTypeTextResourceName = "ImportActionType", ActionTextResourceName = "FileImported", ProductResourceName = "DocumentsProduct", ModuleResourceName = "FilesModule" } }, { MessageAction.FileCopied, new MessageMaps { ActionTypeTextResourceName = "CopyActionType", ActionTextResourceName = "FileCopied", ProductResourceName = "DocumentsProduct", ModuleResourceName = "FilesModule" } }, { MessageAction.FileCopiedWithOverwriting, new MessageMaps { ActionTypeTextResourceName = "CopyActionType", ActionTextResourceName = "FileCopiedWithOverwriting", ProductResourceName = "DocumentsProduct", ModuleResourceName = "FilesModule" } }, { MessageAction.FileMoved, new MessageMaps { ActionTypeTextResourceName = "MoveActionType", ActionTextResourceName = "FileMoved", ProductResourceName = "DocumentsProduct", ModuleResourceName = "FilesModule" } }, { MessageAction.FileMovedWithOverwriting, new MessageMaps { ActionTypeTextResourceName = "MoveActionType", ActionTextResourceName = "FileMovedWithOverwriting", ProductResourceName = "DocumentsProduct", ModuleResourceName = "FilesModule" } }, { MessageAction.FileMovedToTrash, new MessageMaps { ActionTypeTextResourceName = "MoveActionType", ActionTextResourceName = "FileMovedToTrash", ProductResourceName = "DocumentsProduct", ModuleResourceName = "FilesModule" } }, { MessageAction.FileDeleted, new MessageMaps { ActionTypeTextResourceName = "DeleteActionType", ActionTextResourceName = "FileDeleted", ProductResourceName = "DocumentsProduct", ModuleResourceName = "FilesModule" } }, { MessageAction.FolderCreated, new MessageMaps { ActionTypeTextResourceName = "CreateActionType", ActionTextResourceName = "FolderCreated", ProductResourceName = "DocumentsProduct", ModuleResourceName = "FoldersModule" } }, { MessageAction.FolderRenamed, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "FolderRenamed", ProductResourceName = "DocumentsProduct", ModuleResourceName = "FoldersModule" } }, { MessageAction.FolderUpdatedAccess, new MessageMaps { ActionTypeTextResourceName = "UpdateAccessActionType", ActionTextResourceName = "FolderUpdatedAccess", ProductResourceName = "DocumentsProduct", ModuleResourceName = "FoldersModule" } }, { MessageAction.FolderCopied, new MessageMaps { ActionTypeTextResourceName = "CopyActionType", ActionTextResourceName = "FolderCopied", ProductResourceName = "DocumentsProduct", ModuleResourceName = "FoldersModule" } }, { MessageAction.FolderCopiedWithOverwriting, new MessageMaps { ActionTypeTextResourceName = "CopyActionType", ActionTextResourceName = "FolderCopiedWithOverwriting", ProductResourceName = "DocumentsProduct", ModuleResourceName = "FoldersModule" } }, { MessageAction.FolderMoved, new MessageMaps { ActionTypeTextResourceName = "MoveActionType", ActionTextResourceName = "FolderMoved", ProductResourceName = "DocumentsProduct", ModuleResourceName = "FoldersModule" } }, { MessageAction.FolderMovedWithOverwriting, new MessageMaps { ActionTypeTextResourceName = "MoveActionType", ActionTextResourceName = "FolderMovedWithOverwriting", ProductResourceName = "DocumentsProduct", ModuleResourceName = "FoldersModule" } }, { MessageAction.FolderMovedToTrash, new MessageMaps { ActionTypeTextResourceName = "MoveActionType", ActionTextResourceName = "FolderMovedToTrash", ProductResourceName = "DocumentsProduct", ModuleResourceName = "FoldersModule" } }, { MessageAction.FolderDeleted, new MessageMaps { ActionTypeTextResourceName = "DeleteActionType", ActionTextResourceName = "FolderDeleted", ProductResourceName = "DocumentsProduct", ModuleResourceName = "FoldersModule" } }, { MessageAction.ThirdPartyCreated, new MessageMaps { ActionTypeTextResourceName = "CreateActionType", ActionTextResourceName = "ThirdPartyCreated", ProductResourceName = "DocumentsProduct", ModuleResourceName = "DocumentsSettingsModule" } }, { MessageAction.ThirdPartyUpdated, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "ThirdPartyUpdated", ProductResourceName = "DocumentsProduct", ModuleResourceName = "DocumentsSettingsModule" } }, { MessageAction.ThirdPartyDeleted, new MessageMaps { ActionTypeTextResourceName = "DeleteActionType", ActionTextResourceName = "ThirdPartyDeleted", ProductResourceName = "DocumentsProduct", ModuleResourceName = "DocumentsSettingsModule" } }, { MessageAction.DocumentsThirdPartySettingsUpdated, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "DocumentsThirdPartySettingsUpdated", ProductResourceName = "DocumentsProduct", ModuleResourceName = "DocumentsSettingsModule" } }, { MessageAction.DocumentsOverwritingSettingsUpdated, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "DocumentsOverwritingSettingsUpdated", ProductResourceName = "DocumentsProduct", ModuleResourceName = "DocumentsSettingsModule" } }, { MessageAction.DocumentsForcesave, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "DocumentsForcesave", ProductResourceName = "DocumentsProduct", ModuleResourceName = "DocumentsSettingsModule" } }, { MessageAction.DocumentsStoreForcesave, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "DocumentsStoreForcesave", ProductResourceName = "DocumentsProduct", ModuleResourceName = "DocumentsSettingsModule" } }, { MessageAction.DocumentsUploadingFormatsSettingsUpdated, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "DocumentsUploadingFormatsSettingsUpdated", ProductResourceName = "DocumentsProduct", ModuleResourceName = "DocumentsSettingsModule" } }, { MessageAction.FileConverted, new MessageMaps { ActionTypeTextResourceName = "CreateActionType", ActionTextResourceName = "FileConverted", ProductResourceName = "DocumentsProduct", ModuleResourceName = "FilesModule" } }, { MessageAction.FileSendAccessLink, new MessageMaps { ActionTypeTextResourceName = "SendActionType", ActionTextResourceName = "FileSendAccessLink", ProductResourceName = "DocumentsProduct", ModuleResourceName = "FilesModule" } }, { MessageAction.FileChangeOwner, new MessageMaps { ActionTypeTextResourceName = "SendActionType", ActionTextResourceName = "FileChangeOwner", ProductResourceName = "DocumentsProduct", ModuleResourceName = "FilesModule" } }, { MessageAction.DocumentSignComplete, new MessageMaps { ActionTypeTextResourceName = "SendActionType", ActionTextResourceName = "FilesDocumentSigned", ProductResourceName = "DocumentsProduct", ModuleResourceName = "FilesModule" } }, { MessageAction.DocumentSendToSign, new MessageMaps { ActionTypeTextResourceName = "SendActionType", ActionTextResourceName = "FilesRequestSign", ProductResourceName = "DocumentsProduct", ModuleResourceName = "FilesModule" } }, }; } } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/IO/ReadLineEventArgs.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections.Generic; using System.Text; namespace LumiSoft.Net.IO { /// <summary> /// This class provides data to <see cref="SmartStream.ReadLine">SmartStream.ReadLine</see> method. /// </summary> /// <remarks>This class can be reused on multiple calls of <see cref="SmartStream.ReadLine">SmartStream.ReadLine</see> method.</remarks> public class ReadLineEventArgs : EventArgs { private bool m_IsDisposed = false; private bool m_IsCompleted = false; private byte[] m_pBuffer = null; private SizeExceededAction m_ExceededAction = SizeExceededAction.JunkAndThrowException; private bool m_CRLFLinesOnly = false; private int m_BytesInBuffer = 0; private Exception m_pException = null; /// <summary> /// Default constructor. /// </summary> /// <param name="buffer">Line buffer.</param> /// <param name="exceededAction">Specifies how line-reader behaves when maximum line size exceeded.</param> /// <exception cref="ArgumentNullException">Is raised when <b>buffer</b> is null reference.</exception> public ReadLineEventArgs(byte[] buffer,SizeExceededAction exceededAction) { if(buffer == null){ throw new ArgumentNullException("buffer"); } m_pBuffer = buffer; m_ExceededAction = exceededAction; } #region method Start internal bool Start(SmartStream stream) { // TODO: Clear old data, if any. m_IsCompleted = false; m_BytesInBuffer = 0; m_pException = null; return DoLineReading(); } #endregion #region method Buffering_Completed /// <summary> /// Is called when asynchronous read buffer buffering has completed. /// </summary> /// <param name="x">Exception that occured during async operation.</param> private void Buffering_Completed(Exception x) { /* if(x != null){ m_pException = x; Completed(); } // We reached end of stream, no more data. else if(m_pOwner.BytesInReadBuffer == 0){ Completed(); } // Continue line reading. else{ DoLineReading(); }*/ } #endregion #region method DoLineReading /// <summary> /// Starts/continues line reading. /// </summary> /// <returns>Returns true if line reading completed.</returns> private bool DoLineReading() { try{ while(true){ /* // Read buffer empty, buff next data block. if(m_pOwner.BytesInReadBuffer == 0){ // Buffering started asynchronously. if(m_pOwner.BufferRead(true,this.Buffering_Completed)){ return; } // Buffering completed synchronously, continue processing. else{ // We reached end of stream, no more data. if(m_pOwner.BytesInReadBuffer == 0){ Completed(); return; } } }*/ byte b = 1; //m_pOwner.m_pReadBuffer[m_pOwner.m_ReadBufferOffset++]; //m_BytesInBuffer++; // TODO: Check for room, Store byte. // We have LF line. if(b == '\n'){ // TODO: // m_CRLFLinesOnly } } } catch(Exception x){ m_pException = x; OnCompleted(); } return true; } #endregion #region Properties implementation /// <summary> /// Gets if this object is disposed. /// </summary> public bool IsDisposed { get{ return m_IsDisposed; } } /// <summary> /// Gets if asynchronous operation has completed. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> public bool IsCompleted { get{ if(m_IsDisposed){ throw new ObjectDisposedException(this.GetType().Name); } return m_IsCompleted; } } /// <summary> /// Gets line buffer. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> public byte[] Buffer { get{ if(m_IsDisposed){ throw new ObjectDisposedException(this.GetType().Name); } return m_pBuffer; } } /// <summary> /// Gets number of bytes stored in the buffer. Line feed characters not included. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> public int BytesInBuffer { get{ if(m_IsDisposed){ throw new ObjectDisposedException(this.GetType().Name); } return m_BytesInBuffer; } } /// <summary> /// Gets line as ASCII string. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> public string LineAscii { get{ if(m_IsDisposed){ throw new ObjectDisposedException(this.GetType().Name); } return Encoding.ASCII.GetString(m_pBuffer,0,m_BytesInBuffer); } } /// <summary> /// Gets line as UTF-8 string. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> public string LineUtf8 { get{ if(m_IsDisposed){ throw new ObjectDisposedException(this.GetType().Name); } return Encoding.UTF8.GetString(m_pBuffer,0,m_BytesInBuffer); } } /// <summary> /// Gets error occured during asynchronous operation. Value null means no error. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> public Exception Error { get{ if(m_IsDisposed){ throw new ObjectDisposedException(this.GetType().Name); } return m_pException; } } #endregion #region Events implementation /// <summary> /// Is raised when asynchronous operation has completed. /// </summary> public event EventHandler<ReadLineEventArgs> Completed = null; #region method OnCompleted /// <summary> /// Raises <b>Completed</b> event. /// </summary> private void OnCompleted() { if(this.Completed != null){ this.Completed(this,this); } } #endregion #endregion } } <file_sep>/module/ASC.Api/ASC.Api.Mail/MailApi.Folders.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections.Generic; using System.Linq; using System.Threading; using ASC.Api.Attributes; using ASC.Mail; using ASC.Mail.Core.Engine.Operations.Base; using ASC.Mail.Data.Contracts; using ASC.Mail.Enums; using ASC.Mail.Exceptions; using ASC.Mail.Extensions; using ASC.Web.Mail.Resources; namespace ASC.Api.Mail { public partial class MailApi { /// <summary> /// Returns the list of default folders /// </summary> /// <returns>Folders list</returns> /// <short>Get folders</short> /// <category>Folders</category> [Read(@"folders")] public IEnumerable<MailFolderData> GetFolders() { if (!Defines.IsSignalRAvailable) MailEngineFactory.AccountEngine.SetAccountsActivity(); return MailEngineFactory.FolderEngine.GetFolders() .Where(f => f.id != FolderType.Sending) .ToList() .ToFolderData(); } /// <summary> /// Removes all the messages from the folder. Trash or Spam. /// </summary> /// <param name="folderid">Selected folder id. Trash - 4, Spam 5.</param> /// <short>Remove all messages from folder</short> /// <category>Folders</category> [Delete(@"folders/{folderid:[0-9]+}/messages")] public int RemoveFolderMessages(int folderid) { var folderType = (FolderType) folderid; if (folderType == FolderType.Trash || folderType == FolderType.Spam) { MailEngineFactory.MessageEngine.SetRemoved(folderType); } return folderid; } /// <summary> /// Recalculate folders counters /// </summary> /// <returns>MailOperationResult object</returns> /// <short>Get folders</short> /// <category>Folders</category> /// <visible>false</visible> [Read(@"folders/recalculate")] public MailOperationStatus RecalculateFolders() { return MailEngineFactory.OperationEngine.RecalculateFolders(TranslateMailOperationStatus); } /// <summary> /// Returns the list of user folders /// </summary> /// <param name="ids" optional="true">List of folder's id</param> /// <param name="parentId" optional="true">Selected parent folder id (root level equals 0)</param> /// <returns>Folders list</returns> /// <short>Get folders</short> /// <category>Folders</category> [Read(@"userfolders")] public IEnumerable<MailUserFolderData> GetUserFolders(List<uint> ids, uint? parentId) { var list = MailEngineFactory.UserFolderEngine.GetList(ids, parentId); return list; } /// <summary> /// Create user folder /// </summary> /// <param name="name">Folder name</param> /// <param name="parentId">Parent folder id (default = 0)</param> /// <returns>Folders list</returns> /// <short>Create folder</short> /// <category>Folders</category> /// <exception cref="ArgumentException">Exception happens when in parameters is invalid. Text description contains parameter name and text description.</exception> [Create(@"userfolders")] public MailUserFolderData CreateUserFolder(string name, uint parentId = 0) { Thread.CurrentThread.CurrentCulture = CurrentCulture; Thread.CurrentThread.CurrentUICulture = CurrentCulture; try { var userFolder = MailEngineFactory.UserFolderEngine.Create(name, parentId); return userFolder; } catch (AlreadyExistsFolderException) { throw new ArgumentException(MailApiResource.ErrorUserFolderNameAlreadyExists .Replace("%1", "\"" + name + "\"")); } catch (EmptyFolderException) { throw new ArgumentException(MailApiResource.ErrorUserFoldeNameCantBeEmpty); } catch (Exception) { throw new Exception(MailApiErrorsResource.ErrorInternalServer); } } /// <summary> /// Update user folder /// </summary> /// <param name="id">Folder id</param> /// <param name="name">new Folder name</param> /// <param name="parentId">new Parent folder id (default = 0)</param> /// <returns>Folders list</returns> /// <short>Update folder</short> /// <category>Folders</category> /// <exception cref="ArgumentException">Exception happens when in parameters is invalid. Text description contains parameter name and text description.</exception> [Update(@"userfolders/{id}")] public MailUserFolderData UpdateUserFolder(uint id, string name, uint? parentId = null) { Thread.CurrentThread.CurrentCulture = CurrentCulture; Thread.CurrentThread.CurrentUICulture = CurrentCulture; try { var userFolder = MailEngineFactory.UserFolderEngine.Update(id, name, parentId); return userFolder; } catch (AlreadyExistsFolderException) { throw new ArgumentException(MailApiResource.ErrorUserFolderNameAlreadyExists .Replace("%1", "\"" + name + "\"")); } catch (EmptyFolderException) { throw new ArgumentException(MailApiResource.ErrorUserFoldeNameCantBeEmpty); } catch (Exception) { throw new Exception(MailApiErrorsResource.ErrorInternalServer); } } /// <summary> /// Delete user folder /// </summary> /// <param name="id">Folder id</param> /// <short>Delete folder</short> /// <category>Folders</category> /// <exception cref="ArgumentException">Exception happens when in parameters is invalid. Text description contains parameter name and text description.</exception> /// <returns>MailOperationResult object</returns> [Delete(@"userfolders/{id}")] public MailOperationStatus DeleteUserFolder(uint id) { Thread.CurrentThread.CurrentCulture = CurrentCulture; Thread.CurrentThread.CurrentUICulture = CurrentCulture; try { return MailEngineFactory.OperationEngine.RemoveUserFolder(id, TranslateMailOperationStatus); } catch (Exception) { throw new Exception(MailApiErrorsResource.ErrorInternalServer); } } /// <summary> /// Returns the user folders by mail id /// </summary> /// <param name="mailId">List of folder's id</param> /// <returns>User Folder</returns> /// <short>Get folder by mail id</short> /// <category>Folders</category> [Read(@"userfolders/bymail")] public MailUserFolderData GetUserFolderByMailId(uint mailId) { var folder = MailEngineFactory.UserFolderEngine.GetByMail(mailId); return folder; } } } <file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/CircleCollection.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net { #region usings using System; using System.Collections.Generic; #endregion /// <summary> /// Circle collection. Elements will be circled clockwise. /// </summary> public class CircleCollection<T> { #region Members private readonly List<T> m_pItems; private int m_Index; #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> public CircleCollection() { m_pItems = new List<T>(); } #endregion #region Properties /// <summary> /// Gets number of items in the collection. /// </summary> public int Count { get { return m_pItems.Count; } } /// <summary> /// Gets item at the specified index. /// </summary> /// <param name="index">Item zero based index.</param> /// <returns>Returns item at the specified index.</returns> public T this[int index] { get { return m_pItems[index]; } } #endregion #region Methods /// <summary> /// Adds specified items to the collection. /// </summary> /// <param name="items">Items to add.</param> /// <exception cref="ArgumentNullException">Is raised when <b>items</b> is null.</exception> public void Add(T[] items) { if (items == null) { throw new ArgumentNullException("items"); } foreach (T item in items) { Add(item); } } /// <summary> /// Adds specified item to the collection. /// </summary> /// <param name="item">Item to add.</param> /// <exception cref="ArgumentNullException">Is raised when <b>item</b> is null.</exception> public void Add(T item) { if (item == null) { throw new ArgumentNullException("item"); } m_pItems.Add(item); // Reset loop index. m_Index = 0; } /// <summary> /// Removes specified item from the collection. /// </summary> /// <param name="item">Item to remove.</param> /// <exception cref="ArgumentNullException">Is raised when <b>item</b> is null.</exception> public void Remove(T item) { if (item == null) { throw new ArgumentNullException("item"); } m_pItems.Remove(item); // Reset loop index. m_Index = 0; } /// <summary> /// Clears all items from collection. /// </summary> public void Clear() { m_pItems.Clear(); // Reset loop index. m_Index = 0; } /// <summary> /// Gets if the collection contain the specified item. /// </summary> /// <param name="item">Item to check.</param> /// <returns>Returns true if the collection contain the specified item, otherwise false.</returns> public bool Contains(T item) { return m_pItems.Contains(item); } /// <summary> /// Gets next item from the collection. This method is thread-safe. /// </summary> /// <exception cref="InvalidOperationException">Is raised when thre is no items in the collection.</exception> public T Next() { if (m_pItems.Count == 0) { throw new InvalidOperationException("There is no items in the collection."); } lock (m_pItems) { T item = m_pItems[m_Index]; m_Index++; if (m_Index >= m_pItems.Count) { m_Index = 0; } return item; } } /// <summary> /// Copies all elements to new array, all elements will be in order they added. This method is thread-safe. /// </summary> /// <returns>Returns elements in a new array.</returns> public T[] ToArray() { lock (m_pItems) { return m_pItems.ToArray(); } } /// <summary> /// Copies all elements to new array, all elements will be in current circle order. This method is thread-safe. /// </summary> /// <returns>Returns elements in a new array.</returns> public T[] ToCurrentOrderArray() { lock (m_pItems) { int index = m_Index; T[] retVal = new T[m_pItems.Count]; for (int i = 0; i < m_pItems.Count; i++) { retVal[i] = m_pItems[index]; index++; if (index >= m_pItems.Count) { index = 0; } } return retVal; } } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/SDP/SDP_MediaDescription.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.SDP { #region usings using System; #endregion /// <summary> /// A SDP_MediaDescription represents an <B>m=</B> SDP message field. Defined in RFC 4566 5.14. Media Descriptions. /// </summary> public class SDP_MediaDescription { #region Members private string m_MediaFormat = ""; private string m_MediaType = ""; private int m_NumberOfPorts = 1; private int m_Port; private string m_Protocol = ""; #endregion #region Properties /// <summary> /// Gets or sets meadia type. Currently defined media are "audio", "video", "text", /// "application", and "message", although this list may be extended in the future. /// </summary> public string MediaType { get { return m_MediaType; } set { if (string.IsNullOrEmpty(value)) { throw new ArgumentException("Property Protocol can't be null or empty !"); } m_MediaType = value; } } /// <summary> /// Gets or sets the transport port to which the media stream is sent. /// </summary> public int Port { get { return m_Port; } set { m_Port = value; } } /// <summary> /// Gets or sets number of continuos media ports. /// </summary> public int NumberOfPorts { get { return m_NumberOfPorts; } set { if (value < 1) { throw new ArgumentException("Property NumberOfPorts must be >= 1 !"); } m_NumberOfPorts = value; } } /// <summary> /// Gets or sets transport protocol. Currently known protocols: UDP;RTP/AVP;RTP/SAVP. /// </summary> public string Protocol { get { return m_Protocol; } set { if (string.IsNullOrEmpty(value)) { throw new ArgumentException("Property Protocol cant be null or empty !"); } m_Protocol = value; } } /// <summary> /// Gets or sets media format description. The interpretation of the media /// format depends on the value of the "proto" sub-field. /// </summary> public string MediaFormatDescription { get { return m_MediaFormat; } set { if (value == null) { throw new ArgumentException("Property Protocol cant be null !"); } m_MediaFormat = value; } } #endregion #region Methods /// <summary> /// Parses media from "m" SDP message field. /// </summary> /// <param name="mValue">"m" SDP message field.</param> /// <returns></returns> public static SDP_MediaDescription Parse(string mValue) { SDP_MediaDescription media = new SDP_MediaDescription(); // m=<media> <port>/<number of ports> <proto> <fmt> ... StringReader r = new StringReader(mValue); r.QuotedReadToDelimiter('='); //--- <media> ------------------------------------------------------------ string word = r.ReadWord(); if (word == null) { throw new Exception("SDP message \"m\" field <media> value is missing !"); } media.m_MediaType = word; //--- <port>/<number of ports> ------------------------------------------- word = r.ReadWord(); if (word == null) { throw new Exception("SDP message \"m\" field <port> value is missing !"); } if (word.IndexOf('/') > -1) { string[] port_nPorts = word.Split('/'); media.m_Port = Convert.ToInt32(port_nPorts[0]); media.m_NumberOfPorts = Convert.ToInt32(port_nPorts[1]); } else { media.m_Port = Convert.ToInt32(word); media.m_NumberOfPorts = 1; } //--- <proto> -------------------------------------------------------------- word = r.ReadWord(); if (word == null) { throw new Exception("SDP message \"m\" field <proto> value is missing !"); } media.m_Protocol = word; //--- <fmt> ---------------------------------------------------------------- word = r.ReadWord(); if (word == null) { media.m_MediaFormat = ""; } else { media.m_MediaFormat = word; } return media; } /// <summary> /// Converts this to valid media string. /// </summary> /// <returns></returns> public string ToValue() { // m=<media> <port>/<number of ports> <proto> <fmt> ... return "m=" + MediaType + " " + Port + "/" + NumberOfPorts + " " + Protocol + " " + MediaFormatDescription + "\r\n"; } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/_Obsolete/SocketCallBackResult.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net { #region usings using System; #endregion /// <summary> /// /// </summary> public delegate void SocketCallBack(SocketCallBackResult result, long count, Exception x, object tag); /// <summary> /// Asynchronous command execute result. /// </summary> public enum SocketCallBackResult { /// <summary> /// Operation was successfull. /// </summary> Ok, /// <summary> /// Exceeded maximum allowed size. /// </summary> LengthExceeded, /// <summary> /// Connected client closed connection. /// </summary> SocketClosed, /// <summary> /// Exception happened. /// </summary> Exception } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/_Obsolete/SocketServerSession.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net { #region usings using System; using System.Net; #endregion /// <summary> /// This is base class for SocketServer sessions. /// </summary> public abstract class SocketServerSession { #region Members private readonly IPBindInfo m_pBindInfo; private readonly SocketServer m_pServer; private readonly SocketEx m_pSocket; private readonly string m_SessionID = ""; private readonly DateTime m_SessionStartTime; private string m_UserName = ""; #endregion #region Properties /// <summary> /// Gets session ID. /// </summary> public string SessionID { get { return m_SessionID; } } /// <summary> /// Gets session start time. /// </summary> public DateTime SessionStartTime { get { return m_SessionStartTime; } } /// <summary> /// Gets if session is authenticated. /// </summary> public bool Authenticated { get { if (m_UserName.Length > 0) { return true; } else { return false; } } } /// <summary> /// Gets authenticated user name. /// </summary> public string UserName { get { return m_UserName; } } /// <summary> /// Gets how many seconds has left before timout is triggered. /// </summary> public int ExpectedTimeout { get { return (int) ((m_pServer.SessionIdleTimeOut - ((DateTime.Now.Ticks - SessionLastDataTime.Ticks)/10000))/ 1000); } } /// <summary> /// Gets last data activity time. /// </summary> public DateTime SessionLastDataTime { get { if (m_pSocket == null) { return DateTime.MinValue; } else { return m_pSocket.LastActivity; } } } /// <summary> /// Gets EndPoint which accepted conection. /// </summary> public IPEndPoint LocalEndPoint { get { return (IPEndPoint) m_pSocket.LocalEndPoint; } } /// <summary> /// Gets connected Host(client) EndPoint. /// </summary> public IPEndPoint RemoteEndPoint { get { try { return (IPEndPoint) m_pSocket.RemoteEndPoint; } catch { // Socket closed/disposed already return null; } } } /// <summary> /// Gets or sets custom user data. /// </summary> public object Tag { get; set; } /// <summary> /// Gets log entries that are currently in log buffer. /// </summary> public SocketLogger SessionActiveLog { get { return m_pSocket.Logger; } } /// <summary> /// Gets how many bytes are readed through this session. /// </summary> public long ReadedCount { get { return m_pSocket.ReadedCount; } } /// <summary> /// Gets how many bytes are written through this session. /// </summary> public long WrittenCount { get { return m_pSocket.WrittenCount; } } /// <summary> /// Gets if the connection is an SSL connection. /// </summary> public bool IsSecureConnection { get { return m_pSocket.SSL; } } /// <summary> /// Gets access to SocketEx. /// </summary> protected SocketEx Socket { get { return m_pSocket; } } /// <summary> /// Gets access to BindInfo what accepted socket. /// </summary> protected IPBindInfo BindInfo { get { return m_pBindInfo; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="sessionID">Session ID.</param> /// <param name="socket">Server connected socket.</param> /// <param name="bindInfo">BindInfo what accepted socket.</param> /// <param name="server">Reference to server.</param> public SocketServerSession(string sessionID, SocketEx socket, IPBindInfo bindInfo, SocketServer server) { m_SessionID = sessionID; m_pSocket = socket; m_pBindInfo = bindInfo; m_pServer = server; m_SessionStartTime = DateTime.Now; } #endregion #region Methods /// <summary> /// Kills session. /// </summary> public virtual void Kill() {} #endregion #region Virtual methods /// <summary> /// Times session out. /// </summary> protected internal virtual void OnSessionTimeout() {} #endregion /// <summary> /// Sets property UserName value. /// </summary> /// <param name="userName">User name.</param> protected void SetUserName(string userName) { m_UserName = userName; if (m_pSocket.Logger != null) { m_pSocket.Logger.UserName = m_UserName; } } } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/IMAP/Server/AuthUser_EventArgs.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.IMAP.Server { using POP3.Server; /// <summary> /// Provides data for the AuthUser event for IMAP_Server. /// </summary> public class AuthUser_EventArgs : AuthUser_EventArgsBase { #region Members private readonly IMAP_Session m_pSession; #endregion #region Properties /// <summary> /// Gets reference to smtp session. /// </summary> public IMAP_Session Session { get { return m_pSession; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="session">Reference to IMAP session.</param> /// <param name="userName">Username.</param> /// <param name="passwData">Password data.</param> /// <param name="data">Authentication specific data(as tag).</param> /// <param name="authType">Authentication type.</param> public AuthUser_EventArgs(IMAP_Session session, string userName, string passwData, string data, AuthType authType) { m_pSession = session; m_UserName = userName; m_PasswData = passwData; m_Data = data; m_AuthType = authType; } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/vCard/PhoneNumber.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.Mime.vCard { /// <summary> /// vCard phone number implementation. /// </summary> public class PhoneNumber { #region Members private readonly Item m_pItem; private string m_Number = ""; private PhoneNumberType_enum m_Type = PhoneNumberType_enum.Voice; #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="item">Owner vCard item.</param> /// <param name="type">Phone number type. Note: This value can be flagged value !</param> /// <param name="number">Phone number.</param> internal PhoneNumber(Item item, PhoneNumberType_enum type, string number) { m_pItem = item; m_Type = type; m_Number = number; } #endregion #region Properties /// <summary> /// Gets underlaying vCrad item. /// </summary> public Item Item { get { return m_pItem; } } /// <summary> /// Gets or sets phone number. /// </summary> public string Number { get { return m_Number; } set { m_Number = value; Changed(); } } /// <summary> /// Gets or sets phone number type. Note: This property can be flagged value ! /// </summary> public PhoneNumberType_enum NumberType { get { return m_Type; } set { m_Type = value; Changed(); } } #endregion #region Internal methods /// <summary> /// Parses phone from vCard TEL structure string. /// </summary> /// <param name="item">vCard TEL item.</param> internal static PhoneNumber Parse(Item item) { PhoneNumberType_enum type = PhoneNumberType_enum.NotSpecified; if (item.ParametersString.ToUpper().IndexOf("PREF") != -1) { type |= PhoneNumberType_enum.Preferred; } if (item.ParametersString.ToUpper().IndexOf("HOME") != -1) { type |= PhoneNumberType_enum.Home; } if (item.ParametersString.ToUpper().IndexOf("MSG") != -1) { type |= PhoneNumberType_enum.Msg; } if (item.ParametersString.ToUpper().IndexOf("WORK") != -1) { type |= PhoneNumberType_enum.Work; } if (item.ParametersString.ToUpper().IndexOf("VOICE") != -1) { type |= PhoneNumberType_enum.Voice; } if (item.ParametersString.ToUpper().IndexOf("FAX") != -1) { type |= PhoneNumberType_enum.Fax; } if (item.ParametersString.ToUpper().IndexOf("CELL") != -1) { type |= PhoneNumberType_enum.Cellular; } if (item.ParametersString.ToUpper().IndexOf("VIDEO") != -1) { type |= PhoneNumberType_enum.Video; } if (item.ParametersString.ToUpper().IndexOf("PAGER") != -1) { type |= PhoneNumberType_enum.Pager; } if (item.ParametersString.ToUpper().IndexOf("BBS") != -1) { type |= PhoneNumberType_enum.BBS; } if (item.ParametersString.ToUpper().IndexOf("MODEM") != -1) { type |= PhoneNumberType_enum.Modem; } if (item.ParametersString.ToUpper().IndexOf("CAR") != -1) { type |= PhoneNumberType_enum.Car; } if (item.ParametersString.ToUpper().IndexOf("ISDN") != -1) { type |= PhoneNumberType_enum.ISDN; } if (item.ParametersString.ToUpper().IndexOf("PCS") != -1) { type |= PhoneNumberType_enum.PCS; } return new PhoneNumber(item, type, item.Value); } /// <summary> /// Converts PhoneNumberType_enum to vCard item parameters string. /// </summary> /// <param name="type">Value to convert.</param> /// <returns></returns> internal static string PhoneTypeToString(PhoneNumberType_enum type) { string retVal = ""; if ((type & PhoneNumberType_enum.BBS) != 0) { retVal += "BBS,"; } if ((type & PhoneNumberType_enum.Car) != 0) { retVal += "CAR,"; } if ((type & PhoneNumberType_enum.Cellular) != 0) { retVal += "CELL,"; } if ((type & PhoneNumberType_enum.Fax) != 0) { retVal += "FAX,"; } if ((type & PhoneNumberType_enum.Home) != 0) { retVal += "HOME,"; } if ((type & PhoneNumberType_enum.ISDN) != 0) { retVal += "ISDN,"; } if ((type & PhoneNumberType_enum.Modem) != 0) { retVal += "MODEM,"; } if ((type & PhoneNumberType_enum.Msg) != 0) { retVal += "MSG,"; } if ((type & PhoneNumberType_enum.Pager) != 0) { retVal += "PAGER,"; } if ((type & PhoneNumberType_enum.PCS) != 0) { retVal += "PCS,"; } if ((type & PhoneNumberType_enum.Preferred) != 0) { retVal += "PREF,"; } if ((type & PhoneNumberType_enum.Video) != 0) { retVal += "VIDEO,"; } if ((type & PhoneNumberType_enum.Voice) != 0) { retVal += "VOICE,"; } if ((type & PhoneNumberType_enum.Work) != 0) { retVal += "WORK,"; } if (retVal.EndsWith(",")) { retVal = retVal.Substring(0, retVal.Length - 1); } return retVal; } #endregion #region Utility methods /// <summary> /// This method is called when some property has changed, wee need to update underlaying vCard item. /// </summary> private void Changed() { m_pItem.ParametersString = PhoneTypeToString(m_Type); m_pItem.Value = m_Number; } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/FTP/Server/FileSysEntry_EventArgs.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.FTP.Server { #region usings using System; using System.Data; using System.IO; #endregion /// <summary> /// Provides data for the filesytem related events for FTP_Server. /// </summary> public class FileSysEntry_EventArgs { #region Members private readonly DataSet m_DsDirInfo; private readonly string m_Name = ""; private readonly string m_NewName = ""; private readonly FTP_Session m_pSession; private bool m_Validated = true; #endregion #region Properties /// <summary> /// Gets reference to FTP session. /// </summary> public FTP_Session Session { get { return m_pSession; } } /// <summary> /// Gets directory or file name with path. /// </summary> public string Name { get { return m_Name; } } /// <summary> /// Gets new directory or new file name with path. This filled for Rename event only. /// </summary> public string NewName { get { return m_NewName; } } /// <summary> /// Gets or sets file stream. /// </summary> public Stream FileStream { get; set; } /// <summary> /// Gets or sets if operation was successful. NOTE: default value is true. /// </summary> public bool Validated { get { return m_Validated; } set { m_Validated = value; } } /// <summary> /// Gets reference to dir listing info. Please Fill .Tables["DirInfo"] table with required fields. /// </summary> public DataSet DirInfo { get { return m_DsDirInfo; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="name"></param> /// <param name="newName"></param> /// <param name="session"></param> public FileSysEntry_EventArgs(FTP_Session session, string name, string newName) { m_Name = name; m_NewName = newName; m_pSession = session; m_DsDirInfo = new DataSet(); DataTable dt = m_DsDirInfo.Tables.Add("DirInfo"); dt.Columns.Add("Name"); dt.Columns.Add("Date", typeof (DateTime)); dt.Columns.Add("Size", typeof (long)); dt.Columns.Add("IsDirectory", typeof (bool)); } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/SDP/SDP_Message.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.SDP { #region usings using System; using System.Collections.Generic; using System.IO; using System.Text; #endregion /// <summary> /// Session Description Protocol. Defined in RFC 4566. /// </summary> public class SDP_Message { #region Members private readonly List<SDP_Attribute> m_pAttributes; private readonly List<SDP_Media> m_pMedias; private readonly List<SDP_Time> m_pTimes; private string m_Origin = ""; private string m_RepeatTimes = ""; private string m_SessionDescription = ""; private string m_SessionName = ""; private string m_Uri = ""; private string m_Version = "0"; #endregion #region Properties /// <summary> /// Gets or sets version of the Session Description Protocol. /// </summary> public string Version { get { return m_Version; } set { if (string.IsNullOrEmpty(value)) { throw new ArgumentException("Property Version can't be null or empty !"); } m_Version = value; } } /// <summary> /// Gets originator and session identifier. /// </summary> public string Originator { get { return m_Origin; } set { m_Origin = value; } } /// <summary> /// Gets or sets textual session name. /// </summary> public string SessionName { get { return m_SessionName; } set { if (string.IsNullOrEmpty(value)) { throw new ArgumentException("Property SessionName can't be null or empty !"); } m_SessionName = value; } } /// <summary> /// Gets or sets textual information about the session. This is optional value, null means not specified. /// </summary> public string SessionDescription { get { return m_SessionDescription; } set { m_SessionDescription = value; } } /// <summary> /// Gets or sets Uniform Resource Identifier. The URI should be a pointer to additional information /// about the session. This is optional value, null means not specified. /// </summary> public string Uri { get { return m_Uri; } set { m_Uri = value; } } /// <summary> /// Gets or sets connection data. This is optional value if each media part specifies this value, /// null means not specified. /// </summary> public SDP_ConnectionData ConnectionData { get; set; } /// <summary> /// Gets start and stop times for a session. If Count = 0, t field not written dot SDP data. /// </summary> public List<SDP_Time> Times { get { return m_pTimes; } } /// <summary> /// Gets or sets repeat times for a session. This is optional value, null means not specified. /// </summary> public string RepeatTimes { get { return m_RepeatTimes; } set { m_RepeatTimes = value; } } /// <summary> /// Gets attributes collection. This is optional value, Count == 0 means not specified. /// </summary> public List<SDP_Attribute> Attributes { get { return m_pAttributes; } } /// <summary> /// Gets media parts collection. /// </summary> public List<SDP_Media> Media { get { return m_pMedias; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> public SDP_Message() { m_pTimes = new List<SDP_Time>(); m_pAttributes = new List<SDP_Attribute>(); m_pMedias = new List<SDP_Media>(); } #endregion #region Methods /// <summary> /// Parses SDP from raw data. /// </summary> /// <param name="data">Raw SDP data.</param> /// <exception cref="ArgumentNullException">Is raised when <b>data</b> is null reference.</exception> public static SDP_Message Parse(string data) { if (data == null) { throw new ArgumentNullException("data"); } SDP_Message sdp = new SDP_Message(); StringReader r = new StringReader(data); string line = r.ReadLine(); //--- Read global fields --------------------------------------------- while (line != null) { line = line.Trim(); // We reached to media descriptions if (line.ToLower().StartsWith("m")) { /* m= (media name and transport address) i=* (media title) c=* (connection information -- optional if included at session level) b=* (zero or more bandwidth information lines) k=* (encryption key) a=* (zero or more media attribute lines) */ SDP_Media media = new SDP_Media(); media.MediaDescription = SDP_MediaDescription.Parse(line); sdp.Media.Add(media); line = r.ReadLine(); // Pasrse media fields and attributes while (line != null) { line = line.Trim(); // Next media descrition, just stop active media description parsing, // fall through main while, allow next while loop to process it. if (line.ToLower().StartsWith("m")) { break; } // i media title else if (line.ToLower().StartsWith("i")) { media.Title = line.Split(new[] {'='}, 2)[1].Trim(); } // c connection information else if (line.ToLower().StartsWith("c")) { media.ConnectionData = SDP_ConnectionData.Parse(line); } // a Attributes else if (line.ToLower().StartsWith("a")) { media.Attributes.Add(SDP_Attribute.Parse(line)); } line = r.ReadLine(); } break; } // v Protocol Version else if (line.ToLower().StartsWith("v")) { sdp.Version = line.Split(new[] {'='}, 2)[1].Trim(); } // o Origin else if (line.ToLower().StartsWith("o")) { sdp.Originator = line.Split(new[] {'='}, 2)[1].Trim(); } // s Session Name else if (line.ToLower().StartsWith("s")) { sdp.SessionName = line.Split(new[] {'='}, 2)[1].Trim(); } // i Session Information else if (line.ToLower().StartsWith("i")) { sdp.SessionDescription = line.Split(new[] {'='}, 2)[1].Trim(); } // u URI else if (line.ToLower().StartsWith("u")) { sdp.Uri = line.Split(new[] {'='}, 2)[1].Trim(); } // c Connection Data else if (line.ToLower().StartsWith("c")) { sdp.ConnectionData = SDP_ConnectionData.Parse(line); } // t Timing else if (line.ToLower().StartsWith("t")) { sdp.Times.Add(SDP_Time.Parse(line)); } // a Attributes else if (line.ToLower().StartsWith("a")) { sdp.Attributes.Add(SDP_Attribute.Parse(line)); } line = r.ReadLine().Trim(); } return sdp; } /// <summary> /// Stores SDP data to specified file. Note: official suggested file extention is .sdp. /// </summary> /// <param name="fileName">File name with path where to store SDP data.</param> public void ToFile(string fileName) { File.WriteAllText(fileName, ToStringData()); } /// <summary> /// Returns SDP as string data. /// </summary> /// <returns></returns> public string ToStringData() { StringBuilder retVal = new StringBuilder(); // v Protocol Version retVal.AppendLine("v=" + Version); // o Origin if (!string.IsNullOrEmpty(Originator)) { retVal.AppendLine("o=" + Originator); } // s Session Name if (!string.IsNullOrEmpty(SessionName)) { retVal.AppendLine("s=" + SessionName); } // i Session Information if (!string.IsNullOrEmpty(SessionDescription)) { retVal.AppendLine("i=" + SessionDescription); } // u URI if (!string.IsNullOrEmpty(Uri)) { retVal.AppendLine("u=" + Uri); } // c Connection Data if (ConnectionData != null) { retVal.Append(ConnectionData.ToValue()); } // t Timing foreach (SDP_Time time in Times) { retVal.Append(time.ToValue()); } // a Attributes foreach (SDP_Attribute attribute in Attributes) { retVal.Append(attribute.ToValue()); } // m media description(s) foreach (SDP_Media media in Media) { retVal.Append(media.ToValue()); } return retVal.ToString(); } #endregion } }<file_sep>/module/ASC.Api/ASC.Api.Community/CommunityApiCommon.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Web; using ASC.Api.Attributes; using ASC.Core; using ASC.Web.Community.Birthdays; using ASC.Web.Studio.Utility.HtmlUtility; namespace ASC.Api.Community { public partial class CommunityApi { /// <summary> /// Subscribe or unsubscribe on birthday of user with the ID specified /// </summary> /// <short>Subscribe/unsubscribe on birthday</short> /// <param name="userid">user ID</param> /// <param name="onRemind">should be subscribed or unsubscribed</param> /// <returns>onRemind value</returns> /// <category>Birthday</category> [Create("birthday")] public bool RemindAboutBirthday(Guid userid, bool onRemind) { BirthdaysNotifyClient.Instance.SetSubscription(SecurityContext.CurrentAccount.ID, userid, onRemind); return onRemind; } [Create("preview")] public object GetPreview(string title, string content) { return new { title = HttpUtility.HtmlEncode(title), content = HtmlUtility.GetFull(content) }; } } } <file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/IMAP/Server/Message_EventArgs.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.IMAP.Server { /// <summary> /// Provides data for message related events. /// </summary> public class Message_EventArgs { #region Members private readonly string m_CopyLocation = ""; private readonly string m_Folder = ""; private readonly bool m_HeadersOnly; private readonly IMAP_Message m_pMessage; #endregion #region Properties /// <summary> /// Gets IMAP folder. /// </summary> public string Folder { get { return m_Folder; } } /// <summary> /// Gets IMAP message info. /// </summary> public IMAP_Message Message { get { return m_pMessage; } } /// <summary> /// Gets message new location. NOTE: this is available for copy command only. /// </summary> public string CopyLocation { get { return m_CopyLocation; } } /// <summary> /// Gets or sets message data. NOTE: this is available for GetMessage and StoreMessage event only. /// </summary> public byte[] MessageData { get; set; } /// <summary> /// Gets if message headers or full message wanted. NOTE: this is available for GetMessage event only. /// </summary> public bool HeadersOnly { get { return m_HeadersOnly; } } /// <summary> /// Gets or sets custom error text, which is returned to client. /// </summary> public string ErrorText { get; set; } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="folder">IMAP folder which message is.</param> /// <param name="msg"></param> public Message_EventArgs(string folder, IMAP_Message msg) { m_Folder = folder; m_pMessage = msg; } /// <summary> /// Copy constructor. /// </summary> /// <param name="folder">IMAP folder which message is.</param> /// <param name="msg"></param> /// <param name="copyLocation"></param> public Message_EventArgs(string folder, IMAP_Message msg, string copyLocation) { m_Folder = folder; m_pMessage = msg; m_CopyLocation = copyLocation; } /// <summary> /// GetMessage constructor. /// </summary> /// <param name="folder">IMAP folder which message is.</param> /// <param name="msg"></param> /// <param name="headersOnly">Specifies if messages headers or full message is needed.</param> public Message_EventArgs(string folder, IMAP_Message msg, bool headersOnly) { m_Folder = folder; m_pMessage = msg; m_HeadersOnly = headersOnly; } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/AUTH/AUTH_SASL_ServerMechanism.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.AUTH { #region usings using System; using System.Collections.Generic; #endregion /// <summary> /// This base class for server SASL authentication mechanisms. /// </summary> public abstract class AUTH_SASL_ServerMechanism { #region Properties /// <summary> /// Gets if user has authenticated sucessfully. /// </summary> public abstract bool IsAuthenticated { get; } /// <summary> /// Gets if the authentication exchange has completed. /// </summary> public abstract bool IsCompleted { get; } /// <summary> /// Gets IANA-registered SASL authentication mechanism name. /// </summary> /// <remarks>The registered list is available from: http://www.iana.org/assignments/sasl-mechanisms .</remarks> public abstract string Name { get; } /// <summary> /// Gets if specified SASL mechanism is available only to SSL connection. /// </summary> public abstract bool RequireSSL { get; } /// <summary> /// Gets user login name. /// </summary> public abstract string UserName { get; } #endregion #region Methods /// <summary> /// Continues authentication process. /// </summary> /// <param name="clientResponse">Client sent SASL response.</param> /// <returns>Retunrns challange response what must be sent to client or null if authentication has completed.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>clientRespone</b> is null reference.</exception> public abstract string Continue(string clientResponse); #endregion } }<file_sep>/web/studio/ASC.Web.Studio/UserControls/Common/AuthorizeDocs/js/authorizedocs.js /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ jq(function () { var recaptchaEmail = null; var recaptchaLogin = null; jq('#login').blur(); if (jq.cookies.get('onluoffice_personal_cookie') == null || jq.cookies.get('onluoffice_personal_cookie') == false) { jq('.cookieMess').css('display', 'table'); } if (jq("#agree_to_terms").prop("checked")) { bindConfirmEmailBtm(); jq('.auth-form-with_btns_social .account-links a') .removeClass('disabled') .unbind('click'); } else { jq('.auth-form-with_btns_social .account-links a') .addClass('disabled'); } jq('.auth-form-with_form_btn') .click(function () { return false; }); function bindConfirmEmailBtm() { jq('.auth-form-with_btns_social .account-links a').removeClass('disabled'); jq("#confirmEmailBtn") .removeClass('disabled') .on("click", function () { var $email = jq("#confirmEmail"), email = $email.val().trim(), spam = jq("#spam").prop("checked"), analytics = jq("#analytics").prop("checked"), $error = jq("#confirmEmailError"), errorText = "", isError = false; $email.removeClass("error"); if (!email) { errorText = ASC.Resources.Master.Resource.ErrorEmptyEmail; isError = true; } else if (!jq.isValidEmail(email)) { errorText = ASC.Resources.Master.Resource.ErrorNotCorrectEmail; isError = true; } if (isError) { $error.html(errorText); $email.addClass("error"); return; } var data = { "email": email, "lang": jq(".personal-languages_select").attr("data-lang"), "campaign": jq("#confirmEmailBtn").attr("data-campaign") ? !!(jq("#confirmEmailBtn").attr("data-campaign").length) : false, "spam": spam, "analytics": analytics, "recaptchaResponse": recaptchaEmail != null ? window.grecaptcha.getResponse(recaptchaEmail) : "" }; var onError = function (error) { $error.html(error); $email.addClass("error"); if (recaptchaEmail != null) { window.grecaptcha.reset(recaptchaEmail); } }; Teamlab.registerUserOnPersonal(data, { success: function (arg, res) { if (res && res.length) { onError(res); return; } $error.empty(); jq("#activationEmail").html(email); jq(".auth-form-with_form_w").hide(); jq("#sendEmailSuccessPopup").show(); }, error: function (params, errors) { onError(errors[0]); } }); }); } function bindEvents () { jq(function () { jq("#loginSignUp").on("click", function () { enableScroll(); jq('#login').blur(); jq("#loginPopup").hide(); hideAccountLinks(); jq(".auth-form-with_form_w").show(); jq("#confirmEmail").focus(); }); }); jq('.create-link').on("click", function () { jq('html, body').animate({ scrollTop: 0 }, 300); jq(".auth-form-with_form_w").show(); jq("#confirmEmail").focus(); }); // close popup window jq(".default-personal-popup_closer").on("click", function () { hideAccountLinks(); jq(this).parents(".default-personal-popup").fadeOut(200, function() { enableScroll(); }); if ((jq('body').hasClass('desktop'))) { jq("#personalLogin a").click(); } jq('.auth-form-with_form_btn') .click(function () { return false; }); }); // close register form jq(".register_form_closer").on("click", function () { jq(this).parents(".auth-form-with_form_w").fadeOut(200, function () {}); }); // close cookie mess jq(".cookieMess_closer").on("click", function () { jq.cookies.set('onluoffice_personal_cookie', true); closeCookieMess(); }); jq("#personalcookie").on("click", function () { jq.cookies.set('onluoffice_personal_cookie', true); closeCookieMess(); }); function closeCookieMess() { jq('.cookieMess').hide(); } // confirm the email jq(document).on("keypress", "#confirmEmail", function (evt) { jq(this).removeClass("error"); if (evt.keyCode == 13) { evt.preventDefault(); jq("#confirmEmailBtn").trigger("click"); } }); jq('.account-links a').click(function () { return false; }); // change in consent to terms function showAccountLinks() { jq('.account-links a') .removeClass('disabled') .unbind('click'); bindConfirmEmailBtm(); } function hideAccountLinks() { if (!jq("#agree_to_terms")[0].checked) { jq('.auth-form-with_btns_social .account-links a') .click(function () { return false; }) .addClass('disabled'); jq("#confirmEmailBtn") .addClass('disabled') .unbind('click'); } } jq("#agree_to_terms").change(function () { if (this.checked) { showAccountLinks(); } else { hideAccountLinks(); } }); jq("#desktop_agree_to_terms").change(function () { var btn = jq("#loginBtn"); if (this.checked) { btn.removeClass('disabled').unbind('click'); } else { btn.addClass('disabled').click(function() { return false; }); } }); jq(document).on("click", "#loginBtn:not(.disabled)", function () { Authorize.SubmitDocs(); return false; }); jq(document).keyup(function (event) { var code; if (!e) { var e = event; } if (e.keyCode) { code = e.keyCode; } else if (e.which) { code = e.which; } if (code == 27 && !jq('body').hasClass('desktop')) { jq(".default-personal-popup").fadeOut(200, function () { enableScroll(); hideAccountLinks(); }); } }); var $body = jq(window.document.body); var marginRight; function disableScroll() { var bodyWidth = $body.innerWidth(); $body.css('overflow-y', 'hidden'); marginRight = $body.innerWidth() - bodyWidth; $body.css('marginRight', ($body.css('marginRight') ? '+=' : '') + marginRight); } function enableScroll() { if (parseInt($body.css('marginRight')) >= marginRight) { $body.css('marginRight', '-=' + marginRight); } $body.css('overflow-y', 'auto'); } // Login jq("#personalLogin a").on("click", function () { jq(".auth-form-with_form_w").fadeOut(200, function () { }); showAccountLinks(); jq('.auth-form-with_form_btn').removeClass('disabled').unbind('click'); jq("#loginPopup").show(); jq('#login').focus(); disableScroll(); if (jq("#recaptchaLogin").length) { if (recaptchaLogin != null) { window.grecaptcha.reset(recaptchaLogin); } else { var recaptchaLoginRender = function () { recaptchaLogin = window.grecaptcha.render("recaptchaLogin", {"sitekey": jq("#recaptchaData").val()}); }; if (window.grecaptcha && window.grecaptcha.render) { recaptchaLoginRender(); } else { jq(document).ready(recaptchaLoginRender); } } } }); // open form jq(".open-form").on("click", function () { jq(".auth-form-with_form_w").show(); jq("#confirmEmail").focus(); //disableScroll(); if (jq("#recaptchaEmail").length) { if (recaptchaEmail != null) { window.grecaptcha.reset(recaptchaEmail); } else { recaptchaEmail = window.grecaptcha.render("recaptchaEmail", {"sitekey": jq("#recaptchaData").val()}); } } }); var loginMessage = jq(".login-message[value!='']").val(); if (loginMessage && loginMessage.length) { jq("#personalLogin a").click(); var type = jq(".login-message[value!='']").attr("data-type"); if (type | 0) { toastr.success(loginMessage); } else { toastr.error(loginMessage); } } try { var anch = ASC.Controls.AnchorController.getAnchor(); if (jq.trim(anch) == "passrecovery") { PasswordTool.ShowPwdReminderDialog(); } } catch (e) { } if (jq('body').hasClass('desktop')) { showAccountLinks(); } } function getReviewList () { var lng = jq("#reviewsContainer").attr("data-lng"); lng = lng ? lng.toLowerCase() : "en"; jq.getJSON("/UserControls/Common/AuthorizeDocs/js/reviews.json", function (data) { var reviews = data.en.reviews; jq.each(data, function (key, val) { if (key == lng) { reviews = val.reviews; } }); //shuffle(reviews); reviews.forEach(function (review) { review.stars = new Array(parseInt(review.rating)); if (review.photo) { review.photoUrl = "/UserControls/Common/AuthorizeDocs/css/images/foto_commets/" + review.photo; } jq("#personalReviewTmpl").tmpl(review).appendTo("#reviewsContainer"); }); carouselAuto(reviews.length); }); } function shuffle (array) { var counter = array.length, temp, index; // While there are elements in the array while (counter > 0) { // Pick a random index index = Math.floor(Math.random() * counter); // Decrease counter by 1 counter--; // And swap the last element with it temp = array[counter]; array[counter] = array[index]; array[index] = temp; } } function carouselSlider ($carousel) { var blockWidth = $carousel.find('.carousel-block').outerWidth(true); $carousel.animate({ left: "-" + blockWidth + "px" }, 800, function () { $carousel.find(".carousel-block").eq(0).clone().appendTo($carousel); $carousel.find(".carousel-block").eq(0).remove(); $carousel.css({ "left": "0px" }); }); } var StickyElement = function (node) { var doc = jq(document), fixed = false, anchor = node.find('.auth-form-with_form_w_anchor'), content = node.find('.auth-form-with_form_w'); /* var onScroll = function (e) { var docTop = doc.scrollTop(), anchorTop = anchor.offset().top; if (docTop > anchorTop) { if (!fixed) { anchor.height(content.outerHeight()); content.addClass('fixed'); fixed = true; } } else { if (fixed) { anchor.height(0); content.removeClass('fixed'); fixed = false; } } }; jq(window).on('scroll', onScroll);*/ }; var StEl = jq(window).width() >= '700'? new StickyElement(jq('.auth-form-head')) : null; jq('.share-collaborate-picture-carousel').slick({ slidesToShow: 1, dots: true, arrows: true, }); function carouselAuto(slidesCount) { jq('.carousel').slick({ slidesToShow: slidesCount < 3 ? slidesCount : 2, centerMode: false, responsive: [ { breakpoint: 1041, settings: { slidesToShow: 1, } }] }); /* var $carousel = jq("#reviewsContainer"); setInterval(function () { carouselSlider($carousel); }, 8000);*/ } jq.fn.duplicate = function (count, cloneEvents) { var tmp = []; for (var i = 0; i < count; i++) { jq.merge(tmp, this.clone(cloneEvents).get()); } return this.pushStack(tmp); }; jq('.create-carousel').slick({ slidesToShow: 1, slidesToScroll: 1, arrows: false, fade: true, asNavFor: '.slick-carousel' }); jq('.slick-carousel').slick({ slidesToShow: 1, arrows: true, dots: true, centerMode: true, asNavFor: '.create-carousel' }); bindEvents(); getReviewList(); }); <file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/IMAP/Server/IMAP_Session.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System.Collections.Generic; using System.Security.Principal; using ASC.Mail.Net.IO; namespace ASC.Mail.Net.IMAP.Server { #region usings using System; using System.Collections; using System.IO; using System.Net.Sockets; using System.Text; using System.Timers; using AUTH; using Mime; using StringReader = StringReader; using ASC.Mail.Net.TCP; #endregion /// <summary> /// IMAP session. /// </summary> public class IMAP_Session : TCP_ServerSession { #region Nested type: Command_IDLE /// <summary> /// This class implements IDLE command. Defined in RFC 2177. /// </summary> private class Command_IDLE: IDisposable { #region Members private readonly string m_CmdTag = ""; private readonly string folder; private bool m_IsDisposed; private IMAP_Session m_pSession; private TimerEx m_pTimer; #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="session">Owner IMAP session.</param> /// <param name="cmdTag">IDLE command command-tag.</param> /// <exception cref="ArgumentNullException">Is raised when <b>session</b> or <b>cmdTag</b> is null reference.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> public Command_IDLE(IMAP_Session session, string cmdTag) : this(session, cmdTag, session.SelectedMailbox) { } /// <summary> /// Default constructor. /// </summary> /// <param name="session">Owner IMAP session.</param> /// <param name="cmdTag">IDLE command command-tag.</param> /// <exception cref="ArgumentNullException">Is raised when <b>session</b> or <b>cmdTag</b> is null reference.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> public Command_IDLE(IMAP_Session session, string cmdTag, string folder) { if (session == null) { throw new ArgumentNullException("session"); } if (cmdTag == null) { throw new ArgumentNullException("cmdTag"); } if (cmdTag == string.Empty) { throw new ArgumentException("Argument 'cmdTag' value must be specified.", "cmdTag"); } try { m_pSession = session; m_CmdTag = cmdTag; this.folder = folder; Start(); } catch (Exception x) { m_pSession.OnError(x); } } void m_pSession_FolderChanged(string folderName, string username) { //tada if (!m_IsDisposed) m_pSession.ProcessMailboxChanges(folder); } #endregion #region Methods /// <summary> /// Cleans up any resources being used. /// </summary> /// public void Dispose() { if (m_IsDisposed) { return; } m_IsDisposed = true; try { m_pTimer.Stop(); m_pSession.FolderChanged -= m_pSession_FolderChanged; m_pSession.m_pIDLE = null; m_pSession = null; m_pTimer.Dispose(); m_pTimer = null; } catch (Exception) { } } #endregion #region Event handlers private void m_pTimer_Elapsed(object sender, ElapsedEventArgs e) { // If mailbox changes, report them to connected client. if (!m_IsDisposed) m_pSession.ProcessMailboxChanges(folder); } #endregion #region Utility methods private void ReadLineCompleted(object sender, EventArgs<SmartStream.ReadLineAsyncOP> eventArgs) { try { // Accoridng RFC, we should get only "DONE" here. if (m_IsDisposed) return; if (eventArgs.Value.IsCompleted && eventArgs.Value.Error == null) { if (eventArgs.Value.LineUtf8 == "DONE") { // Send "cmd-tag OK IDLE terminated" to connected client. m_pSession.WriteLine(m_CmdTag + " OK IDLE terminated"); m_pSession.BeginRecieveCmd(); Dispose(); } // Connected client send illegal stuff us, end session. else { m_pSession.EndSession(); Dispose(); } } // Receive errors, probably TCP connection broken. else { m_pSession.EndSession(); Dispose(); } } catch (Exception) { } } /// <summary> /// Starts IDLE command processing. /// </summary> private void Start() { /* RFC 2177 IDLE command example. C: A004 IDLE S: * 2 EXPUNGE S: * 3 EXISTS S: + idling ...time passes; another client expunges message 3... S: * 3 EXPUNGE S: * 2 EXISTS ...time passes; new mail arrives... S: * 3 EXISTS C: DONE S: A004 OK IDLE terminated */ // Send status reponse to connected client if any. m_pSession.ProcessMailboxChanges(folder); // Send "+ idling" to connected client. m_pSession.WriteLine("+ idling"); // Start timer to poll mailbox changes. m_pSession.FolderChanged += m_pSession_FolderChanged; m_pTimer = new TimerEx(5000, true); m_pTimer.Elapsed += m_pTimer_Elapsed; m_pTimer.Enabled = true; // Start waiting DONE command from connected client. m_pSession.ReadAsync(ReadLineCompleted); } #endregion } #endregion #region Members private IMAP_Server ImapServer { get { return Server as IMAP_Server; } } private Command_IDLE m_pIDLE; private IMAP_SelectedFolder m_pSelectedFolder; private IMAP_SelectedFolder m_pAdditionalFolder; private string m_StatusedMailbox = ""; private int m_BadCmdCount; private GenericIdentity m_pUser; public IMAP_Session() { SelectedMailbox = ""; } public override void Dispose() { base.Dispose(); if (!IsDisposed) { if (m_pIDLE!=null) { m_pIDLE.Dispose(); } if (m_pSelectedFolder!=null) { m_pSelectedFolder.Dispose(); } if (m_pAdditionalFolder != null) { m_pAdditionalFolder.Dispose(); } } } internal event IMAP_Server.FolderChangedHandler FolderChanged = null; public void OnFolderChanged(string folderName, string username) { if (FolderChanged != null) { FolderChanged(folderName, username); } } #endregion #region Properties /// <summary> /// Gets selected mailbox. /// </summary> public string SelectedMailbox { get; private set; } #endregion #region Constructor #endregion #region Methods #endregion #region Overrides protected override void OnTimeout() { base.OnTimeout(); WriteLine("* BYE Session timeout"); TcpStream.Flush(); } #endregion #region Utility methods protected internal override void Start() { base.Start(); try { ImapServer.FolderChanged += OnFolderChanged; // Check if ip is allowed to connect this computer if (ImapServer.OnValidate_IpAddress(LocalEndPoint, RemoteEndPoint)) { WriteLine(string.Format("* OK {0} IMAP Server ready", LocalHostName)); BeginRecieveCmd(); } else { EndSession(); } } catch (Exception x) { OnError(x); } } /// <summary> /// Ends session, closes socket. /// </summary> private void EndSession() { Disconnect(); } /// <summary> /// Is called when error occures. /// </summary> /// <param name="x"></param> private new void OnError(Exception x) { // Session disposed, so we don't care about terminating errors any more. if (IsDisposed) { return; } try { ImapServer.OnSysError("ending session", x); EndSession(); } catch (Exception) { } } private void AddLog(string message) { // Log if (ImapServer.Logger != null) { ImapServer.Logger.AddText(ID, message); } } private void AddReadEntry(string cmd) { // Log if (ImapServer.Logger != null) { ImapServer.Logger.AddRead(ID, AuthenticatedUserIdentity, cmd.Length, cmd, LocalEndPoint, RemoteEndPoint); } } private void AddWriteEntry(string cmd) { // Log if (ImapServer.Logger != null) { ImapServer.Logger.AddWrite(ID, AuthenticatedUserIdentity, cmd.Length, cmd, LocalEndPoint, RemoteEndPoint); } } /// <summary> /// Starts recieveing command. /// </summary> private void BeginRecieveCmd() { SmartStream.ReadLineAsyncOP args = new SmartStream.ReadLineAsyncOP(new byte[Workaround.Definitions.MaxStreamLineLength], SizeExceededAction. JunkAndThrowException); args.Completed += new EventHandler<EventArgs<SmartStream.ReadLineAsyncOP>>(ReciveCmdComleted); TcpStream.ReadLine(args, true); } internal void ReadAsync(EventHandler<EventArgs<SmartStream.ReadLineAsyncOP>> completed) { SmartStream.ReadLineAsyncOP args = new SmartStream.ReadLineAsyncOP(new byte[Workaround.Definitions.MaxStreamLineLength], SizeExceededAction. JunkAndThrowException); args.Completed += completed; TcpStream.ReadLine(args, true); } protected void WriteLine(string line) { try { AddWriteEntry(line); TcpStream.WriteLine(line); } catch (Exception x) { OnError(x); } } private void ReciveCmdComleted(object sender, EventArgs<SmartStream.ReadLineAsyncOP> e) { if (e.Value.IsCompleted && e.Value.Error == null) { //Call bool sessionEnd = false; try { string cmdLine = e.Value.LineUtf8; AddReadEntry(cmdLine); // Exceute command TcpStream.MemoryBuffer = true; sessionEnd = SwitchCommand(cmdLine); TcpStream.Flush(); if (sessionEnd) { // Session end, close session EndSession(); } } catch (Exception ex) { OnError(ex); } } else if (e.Value.Error != null) { OnError(e.Value.Error); } } private void EndSession(string text) { Disconnect(text); } /// <summary> /// Executes IMAP command. /// </summary> /// <param name="IMAP_commandTxt">Original command text.</param> /// <returns>Returns true if must end session(command loop).</returns> private bool SwitchCommand(string IMAP_commandTxt) { // Parse commandTag + comand + args // eg. C: a100 SELECT INBOX<CRLF> // a100 - commandTag // SELECT - command // INBOX - arg //---- Parse command --------------------------------------------------// string[] cmdParts = IMAP_commandTxt.TrimStart().Split(new[] { ' ' }); // For bad command, just return empty cmdTag and command name if (cmdParts.Length < 2) { cmdParts = new[] { "", "" }; } string commandTag = cmdParts[0].Trim().Trim(); string command = cmdParts[1].ToUpper().Trim(); string argsText = Core.GetArgsText(IMAP_commandTxt, cmdParts[0] + " " + cmdParts[1]); //---------------------------------------------------------------------// bool getNextCmd = true; switch (command) { //--- Non-IsAuthenticated State case "STARTTLS": STARTTLS(commandTag, argsText); break; case "AUTHENTICATE": Authenticate(commandTag, argsText); break; case "LOGIN": LogIn(commandTag, argsText); break; //--- End of non-IsAuthenticated //--- IsAuthenticated State case "SELECT": Select(commandTag, argsText); break; case "EXAMINE": Examine(commandTag, argsText); break; case "CREATE": Create(commandTag, argsText); break; case "DELETE": Delete(commandTag, argsText); break; case "RENAME": Rename(commandTag, argsText); break; case "SUBSCRIBE": Suscribe(commandTag, argsText); break; case "UNSUBSCRIBE": UnSuscribe(commandTag, argsText); break; case "LIST": List(commandTag, argsText); break; case "LSUB": LSub(commandTag, argsText); break; case "STATUS": Status(commandTag, argsText); break; case "APPEND": getNextCmd = BeginAppendCmd(commandTag, argsText); break; case "NAMESPACE": Namespace(commandTag, argsText); break; case "GETACL": GETACL(commandTag, argsText); break; case "SETACL": SETACL(commandTag, argsText); break; case "DELETEACL": DELETEACL(commandTag, argsText); break; case "LISTRIGHTS": LISTRIGHTS(commandTag, argsText); break; case "MYRIGHTS": MYRIGHTS(commandTag, argsText); break; case "GETQUOTA": GETQUOTA(commandTag, argsText); break; case "GETQUOTAROOT": GETQUOTAROOT(commandTag, argsText); break; //--- End of IsAuthenticated //--- Selected State case "CHECK": Check(commandTag); break; case "CLOSE": Close(commandTag); break; case "EXPUNGE": Expunge(commandTag); break; case "SEARCH": Search(commandTag, argsText, false); break; case "FETCH": Fetch(commandTag, argsText, false); break; case "STORE": Store(commandTag, argsText, false); break; case "COPY": Copy(commandTag, argsText, false); break; case "UID": Uid(commandTag, argsText); break; case "IDLE": getNextCmd = !Idle(commandTag, argsText); break; //--- End of Selected //--- Any State case "CAPABILITY": Capability(commandTag); break; case "NOOP": Noop(commandTag); break; case "LOGOUT": LogOut(commandTag); return true; //--- End of Any default: WriteLine(commandTag + " BAD command unrecognized"); //---- Check that maximum bad commands count isn't exceeded ---------------// if (m_BadCmdCount > ImapServer.MaxBadCommands - 1) { WriteLine("* BAD Too many bad commands, closing transmission channel"); return true; } m_BadCmdCount++; //-------------------------------------------------------------------------// break; } if (getNextCmd) { BeginRecieveCmd(); } return false; } //--- Non-IsAuthenticated State ------ private void STARTTLS(string cmdTag, string argsText) { /* RFC 2595 3. IMAP STARTTLS extension. 3. IMAP STARTTLS extension When the TLS extension is present in IMAP, "STARTTLS" is listed as a capability in response to the CAPABILITY command. This extension adds a single command, "STARTTLS" to the IMAP protocol which is used to begin a TLS negotiation. 3.1. STARTTLS Command Arguments: none Responses: no specific responses for this command Result: OK - begin TLS negotiation BAD - command unknown or arguments invalid A TLS negotiation begins immediately after the CRLF at the end of the tagged OK response from the server. Once a client issues a STARTTLS command, it MUST NOT issue further commands until a server response is seen and the TLS negotiation is complete. The STARTTLS command is only valid in non-authenticated state. The server remains in non-authenticated state, even if client credentials are supplied during the TLS negotiation. The SASL [SASL] EXTERNAL mechanism MAY be used to authenticate once TLS client credentials are successfully exchanged, but servers supporting the STARTTLS command are not required to support the EXTERNAL mechanism. Once TLS has been started, the client MUST discard cached information about server capabilities and SHOULD re-issue the CAPABILITY command. This is necessary to protect against man-in-the-middle attacks which alter the capabilities list prior to STARTTLS. The server MAY advertise different capabilities after STARTTLS. The formal syntax for IMAP is amended as follows: command_any =/ "STARTTLS" Example: C: a001 CAPABILITY S: * CAPABILITY IMAP4rev1 STARTTLS LOGINDISABLED S: a001 OK CAPABILITY completed C: a002 STARTTLS S: a002 OK Begin TLS negotiation now <TLS negotiation, further commands are under TLS layer> C: a003 CAPABILITY S: * CAPABILITY IMAP4rev1 AUTH=EXTERNAL S: a003 OK CAPABILITY completed C: a004 LOGIN joe password S: a004 OK LOGIN completed */ if (IsAuthenticated) { WriteLine(cmdTag + " NO The STARTTLS command is only valid in non-authenticated state !"); return; } if (IsSecureConnection) { WriteLine(cmdTag + " NO The STARTTLS already started !"); return; } if (Certificate == null) { WriteLine(cmdTag + " NO TLS not available, SSL certificate isn't specified !"); return; } WriteLine(cmdTag + " OK Ready to start TLS"); try { SwitchToSecure(); AddLog("TLS negotiation completed successfully."); } catch (Exception x) { WriteLine(cmdTag + " NO TLS handshake failed ! " + x.Message); } } private void Authenticate(string cmdTag, string argsText) { /* Rfc 3501 6.2.2. AUTHENTICATE Command Arguments: authentication mechanism name Responses: continuation data can be requested Result: OK - authenticate completed, now in authenticated state NO - authenticate failure: unsupported authentication mechanism, credentials rejected BAD - command unknown or arguments invalid, authentication exchange cancelled */ if (IsAuthenticated) { WriteLine(string.Format("{0} NO AUTH you are already logged in", cmdTag)); return; } string userName = ""; // string password = ""; AuthUser_EventArgs aArgs = null; switch (argsText.ToUpper()) { case "CRAM-MD5": #region CRAM-MDD5 authentication /* Cram-M5 C: A0001 AUTH CRAM-MD5 S: + <md5_calculation_hash_in_base64> C: base64(decoded:username password_hash) S: A0001 OK CRAM authentication successful */ string md5Hash = string.Format("<{0}>", Guid.NewGuid().ToString().ToLower()); WriteLine(string.Format("+ {0}", Convert.ToBase64String(Encoding.ASCII.GetBytes(md5Hash)))); string reply = ReadLine(); reply = Encoding.Default.GetString(Convert.FromBase64String(reply)); string[] replyArgs = reply.Split(' '); userName = replyArgs[0]; aArgs = ImapServer.OnAuthUser(this, userName, replyArgs[1], md5Hash, AuthType.CRAM_MD5); // There is custom error, return it if (aArgs.ErrorText != null) { WriteLine(string.Format("{0} NO {1}", cmdTag, aArgs.ErrorText)); return; } if (aArgs.Validated) { WriteLine(string.Format("{0} OK Authentication successful.", cmdTag)); SetUserName(userName); } else { WriteLine(string.Format("{0} NO Authentication failed", cmdTag)); } #endregion break; case "DIGEST-MD5": #region DIGEST-MD5 authentication /* RFC 2831 AUTH DIGEST-MD5 * * Example: * * C: AUTH DIGEST-MD5 * S: + base64(realm="elwood.innosoft.com",nonce="OA6MG9tEQGm2hh",qop="auth",algorithm=md5-sess) * C: base64(username="chris",realm="elwood.innosoft.com",nonce="OA6MG9tEQGm2hh", * nc=00000001,cnonce="OA6MHXh6VqTrRk",digest-uri="imap/elwood.innosoft.com", * response=d388dad90d4bbd760a152321f2143af7,qop=auth) * S: + base64(rspauth=ea40f60335c427b5527b84dbabcdfffd) * C: * S: A0001 OK Authentication successful. */ string realm = LocalHostName; string nonce = AuthHelper.GenerateNonce(); WriteLine("+ " + AuthHelper.Base64en(AuthHelper.Create_Digest_Md5_ServerResponse(realm, nonce))); string clientResponse = AuthHelper.Base64de(ReadLine()); // Check that realm and nonce in client response are same as we specified if (clientResponse.IndexOf(string.Format("realm=\"{0}\"", realm)) > -1 && clientResponse.IndexOf(string.Format("nonce=\"{0}\"", nonce)) > -1) { // Parse user name and password compare value // string userName = ""; string passwData = ""; string cnonce = ""; foreach (string clntRespParam in clientResponse.Split(',')) { if (clntRespParam.StartsWith("username=")) { userName = clntRespParam.Split(new[] { '=' }, 2)[1].Replace("\"", ""); } else if (clntRespParam.StartsWith("response=")) { passwData = clntRespParam.Split(new[] { '=' }, 2)[1]; } else if (clntRespParam.StartsWith("cnonce=")) { cnonce = clntRespParam.Split(new[] { '=' }, 2)[1].Replace("\"", ""); } } aArgs = ImapServer.OnAuthUser(this, userName, passwData, clientResponse, AuthType.DIGEST_MD5); // There is custom error, return it if (aArgs.ErrorText != null) { WriteLine(string.Format("{0} NO {1}", cmdTag, aArgs.ErrorText)); return; } if (aArgs.Validated) { // Send server computed password hash WriteLine("+ " + AuthHelper.Base64en("rspauth=" + aArgs.ReturnData)); // We must got empty line here clientResponse = ReadLine(); if (clientResponse == "") { WriteLine(string.Format("{0} OK Authentication successful.", cmdTag)); SetUserName(userName); } else { WriteLine(string.Format("{0} NO Authentication failed", cmdTag)); } } else { WriteLine(string.Format("{0} NO Authentication failed", cmdTag)); } } else { WriteLine(string.Format("{0} NO Authentication failed", cmdTag)); } #endregion break; default: WriteLine(string.Format("{0} NO unsupported authentication mechanism", cmdTag)); break; } } private void LogIn(string cmdTag, string argsText) { /* RFC 3501 6.2.3 LOGIN Command Arguments: user name password Responses: no specific responses for this command Result: OK - login completed, now in authenticated state NO - login failure: user name or password rejected BAD - command unknown or arguments invalid The LOGIN command identifies the client to the server and carries the plaintext password authenticating this user. Example: C: a001 LOGIN SMITH SESAME S: a001 OK LOGIN completed //---- C: a001 LOGIN "SMITH" "SESAME" S: a001 OK LOGIN completed */ /*if (IsAuthenticated) { WriteLine(cmdTag + " NO Reauthentication error, you are already logged in"); return; }*/ string[] args = TextUtils.SplitQuotedString(argsText, ' ', true); if (args.Length != 2) { WriteLine(string.Format("{0} BAD Invalid arguments, syntax: {{<command-tag> LOGIN \"<user-name>\" \"<password>\"}}", cmdTag)); return; } string userName = args[0]; string password = args[1]; // Store start time long startTime = DateTime.Now.Ticks; AuthUser_EventArgs aArgs = ImapServer.OnAuthUser(this, userName, password, "", AuthType.Plain); // There is custom error, return it if (aArgs.ErrorText != null) { WriteLine(string.Format("{0} NO {1}", cmdTag, aArgs.ErrorText)); return; } if (aArgs.Validated) { WriteLine(string.Format("{0} OK LOGIN Completed in {1} seconds", cmdTag, ((DateTime.Now.Ticks - startTime) / (decimal)10000000).ToString("f2"))); SetUserName(userName); } else { WriteLine(string.Format("{0} NO LOGIN failed", cmdTag)); } } public override GenericIdentity AuthenticatedUserIdentity { get { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_pUser; } } private void SetUserName(string userName) { UserName = userName; m_pUser = new GenericIdentity(UserName); } public string UserName { get; set; } //--- End of non-IsAuthenticated State //--- IsAuthenticated State ------ private void Select(string cmdTag, string argsText) { /* Rfc 3501 6.3.1 SELECT Command Arguments: mailbox name Responses: REQUIRED untagged responses: FLAGS, EXISTS, RECENT REQUIRED OK untagged responses: UNSEEN, PERMANENTFLAGS, UIDNEXT, UIDVALIDITY Result: OK - select completed, now in selected state NO - select failure, now in authenticated state: no such mailbox, can't access mailbox BAD - command unknown or arguments invalid The SELECT command selects a mailbox so that messages in the mailbox can be accessed. Before returning an OK to the client, the server MUST send the following untagged data to the client. Note that earlier versions of this protocol only required the FLAGS, EXISTS, and RECENT untagged data; consequently, client implementations SHOULD implement default behavior for missing data as discussed with the individual item. FLAGS Defined flags in the mailbox. See the description of the FLAGS response for more detail. <n> EXISTS The number of messages in the mailbox. See the description of the EXISTS response for more detail. <n> RECENT The number of messages with the \Recent flag set. See the description of the RECENT response for more detail. OK [UNSEEN <n>] The message sequence number of the first unseen message in the mailbox. If this is missing, the client can not make any assumptions about the first unseen message in the mailbox, and needs to issue a SEARCH command if it wants to find it. OK [PERMANENTFLAGS (<list of flags>)] A list of message flags that the client can change permanently. If this is missing, the client should assume that all flags can be changed permanently. OK [UIDNEXT <n>] The next unique identifier value. Refer to section 2.3.1.1 for more information. If this is missing, the client can not make any assumptions about the next unique identifier value. OK [UIDVALIDITY <n>] The unique identifier validity value. Refer to section 2.3.1.1 for more information. If this is missing, the server does not support unique identifiers. Only one mailbox can be selected at a time in a connection; simultaneous access to multiple mailboxes requires multiple connections. The SELECT command automatically deselects any currently selected mailbox before attempting the new selection. Consequently, if a mailbox is selected and a SELECT command that fails is attempted, no mailbox is selected. If the client is permitted to modify the mailbox, the server SHOULD prefix the text of the tagged OK response with the "[READ-WRITE]" response code. If the client is not permitted to modify the mailbox but is permitted read access, the mailbox is selected as read-only, and the server MUST prefix the text of the tagged OK response to SELECT with the "[READ-ONLY]" response code. Read-only access through SELECT differs from the EXAMINE command in that certain read-only mailboxes MAY permit the change of permanent state on a per-user (as opposed to global) basis. Netnews messages marked in a server-based .newsrc file are an example of such per-user permanent state that can be modified with read-only mailboxes. Example: C: A142 SELECT INBOX S: * 172 EXISTS S: * 1 RECENT S: * OK [UNSEEN 12] Message 12 is first unseen S: * OK [UIDVALIDITY 3857529045] UIDs valid S: * OK [UIDNEXT 4392] Predicted next UID S: * FLAGS (\Answered \Flagged \Deleted \Seen \Draft) S: * OK [PERMANENTFLAGS (\Deleted \Seen \*)] Limited S: A142 OK [READ-WRITE] SELECT completed */ if (!IsAuthenticated) { WriteLine(string.Format("{0} NO Authenticate first !", cmdTag)); return; } string[] args = TextUtils.SplitQuotedString(argsText, ' ', true); if (args.Length != 1) { WriteLine(string.Format("{0} BAD SELECT invalid arguments. Syntax: {{<command-tag> SELECT \"mailboxName\"}}", cmdTag)); return; } // Store start time long startTime = DateTime.Now.Ticks; IMAP_SelectedFolder selectedFolder = new IMAP_SelectedFolder(Core.Decode_IMAP_UTF7_String(args[0])); IMAP_eArgs_GetMessagesInfo eArgs = ImapServer.OnGetMessagesInfo(this, selectedFolder); if (eArgs.ErrorText == null) { m_pSelectedFolder = selectedFolder; SelectedMailbox = Core.Decode_IMAP_UTF7_String(args[0]); string response = ""; response += "* FLAGS (\\Answered \\Flagged \\Deleted \\Seen \\Draft)\r\n"; response += string.Format("* {0} EXISTS\r\n", m_pSelectedFolder.Messages.Count); response += string.Format("* {0} RECENT\r\n", m_pSelectedFolder.RecentCount); response += string.Format("* OK [UNSEEN {0}] Message {1} is first unseen\r\n", m_pSelectedFolder.FirstUnseen, m_pSelectedFolder.FirstUnseen); response += string.Format("* OK [UIDVALIDITY {0}] Folder UID\r\n", m_pSelectedFolder.FolderUID); response += string.Format("* OK [UIDNEXT {0}] Predicted next message UID\r\n", m_pSelectedFolder.MessageUidNext); response += "* OK [PERMANENTFLAGS (\\Answered \\Flagged \\Deleted \\Seen \\Draft)] Available permanent flags\r\n"; response += string.Format("{0} OK [{1}] SELECT Completed in {2} seconds\r\n", cmdTag, (m_pSelectedFolder.ReadOnly ? "READ-ONLY" : "READ-WRITE"), ((DateTime.Now.Ticks - startTime) / (decimal)10000000).ToString("f2")); TcpStream.Write(response); } else { WriteLine(string.Format("{0} NO {1}", cmdTag, eArgs.ErrorText)); } } private void Examine(string cmdTag, string argsText) { /* Rfc 3501 6.3.2 EXAMINE Command Arguments: mailbox name Responses: REQUIRED untagged responses: FLAGS, EXISTS, RECENT REQUIRED OK untagged responses: UNSEEN, PERMANENTFLAGS, UIDNEXT, UIDVALIDITY Result: OK - examine completed, now in selected state NO - examine failure, now in authenticated state: no such mailbox, can't access mailbox BAD - command unknown or arguments invalid The EXAMINE command is identical to SELECT and returns the same output; however, the selected mailbox is identified as read-only. No changes to the permanent state of the mailbox, including per-user state, are permitted; in particular, EXAMINE MUST NOT cause messages to lose the \Recent flag. The text of the tagged OK response to the EXAMINE command MUST begin with the "[READ-ONLY]" response code. Example: C: A932 EXAMINE blurdybloop S: * 17 EXISTS S: * 2 RECENT S: * OK [UNSEEN 8] Message 8 is first unseen S: * OK [UIDVALIDITY 3857529045] UIDs valid S: * OK [UIDNEXT 4392] Predicted next UID S: * FLAGS (\Answered \Flagged \Deleted \Seen \Draft) S: * OK [PERMANENTFLAGS ()] No permanent flags permitted S: A932 OK [READ-ONLY] EXAMINE completed */ if (!IsAuthenticated) { WriteLine(string.Format("{0} NO Authenticate first !", cmdTag)); return; } string[] args = TextUtils.SplitQuotedString(argsText, ' ', true); if (args.Length != 1) { WriteLine(string.Format("{0} BAD EXAMINE invalid arguments. Syntax: {{<command-tag> EXAMINE \"mailboxName\"}}", cmdTag)); return; } // Store start time long startTime = DateTime.Now.Ticks; IMAP_SelectedFolder selectedFolder = new IMAP_SelectedFolder(Core.Decode_IMAP_UTF7_String(args[0])); IMAP_eArgs_GetMessagesInfo eArgs = ImapServer.OnGetMessagesInfo(this, selectedFolder); if (eArgs.ErrorText == null) { m_pSelectedFolder = selectedFolder; m_pSelectedFolder.ReadOnly = true; SelectedMailbox = Core.Decode_IMAP_UTF7_String(args[0]); string response = ""; response += "* FLAGS (\\Answered \\Flagged \\Deleted \\Seen \\Draft)\r\n"; response += string.Format("* {0} EXISTS\r\n", m_pSelectedFolder.Messages.Count); response += string.Format("* {0} RECENT\r\n", m_pSelectedFolder.RecentCount); response += string.Format("* OK [UNSEEN {0}] Message {1} is first unseen\r\n", m_pSelectedFolder.FirstUnseen, m_pSelectedFolder.FirstUnseen); response += string.Format("* OK [UIDVALIDITY {0}] UIDs valid\r\n", m_pSelectedFolder.FolderUID); response += string.Format("* OK [UIDNEXT {0}] Predicted next UID\r\n", m_pSelectedFolder.MessageUidNext); response += "* OK [PERMANENTFLAGS (\\Answered \\Flagged \\Deleted \\Seen \\Draft)] Available permanent falgs\r\n"; response += string.Format("{0} OK [READ-ONLY] EXAMINE Completed in {1} seconds\r\n", cmdTag, ((DateTime.Now.Ticks - startTime) / (decimal)10000000).ToString("f2")); TcpStream.Write(response); } else { WriteLine(string.Format("{0} NO {1}", cmdTag, eArgs.ErrorText)); } } private void Create(string cmdTag, string argsText) { /* RFC 3501 6.3.3 Arguments: mailbox name Responses: no specific responses for this command Result: OK - create completed NO - create failure: can't create mailbox with that name BAD - command unknown or arguments invalid The CREATE command creates a mailbox with the given name. An OK response is returned only if a new mailbox with that name has been created. It is an error to attempt to create INBOX or a mailbox with a name that refers to an extant mailbox. Any error in creation will return a tagged NO response. If the mailbox name is suffixed with the server's hierarchy separator character (as returned from the server by a LIST command), this is a declaration that the client intends to create mailbox names under this name in the hierarchy. Server implementations that do not require this declaration MUST ignore it. If the server's hierarchy separator character appears elsewhere in the name, the server SHOULD create any superior hierarchical names that are needed for the CREATE command to complete successfully. In other words, an attempt to create "foo/bar/zap" on a server in which "/" is the hierarchy separator character SHOULD create foo/ and foo/bar/ if they do not already exist. If a new mailbox is created with the same name as a mailbox which was deleted, its unique identifiers MUST be greater than any unique identifiers used in the previous incarnation of the mailbox UNLESS the new incarnation has a different unique identifier validity value. See the description of the UID command for more detail. Example: C: A003 CREATE owatagusiam/ S: A003 OK CREATE completed C: A004 CREATE owatagusiam/blurdybloop S: A004 OK CREATE completed */ if (!IsAuthenticated) { WriteLine(string.Format("{0} NO Authenticate first !", cmdTag)); return; } string[] args = TextUtils.SplitQuotedString(argsText, ' ', true); if (args.Length != 1) { WriteLine(string.Format("{0} BAD CREATE invalid arguments. Syntax: {{<command-tag> CREATE \"mailboxName\"}}", cmdTag)); return; } // Store start time long startTime = DateTime.Now.Ticks; string errorText = ImapServer.OnCreateMailbox(this, Core.Decode_IMAP_UTF7_String(args[0])); if (errorText == null) { WriteLine(string.Format("{0} OK CREATE Completed in {1} seconds", cmdTag, ((DateTime.Now.Ticks - startTime) / (decimal)10000000).ToString("f2"))); } else { WriteLine(string.Format("{0} NO {1}", cmdTag, errorText)); } } private void Delete(string cmdTag, string argsText) { /* RFC 3501 6.3.4 DELETE Command Arguments: mailbox name Responses: no specific responses for this command Result: OK - create completed NO - create failure: can't create mailbox with that name BAD - command unknown or arguments invalid The DELETE command permanently removes the mailbox with the given name. A tagged OK response is returned only if the mailbox has been deleted. It is an error to attempt to delete INBOX or a mailbox name that does not exist. The DELETE command MUST NOT remove inferior hierarchical names. For example, if a mailbox "foo" has an inferior "foo.bar" (assuming "." is the hierarchy delimiter character), removing "foo" MUST NOT remove "foo.bar". It is an error to attempt to delete a name that has inferior hierarchical names and also has the \Noselect mailbox name attribute (see the description of the LIST response for more details). It is permitted to delete a name that has inferior hierarchical names and does not have the \Noselect mailbox name attribute. In this case, all messages in that mailbox are removed, and the name will acquire the \Noselect mailbox name attribute. The value of the highest-used unique identifier of the deleted mailbox MUST be preserved so that a new mailbox created with the same name will not reuse the identifiers of the former incarnation, UNLESS the new incarnation has a different unique identifier validity value. See the description of the UID command for more detail. Examples: C: A682 LIST "" * S: * LIST () "/" blurdybloop S: * LIST (\Noselect) "/" foo S: * LIST () "/" foo/bar S: A682 OK LIST completed C: A683 DELETE blurdybloop S: A683 OK DELETE completed C: A684 DELETE foo S: A684 NO Name "foo" has inferior hierarchical names C: A685 DELETE foo/bar S: A685 OK DELETE Completed C: A686 LIST "" * S: * LIST (\Noselect) "/" foo S: A686 OK LIST completed C: A687 DELETE foo S: A687 OK DELETE Completed */ if (!IsAuthenticated) { WriteLine(string.Format("{0} NO Authenticate first !", cmdTag)); return; } string[] args = TextUtils.SplitQuotedString(argsText, ' ', true); if (args.Length != 1) { WriteLine(string.Format("{0} BAD DELETE invalid arguments. Syntax: {{<command-tag> DELETE \"mailboxName\"}}", cmdTag)); return; } string errorText = ImapServer.OnDeleteMailbox(this, Core.Decode_IMAP_UTF7_String(args[0])); if (errorText == null) { WriteLine(string.Format("{0} OK DELETE Completed", cmdTag)); } else { WriteLine(string.Format("{0} NO {1}", cmdTag, errorText)); } } private void Rename(string cmdTag, string argsText) { /* RFC 3501 6.3.5 RENAME Command Arguments: existing mailbox name new mailbox name Responses: no specific responses for this command Result: OK - rename completed NO - rename failure: can't rename mailbox with that name, can't rename to mailbox with that name BAD - command unknown or arguments invalid The RENAME command changes the name of a mailbox. A tagged OK response is returned only if the mailbox has been renamed. It is an error to attempt to rename from a mailbox name that does not exist or to a mailbox name that already exists. Any error in renaming will return a tagged NO response. If the name has inferior hierarchical names, then the inferior hierarchical names MUST also be renamed. For example, a rename of "foo" to "zap" will rename "foo/bar" (assuming "/" is the hierarchy delimiter character) to "zap/bar". The value of the highest-used unique identifier of the old mailbox name MUST be preserved so that a new mailbox created with the same name will not reuse the identifiers of the former incarnation, UNLESS the new incarnation has a different unique identifier validity value. See the description of the UID command for more detail. Renaming INBOX is permitted, and has special behavior. It moves all messages in INBOX to a new mailbox with the given name, leaving INBOX empty. If the server implementation supports inferior hierarchical names of INBOX, these are unaffected by a rename of INBOX. Examples: C: A682 LIST "" * S: * LIST () "/" blurdybloop S: * LIST (\Noselect) "/" foo S: * LIST () "/" foo/bar S: A682 OK LIST completed C: A683 RENAME blurdybloop sarasoop S: A683 OK RENAME completed C: A684 RENAME foo zowie S: A684 OK RENAME Completed C: A685 LIST "" * S: * LIST () "/" sarasoop S: * LIST (\Noselect) "/" zowie S: * LIST () "/" zowie/bar S: A685 OK LIST completed */ if (!IsAuthenticated) { WriteLine(string.Format("{0} NO Authenticate first !", cmdTag)); return; } string[] args = TextUtils.SplitQuotedString(argsText, ' ', true); if (args.Length != 2) { WriteLine(string.Format("{0} BAD RENAME invalid arguments. Syntax: {{<command-tag> RENAME \"mailboxName\" \"newMailboxName\"}}", cmdTag)); return; } string mailbox = Core.Decode_IMAP_UTF7_String(args[0]); string newMailbox = Core.Decode_IMAP_UTF7_String(args[1]); string errorText = ImapServer.OnRenameMailbox(this, mailbox, newMailbox); if (errorText == null) { WriteLine(string.Format("{0} OK RENAME Completed", cmdTag)); } else { WriteLine(string.Format("{0} NO {1}", cmdTag, errorText)); } } private void Suscribe(string cmdTag, string argsText) { /* RFC 3501 6.3.6 SUBSCRIBE Commmand Arguments: mailbox Responses: no specific responses for this command Result: OK - subscribe completed NO - subscribe failure: can't subscribe to that name BAD - command unknown or arguments invalid The SUBSCRIBE command adds the specified mailbox name to the server's set of "active" or "subscribed" mailboxes as returned by the LSUB command. This command returns a tagged OK response only if the subscription is successful. A server MAY validate the mailbox argument to SUBSCRIBE to verify that it exists. However, it MUST NOT unilaterally remove an existing mailbox name from the subscription list even if a mailbox by that name no longer exists. Note: this requirement is because some server sites may routinely remove a mailbox with a well-known name (e.g. "system-alerts") after its contents expire, with the intention of recreating it when new contents are appropriate. Example: C: A002 SUBSCRIBE #news.comp.mail.mime S: A002 OK SUBSCRIBE completed */ if (!IsAuthenticated) { WriteLine(string.Format("{0} NO Authenticate first !", cmdTag)); return; } string[] args = TextUtils.SplitQuotedString(argsText, ' ', true); if (args.Length != 1) { WriteLine(string.Format("{0} BAD SUBSCRIBE invalid arguments. Syntax: {{<command-tag> SUBSCRIBE \"mailboxName\"}}", cmdTag)); return; } string errorText = ImapServer.OnSubscribeMailbox(this, Core.Decode_IMAP_UTF7_String(args[0])); if (errorText == null) { AdditionalSelect(Core.Decode_IMAP_UTF7_String(args[0])); WriteLine(string.Format("{0} OK SUBSCRIBE completed", cmdTag)); } else { WriteLine(string.Format("{0} NO {1}", cmdTag, errorText)); } } private void AdditionalSelect(string folder) { m_StatusedMailbox = folder; m_pAdditionalFolder = new IMAP_SelectedFolder(folder); IMAP_eArgs_GetMessagesInfo eArgs = ImapServer.OnGetMessagesInfo(this, m_pAdditionalFolder); } private void UnSuscribe(string cmdTag, string argsText) { /* RFC 3501 6.3.7 UNSUBSCRIBE Command Arguments: mailbox Responses: no specific responses for this command Result: OK - subscribe completed NO - subscribe failure: can't subscribe to that name BAD - command unknown or arguments invalid The UNSUBSCRIBE command removes the specified mailbox name from the server's set of "active" or "subscribed" mailboxes as returned by the LSUB command. This command returns a tagged OK response only if the unsubscription is successful. Example: C: A002 UNSUBSCRIBE #news.comp.mail.mime S: A002 OK UNSUBSCRIBE completed */ if (!IsAuthenticated) { WriteLine(string.Format("{0} NO Authenticate first !", cmdTag)); return; } string[] args = TextUtils.SplitQuotedString(argsText, ' ', true); if (args.Length != 1) { WriteLine(string.Format("{0} BAD UNSUBSCRIBE invalid arguments. Syntax: {{<command-tag> UNSUBSCRIBE \"mailboxName\"}}", cmdTag)); return; } string errorText = ImapServer.OnUnSubscribeMailbox(this, Core.Decode_IMAP_UTF7_String(args[0])); if (errorText == null) { AdditionalSelect(Core.Decode_IMAP_UTF7_String(args[0])); WriteLine(string.Format("{0} OK UNSUBSCRIBE completed", cmdTag)); } else { WriteLine(string.Format("{0} NO {1}", cmdTag, errorText)); } } private void List(string cmdTag, string argsText) { /* Rc 3501 6.3.8 LIST Command Arguments: reference name mailbox name with possible wildcards Responses: untagged responses: LIST Result: OK - list completed NO - list failure: can't list that reference or name BAD - command unknown or arguments invalid The LIST command returns a subset of names from the complete set of all names available to the client. Zero or more untagged LIST replies are returned, containing the name attributes, hierarchy delimiter, and name; see the description of the LIST reply for more detail. An empty ("" string) reference name argument indicates that the mailbox name is interpreted as by SELECT. The returned mailbox names MUST match the supplied mailbox name pattern. A non-empty reference name argument is the name of a mailbox or a level of mailbox hierarchy, and indicates a context in which the mailbox name is interpreted in an implementation-defined manner. An empty ("" string) mailbox name argument is a special request to return the hierarchy delimiter and the root name of the name given in the reference. The value returned as the root MAY be null if the reference is non-rooted or is null. In all cases, the hierarchy delimiter is returned. This permits a client to get the hierarchy delimiter even when no mailboxes by that name currently exist. The character "*" is a wildcard, and matches zero or more characters at this position. The character "%" is similar to "*", but it does not match a hierarchy delimiter. If the "%" wildcard is the last character of a mailbox name argument, matching levels of hierarchy are also returned. */ if (!IsAuthenticated) { WriteLine(string.Format("{0} NO Authenticate first !", cmdTag)); return; } string[] args = TextUtils.SplitQuotedString(argsText, ' ', true); if (args.Length != 2) { WriteLine(string.Format("{0} BAD Invalid LIST arguments. Syntax: {{<command-tag> LIST \"<reference-name>\" \"<mailbox-name>\"}}", cmdTag)); return; } // Store start time long startTime = DateTime.Now.Ticks; string refName = Core.Decode_IMAP_UTF7_String(args[0]); string mailbox = Core.Decode_IMAP_UTF7_String(args[1]); string reply = ""; // Folder separator wanted if (mailbox.Length == 0) { reply += "* LIST (\\Noselect) \"/\" \"\"\r\n"; } // List mailboxes else { IMAP_Folders mailboxes = ImapServer.OnGetMailboxes(this, refName, mailbox); foreach (IMAP_Folder mBox in mailboxes.Folders) { if (mBox.Selectable) { reply += string.Format("* LIST () \"/\" \"{0}\" \r\n", Core.Encode_IMAP_UTF7_String(mBox.Folder)); } else { reply += string.Format("* LIST (\\Noselect) \"/\" \"{0}\" \r\n", Core.Encode_IMAP_UTF7_String(mBox.Folder)); } } } reply += string.Format("{0} OK LIST Completed in {1} seconds\r\n", cmdTag, ((DateTime.Now.Ticks - startTime) / (decimal)10000000).ToString("f2")); TcpStream.Write(reply); } private void LSub(string cmdTag, string argsText) { /* RFC 3501 6.3.9 LSUB Command Arguments: reference name mailbox name with possible wildcards Responses: untagged responses: LSUB Result: OK - lsub completed NO - lsub failure: can't list that reference or name BAD - command unknown or arguments invalid The LSUB command returns a subset of names from the set of names that the user has declared as being "active" or "subscribed". Zero or more untagged LSUB replies are returned. The arguments to LSUB are in the same form as those for LIST. The returned untagged LSUB response MAY contain different mailbox flags from a LIST untagged response. If this should happen, the flags in the untagged LIST are considered more authoritative. A special situation occurs when using LSUB with the % wildcard. Consider what happens if "foo/bar" (with a hierarchy delimiter of "/") is subscribed but "foo" is not. A "%" wildcard to LSUB must return foo, not foo/bar, in the LSUB response, and it MUST be flagged with the \Noselect attribute. The server MUST NOT unilaterally remove an existing mailbox name from the subscription list even if a mailbox by that name no longer exists. Example: C: A002 LSUB "#news." "comp.mail.*" S: * LSUB () "." #news.comp.mail.mime S: * LSUB () "." #news.comp.mail.misc S: A002 OK LSUB completed */ if (!IsAuthenticated) { WriteLine(string.Format("{0} NO Authenticate first !", cmdTag)); return; } string[] args = TextUtils.SplitQuotedString(argsText, ' ', true); if (args.Length != 2) { WriteLine(string.Format("{0} BAD LSUB invalid arguments", cmdTag)); return; } string refName = Core.Decode_IMAP_UTF7_String(args[0]); string mailbox = Core.Decode_IMAP_UTF7_String(args[1]); string reply = ""; IMAP_Folders mailboxes = ImapServer.OnGetSubscribedMailboxes(this, refName, mailbox); foreach (IMAP_Folder mBox in mailboxes.Folders) { reply += string.Format("* LSUB () \"/\" \"{0}\" \r\n", Core.Encode_IMAP_UTF7_String(mBox.Folder)); } reply += string.Format("{0} OK LSUB Completed\r\n", cmdTag); TcpStream.Write(reply); } private void Status(string cmdTag, string argsText) { /* RFC 3501 6.3.10 STATUS Command Arguments: mailbox name status data item names Responses: untagged responses: STATUS Result: OK - status completed NO - status failure: no status for that name BAD - command unknown or arguments invalid The STATUS command requests the status of the indicated mailbox. It does not change the currently selected mailbox, nor does it affect the state of any messages in the queried mailbox (in particular, STATUS MUST NOT cause messages to lose the \Recent flag). The STATUS command provides an alternative to opening a second IMAP4rev1 connection and doing an EXAMINE command on a mailbox to query that mailbox's status without deselecting the current mailbox in the first IMAP4rev1 connection. Unlike the LIST command, the STATUS command is not guaranteed to be fast in its response. In some implementations, the server is obliged to open the mailbox read-only internally to obtain certain status information. Also unlike the LIST command, the STATUS command does not accept wildcards. The currently defined status data items that can be requested are: MESSAGES The number of messages in the mailbox. RECENT The number of messages with the \Recent flag set. UIDNEXT The next unique identifier value of the mailbox. Refer to section 2.3.1.1 for more information. UIDVALIDITY The unique identifier validity value of the mailbox. Refer to section 2.3.1.1 for more information. UNSEEN The number of messages which do not have the \Seen flag set. Example: C: A042 STATUS blurdybloop (UIDNEXT MESSAGES) S: * STATUS blurdybloop (MESSAGES 231 UIDNEXT 44292) S: A042 OK STATUS completed */ if (!IsAuthenticated) { WriteLine(string.Format("{0} NO Authenticate first !", cmdTag)); return; } string[] args = ParseParams(argsText); if (args.Length != 2) { WriteLine(string.Format("{0} BAD Invalid STATUS arguments. Syntax: {{<command-tag> STATUS \"<mailbox-name>\" \"(status-data-items)\"}}", cmdTag)); return; } string folder = Core.Decode_IMAP_UTF7_String(args[0]); string wantedItems = args[1].ToUpper(); // See wanted items are valid. if ( wantedItems.Replace("MESSAGES", "").Replace("RECENT", "").Replace("UIDNEXT", "").Replace( "UIDVALIDITY", "").Replace("UNSEEN", "").Trim().Length > 0) { WriteLine(string.Format("{0} BAD STATUS invalid arguments", cmdTag)); return; } AdditionalSelect(folder); IMAP_SelectedFolder selectedFolder = new IMAP_SelectedFolder(folder); IMAP_eArgs_GetMessagesInfo eArgs = ImapServer.OnGetMessagesInfo(this, selectedFolder); if (eArgs.ErrorText == null) { string itemsReply = ""; if (wantedItems.IndexOf("MESSAGES") > -1) { itemsReply += string.Format(" MESSAGES {0}", selectedFolder.Messages.Count); } if (wantedItems.IndexOf("RECENT") > -1) { itemsReply += string.Format(" RECENT {0}", selectedFolder.RecentCount); } if (wantedItems.IndexOf("UNSEEN") > -1) { itemsReply += string.Format(" UNSEEN {0}", selectedFolder.UnSeenCount); } if (wantedItems.IndexOf("UIDVALIDITY") > -1) { itemsReply += string.Format(" UIDVALIDITY {0}", selectedFolder.FolderUID); } if (wantedItems.IndexOf("UIDNEXT") > -1) { itemsReply += string.Format(" UIDNEXT {0}", selectedFolder.MessageUidNext); } itemsReply = itemsReply.Trim(); WriteLine(string.Format("* STATUS {0} ({1})", args[0], itemsReply)); WriteLine(string.Format("{0} OK STATUS completed", cmdTag)); } else { WriteLine(string.Format("{0} NO {1}", cmdTag, eArgs.ErrorText)); } } /// <summary> /// Returns true if command ended syncronously. /// </summary> private bool BeginAppendCmd(string cmdTag, string argsText) { /* Rfc 3501 6.3.11 APPEND Command Arguments: mailbox name OPTIONAL flag parenthesized list OPTIONAL date/time string message literal Responses: no specific responses for this command Result: OK - append completed NO - append error: can't append to that mailbox, error in flags or date/time or message text BAD - command unknown or arguments invalid The APPEND command appends the literal argument as a new message to the end of the specified destination mailbox. This argument SHOULD be in the format of an [RFC-2822] message. 8-bit characters are permitted in the message. A server implementation that is unable to preserve 8-bit data properly MUST be able to reversibly convert 8-bit APPEND data to 7-bit using a [MIME-IMB] content transfer encoding. If a flag parenthesized list is specified, the flags SHOULD be set in the resulting message; otherwise, the flag list of the resulting message is set to empty by default. In either case, the Recent flag is also set. If a date-time is specified, the internal date SHOULD be set in the resulting message; otherwise, the internal date of the resulting message is set to the current date and time by default. If the append is unsuccessful for any reason, the mailbox MUST be restored to its state before the APPEND attempt; no partial appending is permitted. If the destination mailbox does not exist, a server MUST return an error, and MUST NOT automatically create the mailbox. Unless it is certain that the destination mailbox can not be created, the server MUST send the response code "[TRYCREATE]" as the prefix of the text of the tagged NO response. This gives a hint to the client that it can attempt a CREATE command and retry the APPEND if the CREATE is successful. Example: C: A003 APPEND saved-messages (\Seen) {310} S: + Ready for literal data C: Date: Mon, 7 Feb 1994 21:52:25 -0800 (PST) C: From: <NAME> <<EMAIL>> C: Subject: afternoon meeting C: To: <EMAIL> C: Message-Id: <<EMAIL>> C: MIME-Version: 1.0 C: Content-Type: TEXT/PLAIN; CHARSET=US-ASCII C: C: Hello Joe, do you think we can meet at 3:30 tomorrow? C: S: A003 OK APPEND completed */ if (!IsAuthenticated) { WriteLine(string.Format("{0} NO Authenticate first !", cmdTag)); return true; } string[] args = ParseParams(argsText); if (args.Length < 2 || args.Length > 4) { WriteLine(string.Format("{0} BAD APPEND Invalid arguments", cmdTag)); return true; } string mailbox = Core.Decode_IMAP_UTF7_String(args[0]); IMAP_MessageFlags mFlags = 0; DateTime date = DateTime.Now; long msgLen = Convert.ToInt64(args[args.Length - 1].Replace("{", "").Replace("}", "")); if (args.Length == 4) { //--- Parse flags, see if valid ---------------- string flags = args[1].ToUpper(); if ( flags.Replace("\\ANSWERED", "").Replace("\\FLAGGED", "").Replace("\\DELETED", "").Replace( "\\SEEN", "").Replace("\\DRAFT", "").Trim().Length > 0) { WriteLine(string.Format("{0} BAD arguments invalid", cmdTag)); return false; } mFlags = IMAP_Utils.ParseMessageFlags(flags); date = MimeUtils.ParseDate(args[2]); } else if (args.Length == 3) { // See if date or flags specified, try date first try { date = MimeUtils.ParseDate(args[1]); } catch { //--- Parse flags, see if valid ---------------- string flags = args[1].ToUpper(); if ( flags.Replace("\\ANSWERED", "").Replace("\\FLAGGED", "").Replace("\\DELETED", ""). Replace("\\SEEN", "").Replace("\\DRAFT", "").Trim().Length > 0) { WriteLine(string.Format("{0} BAD arguments invalid", cmdTag)); return false; } mFlags = IMAP_Utils.ParseMessageFlags(flags); } } // Request data WriteLine("+ Ready for literal data"); MemoryStream strm = new MemoryStream(); Hashtable param = new Hashtable(); param.Add("cmdTag", cmdTag); param.Add("mailbox", mailbox); param.Add("mFlags", mFlags); param.Add("date", date); param.Add("strm", strm); // Begin recieving data Why needed msgLen+2 ??? TcpStream.BeginReadFixedCount(strm, (int)msgLen + 2, EndAppendCmd, param); return false; } /// <summary> /// Is called when DATA command is finnished. /// </summary> /// <param name="result"></param> /// <param name="count"></param> /// <param name="exception"></param> /// <param name="tag"></param> private void EndAppendCmd(IAsyncResult ar) { try { TcpStream.EndReadFixedCount(ar); if (ar.IsCompleted) { Hashtable param = (Hashtable)ar.AsyncState; string cmdTag = (string)param["cmdTag"]; string mailbox = (string)param["mailbox"]; IMAP_MessageFlags mFlags = (IMAP_MessageFlags)param["mFlags"]; DateTime date = (DateTime)param["date"]; MemoryStream strm = (MemoryStream)param["strm"]; IMAP_Message msg = new IMAP_Message(null, "", 0, date, 0, mFlags); string errotText = ImapServer.OnStoreMessage(this, mailbox, msg, strm.ToArray()); if (errotText == null) { WriteLine(string.Format("{0} OK APPEND completed, recieved {1} bytes", cmdTag, strm.Length)); } else { WriteLine(string.Format("{0} NO {1}", cmdTag, errotText)); } } // Command completed ok, get next command BeginRecieveCmd(); } catch (Exception x) { OnError(x); } } private void Namespace(string cmdTag, string argsText) { /* Rfc 2342 5. NAMESPACE Command. Arguments: none Response: an untagged NAMESPACE response that contains the prefix and hierarchy delimiter to the server's Personal Namespace(s), Other Users' Namespace(s), and Shared Namespace(s) that the server wishes to expose. The response will contain a NIL for any namespace class that is not available. Namespace_Response_Extensions MAY be included in the response. Namespace_Response_Extensions which are not on the IETF standards track, MUST be prefixed with an "X-". Result: OK - Command completed NO - Error: Can't complete command BAD - argument invalid Example: < A server that contains a Personal Namespace and a single Shared Namespace. > C: A001 NAMESPACE S: * NAMESPACE (("" "/")) NIL (("Public Folders/" "/")) S: A001 OK NAMESPACE command completed */ if (!IsAuthenticated) { WriteLine(string.Format("{0} NO Authenticate first !", cmdTag)); return; } SharedRootFolders_EventArgs eArgs = ImapServer.OnGetSharedRootFolders(this); string publicRootFolders = "NIL"; if (eArgs.PublicRootFolders != null && eArgs.PublicRootFolders.Length > 0) { publicRootFolders = "("; foreach (string publicRootFolder in eArgs.PublicRootFolders) { publicRootFolders += string.Format("(\"{0}/\" \"/\")", publicRootFolder); } publicRootFolders += ")"; } string sharedRootFolders = "NIL"; if (eArgs.SharedRootFolders != null && eArgs.SharedRootFolders.Length > 0) { sharedRootFolders = "("; foreach (string sharedRootFolder in eArgs.SharedRootFolders) { sharedRootFolders += string.Format("(\"{0}/\" \"/\")", sharedRootFolder); } sharedRootFolders += ")"; } string response = string.Format("* NAMESPACE ((\"\" \"/\")) {0} {1}\r\n", sharedRootFolders, publicRootFolders); response += string.Format("{0} OK NAMESPACE completed", cmdTag); WriteLine(response); } private void GETACL(string cmdTag, string argsText) { /* RFC 2086 4.3. GETACL Arguments: mailbox name Data: untagged responses: ACL Result: OK - getacl completed NO - getacl failure: can't get acl BAD - command unknown or arguments invalid The GETACL command returns the access control list for mailbox in an untagged ACL reply. Example: C: A002 GETACL INBOX S: * ACL INBOX Fred rwipslda S: A002 OK Getacl complete .... Multiple users S: * ACL INBOX Fred rwipslda test rwipslda .... No acl flags for Fred S: * ACL INBOX Fred "" test rwipslda */ if (!IsAuthenticated) { WriteLine(string.Format("{0} NO Authenticate first !", cmdTag)); return; } string[] args = TextUtils.SplitQuotedString(argsText, ' ', true); if (args.Length != 1) { WriteLine(string.Format("{0} BAD GETACL invalid arguments. Syntax: GETACL<SP>FolderName<CRLF>", cmdTag)); return; } IMAP_GETACL_eArgs eArgs = ImapServer.OnGetFolderACL(this, Core.Decode_IMAP_UTF7_String( IMAP_Utils.NormalizeFolder(args[0]))); if (eArgs.ErrorText.Length > 0) { WriteLine(string.Format("{0} NO GETACL {1}", cmdTag, eArgs.ErrorText)); } else { string response = ""; if (eArgs.ACL.Count > 0) { response += string.Format("* ACL \"{0}\"", args[0]); foreach (DictionaryEntry ent in eArgs.ACL) { string aclFalgs = IMAP_Utils.ACL_to_String((IMAP_ACL_Flags)ent.Value); if (aclFalgs.Length == 0) { aclFalgs = "\"\""; } response += string.Format(" \"{0}\" {1}", ent.Key, aclFalgs); } response += "\r\n"; } response += string.Format("{0} OK Getacl complete\r\n", cmdTag); TcpStream.Write(response); } } private void SETACL(string cmdTag, string argsText) { /* RFC 2086 4.1. SETACL Arguments: mailbox name authentication identifier access right modification Data: no specific data for this command Result: OK - setacl completed NO - setacl failure: can't set acl BAD - command unknown or arguments invalid The SETACL command changes the access control list on the specified mailbox so that the specified identifier is granted permissions as specified in the third argument. The third argument is a string containing an optional plus ("+") or minus ("-") prefix, followed by zero or more rights characters. If the string starts with a plus, the following rights are added to any existing rights for the identifier. If the string starts with a minus, the following rights are removed from any existing rights for the identifier. If the string does not start with a plus or minus, the rights replace any existing rights for the identifier. */ if (!IsAuthenticated) { WriteLine(string.Format("{0} NO Authenticate first !", cmdTag)); return; } string[] args = ParseParams(argsText); if (args.Length != 3) { WriteLine(string.Format("{0} BAD GETACL invalid arguments. Syntax: SETACL<SP>FolderName<SP>UserName<SP>ACL_Flags<CRLF>", cmdTag)); return; } string aclFlags = args[2]; IMAP_Flags_SetType setType = IMAP_Flags_SetType.Replace; if (aclFlags.StartsWith("+")) { setType = IMAP_Flags_SetType.Add; } else if (aclFlags.StartsWith("-")) { setType = IMAP_Flags_SetType.Remove; } IMAP_SETACL_eArgs eArgs = ImapServer.OnSetFolderACL(this, IMAP_Utils.NormalizeFolder(args[0]), args[1], setType, IMAP_Utils.ACL_From_String(aclFlags)); if (eArgs.ErrorText.Length > 0) { WriteLine(string.Format("{0} NO SETACL {1}", cmdTag, eArgs.ErrorText)); } else { WriteLine(string.Format("{0} OK SETACL completed", cmdTag)); } } private void DELETEACL(string cmdTag, string argsText) { /* RFC 2086 4.2. DELETEACL Arguments: mailbox name authentication identifier Data: no specific data for this command Result: OK - deleteacl completed NO - deleteacl failure: can't delete acl BAD - command unknown or arguments invalid The DELETEACL command removes any <identifier,rights> pair for the specified identifier from the access control list for the specified mailbox. Example: C: A002 DELETEACL INBOX test S: A002 OK DELETEACL completed */ if (!IsAuthenticated) { WriteLine(string.Format("{0} NO Authenticate first !", cmdTag)); return; } string[] args = TextUtils.SplitQuotedString(argsText, ' ', true); if (args.Length != 2) { WriteLine(string.Format("{0} BAD GETACL invalid arguments. Syntax: DELETEACL<SP>FolderName<SP>UserName<CRLF>", cmdTag)); return; } IMAP_DELETEACL_eArgs eArgs = ImapServer.OnDeleteFolderACL(this, IMAP_Utils.NormalizeFolder(args[0]), args[1]); if (eArgs.ErrorText.Length > 0) { WriteLine(string.Format("{0} NO DELETEACL {1}", cmdTag, eArgs.ErrorText)); } else { WriteLine(string.Format("{0} OK DELETEACL completed", cmdTag)); } } private void LISTRIGHTS(string cmdTag, string argsText) { /* RFC 2086 4.4. LISTRIGHTS Arguments: mailbox name authentication identifier Data: untagged responses: LISTRIGHTS Result: OK - listrights completed NO - listrights failure: can't get rights list BAD - command unknown or arguments invalid The LISTRIGHTS command takes a mailbox name and an identifier and returns information about what rights may be granted to the identifier in the ACL for the mailbox. Example: C: a001 LISTRIGHTS ~/Mail/saved smith S: * LISTRIGHTS ~/Mail/saved "smith" la r swicd S: a001 OK Listrights completed C: a005 LISTRIGHTS archive.imap anyone S: * LISTRIGHTS archive.imap "anyone" "" l r s w i p c d a 0 1 2 3 4 5 6 7 8 9 */ if (!IsAuthenticated) { WriteLine(string.Format("{0} NO Authenticate first !", cmdTag)); return; } string[] args = TextUtils.SplitQuotedString(argsText, ' ', true); if (args.Length != 2) { WriteLine(string.Format("{0} BAD GETACL invalid arguments. Syntax: LISTRIGHTS<SP>FolderName<SP>UserName<CRLF>", cmdTag)); return; } string response = string.Format("* LISTRIGHTS \"{0}\" \"{1}\" l r s w i p c d a\r\n", args[0], args[1]); response += string.Format("{0} OK MYRIGHTS Completed\r\n", cmdTag); TcpStream.Write(response); } private void MYRIGHTS(string cmdTag, string argsText) { /* RFC 2086 4.5. MYRIGHTS Arguments: mailbox name Data: untagged responses: MYRIGHTS Result: OK - myrights completed NO - myrights failure: can't get rights BAD - command unknown or arguments invalid The MYRIGHTS command returns the set of rights that the user has to mailbox in an untagged MYRIGHTS reply. Example: C: A003 MYRIGHTS INBOX S: * MYRIGHTS INBOX rwipslda S: A003 OK Myrights complete */ if (!IsAuthenticated) { WriteLine(string.Format("{0} NO Authenticate first !", cmdTag)); return; } string[] args = TextUtils.SplitQuotedString(argsText, ' ', true); if (args.Length != 1) { WriteLine(string.Format("{0} BAD GETACL invalid arguments. Syntax: MYRIGHTS<SP>FolderName<CRLF>", cmdTag)); return; } IMAP_GetUserACL_eArgs eArgs = ImapServer.OnGetUserACL(this, IMAP_Utils.NormalizeFolder(args[0]), UserName); if (eArgs.ErrorText.Length > 0) { WriteLine(string.Format("{0} NO MYRIGHTS {1}", cmdTag, eArgs.ErrorText)); } else { string aclFlags = IMAP_Utils.ACL_to_String(eArgs.ACL); if (aclFlags.Length == 0) { aclFlags = "\"\""; } string response = string.Format("* MYRIGHTS \"{0}\" {1}\r\n", args[0], aclFlags); response += string.Format("{0} OK MYRIGHTS Completed\r\n", cmdTag); TcpStream.Write(response); } } private void GETQUOTA(string cmdTag, string argsText) { /* RFC 2087 4.2. GETQUOTA Arguments: quota root Data: untagged responses: QUOTA Result: OK - getquota completed NO - getquota error: no such quota root, permission denied BAD - command unknown or arguments invalid The GETQUOTA command takes the name of a quota root and returns the quota root's resource usage and limits in an untagged QUOTA response. Example: C: A003 GETQUOTA "" S: * QUOTA "" (STORAGE 10 512) S: A003 OK Getquota completed */ if (!IsAuthenticated) { WriteLine(string.Format("{0} NO Authenticate first !", cmdTag)); return; } string[] args = TextUtils.SplitQuotedString(argsText, ' ', true); if (args.Length != 1) { WriteLine(string.Format("{0} BAD GETQUOTA invalid arguments. Syntax: GETQUOTA \"quota_root\"<CRLF>", cmdTag)); return; } IMAP_eArgs_GetQuota eArgs = ImapServer.OnGetUserQuota(this); string reply = string.Format("* QUOTA \"\" (STORAGE {0} {1})\r\n", eArgs.MailboxSize, eArgs.MaxMailboxSize); reply += string.Format("{0} OK GETQUOTA completed\r\n", cmdTag); TcpStream.Write(reply); } private void GETQUOTAROOT(string cmdTag, string argsText) { /* RFC 2087 4.3. GETQUOTAROOT Arguments: mailbox name Data: untagged responses: QUOTAROOT, QUOTA Result: OK - getquota completed NO - getquota error: no such mailbox, permission denied BAD - command unknown or arguments invalid The GETQUOTAROOT command takes the name of a mailbox and returns the list of quota roots for the mailbox in an untagged QUOTAROOT response. For each listed quota root, it also returns the quota root's resource usage and limits in an untagged QUOTA response. Example: C: A003 GETQUOTAROOT INBOX S: * QUOTAROOT INBOX "" S: * QUOTA "" (STORAGE 10 512) S: A003 OK Getquota completed */ if (!IsAuthenticated) { WriteLine(string.Format("{0} NO Authenticate first !", cmdTag)); return; } string[] args = TextUtils.SplitQuotedString(argsText, ' ', true); if (args.Length != 1) { WriteLine(string.Format("{0} BAD GETQUOTAROOT invalid arguments. Syntax: GETQUOTAROOT \"folder\"<CRLF>", cmdTag)); return; } IMAP_eArgs_GetQuota eArgs = ImapServer.OnGetUserQuota(this); string reply = string.Format("* QUOTAROOT \"{0}\" \"\"\r\n", args[0]); reply += string.Format("* QUOTA \"\" (STORAGE {0} {1})\r\n", eArgs.MailboxSize, eArgs.MaxMailboxSize); reply += string.Format("{0} OK GETQUOTAROOT completed\r\n", cmdTag); TcpStream.Write(reply); } //--- End of IsAuthenticated State //--- Selected State ------ private void Check(string cmdTag) { /* RFC 3501 6.4.1 CHECK Command Arguments: none Responses: no specific responses for this command Result: OK - check completed BAD - command unknown or arguments invalid The CHECK command requests a checkpoint of the currently selected mailbox. A checkpoint refers to any implementation-dependent housekeeping associated with the mailbox (e.g. resolving the server's in-memory state of the mailbox with the state on its disk) that is not normally executed as part of each command. A checkpoint MAY take a non-instantaneous amount of real time to complete. If a server implementation has no such housekeeping considerations, CHECK is equivalent to NOOP. There is no guarantee that an EXISTS untagged response will happen as a result of CHECK. NOOP, not CHECK, SHOULD be used for new mail polling. Example: C: FXXZ CHECK S: FXXZ OK CHECK Completed */ if (!IsAuthenticated) { WriteLine(string.Format("{0} NO Authenticate first !", cmdTag)); return; } if (SelectedMailbox.Length == 0) { WriteLine(string.Format("{0} NO Select mailbox first !", cmdTag)); return; } WriteLine(string.Format("{0} OK CHECK completed", cmdTag)); } private void Close(string cmdTag) { /* RFC 3501 6.4.2 CLOSE Command Arguments: none Responses: no specific responses for this command Result: OK - close completed, now in authenticated state BAD - command unknown or arguments invalid The CLOSE command permanently removes from the currently selected mailbox all messages that have the \Deleted flag set, and returns to authenticated state from selected state. No untagged EXPUNGE responses are sent. No messages are removed, and no error is given, if the mailbox is selected by an EXAMINE command or is otherwise selected read-only. Even if a mailbox is selected, a SELECT, EXAMINE, or LOGOUT command MAY be issued without previously issuing a CLOSE command. The SELECT, EXAMINE, and LOGOUT commands implicitly close the currently selected mailbox without doing an expunge. However, when many messages are deleted, a CLOSE-LOGOUT or CLOSE-SELECT sequence is considerably faster than an EXPUNGE-LOGOUT or EXPUNGE-SELECT because no untagged EXPUNGE responses (which the client would probably ignore) are sent. Example: C: A341 CLOSE S: A341 OK CLOSE completed */ if (!IsAuthenticated) { WriteLine(string.Format("{0} NO Authenticate first !", cmdTag)); return; } if (SelectedMailbox.Length == 0) { WriteLine(string.Format("{0} NO Select mailbox first !", cmdTag)); return; } if (!m_pSelectedFolder.ReadOnly) { IMAP_Message[] messages = m_pSelectedFolder.Messages.GetWithFlags(IMAP_MessageFlags.Deleted); foreach (IMAP_Message msg in messages) { ImapServer.OnDeleteMessage(this, msg); } } SelectedMailbox = ""; m_pSelectedFolder = null; WriteLine(string.Format("{0} OK CLOSE completed", cmdTag)); //EndSession(); } private void Expunge(string cmdTag) { /* RFC 3501 6.4.3 EXPUNGE Command Arguments: none Responses: untagged responses: EXPUNGE Result: OK - expunge completed NO - expunge failure: can't expunge (e.g., permission denied) BAD - command unknown or arguments invalid The EXPUNGE command permanently removes all messages that have the \Deleted flag set from the currently selected mailbox. Before returning an OK to the client, an untagged EXPUNGE response is sent for each message that is removed. The EXPUNGE response reports that the specified message sequence number has been permanently removed from the mailbox. The message sequence number for each successive message in the mailbox is IMMEDIATELY DECREMENTED BY 1, and this decrement is reflected in message sequence numbers in subsequent responses (including other untagged EXPUNGE responses). Example: C: A202 EXPUNGE S: * 3 EXPUNGE S: * 3 EXPUNGE S: * 5 EXPUNGE S: * 8 EXPUNGE S: A202 OK EXPUNGE completed Note: In this example, messages 3, 4, 7, and 11 had the \Deleted flag set. See the description of the EXPUNGE response for further explanation. */ if (!IsAuthenticated) { WriteLine(string.Format("{0} NO Authenticate first !", cmdTag)); return; } if (SelectedMailbox.Length == 0) { WriteLine(string.Format("{0} NO Select mailbox first !", cmdTag)); return; } IMAP_Message[] messages = m_pSelectedFolder.Messages.GetWithFlags(IMAP_MessageFlags.Deleted); for (int i = 0; i < messages.Length; i++) { IMAP_Message msg = messages[i]; string errorText = ImapServer.OnDeleteMessage(this, msg); if (errorText == null) { WriteLine(string.Format("* {0} EXPUNGE", msg.SequenceNo)); m_pSelectedFolder.Messages.Remove(msg); } else { WriteLine(string.Format("{0} NO {1}", cmdTag, errorText)); return; } } WriteLine(string.Format("{0} OK EXPUNGE completed", cmdTag)); } private void Search(string cmdTag, string argsText, bool uidSearch) { /* RFC 3501 6.4.4 SEARCH Command Arguments: OPTIONAL [CHARSET] specification searching criteria (one or more) Responses: REQUIRED untagged response: SEARCH Result: OK - search completed NO - search error: can't search that [CHARSET] or criteria BAD - command unknown or arguments invalid The SEARCH command searches the mailbox for messages that match the given searching criteria. Searching criteria consist of one or more search keys. The untagged SEARCH response from the server contains a listing of message sequence numbers corresponding to those messages that match the searching criteria. When multiple keys are specified, the result is the intersection (AND function) of all the messages that match those keys. For example, the criteria DELETED FROM "SMITH" SINCE 1-Feb-1994 refers to all deleted messages from Smith that were placed in the mailbox since February 1, 1994. A search key can also be a parenthesized list of one or more search keys (e.g., for use with the OR and NOT keys). Server implementations MAY exclude [MIME-IMB] body parts with terminal content media types other than TEXT and MESSAGE from consideration in SEARCH matching. The OPTIONAL [CHARSET] specification consists of the word "CHARSET" followed by a registered [CHARSET]. It indicates the [CHARSET] of the strings that appear in the search criteria. [MIME-IMB] content transfer encodings, and [MIME-HDRS] strings in [RFC-2822]/[MIME-IMB] headers, MUST be decoded before comparing text in a [CHARSET] other than US-ASCII. US-ASCII MUST be supported; other [CHARSET]s MAY be supported. If the server does not support the specified [CHARSET], it MUST return a tagged NO response (not a BAD). This response SHOULD contain the BADCHARSET response code, which MAY list the [CHARSET]s supported by the server. In all search keys that use strings, a message matches the key if the string is a substring of the field. The matching is case-insensitive. The defined search keys are as follows. Refer to the Formal Syntax section for the precise syntactic definitions of the arguments. <sequence set> Messages with message sequence numbers corresponding to the specified message sequence number set. ALL All messages in the mailbox; the default initial key for ANDing. ANSWERED Messages with the \Answered flag set. BCC <string> Messages that contain the specified string in the envelope structure's BCC field. BEFORE <date> Messages whose internal date (disregarding time and timezone) is earlier than the specified date. BODY <string> Messages that contain the specified string in the body of the message. CC <string> Messages that contain the specified string in the envelope structure's CC field. DELETED Messages with the \Deleted flag set. DRAFT Messages with the \Draft flag set. FLAGGED Messages with the \Flagged flag set. FROM <string> Messages that contain the specified string in the envelope structure's FROM field. HEADER <field-name> <string> Messages that have a header with the specified field-name (as defined in [RFC-2822]) and that contains the specified string in the text of the header (what comes after the colon). If the string to search is zero-length, this matches all messages that have a header line with the specified field-name regardless of the contents. KEYWORD <flag> Messages with the specified keyword flag set. LARGER <n> Messages with an [RFC-2822] size larger than the specified number of octets. NEW Messages that have the \Recent flag set but not the \Seen flag. This is functionally equivalent to "(RECENT UNSEEN)". NOT <search-key> Messages that do not match the specified search key. OLD Messages that do not have the \Recent flag set. This is functionally equivalent to "NOT RECENT" (as opposed to "NOT NEW"). ON <date> Messages whose internal date (disregarding time and timezone) is within the specified date. OR <search-key1> <search-key2> Messages that match either search key. RECENT Messages that have the \Recent flag set. SEEN Messages that have the \Seen flag set. SENTBEFORE <date> Messages whose [RFC-2822] Date: header (disregarding time and timezone) is earlier than the specified date. SENTON <date> Messages whose [RFC-2822] Date: header (disregarding time and timezone) is within the specified date. SENTSINCE <date> Messages whose [RFC-2822] Date: header (disregarding time and timezone) is within or later than the specified date. SINCE <date> Messages whose internal date (disregarding time and timezone) is within or later than the specified date. SMALLER <n> Messages with an [RFC-2822] size smaller than the specified number of octets. SUBJECT <string> Messages that contain the specified string in the envelope structure's SUBJECT field. TEXT <string> Messages that contain the specified string in the header or body of the message. TO <string> Messages that contain the specified string in the envelope structure's TO field. UID <sequence set> Messages with unique identifiers corresponding to the specified unique identifier set. Sequence set ranges are permitted. UNANSWERED Messages that do not have the \Answered flag set. UNDELETED Messages that do not have the \Deleted flag set. UNDRAFT Messages that do not have the \Draft flag set. UNFLAGGED Messages that do not have the \Flagged flag set. UNKEYWORD <flag> Messages that do not have the specified keyword flag set. UNSEEN Messages that do not have the \Seen flag set. Example: C: A282 SEARCH FLAGGED SINCE 1-Feb-1994 NOT FROM "Smith" S: * SEARCH 2 84 882 S: A282 OK SEARCH completed C: A283 SEARCH TEXT "string not in mailbox" S: * SEARCH S: A283 OK SEARCH completed C: A284 SEARCH CHARSET UTF-8 TEXT {6} S: + Continue ### THIS IS UNDOCUMENTED !!! C: XXXXXX[arg conitnue]<CRLF> S: * SEARCH 43 S: A284 OK SEARCH completed Note: Since this document is restricted to 7-bit ASCII text, it is not possible to show actual UTF-8 data. The "XXXXXX" is a placeholder for what would be 6 octets of 8-bit data in an actual transaction. */ if (!IsAuthenticated) { WriteLine(string.Format("{0} NO Authenticate first !", cmdTag)); return; } if (SelectedMailbox.Length == 0) { WriteLine(string.Format("{0} NO Select mailbox first !", cmdTag)); return; } // Store start time long startTime = DateTime.Now.Ticks; //--- Get Optional charset, if specified -----------------------------------------------------------------// string charset = "ASCII"; // CHARSET charset if (argsText.ToUpper().StartsWith("CHARSET")) { // Remove CHARSET from argsText argsText = argsText.Substring(7).Trim(); string charsetValueString = IMAP_Utils.ParseQuotedParam(ref argsText); try { EncodingTools.GetEncodingByCodepageName_Throws(charsetValueString); charset = charsetValueString; } catch { WriteLine(string.Format("{0} NO [BADCHARSET UTF-8] {1} is not supported", cmdTag, charsetValueString)); return; } } //---------------------------------------------------------------------------------------------------------// /* If multiline command, read all lines C: A284 SEARCH CHARSET UTF-8 TEXT {6} S: + Continue ### THIS IS UNDOCUMENTED !!! C: XXXXXX[arg conitnue]<CRLF> */ argsText = argsText.Trim(); while (argsText.EndsWith("}") && argsText.IndexOf("{") > -1) { long dataLength = 0; try { // Get data length from {xxx} dataLength = Convert.ToInt64(argsText.Substring(argsText.LastIndexOf("{") + 1, argsText.Length - argsText.LastIndexOf("{") - 2)); } // There is no valid numeric value between {}, just skip and allow SearchGroup parser to handle this value catch { break; } MemoryStream dataStream = new MemoryStream(); WriteLine("+ Continue"); ReadSpecifiedLength((int)dataLength, dataStream); string argsContinueLine = ReadLine(); // Append readed data + [args conitnue] line argsText += EncodingTools.GetEncodingByCodepageName_Throws(charset).GetString(dataStream.ToArray()) + argsContinueLine; // There is no more argumets, stop getting. // We must check this because if length = 0 and no args returned, last line ends with {0}, // leaves this into endless loop. if (argsContinueLine == "") { break; } } //--- Parse search criteria ------------------------// SearchGroup searchCriteria = new SearchGroup(); try { searchCriteria.Parse(new StringReader(argsText)); } catch (Exception x) { WriteLine(cmdTag + " NO " + x.Message); return; } //--------------------------------------------------// /* string searchResponse = "* SEARCH"; // No header and body text needed, can do search on internal messages info data if(!searchCriteria.IsHeaderNeeded() && !searchCriteria.IsBodyTextNeeded()){ // Loop internal messages info, see what messages match for(int i=0;i<m_Messages.Count;i++){ IMAP_Message messageInfo = m_Messages[i]; // See if message matches if(searchCriteria.Match(i,messageInfo.MessageUID,(int)messageInfo.Size,messageInfo.Date,messageInfo.Flags,null,"")){ // For UID search we must return message UID's if(uidSearch){ searchResponse += " " + messageInfo.MessageUID.ToString(); } // For normal search we must return message index numbers. else{ searchResponse += " " + messageInfo.MessageNo.ToString(); } } } } // Can't search on iternal messages info, need to do header or body text search, call Search event else{ // Call 'Search' event, get search criteria matching messages IMAP_eArgs_Search eArgs = ImapServer.OnSearch(this,Core.Decode_IMAP_UTF7_String(this.SelectedMailbox),new IMAP_SearchMatcher(searchCriteria)); // Constuct matching messages search response for(int i=0;i<eArgs.MatchingMessages.Count;i++){ IMAP_Message messageInfo = eArgs.MatchingMessages[i]; // For UID search we must return message UID's if(uidSearch){ searchResponse += " " + messageInfo.MessageUID.ToString(); } // For normal search we must return message index numbers. else{ // Map search returnded message to internal message number int no = m_Messages.IndexFromUID(messageInfo.MessageUID); if(no > -1){ searchResponse += " " + no.ToString(); } } } } searchResponse += "\r\n"; searchResponse += cmdTag + " OK SEARCH completed in " + ((DateTime.Now.Ticks - startTime) / (decimal)10000000).ToString("f2") + " seconds\r\n"; */ ProcessMailboxChanges(); // Just loop messages headers or full messages (depends on search type) // string searchResponse = "* SEARCH"; TcpStream.Write("* SEARCH"); string searchResponse = ""; IMAP_MessageItems_enum messageItems = IMAP_MessageItems_enum.None; if (searchCriteria.IsBodyTextNeeded()) { messageItems |= IMAP_MessageItems_enum.Message; } else if (searchCriteria.IsHeaderNeeded()) { messageItems |= IMAP_MessageItems_enum.Header; } for (int i = 0; i < m_pSelectedFolder.Messages.Count; i++) { IMAP_Message msg = m_pSelectedFolder.Messages[i]; //-- Get message only if matching needs it ------------------------// Mime parser = null; if ((messageItems & IMAP_MessageItems_enum.Message) != 0 || (messageItems & IMAP_MessageItems_enum.Header) != 0) { // Raise event GetMessageItems, get requested message items. IMAP_eArgs_MessageItems eArgs = ImapServer.OnGetMessageItems(this, msg, messageItems); // Message data is null if no such message available, just skip that message if (!eArgs.MessageExists) { continue; } try { // Ensure that all requested items were provided. eArgs.Validate(); } catch (Exception x) { ImapServer.OnSysError(x.Message, x); WriteLine(cmdTag + " NO Internal IMAP server component error: " + x.Message); return; } try { if (eArgs.MessageStream != null) { parser = Mime.Parse(eArgs.MessageStream); } else { parser = Mime.Parse(eArgs.Header); } } // Message parsing failed, bad message. Just make new warning message. catch (Exception x) { parser = Mime.CreateSimple(new AddressList(), new AddressList(), "[BAD MESSAGE] Bad message, message parsing failed !", "NOTE: Bad message, message parsing failed !\r\n\r\n" + x.Message, ""); } } //-----------------------------------------------------------------// string bodyText = ""; if (searchCriteria.IsBodyTextNeeded()) { bodyText = parser.BodyText; } // See if message matches to search criteria if (searchCriteria.Match(i, msg.UID, (int)msg.Size, msg.InternalDate, msg.Flags, parser, bodyText)) { if (uidSearch) { TcpStream.Write(" " + msg.UID); // searchResponse += " " + msg.MessageUID.ToString(); } else { TcpStream.Write(" " + (i + 1)); // searchResponse += " " + i.ToString(); } } } searchResponse += "\r\n"; searchResponse += string.Format("{0} OK SEARCH completed in {1} seconds\r\n", cmdTag, ((DateTime.Now.Ticks - startTime) / (decimal)10000000).ToString("f2")); // Send search server response TcpStream.Write(searchResponse); } private void ReadSpecifiedLength(int dataLength, MemoryStream dataStream) { TcpStream.ReadFixedCount(dataStream, dataLength); } private string ReadLine() { SmartStream.ReadLineAsyncOP args = new SmartStream.ReadLineAsyncOP(new byte[Workaround.Definitions.MaxStreamLineLength], SizeExceededAction. JunkAndThrowException); if (TcpStream.ReadLine(args, false)) { return args.LineUtf8; } return string.Empty; } private void Fetch(string cmdTag, string argsText, bool uidFetch) { /* Rfc 3501 6.4.5 FETCH Command Arguments: message set message data item names Responses: untagged responses: FETCH Result: OK - fetch completed NO - fetch error: can't fetch that data BAD - command unknown or arguments invalid The FETCH command retrieves data associated with a message in the mailbox. The data items to be fetched can be either a single atom or a parenthesized list. Most data items, identified in the formal syntax under the msg-att-static rule, are static and MUST NOT change for any particular message. Other data items, identified in the formal syntax under the msg-att-dynamic rule, MAY change, either as a result of a STORE command or due to external events. For example, if a client receives an ENVELOPE for a message when it already knows the envelope, it can safely ignore the newly transmitted envelope. There are three macros which specify commonly-used sets of data items, and can be used instead of data items. A macro must be used by itself, and not in conjunction with other macros or data items. ALL Macro equivalent to: (FLAGS INTERNALDATE RFC822.SIZE ENVELOPE) FAST Macro equivalent to: (FLAGS INTERNALDATE RFC822.SIZE) FULL Macro equivalent to: (FLAGS INTERNALDATE RFC822.SIZE ENVELOPE BODY) The currently defined data items that can be fetched are: BODY Non-extensible form of BODYSTRUCTURE. BODY[<section>]<<partial>> The text of a particular body section. The section specification is a set of zero or more part specifiers delimited by periods. A part specifier is either a part number or one of the following: HEADER, HEADER.FIELDS, HEADER.FIELDS.NOT, MIME, and TEXT. An empty section specification refers to the entire message, including the header. Every message has at least one part number. Non-[MIME-IMB] messages, and non-multipart [MIME-IMB] messages with no encapsulated message, only have a part 1. Multipart messages are assigned consecutive part numbers, as they occur in the message. If a particular part is of type message or multipart, its parts MUST be indicated by a period followed by the part number within that nested multipart part. A part of type MESSAGE/RFC822 also has nested part numbers, referring to parts of the MESSAGE part's body. The HEADER, HEADER.FIELDS, HEADER.FIELDS.NOT, and TEXT part specifiers can be the sole part specifier or can be prefixed by one or more numeric part specifiers, provided that the numeric part specifier refers to a part of type MESSAGE/RFC822. The MIME part specifier MUST be prefixed by one or more numeric part specifiers. The HEADER, HEADER.FIELDS, and HEADER.FIELDS.NOT part specifiers refer to the [RFC-2822] header of the message or of an encapsulated [MIME-IMT] MESSAGE/RFC822 message. HEADER.FIELDS and HEADER.FIELDS.NOT are followed by a list of field-name (as defined in [RFC-2822]) names, and return a subset of the header. The subset returned by HEADER.FIELDS contains only those header fields with a field-name that matches one of the names in the list; similarly, the subset returned by HEADER.FIELDS.NOT contains only the header fields with a non-matching field-name. The field-matching is case-insensitive but otherwise exact. Subsetting does not exclude the [RFC-2822] delimiting blank line between the header and the body; the blank line is included in all header fetches, except in the case of a message which has no body and no blank line. The MIME part specifier refers to the [MIME-IMB] header for this part. The TEXT part specifier refers to the text body of the message, omitting the [RFC-2822] header. Here is an example of a complex message with some of its part specifiers: HEADER ([RFC-2822] header of the message) TEXT ([RFC-2822] text body of the message) MULTIPART/MIXED 1 TEXT/PLAIN 2 APPLICATION/OCTET-STREAM 3 MESSAGE/RFC822 3.HEADER ([RFC-2822] header of the message) 3.TEXT ([RFC-2822] text body of the message) MULTIPART/MIXED 3.1 TEXT/PLAIN 3.2 APPLICATION/OCTET-STREAM 4 MULTIPART/MIXED 4.1 IMAGE/GIF 4.1.MIME ([MIME-IMB] header for the IMAGE/GIF) 4.2 MESSAGE/RFC822 4.2.HEADER ([RFC-2822] header of the message) 4.2.TEXT ([RFC-2822] text body of the message) MULTIPART/MIXED 4.2.1 TEXT/PLAIN 4.2.2 MULTIPART/ALTERNATIVE 4.2.2.1 TEXT/PLAIN 4.2.2.2 TEXT/RICHTEXT It is possible to fetch a substring of the designated text. This is done by appending an open angle bracket ("<"), the octet position of the first desired octet, a period, the maximum number of octets desired, and a close angle bracket (">") to the part specifier. If the starting octet is beyond the end of the text, an empty string is returned. Any partial fetch that attempts to read beyond the end of the text is truncated as appropriate. A partial fetch that starts at octet 0 is returned as a partial fetch, even if this truncation happened. Note: This means that BODY[]<0.2048> of a 1500-octet message will return BODY[]<0> with a literal of size 1500, not BODY[]. Note: A substring fetch of a HEADER.FIELDS or HEADER.FIELDS.NOT part specifier is calculated after subsetting the header. The \Seen flag is implicitly set; if this causes the flags to change, they SHOULD be included as part of the FETCH responses. BODY.PEEK[<section>]<<partial>> An alternate form of BODY[<section>] that does not implicitly set the \Seen flag. BODYSTRUCTURE The [MIME-IMB] body structure of the message. This is computed by the server by parsing the [MIME-IMB] header fields in the [RFC-2822] header and [MIME-IMB] headers. ENVELOPE The envelope structure of the message. This is computed by the server by parsing the [RFC-2822] header into the component parts, defaulting various fields as necessary. FLAGS The flags that are set for this message. INTERNALDATE The internal date of the message. RFC822 Functionally equivalent to BODY[], differing in the syntax of the resulting untagged FETCH data (RFC822 is returned). RFC822.HEADER Functionally equivalent to BODY.PEEK[HEADER], differing in the syntax of the resulting untagged FETCH data (RFC822.HEADER is returned). RFC822.SIZE The [RFC-2822] size of the message. RFC822.TEXT Functionally equivalent to BODY[TEXT], differing in the syntax of the resulting untagged FETCH data (RFC822.TEXT is returned). UID The unique identifier for the message. Example: C: A654 FETCH 2:4 (FLAGS BODY[HEADER.FIELDS (DATE FROM)]) S: * 2 FETCH .... S: * 3 FETCH .... S: * 4 FETCH .... S: A654 OK FETCH completed */ if (!this.IsAuthenticated) { TcpStream.WriteLine(string.Format("{0} NO Authenticate first !", cmdTag)); return; } if (SelectedMailbox.Length == 0) { this.TcpStream.WriteLine(string.Format("{0} NO Select mailbox first !", cmdTag)); return; } TcpStream.MemoryBuffer = true; // Store start time long startTime = DateTime.Now.Ticks; IMAP_MessageItems_enum messageItems = IMAP_MessageItems_enum.None; #region Parse parameters string[] args = ParseParams(argsText); if (args.Length != 2) { this.TcpStream.WriteLine(string.Format("{0} BAD Invalid arguments", cmdTag)); return; } IMAP_SequenceSet sequenceSet = new IMAP_SequenceSet(); // Just try if it can be parsed as sequence-set try { if (uidFetch) { if (m_pSelectedFolder.Messages.Count > 0) { sequenceSet.Parse(args[0], m_pSelectedFolder.Messages[m_pSelectedFolder.Messages.Count - 1].UID); } } else { sequenceSet.Parse(args[0], m_pSelectedFolder.Messages.Count); } } // This isn't valid sequnce-set value catch { this.TcpStream.WriteLine(string.Format("{0} BAD Invalid <sequnce-set> value '{1}' Syntax: {{<command-tag> FETCH <sequnce-set> (<fetch-keys>)}}!", cmdTag, args[0])); return; } // Replace macros string fetchItems = args[1].ToUpper(); fetchItems = fetchItems.Replace("ALL", "FLAGS INTERNALDATE RFC822.SIZE ENVELOPE"); fetchItems = fetchItems.Replace("FAST", "FLAGS INTERNALDATE RFC822.SIZE"); fetchItems = fetchItems.Replace("FULL", "FLAGS INTERNALDATE RFC822.SIZE ENVELOPE BODY"); // If UID FETCH and no UID, we must implicity add it, it's required if (uidFetch && fetchItems.ToUpper().IndexOf("UID") == -1) { fetchItems += " UID"; } // Start parm parsing from left to end in while loop while params parsed or bad param found ArrayList fetchFlags = new ArrayList(); StringReader argsReader = new StringReader(fetchItems.Trim()); while (argsReader.Available > 0) { argsReader.ReadToFirstChar(); #region BODYSTRUCTURE // BODYSTRUCTURE if (argsReader.StartsWith("BODYSTRUCTURE")) { argsReader.ReadSpecifiedLength("BODYSTRUCTURE".Length); fetchFlags.Add(new object[] { "BODYSTRUCTURE" }); messageItems |= IMAP_MessageItems_enum.BodyStructure; } #endregion #region BODY, BODY[<section>]<<partial>>, BODY.PEEK[<section>]<<partial>> // BODY, BODY[<section>]<<partial>>, BODY.PEEK[<section>]<<partial>> else if (argsReader.StartsWith("BODY")) { // Remove BODY argsReader.ReadSpecifiedLength("BODY".Length); bool peek = false; // BODY.PEEK if (argsReader.StartsWith(".PEEK")) { // Remove .PEEK argsReader.ReadSpecifiedLength(".PEEK".Length); peek = true; } // [<section>]<<partial>> if (argsReader.StartsWith("[")) { // Read value between [] string section = ""; try { section = argsReader.ReadParenthesized(); } catch { this.TcpStream.WriteLine(cmdTag + " BAD Invalid BODY[], closing ] parenthesize is missing !"); return; } string originalSectionValue = section; string mimePartsSpecifier = ""; string sectionType = ""; string sectionArgs = ""; /* Validate <section> Section can be: "" - entire message [MimePartsSepcifier.]HEADER - message header [MimePartsSepcifier.]HEADER.FIELDS (headerFields) - message header fields [MimePartsSepcifier.]HEADER.FIELDS.NOT (headerFields) - message header fields except requested [MimePartsSepcifier.]TEXT - message text [MimePartsSepcifier.]MIME - same as header, different response */ if (section.Length > 0) { string[] section_args = section.Split(new char[] { ' ' }, 2); section = section_args[0]; if (section_args.Length == 2) { sectionArgs = section_args[1]; } if (section.EndsWith("HEADER")) { // Remove HEADER from end section = section.Substring(0, section.Length - "HEADER".Length); sectionType = "HEADER"; messageItems |= IMAP_MessageItems_enum.Header; } else if (section.EndsWith("HEADER.FIELDS")) { // Remove HEADER.FIELDS from end section = section.Substring(0, section.Length - "HEADER.FIELDS".Length); sectionType = "HEADER.FIELDS"; messageItems |= IMAP_MessageItems_enum.Header; } else if (section.EndsWith("HEADER.FIELDS.NOT")) { // Remove HEADER.FIELDS.NOT from end section = section.Substring(0, section.Length - "HEADER.FIELDS.NOT".Length); sectionType = "HEADER.FIELDS.NOT"; messageItems |= IMAP_MessageItems_enum.Header; } else if (section.EndsWith("TEXT")) { // Remove TEXT from end section = section.Substring(0, section.Length - "TEXT".Length); sectionType = "TEXT"; messageItems |= IMAP_MessageItems_enum.Message; } else if (section.EndsWith("MIME")) { // Remove MIME from end section = section.Substring(0, section.Length - "MIME".Length); sectionType = "MIME"; messageItems = IMAP_MessageItems_enum.Header; } // Remove last ., if there is any if (section.EndsWith(".")) { section = section.Substring(0, section.Length - 1); } // MimePartsSepcifier is specified, validate it. It can contain numbers only. if (section.Length > 0) { // Now we certainly need full message, because nested mime parts wanted messageItems |= IMAP_MessageItems_enum.Message; string[] sectionParts = section.Split('.'); foreach (string sectionPart in sectionParts) { if (!Core.IsNumber(sectionPart)) { this.TcpStream.WriteLine(string.Format("{0} BAD Invalid BODY[<section>] argument. Invalid <section>: {1}", cmdTag, section)); return; } } mimePartsSpecifier = section; } } else { messageItems |= IMAP_MessageItems_enum.Message; } long startPosition = -1; long length = -1; // See if partial fetch if (argsReader.StartsWith("<")) { /* <partial> syntax: startPosition[.endPosition] */ // Read partial value between <> string partial = ""; try { partial = argsReader.ReadParenthesized(); } catch { this.TcpStream.WriteLine(string.Format("{0} BAD Invalid BODY[]<start[.length]>, closing > parenthesize is missing !", cmdTag)); return; } string[] start_length = partial.Split('.'); // Validate <partial> if (start_length.Length == 0 || start_length.Length > 2 || !Core.IsNumber(start_length[0]) || (start_length.Length == 2 && !Core.IsNumber(start_length[1]))) { this.TcpStream.WriteLine(string.Format("{0} BAD Invalid BODY[]<partial> argument. Invalid <partial>: {1}", cmdTag, partial)); return; } startPosition = Convert.ToInt64(start_length[0]); if (start_length.Length == 2) { length = Convert.ToInt64(start_length[1]); } } // object[] structure for BODY[] // fetchFlagName // isPeek // mimePartsSpecifier // originalSectionValue // sectionType // sectionArgs // startPosition // length fetchFlags.Add(new object[] { "BODY[]", peek, mimePartsSpecifier, originalSectionValue, sectionType, sectionArgs, startPosition, length }); } // BODY else { fetchFlags.Add(new object[] { "BODY" }); messageItems |= IMAP_MessageItems_enum.BodyStructure; } } #endregion #region ENVELOPE // ENVELOPE else if (argsReader.StartsWith("ENVELOPE")) { argsReader.ReadSpecifiedLength("ENVELOPE".Length); fetchFlags.Add(new object[] { "ENVELOPE" }); messageItems |= IMAP_MessageItems_enum.Envelope; } #endregion #region FLAGS // FLAGS // The flags that are set for this message. else if (argsReader.StartsWith("FLAGS")) { argsReader.ReadSpecifiedLength("FLAGS".Length); fetchFlags.Add(new object[] { "FLAGS" }); } #endregion #region INTERNALDATE // INTERNALDATE else if (argsReader.StartsWith("INTERNALDATE")) { argsReader.ReadSpecifiedLength("INTERNALDATE".Length); fetchFlags.Add(new object[] { "INTERNALDATE" }); } #endregion #region RFC822.HEADER // RFC822.HEADER else if (argsReader.StartsWith("RFC822.HEADER")) { argsReader.ReadSpecifiedLength("RFC822.HEADER".Length); fetchFlags.Add(new object[] { "RFC822.HEADER" }); messageItems |= IMAP_MessageItems_enum.Header; } #endregion #region RFC822.SIZE // RFC822.SIZE // The [RFC-2822] size of the message. else if (argsReader.StartsWith("RFC822.SIZE")) { argsReader.ReadSpecifiedLength("RFC822.SIZE".Length); fetchFlags.Add(new object[] { "RFC822.SIZE" }); } #endregion #region RFC822.TEXT // RFC822.TEXT else if (argsReader.StartsWith("RFC822.TEXT")) { argsReader.ReadSpecifiedLength("RFC822.TEXT".Length); fetchFlags.Add(new object[] { "RFC822.TEXT" }); messageItems |= IMAP_MessageItems_enum.Message; } #endregion #region RFC822 // RFC822 NOTE: RFC822 must be below RFC822.xxx or is parsed wrong ! else if (argsReader.StartsWith("RFC822")) { argsReader.ReadSpecifiedLength("RFC822".Length); fetchFlags.Add(new object[] { "RFC822" }); messageItems |= IMAP_MessageItems_enum.Message; } #endregion #region UID // UID // The unique identifier for the message. else if (argsReader.StartsWith("UID")) { argsReader.ReadSpecifiedLength("UID".Length); fetchFlags.Add(new object[] { "UID" }); } #endregion // This must be unknown fetch flag else { this.TcpStream.WriteLine(string.Format("{0} BAD Invalid fetch-items argument. Unkown part starts from: {1}", cmdTag, argsReader.SourceString)); return; } } #endregion // ToDo: ??? But non of the servers do it ? // The server should respond with a tagged BAD response to a command that uses a message // sequence number greater than the number of messages in the selected mailbox. This // includes "*" if the selected mailbox is empty. // if(m_Messages.Count == 0 || ){ // SendData(cmdTag + " BAD Sequence number greater than the number of messages in the selected mailbox !\r\n"); // return; // } // Create buffered writer, so we make less network calls. for (int i = 0; i < m_pSelectedFolder.Messages.Count; i++) { IMAP_Message msg = m_pSelectedFolder.Messages[i]; // For UID FETCH we must compare UIDs and for normal FETCH message numbers. bool sequenceSetContains = false; if (uidFetch) { sequenceSetContains = sequenceSet.Contains(msg.UID); } else { sequenceSetContains = sequenceSet.Contains(i + 1); } if (sequenceSetContains) { IMAP_eArgs_MessageItems eArgs = null; // Get message items only if they are needed. if (messageItems != IMAP_MessageItems_enum.None) { // Raise event GetMessageItems to get all neccesary message itmes eArgs = ImapServer.OnGetMessageItems(this, msg, messageItems); // Message doesn't exist any more, notify email client. if (!eArgs.MessageExists) { TcpStream.Write("* " + msg.SequenceNo + " EXPUNGE"); ImapServer.OnDeleteMessage(this, msg); m_pSelectedFolder.Messages.Remove(msg); i--; continue; } try { // Ensure that all requested items were provided. eArgs.Validate(); } catch (Exception x) { ImapServer.OnSysError(x.Message, x); this.TcpStream.WriteLine(string.Format("{0} NO Internal IMAP server component error: {1}", cmdTag, x.Message)); return; } } // Write fetch start data "* msgNo FETCH (" TcpStream.Write("* " + (i + 1) + " FETCH ("); IMAP_MessageFlags msgFlagsOr = msg.Flags; // Construct reply here, based on requested fetch items int nCount = 0; foreach (object[] fetchFlag in fetchFlags) { string fetchFlagName = (string)fetchFlag[0]; #region BODY // BODY if (fetchFlagName == "BODY") { // Sets \seen flag msg.SetFlags(msg.Flags | IMAP_MessageFlags.Seen); // BODY () TcpStream.Write("BODY " + eArgs.BodyStructure); } #endregion #region BODY[], BODY.PEEK[] // BODY[<section>]<<partial>>, BODY.PEEK[<section>]<<partial>> else if (fetchFlagName == "BODY[]") { // Force to write all buffered data. TcpStream.Flush(); // object[] structure for BODY[] // fetchFlagName // isPeek // mimePartsSpecifier // originalSectionValue // sectionType // sectionArgs // startPosition // length bool isPeek = (bool)fetchFlag[1]; string mimePartsSpecifier = (string)fetchFlag[2]; string originalSectionValue = (string)fetchFlag[3]; string sectionType = (string)fetchFlag[4]; string sectionArgs = (string)fetchFlag[5]; long startPosition = (long)fetchFlag[6]; long length = (long)fetchFlag[7]; // Difference between BODY[] and BODY.PEEK[] is that .PEEK won't set seen flag if (!isPeek) { // Sets \seen flag msg.SetFlags(msg.Flags | IMAP_MessageFlags.Seen); } /* Section value: "" - entire message HEADER - message header HEADER.FIELDS - message header fields HEADER.FIELDS.NOT - message header fields except requested TEXT - message text MIME - same as header, different response */ Stream dataStream = null; if (sectionType == "" && mimePartsSpecifier == "") { dataStream = eArgs.MessageStream; } else { Mime parser = null; try { if (eArgs.MessageStream == null) { parser = Mime.Parse(eArgs.Header); } else { parser = Mime.Parse(eArgs.MessageStream); } } // Invalid message, parsing failed catch { parser = Mime.CreateSimple(new AddressList(), new AddressList(), "BAD Message", "This is BAD message, mail server failed to parse it !", ""); } MimeEntity currentEntity = parser.MainEntity; // Specific mime entity requested, get it if (mimePartsSpecifier != "") { currentEntity = FetchHelper.GetMimeEntity(parser, mimePartsSpecifier); } if (currentEntity != null) { if (sectionType == "HEADER") { dataStream = new MemoryStream(FetchHelper.GetMimeEntityHeader(currentEntity)); } else if (sectionType == "HEADER.FIELDS") { dataStream = new MemoryStream(FetchHelper.ParseHeaderFields(sectionArgs, currentEntity)); } else if (sectionType == "HEADER.FIELDS.NOT") { dataStream = new MemoryStream(FetchHelper.ParseHeaderFieldsNot(sectionArgs, currentEntity)); } else if (sectionType == "TEXT") { try { if (currentEntity.DataEncoded != null) { dataStream = new MemoryStream(currentEntity.DataEncoded); } } catch { // This probably multipart entity, data isn't available } } else if (sectionType == "MIME") { dataStream = new MemoryStream(FetchHelper.GetMimeEntityHeader(currentEntity)); } else if (sectionType == "") { try { dataStream = new MemoryStream(currentEntity.DataEncoded); } catch { // This probably multipart entity, data isn't available } } } } // Partial fetch. Reports <origin position> in fetch reply. if (startPosition > -1) { if (dataStream == null) { this.TcpStream.Write("BODY[" + originalSectionValue + "]<" + startPosition.ToString() + "> \"\"\r\n"); } else { long lengthToSend = length; if (lengthToSend == -1) { lengthToSend = (dataStream.Length - dataStream.Position) - startPosition; } if ((lengthToSend + startPosition) > (dataStream.Length - dataStream.Position)) { lengthToSend = (dataStream.Length - dataStream.Position) - startPosition; } if (startPosition >= (dataStream.Length - dataStream.Position)) { this.TcpStream.Write("BODY[" + originalSectionValue + "]<" + startPosition.ToString() + "> \"\"\r\n"); } else { this.TcpStream.Write("BODY[" + originalSectionValue + "]<" + startPosition.ToString() + "> {" + lengthToSend + "}\r\n"); dataStream.Position += startPosition; this.TcpStream.WriteStream(dataStream, lengthToSend); } } } // Normal fetch else { if (dataStream == null) { this.TcpStream.Write("BODY[" + originalSectionValue + "] \"\"\r\n"); } else { this.TcpStream.Write("BODY[" + originalSectionValue + "] {" + (dataStream.Length - dataStream.Position) + "}\r\n"); this.TcpStream.WriteStream(dataStream); } } } #endregion #region BODYSTRUCTURE // BODYSTRUCTURE else if (fetchFlagName == "BODYSTRUCTURE") { TcpStream.Write("BODYSTRUCTURE " + eArgs.BodyStructure); } #endregion #region ENVELOPE // ENVELOPE else if (fetchFlagName == "ENVELOPE") { TcpStream.Write("ENVELOPE " + eArgs.Envelope); } #endregion #region FLAGS // FLAGS else if (fetchFlagName == "FLAGS") { TcpStream.Write("FLAGS (" + msg.FlagsString + ")"); } #endregion #region INTERNALDATE // INTERNALDATE else if (fetchFlagName == "INTERNALDATE") { // INTERNALDATE "date" TcpStream.Write("INTERNALDATE \"" + IMAP_Utils.DateTimeToString(msg.InternalDate) + "\""); } #endregion #region RFC822 // RFC822 else if (fetchFlagName == "RFC822") { // Force to write all buffered data. TcpStream.Flush(); // Sets \seen flag msg.SetFlags(msg.Flags | IMAP_MessageFlags.Seen); // RFC822 {size} // msg data this.TcpStream.Write("RFC822 {" + eArgs.MessageSize.ToString() + "}\r\n"); this.TcpStream.WriteStream(eArgs.MessageStream); } #endregion #region RFC822.HEADER // RFC822.HEADER else if (fetchFlagName == "RFC822.HEADER") { // Force to write all buffered data. TcpStream.Flush(); // RFC822.HEADER {size} // msg header data this.TcpStream.Write("RFC822.HEADER {" + eArgs.Header.Length + "}\r\n"); this.TcpStream.Write(eArgs.Header); } #endregion #region RFC822.SIZE // RFC822.SIZE else if (fetchFlagName == "RFC822.SIZE") { // RFC822.SIZE size TcpStream.Write("RFC822.SIZE " + msg.Size); } #endregion #region RFC822.TEXT // RFC822.TEXT else if (fetchFlagName == "RFC822.TEXT") { // Force to write all buffered data. TcpStream.Flush(); // Sets \seen flag msg.SetFlags(msg.Flags | IMAP_MessageFlags.Seen); //--- Find body text entity ------------------------------------// Mime parser = Mime.Parse(eArgs.MessageStream); MimeEntity bodyTextEntity = null; if (parser.MainEntity.ContentType == MediaType_enum.NotSpecified) { if (parser.MainEntity.DataEncoded != null) { bodyTextEntity = parser.MainEntity; } } else { MimeEntity[] entities = parser.MimeEntities; foreach (MimeEntity entity in entities) { if (entity.ContentType == MediaType_enum.Text_plain) { bodyTextEntity = entity; break; } } } //----------------------------------------------------------------// // RFC822.TEXT {size} // msg text byte[] data = null; if (bodyTextEntity != null) { data = bodyTextEntity.DataEncoded; } else { data = System.Text.Encoding.ASCII.GetBytes(""); } this.TcpStream.Write("RFC822.TEXT {" + data.Length + "}\r\n"); this.TcpStream.Write(data); } #endregion #region UID // UID else if (fetchFlagName == "UID") { TcpStream.Write("UID " + msg.UID); } #endregion nCount++; // Write fetch item separator data " " // We don't write it for last item if (nCount < fetchFlags.Count) { TcpStream.Write(" "); } } // Write fetch end data ")" TcpStream.Write(")\r\n"); // Free event args, close message stream, ... . if (eArgs != null) { eArgs.Dispose(); } // Set message flags here if required or changed if (((int)IMAP_MessageFlags.Recent & (int)msg.Flags) != 0 || msgFlagsOr != msg.Flags) { msg.SetFlags(msg.Flags & ~IMAP_MessageFlags.Recent); ImapServer.OnStoreMessageFlags(this, msg); } } } // Force to write all buffered data. TcpStream.Flush(); this.TcpStream.WriteLine(string.Format("{0} OK FETCH completed in {1} seconds", cmdTag, ((DateTime.Now.Ticks - startTime) / (decimal)10000000).ToString("f2"))); } private void Store(string cmdTag, string argsText, bool uidStore) { /* Rfc 3501 6.4.6 STORE Command Arguments: message set message data item name value for message data item Responses: untagged responses: FETCH Result: OK - store completed NO - store error: can't store that data BAD - command unknown or arguments invalid The STORE command alters data associated with a message in the mailbox. Normally, STORE will return the updated value of the data with an untagged FETCH response. A suffix of ".SILENT" in the data item name prevents the untagged FETCH, and the server SHOULD assume that the client has determined the updated value itself or does not care about the updated value. Note: regardless of whether or not the ".SILENT" suffix was used, the server SHOULD send an untagged FETCH response if a change to a message's flags from an external source is observed. The intent is that the status of the flags is determinate without a race condition. The currently defined data items that can be stored are: FLAGS <flag list> Replace the flags for the message (other than \Recent) with the argument. The new value of the flags is returned as if a FETCH of those flags was done. FLAGS.SILENT <flag list> Equivalent to FLAGS, but without returning a new value. +FLAGS <flag list> Add the argument to the flags for the message. The new value of the flags is returned as if a FETCH of those flags was done. +FLAGS.SILENT <flag list> Equivalent to +FLAGS, but without returning a new value. -FLAGS <flag list> Remove the argument from the flags for the message. The new value of the flags is returned as if a FETCH of those flags was done. -FLAGS.SILENT <flag list> Equivalent to -FLAGS, but without returning a new value. Example: C: A003 STORE 2:4 +FLAGS (\Deleted) S: * 2 FETCH FLAGS (\Deleted \Seen) S: * 3 FETCH FLAGS (\Deleted) S: * 4 FETCH FLAGS (\Deleted \Flagged \Seen) S: A003 OK STORE completed */ if (!IsAuthenticated) { WriteLine(string.Format("{0} NO Authenticate first !", cmdTag)); return; } if (SelectedMailbox.Length == 0) { WriteLine(string.Format("{0} NO Select mailbox first !", cmdTag)); return; } if (m_pSelectedFolder.ReadOnly) { WriteLine(string.Format("{0} NO Mailbox is read-only", cmdTag)); return; } // Store start time long startTime = DateTime.Now.Ticks; string[] args = ParseParams(argsText); if (args.Length != 3) { WriteLine(string.Format("{0} BAD STORE invalid arguments. Syntax: {{<command-tag> STORE <sequnce-set> <data-item> (<message-flags>)}}", cmdTag)); return; } IMAP_SequenceSet sequenceSet = new IMAP_SequenceSet(); // Just try if it can be parsed as sequence-set try { if (uidStore) { if (m_pSelectedFolder.Messages.Count > 0) { sequenceSet.Parse(args[0], m_pSelectedFolder.Messages[m_pSelectedFolder.Messages.Count - 1].UID); } } else { sequenceSet.Parse(args[0], m_pSelectedFolder.Messages.Count); } } // This isn't vaild sequnce-set value catch { WriteLine(string.Format("{0}BAD Invalid <sequnce-set> value '{1}' Syntax: {{<command-tag> STORE <sequnce-set> <data-item> (<message-flags>)}}!", cmdTag, args[0])); return; } //--- Parse Flags behaviour ---------------// string flagsAction = ""; bool silent = false; string flagsType = args[1].ToUpper(); switch (flagsType) { case "FLAGS": flagsAction = "REPLACE"; break; case "FLAGS.SILENT": flagsAction = "REPLACE"; silent = true; break; case "+FLAGS": flagsAction = "ADD"; break; case "+FLAGS.SILENT": flagsAction = "ADD"; silent = true; break; case "-FLAGS": flagsAction = "REMOVE"; break; case "-FLAGS.SILENT": flagsAction = "REMOVE"; silent = true; break; default: WriteLine(cmdTag + " BAD arguments invalid"); return; } //-------------------------------------------// //--- Parse flags, see if valid ---------------- string flags = args[2].ToUpper(); if ( flags.Replace("\\ANSWERED", "").Replace("\\FLAGGED", "").Replace("\\DELETED", "").Replace( "\\SEEN", "").Replace("\\DRAFT", "").Trim().Length > 0) { WriteLine(string.Format("{0} BAD arguments invalid", cmdTag)); return; } IMAP_MessageFlags mFlags = IMAP_Utils.ParseMessageFlags(flags); // Call OnStoreMessageFlags for each message in sequence set // Calulate new flags(using old message flags + new flags) for message // and request to store all flags to message, don't specify if add, remove or replace falgs. for (int i = 0; i < m_pSelectedFolder.Messages.Count; i++) { IMAP_Message msg = m_pSelectedFolder.Messages[i]; // For UID STORE we must compare UIDs and for normal STORE message numbers. bool sequenceSetContains = false; if (uidStore) { sequenceSetContains = sequenceSet.Contains(msg.UID); } else { sequenceSetContains = sequenceSet.Contains(i + 1); } if (sequenceSetContains) { // Calculate new flags and set to msg switch (flagsAction) { case "REPLACE": msg.SetFlags(mFlags); break; case "ADD": msg.SetFlags(msg.Flags | mFlags); break; case "REMOVE": msg.SetFlags(msg.Flags & ~mFlags); break; } // ToDo: see if flags changed, if not don't call OnStoreMessageFlags string errorText = ImapServer.OnStoreMessageFlags(this, msg); if (errorText == null) { if (!silent) { // Silent doesn't reply untagged lines if (!uidStore) { WriteLine(string.Format("* {0} FETCH FLAGS ({1})", (i + 1), msg.FlagsString)); } // Called from UID command, need to add UID response else { WriteLine(string.Format("* {0} FETCH (FLAGS ({1}) UID {2}))", (i + 1), msg.FlagsString, msg.UID)); } } } else { WriteLine(string.Format("{0} NO {1}", cmdTag, errorText)); return; } } } WriteLine(string.Format("{0} OK STORE completed in {1} seconds", cmdTag, ((DateTime.Now.Ticks - startTime) / (decimal)10000000).ToString("f2"))); } private void Copy(string cmdTag, string argsText, bool uidCopy) { /* RFC 3501 6.4.7 COPY Command Arguments: message set mailbox name Responses: no specific responses for this command Result: OK - copy completed NO - copy error: can't copy those messages or to that name BAD - command unknown or arguments invalid The COPY command copies the specified message(s) to the end of the specified destination mailbox. The flags and internal date of the message(s) SHOULD be preserved in the copy. If the destination mailbox does not exist, a server SHOULD return an error. It SHOULD NOT automatically create the mailbox. Unless it is certain that the destination mailbox can not be created, the server MUST send the response code "[TRYCREATE]" as the prefix of the text of the tagged NO response. This gives a hint to the client that it can attempt a CREATE command and retry the COPY if If the COPY command is unsuccessful for any reason, server implementations MUST restore the destination mailbox to its state before the COPY attempt. Example: C: A003 COPY 2:4 MEETING S: A003 OK COPY completed */ if (!IsAuthenticated) { WriteLine(string.Format("{0} NO Authenticate first !", cmdTag)); return; } if (SelectedMailbox.Length == 0) { WriteLine(string.Format("{0} NO Select mailbox first !", cmdTag)); return; } string[] args = ParseParams(argsText); if (args.Length != 2) { WriteLine(string.Format("{0} BAD Invalid arguments", cmdTag)); return; } IMAP_SequenceSet sequenceSet = new IMAP_SequenceSet(); // Just try if it can be parsed as sequence-set try { if (uidCopy) { if (m_pSelectedFolder.Messages.Count > 0) { sequenceSet.Parse(args[0], m_pSelectedFolder.Messages[m_pSelectedFolder.Messages.Count - 1].UID); } } else { sequenceSet.Parse(args[0], m_pSelectedFolder.Messages.Count); } } // This isn't vaild sequnce-set value catch { WriteLine(string.Format("{0}BAD Invalid <sequnce-set> value '{1}' Syntax: {{<command-tag> COPY <sequnce-set> \"<mailbox-name>\"}}!", cmdTag, args[0])); return; } string errorText = ""; for (int i = 0; i < m_pSelectedFolder.Messages.Count; i++) { IMAP_Message msg = m_pSelectedFolder.Messages[i]; // For UID COPY we must compare UIDs and for normal COPY message numbers. bool sequenceSetContains = false; if (uidCopy) { sequenceSetContains = sequenceSet.Contains(msg.UID); } else { sequenceSetContains = sequenceSet.Contains(i + 1); } if (sequenceSetContains) { errorText = ImapServer.OnCopyMessage(this, msg, Core.Decode_IMAP_UTF7_String(args[1])); if (errorText != null) { break; // Errors return error text, don't try to copy other messages } } } if (errorText == null) { WriteLine(string.Format("{0} OK COPY completed", cmdTag)); } else { WriteLine(string.Format("{0} NO {1}", cmdTag, errorText)); } } private void Uid(string cmdTag, string argsText) { /* Rfc 3501 6.4.8 UID Command Arguments: command name command arguments Responses: untagged responses: FETCH, SEARCH Result: OK - UID command completed NO - UID command error BAD - command unknown or arguments invalid The UID command has two forms. In the first form, it takes as its arguments a COPY, FETCH, or STORE command with arguments appropriate for the associated command. However, the numbers in the message set argument are unique identifiers instead of message sequence numbers. In the second form, the UID command takes a SEARCH command with SEARCH command arguments. The interpretation of the arguments is the same as with SEARCH; however, the numbers returned in a SEARCH response for a UID SEARCH command are unique identifiers instead of message sequence numbers. For example, the command UID SEARCH 1:100 UID 443:557 returns the unique identifiers corresponding to the intersection of the message sequence number set 1:100 and the UID set 443:557. Message set ranges are permitted; however, there is no guarantee that unique identifiers be contiguous. A non-existent unique identifier within a message set range is ignored without any error message generated. The number after the "*" in an untagged FETCH response is always a message sequence number, not a unique identifier, even for a UID command response. However, server implementations MUST implicitly include the UID message data item as part of any FETCH response caused by a UID command, regardless of whether a UID was specified as a message data item to the FETCH. Example: C: A999 UID FETCH 4827313:4828442 FLAGS S: * 23 FETCH (FLAGS (\Seen) UID 4827313) S: * 24 FETCH (FLAGS (\Seen) UID 4827943) S: * 25 FETCH (FLAGS (\Seen) UID 4828442) S: A999 UID FETCH completed */ if (!IsAuthenticated) { WriteLine(string.Format("{0} NO Authenticate first !", cmdTag)); return; } if (SelectedMailbox.Length == 0) { WriteLine(string.Format("{0} NO Select mailbox first !", cmdTag)); return; } string[] args = ParseParams(argsText); if (args.Length < 2) { // We must have at least command and message-set or cmd args WriteLine(string.Format("{0} BAD Invalid arguments", cmdTag)); return; } // Get commands args text, we just remove COMMAND string cmdArgs = Core.GetArgsText(argsText, args[0]); // See if valid command specified with UID command switch (args[0].ToUpper()) { case "COPY": Copy(cmdTag, cmdArgs, true); break; case "FETCH": Fetch(cmdTag, cmdArgs, true); break; case "STORE": Store(cmdTag, cmdArgs, true); break; case "SEARCH": Search(cmdTag, cmdArgs, true); break; default: WriteLine(cmdTag + " BAD Invalid arguments"); return; } } /// <summary> /// Processes IDLE command. /// </summary> /// <param name="cmdTag">Command tag.</param> /// <param name="argsText">Command arguments text.</param> /// <returns>Returns true if IDLE comand accepted, otherwise false.</returns> private bool Idle(string cmdTag, string argsText) { if (!IsAuthenticated) { WriteLine(string.Format("{0} NO Authenticate first !", cmdTag)); return false; } if (SelectedMailbox.Length == 0 && m_StatusedMailbox.Length == 0) { WriteLine(string.Format("{0} BAD Select mailbox first !", cmdTag)); return false; } if (m_pIDLE!=null) { m_pIDLE.Dispose(); } m_pIDLE = new Command_IDLE(this, cmdTag, SelectedMailbox.Length == 0 ? m_StatusedMailbox : SelectedMailbox); return true; } //--- End of Selected State //--- Any State ------ private void Capability(string cmdTag) { /* RFC 3501 6.1.1 Arguments: none Responses: REQUIRED untagged response: CAPABILITY Result: OK - capability completed BAD - command unknown or arguments invalid The CAPABILITY command requests a listing of capabilities that the server supports. The server MUST send a single untagged CAPABILITY response with "IMAP4rev1" as one of the listed capabilities before the (tagged) OK response. A capability name which begins with "AUTH=" indicates that the server supports that particular authentication mechanism. Example: C: abcd CAPABILITY S: * CAPABILITY IMAP4rev1 STARTTLS AUTH=GSSAPI LOGINDISABLED S: abcd OK CAPABILITY completed C: efgh STARTTLS S: efgh OK STARTLS completed <TLS negotiation, further commands are under [TLS] layer> C: ijkl CAPABILITY S: * CAPABILITY IMAP4rev1 AUTH=GSSAPI AUTH=PLAIN S: ijkl OK CAPABILITY completed */ string reply = "* CAPABILITY IMAP4rev1"; if ((ImapServer.SupportedAuthentications & SaslAuthTypes.Digest_md5) != 0) { reply += " AUTH=DIGEST-MD5"; } if ((ImapServer.SupportedAuthentications & SaslAuthTypes.Cram_md5) != 0) { reply += " AUTH=CRAM-MD5"; } if (!IsSecureConnection && Certificate != null) { reply += " STARTTLS"; } reply += " NAMESPACE ACL QUOTA IDLE X-FILTER\r\n"; reply += cmdTag + " OK CAPABILITY completed\r\n"; TcpStream.Write(reply); } private void Noop(string cmdTag) { /* RFC 3501 6.1.2 NOOP Command Arguments: none Responses: no specific responses for this command (but see below) Result: OK - noop completed BAD - command unknown or arguments invalid The NOOP command always succeeds. It does nothing. Since any command can return a status update as untagged data, the NOOP command can be used as a periodic poll for new messages or message status updates during a period of inactivity. The NOOP command can also be used to reset any inactivity autologout timer on the server. Example: C: a002 NOOP S: a002 OK NOOP completed */ // Store start time long startTime = DateTime.Now.Ticks; // If there is selected mailbox, see if messages status has changed if (SelectedMailbox.Length > 0) { ProcessMailboxChanges(); WriteLine(cmdTag + " OK NOOP Completed in " + ((DateTime.Now.Ticks - startTime) / (decimal)10000000).ToString("f2") + " seconds\r\n"); } else { WriteLine(cmdTag + " OK NOOP Completed in " + ((DateTime.Now.Ticks - startTime) / (decimal)10000000).ToString("f2") + " seconds\r\n"); } } private void LogOut(string cmdTag) { /* RFC 3501 6.1.3 Arguments: none Responses: REQUIRED untagged response: BYE Result: OK - logout completed BAD - command unknown or arguments invalid The LOGOUT command informs the server that the client is done with the connection. The server MUST send a BYE untagged response before the (tagged) OK response, and then close the network connection. Example: C: A023 LOGOUT S: * BYE IMAP4rev1 Server logging out S: A023 OK LOGOUT completed (Server and client then close the connection) */ string reply = "* BYE IMAP4rev1 Server logging out\r\n"; reply += cmdTag + " OK LOGOUT completed\r\n"; TcpStream.Write(reply); TcpStream.Flush(); } //--- End of Any State /// <summary> /// Processes changes and sends status responses if there are changes in selected mailbox. /// </summary> private void ProcessMailboxChanges() { ProcessMailboxChanges(SelectedMailbox); } /// <summary> /// Processes changes and sends status responses if there are changes in selected mailbox. /// </summary> private void ProcessMailboxChanges(string mailBox) { //TODO: Many whelps! Handle it! // Get status IMAP_SelectedFolder folderInfo = new IMAP_SelectedFolder(mailBox); IMAP_eArgs_GetMessagesInfo eArgs = ImapServer.OnGetMessagesInfo(this, folderInfo); // Join new info with exisiting if (m_pSelectedFolder != null) { string statusResponse = m_pSelectedFolder.Update(folderInfo); if (!string.IsNullOrEmpty(statusResponse)) { WriteLine(statusResponse); m_pSelectedFolder = folderInfo; } } if (m_pAdditionalFolder != null) { string statusResponse = m_pAdditionalFolder.Update(folderInfo); if (!string.IsNullOrEmpty(statusResponse)) { WriteLine(statusResponse); m_pAdditionalFolder = folderInfo; } } } private string[] ParseParams(string argsText) { List<string> p = new List<string>(); try { while (argsText.Length > 0) { // Parameter is between "" if (argsText.StartsWith("\"")) { p.Add(argsText.Substring(1, argsText.IndexOf("\"", 1) - 1)); // Remove parsed param argsText = argsText.Substring(argsText.IndexOf("\"", 1) + 1).Trim(); } else { // Parameter is between () if (argsText.StartsWith("(")) { p.Add(argsText.Substring(1, argsText.LastIndexOf(")") - 1)); // Remove parsed param argsText = argsText.Substring(argsText.LastIndexOf(")") + 1).Trim(); } else { // Read parameter till " ", probably there is more params // Note: If there is ({ before SP, cosider that it's last parameter. // For example body[header.fields (from to)] if (argsText.IndexOf(" ") > -1 && argsText.IndexOfAny(new[] { '(', '[' }, 0, argsText.IndexOf(" ")) == -1) { p.Add(argsText.Substring(0, argsText.IndexOf(" "))); // Remove parsed param argsText = argsText.Substring(argsText.IndexOf(" ") + 1).Trim(); } // This is last param else { p.Add(argsText); argsText = ""; } } } } } catch { } return p.ToArray(); } #endregion } }<file_sep>/web/studio/ASC.Web.Studio/Core/Users/AffiliateHelper.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Configuration; using ASC.Core.Users; namespace ASC.Web.Studio.Core.Users { public class AffiliateHelper { public static string JoinAffilliateLink { get { return ConfigurationManagerExtension.AppSettings["web.affiliates.link"]; } } private static bool Available(UserInfo user) { return !String.IsNullOrEmpty(JoinAffilliateLink) && user.ActivationStatus == EmployeeActivationStatus.Activated && user.Status == EmployeeStatus.Active; } public static bool ButtonAvailable(UserInfo user) { return Available(user) && user.IsMe(); } public static string Join() { if (!string.IsNullOrEmpty(JoinAffilliateLink)) { return JoinAffilliateLink; /* var request = WebRequest.Create(string.Format("{2}/Account/Register?uid={1}&tenantAlias={0}", CoreContext.TenantManager.GetCurrentTenant().TenantAlias, SecurityContext.CurrentAccount.ID, JoinAffilliateLink)); request.Method = "PUT"; request.ContentLength = 0; using (var response = (HttpWebResponse)request.GetResponse()) { using (var streamReader = new StreamReader(response.GetResponseStream())) { var origin = streamReader.ReadToEnd(); if (response.StatusCode != HttpStatusCode.BadRequest) { return string.Format("{0}/home/Account/SignIn?ticketKey={1}", JoinAffilliateLink, origin); } } }*/ } return ""; } } } <file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/SMTP/Client/SMTP_Client.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.SMTP.Client { #region usings using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Security.Cryptography; using System.Security.Principal; using System.Text; using AUTH; using Dns.Client; using Mime; using TCP; #endregion /// <summary> /// This class implements SMTP client. Defined in RFC 2821. /// </summary> /// <example> /// Simple way: /// <code> /// /* /// To make this code to work, you need to import following namespaces: /// using LumiSoft.Net.SMTP.Client; /// */ /// /// // You can send any valid SMTP message here, from disk,memory, ... or /// // you can use LumiSoft.Net.Mime mime classes to compose valid SMTP mail message. /// /// // SMTP_Client.QuickSendSmartHost(... /// or /// // SMTP_Client.QuickSend(... /// </code> /// /// Advanced way: /// <code> /// /* /// To make this code to work, you need to import following namespaces: /// using LumiSoft.Net.SMTP.Client; /// */ /// /// using(SMTP_Client smtp = new SMTP_Client()){ /// // If you have registered DNS host name, set it here before connecting. /// // That name will be reported to SMTP server. /// // smtp.LocalHostName = "mail.domain.com"; /// /// // You can use SMTP_Client.GetDomainHosts(... to get target receipient SMTP hosts for Connect method. /// smtp.Connect("hostName",WellKnownPorts.SMTP); /// // Authenticate if target server requires. /// // smtp.Authenticate("user","password"); /// smtp.MailFrom("<EMAIL>"); /// // Repeat this for all recipients. /// smtp.RcptTo("<EMAIL>"); /// /// // Send message to server. /// // You can send any valid SMTP message here, from disk,memory, ... or /// // you can use LumiSoft.Net.Mime mieclasses to compose valid SMTP mail message. /// // smtp.SendMessage(.... . /// } /// </code> /// </example> public class SMTP_Client : TCP_Client { #region Delegates /// <summary> /// Internal helper method for asynchronous Authenticate method. /// </summary> private delegate void AuthenticateDelegate(string userName, string password); /// <summary> /// Internal helper method for asynchronous SendMessage method. /// </summary> private delegate string[] GetDomainHostsDelegate(string domain); /// <summary> /// Internal helper method for asynchronous MailFrom method. /// </summary> private delegate void MailFromDelegate(string from, long messageSize); /// <summary> /// Internal helper method for asynchronous Noop method. /// </summary> private delegate void NoopDelegate(); /// <summary> /// Internal helper method for asynchronous RcptTo method. /// </summary> private delegate void RcptToDelegate(string to); /// <summary> /// Internal helper method for asynchronous Reset method. /// </summary> private delegate void ResetDelegate(); /// <summary> /// Internal helper method for asynchronous SendMessage method. /// </summary> private delegate void SendMessageDelegate(Stream message); /// <summary> /// Internal helper method for asynchronous StartTLS method. /// </summary> private delegate void StartTLSDelegate(); #endregion #region Members private string m_GreetingText = ""; private bool m_IsEsmtpSupported; private string m_LocalHostName; private string m_MailFrom; private GenericIdentity m_pAuthdUserIdentity; private List<string> m_pEsmtpFeatures; private List<string> m_pRecipients; private string m_RemoteHostName; #endregion #region Properties /// <summary> /// Gets session authenticated user identity, returns null if not authenticated. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when this property is accessed and SMTP client is not connected.</exception> public override GenericIdentity AuthenticatedUserIdentity { get { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (!IsConnected) { throw new InvalidOperationException("You must connect first."); } return m_pAuthdUserIdentity; } } /// <summary> /// Gets what ESMTP features are supported by connected SMTP server. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when this property is accessed and SMTP client is not connected.</exception> public string[] EsmtpFeatures { get { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (!IsConnected) { throw new InvalidOperationException("You must connect first."); } return m_pEsmtpFeatures.ToArray(); } } /// <summary> /// Gets greeting text which was sent by SMTP server. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when this property is accessed and SMTP client is not connected.</exception> public string GreetingText { get { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (!IsConnected) { throw new InvalidOperationException("You must connect first."); } return m_GreetingText; } } /// <summary> /// Gets if connected SMTP server suports ESMTP. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when this property is accessed and SMTP client is not connected.</exception> public bool IsEsmtpSupported { get { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (!IsConnected) { throw new InvalidOperationException("You must connect first."); } return m_IsEsmtpSupported; } } /// <summary> /// Gets or sets host name which is reported to SMTP server. If value null, then local computer name is used. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when this property is accessed and SMTP client is connected.</exception> public string LocalHostName { get { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_LocalHostName; } set { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (IsConnected) { throw new InvalidOperationException( "Property LocalHostName is available only when SMTP client is not connected."); } m_LocalHostName = value; } } /// <summary> /// Gets maximum message size in bytes what SMTP server accepts. Value null means not known. /// </summary> public long MaxAllowedMessageSize { get { try { foreach (string feature in EsmtpFeatures) { if (feature.ToUpper().StartsWith(SMTP_ServiceExtensions.SIZE)) { return Convert.ToInt64(feature.Split(' ')[1]); } } } catch { // Never should reach here, skip errors here. } return 0; } } /// <summary> /// Gets SMTP server host name which it reported to us. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when this property is accessed and SMTP client is not connected.</exception> public string RemoteHostName { get { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (!IsConnected) { throw new InvalidOperationException("You must connect first."); } return m_RemoteHostName; } } /// <summary> /// Gets SMTP server supported SASL authentication method. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when this property is accessed and SMTP client is not connected.</exception> public string[] SaslAuthMethods { get { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (!IsConnected) { throw new InvalidOperationException("You must connect first."); } // Search AUTH entry. foreach (string feature in EsmtpFeatures) { if (feature.ToUpper().StartsWith(SMTP_ServiceExtensions.AUTH)) { // Remove AUTH<SP> and split authentication methods. return feature.Substring(4).Trim().Split(' '); } } return new string[0]; } } #endregion #region Methods /// <summary> /// Starts getting specified email domain SMTP hosts. /// </summary> /// <param name="domain">Email domain or email address. For example domain.com or [email protected].</param> /// <param name="callback">Callback to call when the asynchronous operation is complete.</param> /// <param name="state">User data.</param> /// <returns>An IAsyncResult that references the asynchronous method.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>domain</b> is null.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> public static IAsyncResult BeginGetDomainHosts(string domain, AsyncCallback callback, object state) { if (domain == null) { throw new ArgumentNullException("domain"); } if (string.IsNullOrEmpty(domain)) { throw new ArgumentException( "Invalid argument 'domain' value, you need to specify domain value."); } GetDomainHostsDelegate asyncMethod = GetDomainHosts; AsyncResultState asyncState = new AsyncResultState(null, asyncMethod, callback, state); asyncState.SetAsyncResult(asyncMethod.BeginInvoke(domain, asyncState.CompletedCallback, null)); return asyncState; } /// <summary> /// Ends a pending asynchronous BeginGetDomainHosts request. /// </summary> /// <param name="asyncResult">An IAsyncResult that stores state information and any user defined data for this asynchronous operation.</param> /// <returns>Returns specified email domain SMTP hosts.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>asyncResult</b> is null.</exception> /// <exception cref="ArgumentException">Is raised when invalid <b>asyncResult</b> passed to this method.</exception> public static string[] EndGetDomainHosts(IAsyncResult asyncResult) { if (asyncResult == null) { throw new ArgumentNullException("asyncResult"); } AsyncResultState castedAsyncResult = asyncResult as AsyncResultState; if (castedAsyncResult == null) { throw new ArgumentException( "Argument asyncResult was not returned by a call to the BeginGetDomainHosts method."); } if (castedAsyncResult.IsEndCalled) { throw new InvalidOperationException( "BeginGetDomainHosts was previously called for the asynchronous connection."); } castedAsyncResult.IsEndCalled = true; if (castedAsyncResult.AsyncDelegate is GetDomainHostsDelegate) { return ((GetDomainHostsDelegate) castedAsyncResult.AsyncDelegate).EndInvoke( castedAsyncResult.AsyncResult); } else { throw new ArgumentException( "Argument asyncResult was not returned by a call to the BeginGetDomainHosts method."); } } /// <summary> /// Gets specified email domain SMTP hosts. Values are in descending priority order. /// </summary> /// <param name="domain">Domain name. This value can be email address too, then domain parsed automatically.</param> /// <returns>Returns specified email domain SMTP hosts.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>domain</b> is null.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> /// <exception cref="DNS_ClientException">Is raised when DNS query failure.</exception> public static string[] GetDomainHosts(string domain) { if (domain == null) { throw new ArgumentNullException("domain"); } if (string.IsNullOrEmpty(domain)) { throw new ArgumentException( "Invalid argument 'domain' value, you need to specify domain value."); } // We have email address, parse domain. if (domain.IndexOf("@") > -1) { domain = domain.Substring(domain.IndexOf('@') + 1); } List<string> retVal = new List<string>(); // Get MX records. Dns_Client dns = new Dns_Client(); DnsServerResponse response = dns.Query(domain, QTYPE.MX); if (response.ResponseCode == RCODE.NO_ERROR) { foreach (DNS_rr_MX mx in response.GetMXRecords()) { // Block invalid MX records. if (!string.IsNullOrEmpty(mx.Host)) { retVal.Add(mx.Host); } } } else { throw new DNS_ClientException(response.ResponseCode); } /* RFC 2821 5. If no MX records are found, but an A RR is found, the A RR is treated as if it was associated with an implicit MX RR, with a preference of 0, pointing to that host. */ if (retVal.Count == 0) { retVal.Add(domain); } return retVal.ToArray(); } /// <summary> /// Sends specified mime message. /// </summary> /// <param name="message">Message to send.</param> /// <exception cref="ArgumentNullException">Is raised when <b>message</b> is null.</exception> public static void QuickSend(Mime message) { if (message == null) { throw new ArgumentNullException("message"); } string from = ""; if (message.MainEntity.From != null && message.MainEntity.From.Count > 0) { from = ((MailboxAddress) message.MainEntity.From[0]).EmailAddress; } List<string> recipients = new List<string>(); if (message.MainEntity.To != null) { MailboxAddress[] addresses = message.MainEntity.To.Mailboxes; foreach (MailboxAddress address in addresses) { recipients.Add(address.EmailAddress); } } if (message.MainEntity.Cc != null) { MailboxAddress[] addresses = message.MainEntity.Cc.Mailboxes; foreach (MailboxAddress address in addresses) { recipients.Add(address.EmailAddress); } } if (message.MainEntity.Bcc != null) { MailboxAddress[] addresses = message.MainEntity.Bcc.Mailboxes; foreach (MailboxAddress address in addresses) { recipients.Add(address.EmailAddress); } // We must hide BCC message.MainEntity.Bcc.Clear(); } foreach (string recipient in recipients) { QuickSend(null, from, recipient, new MemoryStream(message.ToByteData())); } } /// <summary> /// Sends message directly to email domain. Domain email sever resolve order: MX recordds -> A reords if no MX. /// </summary> /// <param name="from">Sender email what is reported to SMTP server.</param> /// <param name="to">Recipient email.</param> /// <param name="message">Raw message to send.</param> /// <exception cref="ArgumentNullException">Is raised when <b>from</b>,<b>to</b> or <b>message</b> is null.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> /// <exception cref="SMTP_ClientException">Is raised when SMTP server returns error.</exception> public static void QuickSend(string from, string to, Stream message) { QuickSend(null, from, to, message); } /// <summary> /// Sends message directly to email domain. Domain email sever resolve order: MX recordds -> A reords if no MX. /// </summary> /// <param name="localHost">Host name which is reported to SMTP server.</param> /// <param name="from">Sender email what is reported to SMTP server.</param> /// <param name="to">Recipient email.</param> /// <param name="message">Raw message to send.</param> /// <exception cref="ArgumentNullException">Is raised when <b>from</b>,<b>to</b> or <b>message</b> is null.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> /// <exception cref="SMTP_ClientException">Is raised when SMTP server returns error.</exception> public static void QuickSend(string localHost, string from, string to, Stream message) { if (from == null) { throw new ArgumentNullException("from"); } if (from != "" && !SMTP_Utils.IsValidAddress(from)) { throw new ArgumentException("Argument 'from' has invalid value."); } if (to == null) { throw new ArgumentNullException("to"); } if (to == "") { throw new ArgumentException("Argument 'to' value must be specified."); } if (!SMTP_Utils.IsValidAddress(to)) { throw new ArgumentException("Argument 'to' has invalid value."); } if (message == null) { throw new ArgumentNullException("message"); } QuickSendSmartHost(localHost, GetDomainHosts(to)[0], 25, false, from, new[] {to}, message); } /// <summary> /// Sends message by using specified smart host. /// </summary> /// <param name="host">Host name or IP address.</param> /// <param name="port">Host port.</param> /// <param name="from">Sender email what is reported to SMTP server.</param> /// <param name="to">Recipients email addresses.</param> /// <param name="message">Raw message to send.</param> /// <exception cref="ArgumentNullException">Is raised when argument <b>host</b>,<b>from</b>,<b>to</b> or <b>stream</b> is null.</exception> /// <exception cref="ArgumentException">Is raised when any of the method arguments has invalid value.</exception> /// <exception cref="SMTP_ClientException">Is raised when SMTP server returns error.</exception> public static void QuickSendSmartHost(string host, int port, string from, string[] to, Stream message) { QuickSendSmartHost(null, host, port, false, null, null, from, to, message); } /// <summary> /// Sends message by using specified smart host. /// </summary> /// <param name="host">Host name or IP address.</param> /// <param name="port">Host port.</param> /// <param name="ssl">Specifies if connected via SSL.</param> /// <param name="from">Sender email what is reported to SMTP server.</param> /// <param name="to">Recipients email addresses.</param> /// <param name="message">Raw message to send.</param> /// <exception cref="ArgumentNullException">Is raised when argument <b>host</b>,<b>from</b>,<b>to</b> or <b>stream</b> is null.</exception> /// <exception cref="ArgumentException">Is raised when any of the method arguments has invalid value.</exception> /// <exception cref="SMTP_ClientException">Is raised when SMTP server returns error.</exception> public static void QuickSendSmartHost(string host, int port, bool ssl, string from, string[] to, Stream message) { QuickSendSmartHost(null, host, port, ssl, null, null, from, to, message); } /// <summary> /// Sends message by using specified smart host. /// </summary> /// <param name="localHost">Host name which is reported to SMTP server.</param> /// <param name="host">Host name or IP address.</param> /// <param name="port">Host port.</param> /// <param name="ssl">Specifies if connected via SSL.</param> /// <param name="from">Sender email what is reported to SMTP server.</param> /// <param name="to">Recipients email addresses.</param> /// <param name="message">Raw message to send.</param> /// <exception cref="ArgumentNullException">Is raised when argument <b>host</b>,<b>from</b>,<b>to</b> or <b>stream</b> is null.</exception> /// <exception cref="ArgumentException">Is raised when any of the method arguments has invalid value.</exception> /// <exception cref="SMTP_ClientException">Is raised when SMTP server returns error.</exception> public static void QuickSendSmartHost(string localHost, string host, int port, bool ssl, string from, string[] to, Stream message) { QuickSendSmartHost(localHost, host, port, ssl, null, null, from, to, message); } /// <summary> /// Sends message by using specified smart host. /// </summary> /// <param name="localHost">Host name which is reported to SMTP server.</param> /// <param name="host">Host name or IP address.</param> /// <param name="port">Host port.</param> /// <param name="ssl">Specifies if connected via SSL.</param> /// <param name="userName">SMTP server user name. This value may be null, then authentication not used.</param> /// <param name="password">SMTP server password.</param> /// <param name="from">Sender email what is reported to SMTP server.</param> /// <param name="to">Recipients email addresses.</param> /// <param name="message">Raw message to send.</param> /// <exception cref="ArgumentNullException">Is raised when argument <b>host</b>,<b>from</b>,<b>to</b> or <b>stream</b> is null.</exception> /// <exception cref="ArgumentException">Is raised when any of the method arguments has invalid value.</exception> /// <exception cref="SMTP_ClientException">Is raised when SMTP server returns error.</exception> public static void QuickSendSmartHost(string localHost, string host, int port, bool ssl, string userName, string password, string from, string[] to, Stream message) { if (host == null) { throw new ArgumentNullException("host"); } if (host == "") { throw new ArgumentException("Argument 'host' value may not be empty."); } if (port < 1) { throw new ArgumentException("Argument 'port' value must be >= 1."); } if (from == null) { throw new ArgumentNullException("from"); } if (from != "" && !SMTP_Utils.IsValidAddress(from)) { throw new ArgumentException("Argument 'from' has invalid value."); } if (to == null) { throw new ArgumentNullException("to"); } if (to.Length == 0) { throw new ArgumentException("Argument 'to' must contain at least 1 recipient."); } foreach (string t in to) { if (!SMTP_Utils.IsValidAddress(t)) { throw new ArgumentException("Argument 'to' has invalid value '" + t + "'."); } } if (message == null) { throw new ArgumentNullException("message"); } using (SMTP_Client smtp = new SMTP_Client()) { if (!string.IsNullOrEmpty(localHost)) { smtp.LocalHostName = localHost; } smtp.Connect(host, port, ssl); if (!string.IsNullOrEmpty(userName)) { smtp.Authenticate(userName, password); } smtp.MailFrom(from, -1); foreach (string t in to) { smtp.RcptTo(t); } smtp.SendMessage(message); } } /// <summary> /// Clean up any resources being used. /// </summary> public override void Dispose() { base.Dispose(); } /// <summary> /// Closes connection to SMTP server. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when SMTP client is not connected.</exception> public override void Disconnect() { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (!IsConnected) { throw new InvalidOperationException("SMTP client is not connected."); } try { // Send QUIT command to server. WriteLine("QUIT"); } catch {} m_LocalHostName = null; m_RemoteHostName = null; m_GreetingText = ""; m_IsEsmtpSupported = false; m_pEsmtpFeatures = null; m_MailFrom = null; m_pRecipients = null; m_pAuthdUserIdentity = null; try { base.Disconnect(); } catch {} } /// <summary> /// Starts sending NOOP command to server. This method can be used for keeping connection alive(not timing out). /// </summary> /// <param name="callback">Callback to call when the asynchronous operation is complete.</param> /// <param name="state">User data.</param> /// <returns>An IAsyncResult that references the asynchronous operation.</returns> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when SMTP client is not connected.</exception> public IAsyncResult BeginNoop(AsyncCallback callback, object state) { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (!IsConnected) { throw new InvalidOperationException("You must connect first."); } NoopDelegate asyncMethod = Noop; AsyncResultState asyncState = new AsyncResultState(this, asyncMethod, callback, state); asyncState.SetAsyncResult(asyncMethod.BeginInvoke(asyncState.CompletedCallback, null)); return asyncState; } /// <summary> /// Ends a pending asynchronous Noop request. /// </summary> /// <param name="asyncResult">An IAsyncResult that stores state information and any user defined data for this asynchronous operation.</param> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="ArgumentNullException">Is raised when <b>asyncResult</b> is null.</exception> /// <exception cref="ArgumentException">Is raised when invalid <b>asyncResult</b> passed to this method.</exception> /// <exception cref="SMTP_ClientException">Is raised when SMTP server returns error.</exception> public void EndNoop(IAsyncResult asyncResult) { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (asyncResult == null) { throw new ArgumentNullException("asyncResult"); } AsyncResultState castedAsyncResult = asyncResult as AsyncResultState; if (castedAsyncResult == null || castedAsyncResult.AsyncObject != this) { throw new ArgumentException( "Argument asyncResult was not returned by a call to the BeginNoop method."); } if (castedAsyncResult.IsEndCalled) { throw new InvalidOperationException( "BeginNoop was previously called for the asynchronous connection."); } castedAsyncResult.IsEndCalled = true; if (castedAsyncResult.AsyncDelegate is NoopDelegate) { ((NoopDelegate) castedAsyncResult.AsyncDelegate).EndInvoke(castedAsyncResult.AsyncResult); } else { throw new ArgumentException( "Argument asyncResult was not returned by a call to the BeginNoop method."); } } /// <summary> /// Send NOOP command to server. This method can be used for keeping connection alive(not timing out). /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when SMTP client is not connected.</exception> /// <exception cref="SMTP_ClientException">Is raised when SMTP server returns error.</exception> public void Noop() { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (!IsConnected) { throw new InvalidOperationException("You must connect first."); } /* RFC 2821 4.1.1.9 NOOP. This command does not affect any parameters or previously entered commands. It specifies no action other than that the receiver send an OK reply. Syntax: "NOOP" [ SP String ] CRLF */ WriteLine("NOOP"); string line = ReadLine(); if (!line.StartsWith("250")) { throw new SMTP_ClientException(line); } } /// <summary> /// Starts switching to SSL. /// </summary> /// <returns>An IAsyncResult that references the asynchronous operation.</returns> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when SMTP client is not connected or is already secure connection.</exception> public IAsyncResult BeginStartTLS(AsyncCallback callback, object state) { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (!IsConnected) { throw new InvalidOperationException("You must connect first."); } if (IsSecureConnection) { throw new InvalidOperationException("Connection is already secure."); } StartTLSDelegate asyncMethod = StartTLS; AsyncResultState asyncState = new AsyncResultState(this, asyncMethod, callback, state); asyncState.SetAsyncResult(asyncMethod.BeginInvoke(asyncState.CompletedCallback, null)); return asyncState; } /// <summary> /// Ends a pending asynchronous StartTLS request. /// </summary> /// <param name="asyncResult">An IAsyncResult that stores state information and any user defined data for this asynchronous operation.</param> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="ArgumentNullException">Is raised when <b>asyncResult</b> is null.</exception> /// <exception cref="ArgumentException">Is raised when invalid <b>asyncResult</b> passed to this method.</exception> /// <exception cref="SMTP_ClientException">Is raised when SMTP server returns error.</exception> public void EndStartTLS(IAsyncResult asyncResult) { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (asyncResult == null) { throw new ArgumentNullException("asyncResult"); } AsyncResultState castedAsyncResult = asyncResult as AsyncResultState; if (castedAsyncResult == null || castedAsyncResult.AsyncObject != this) { throw new ArgumentException( "Argument asyncResult was not returned by a call to the BeginReset method."); } if (castedAsyncResult.IsEndCalled) { throw new InvalidOperationException( "BeginReset was previously called for the asynchronous connection."); } castedAsyncResult.IsEndCalled = true; if (castedAsyncResult.AsyncDelegate is StartTLSDelegate) { ((StartTLSDelegate) castedAsyncResult.AsyncDelegate).EndInvoke(castedAsyncResult.AsyncResult); } else { throw new ArgumentException( "Argument asyncResult was not returned by a call to the BeginReset method."); } } /// <summary> /// Switches SMTP connection to SSL. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when SMTP client is not connected or is already secure connection.</exception> /// <exception cref="SMTP_ClientException">Is raised when SMTP server returns error.</exception> public void StartTLS() { /* RFC 2487 STARTTLS 5. STARTTLS Command. STARTTLS with no parameters. After the client gives the STARTTLS command, the server responds with one of the following reply codes: 220 Ready to start TLS 501 Syntax error (no parameters allowed) 454 TLS not available due to temporary reason */ if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (!IsConnected) { throw new InvalidOperationException("You must connect first."); } if (IsSecureConnection) { throw new InvalidOperationException("Connection is already secure."); } WriteLine("STARTTLS"); string line = ReadLine(); if (!line.ToUpper().StartsWith("220")) { throw new SMTP_ClientException(line); } SwitchToSecure(); } /// <summary> /// Starts authentication. /// </summary> /// <param name="userName">User login name.</param> /// <param name="password"><PASSWORD>.</param> /// <param name="callback">Callback to call when the asynchronous operation is complete.</param> /// <param name="state">User data.</param> /// <returns>An IAsyncResult that references the asynchronous operation.</returns> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when SMTP client is not connected or is already authenticated.</exception> public IAsyncResult BeginAuthenticate(string userName, string password, AsyncCallback callback, object state) { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (!IsConnected) { throw new InvalidOperationException("You must connect first."); } if (IsAuthenticated) { throw new InvalidOperationException("Session is already authenticated."); } AuthenticateDelegate asyncMethod = Authenticate; AsyncResultState asyncState = new AsyncResultState(this, asyncMethod, callback, state); asyncState.SetAsyncResult(asyncMethod.BeginInvoke(userName, password, asyncState.CompletedCallback, null)); return asyncState; } /// <summary> /// Ends a pending asynchronous authentication request. /// </summary> /// <param name="asyncResult">An IAsyncResult that stores state information and any user defined data for this asynchronous operation.</param> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="ArgumentNullException">Is raised when <b>asyncResult</b> is null.</exception> /// <exception cref="ArgumentException">Is raised when invalid <b>asyncResult</b> passed to this method.</exception> /// <exception cref="SMTP_ClientException">Is raised when SMTP server returns error.</exception> public void EndAuthenticate(IAsyncResult asyncResult) { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (asyncResult == null) { throw new ArgumentNullException("asyncResult"); } AsyncResultState castedAsyncResult = asyncResult as AsyncResultState; if (castedAsyncResult == null || castedAsyncResult.AsyncObject != this) { throw new ArgumentException( "Argument 'asyncResult' was not returned by a call to the BeginAuthenticate method."); } if (castedAsyncResult.IsEndCalled) { throw new InvalidOperationException( "BeginAuthenticate was previously called for the asynchronous connection."); } castedAsyncResult.IsEndCalled = true; if (castedAsyncResult.AsyncDelegate is AuthenticateDelegate) { ((AuthenticateDelegate) castedAsyncResult.AsyncDelegate).EndInvoke( castedAsyncResult.AsyncResult); } else { throw new ArgumentException( "Argument asyncResult was not returned by a call to the BeginAuthenticate method."); } } /// <summary> /// Authenticates user. Authenticate method chooses strongest possible authentication method supported by server, /// preference order DIGEST-MD5 -> CRAM-MD5 -> LOGIN. /// </summary> /// <param name="userName">User login name.</param> /// <param name="password"><PASSWORD>.</param> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when SMTP client is not connected or is already authenticated.</exception> /// <exception cref="ArgumentNullException">Is raised when <b>userName</b> is null.</exception> /// <exception cref="SMTP_ClientException">Is raised when SMTP server returns error.</exception> public void Authenticate(string userName, string password) { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (!IsConnected) { throw new InvalidOperationException("You must connect first."); } if (IsAuthenticated) { throw new InvalidOperationException("Session is already authenticated."); } if (string.IsNullOrEmpty(userName)) { throw new ArgumentNullException("userName"); } if (password == null) { password = ""; } // Choose authentication method, we consider LOGIN as default. string authMethod = "LOGIN"; List<string> authMethods = new List<string>(SaslAuthMethods); if (authMethods.Contains("DIGEST-MD5")) { authMethod = "DIGEST-MD5"; } else if (authMethods.Contains("CRAM-MD5")) { authMethod = "CRAM-MD5"; } #region AUTH LOGIN if (authMethod == "LOGIN") { /* LOGIN Example: C: AUTH LOGIN<CRLF> S: 334 VXNlcm5hbWU6<CRLF> VXNlcm5hbWU6 = base64("USERNAME") C: base64(username)<CRLF> S: 334 UGFzc3dvcmQ6<CRLF> UGFzc3dvcmQ6 = base64("PASSWORD") C: base64(password)<CRLF> S: 235 Ok<CRLF> */ WriteLine("AUTH LOGIN"); // Read server response. string line = ReadLine(); // Response line must start with 334 or otherwise it's error response. if (!line.StartsWith("334")) { throw new SMTP_ClientException(line); } // Send user name to server. WriteLine(Convert.ToBase64String(Encoding.ASCII.GetBytes(userName))); // Read server response. line = ReadLine(); // Response line must start with 334 or otherwise it's error response. if (!line.StartsWith("334")) { throw new SMTP_ClientException(line); } // Send password to server. WriteLine(Convert.ToBase64String(Encoding.ASCII.GetBytes(password))); // Read server response. line = ReadLine(); // Response line must start with 334 or otherwise it's error response. if (!line.StartsWith("235")) { throw new SMTP_ClientException(line); } m_pAuthdUserIdentity = new GenericIdentity(userName, "LOGIN"); } #endregion #region AUTH CRAM-MD5 else if (authMethod == "CRAM-MD5") { /* CRAM-M5 Description: HMACMD5 key is "password". Example: C: AUTH CRAM-MD5<CRLF> S: 334 base64(md5_calculation_hash)<CRLF> C: base64(username password_hash)<CRLF> S: 235 Ok<CRLF> */ WriteLine("AUTH CRAM-MD5"); // Read server response. string line = ReadLine(); // Response line must start with 334 or otherwise it's error response. if (!line.StartsWith("334")) { throw new SMTP_ClientException(line); } HMACMD5 kMd5 = new HMACMD5(Encoding.ASCII.GetBytes(password)); string passwordHash = Core.ToHexString(kMd5.ComputeHash(Convert.FromBase64String(line.Split(' ')[1]))).ToLower(); // Send authentication info to server. WriteLine(Convert.ToBase64String(Encoding.ASCII.GetBytes(userName + " " + passwordHash))); // Read server response. line = ReadLine(); // Response line must start with 235 or otherwise it's error response if (!line.StartsWith("235")) { throw new SMTP_ClientException(line); } m_pAuthdUserIdentity = new GenericIdentity(userName, "CRAM-MD5"); } #endregion #region AUTH DIGEST-MD5 else if (authMethod == "DIGEST-MD5") { /* Example: C: AUTH DIGEST-MD5<CRLF> S: 334 base64(digestChallange)<CRLF> C: base64(digestAuthorization)<CRLF> S: 334 base64(serverResponse)<CRLF> C: <CRLF> S: 235 Ok<CRLF> */ WriteLine("AUTH DIGEST-MD5"); // Read server response. string line = ReadLine(); // Response line must start with 334 or otherwise it's error response. if (!line.StartsWith("334")) { throw new SMTP_ClientException(line); } Auth_HttpDigest digestmd5 = new Auth_HttpDigest( Encoding.Default.GetString(Convert.FromBase64String(line.Split(' ')[1])), "AUTHENTICATE"); digestmd5.CNonce = Auth_HttpDigest.CreateNonce(); digestmd5.Uri = "smtp/" + digestmd5.Realm; digestmd5.UserName = userName; digestmd5.Password = <PASSWORD>; // Send authentication info to server. WriteLine(Convert.ToBase64String(Encoding.ASCII.GetBytes(digestmd5.ToAuthorization(false)))); // Read server response. line = ReadLine(); // Response line must start with 334 or otherwise it's error response. if (!line.StartsWith("334")) { throw new SMTP_ClientException(line); } // Send empty line. WriteLine(""); // Read server response. line = ReadLine(); // Response line must start with 235 or otherwise it's error response. if (!line.StartsWith("235")) { throw new SMTP_ClientException(line); } m_pAuthdUserIdentity = new GenericIdentity(userName, "<PASSWORD>"); } #endregion } /// <summary> /// Starts sending MAIL FROM: command to SMTP server. /// </summary> /// <param name="from">Sender email address reported to SMTP server.</param> /// <param name="messageSize">Sendable message size in bytes, -1 if message size unknown.</param> /// <param name="callback">Callback to call when the asynchronous operation is complete.</param> /// <param name="state">User data.</param> /// <returns>An IAsyncResult that references the asynchronous disconnect.</returns> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when SMTP client is not connected.</exception> public IAsyncResult BeginMailFrom(string from, long messageSize, AsyncCallback callback, object state) { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (!IsConnected) { throw new InvalidOperationException("You must connect first."); } MailFromDelegate asyncMethod = MailFrom; AsyncResultState asyncState = new AsyncResultState(this, asyncMethod, callback, state); asyncState.SetAsyncResult(asyncMethod.BeginInvoke(from, messageSize, asyncState.CompletedCallback, null)); return asyncState; } /// <summary> /// Ends a pending asynchronous MailFrom request. /// </summary> /// <param name="asyncResult">An IAsyncResult that stores state information and any user defined data for this asynchronous operation.</param> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="ArgumentNullException">Is raised when <b>asyncResult</b> is null.</exception> /// <exception cref="ArgumentException">Is raised when invalid <b>asyncResult</b> passed to this method.</exception> /// <exception cref="SMTP_ClientException">Is raised when SMTP server returns error.</exception> public void EndMailFrom(IAsyncResult asyncResult) { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (asyncResult == null) { throw new ArgumentNullException("asyncResult"); } AsyncResultState castedAsyncResult = asyncResult as AsyncResultState; if (castedAsyncResult == null || castedAsyncResult.AsyncObject != this) { throw new ArgumentException( "Argument asyncResult was not returned by a call to the BeginReset method."); } if (castedAsyncResult.IsEndCalled) { throw new InvalidOperationException( "BeginReset was previously called for the asynchronous connection."); } castedAsyncResult.IsEndCalled = true; if (castedAsyncResult.AsyncDelegate is MailFromDelegate) { ((MailFromDelegate) castedAsyncResult.AsyncDelegate).EndInvoke(castedAsyncResult.AsyncResult); } else { throw new ArgumentException( "Argument asyncResult was not returned by a call to the BeginReset method."); } } /// <summary> /// Sends MAIL FROM: command to SMTP server. /// </summary> /// <param name="from">Sender email address reported to SMTP server.</param> /// <param name="messageSize">Sendable message size in bytes, -1 if message size unknown.</param> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when SMTP client is not connected.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> /// <exception cref="SMTP_ClientException">Is raised when SMTP server returns error.</exception> public void MailFrom(string from, long messageSize) { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (!IsConnected) { throw new InvalidOperationException("You must connect first."); } if (!SMTP_Utils.IsValidAddress(from)) { throw new ArgumentException("Argument from has invalid value."); } /* RFC 2821 4.1.1.2 MAIL Examples: MAIL FROM:<<EMAIL>> RFC 1870 adds optional SIZE keyword support. SIZE keyword may only be used if it's reported in EHLO command response. Examples: MAIL FROM:<<EMAIL>> SIZE=1000 */ bool isSizeSupported = false; foreach (string feature in m_pEsmtpFeatures) { if (feature.ToLower() == "size") { isSizeSupported = true; break; } } string line = "MAIL FROM:<" + from + ">"; if (isSizeSupported && messageSize > 0) { line = "MAIL FROM:<" + from + "> SIZE=" + messageSize; } WriteLine(line); // Read first line of reply, check if it's ok. line = ReadLine(); if (!line.StartsWith("250")) { throw new SMTP_ClientException(line); } m_MailFrom = from; } /// <summary> /// Starts sending RCPT TO: command to SMTP server. /// </summary> /// <param name="to">Recipient email address.</param> /// <param name="callback">Callback to call when the asynchronous operation is complete.</param> /// <param name="state">User data.</param> /// <returns>An IAsyncResult that references the asynchronous disconnect.</returns> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when SMTP client is not connected.</exception> public IAsyncResult BeginRcptTo(string to, AsyncCallback callback, object state) { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (!IsConnected) { throw new InvalidOperationException("You must connect first."); } RcptToDelegate asyncMethod = RcptTo; AsyncResultState asyncState = new AsyncResultState(this, asyncMethod, callback, state); asyncState.SetAsyncResult(asyncMethod.BeginInvoke(to, asyncState.CompletedCallback, null)); return asyncState; } /// <summary> /// Ends a pending asynchronous RcptTo request. /// </summary> /// <param name="asyncResult">An IAsyncResult that stores state information and any user defined data for this asynchronous operation.</param> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="ArgumentNullException">Is raised when <b>asyncResult</b> is null.</exception> /// <exception cref="ArgumentException">Is raised when invalid <b>asyncResult</b> passed to this method.</exception> /// <exception cref="SMTP_ClientException">Is raised when SMTP server returns error.</exception> public void EndRcptTo(IAsyncResult asyncResult) { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (asyncResult == null) { throw new ArgumentNullException("asyncResult"); } AsyncResultState castedAsyncResult = asyncResult as AsyncResultState; if (castedAsyncResult == null || castedAsyncResult.AsyncObject != this) { throw new ArgumentException( "Argument asyncResult was not returned by a call to the BeginReset method."); } if (castedAsyncResult.IsEndCalled) { throw new InvalidOperationException( "BeginReset was previously called for the asynchronous connection."); } castedAsyncResult.IsEndCalled = true; if (castedAsyncResult.AsyncDelegate is RcptToDelegate) { ((RcptToDelegate) castedAsyncResult.AsyncDelegate).EndInvoke(castedAsyncResult.AsyncResult); } else { throw new ArgumentException( "Argument asyncResult was not returned by a call to the BeginReset method."); } } /// <summary> /// Sends RCPT TO: command to SMTP server. /// </summary> /// <param name="to">Recipient email address.</param> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when SMTP client is not connected.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> /// <exception cref="SMTP_ClientException">Is raised when SMTP server returns error.</exception> public void RcptTo(string to) { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (!IsConnected) { throw new InvalidOperationException("You must connect first."); } if (!SMTP_Utils.IsValidAddress(to)) { throw new ArgumentException("Argument from has invalid value."); } /* RFC 2821 4.1.1.2 RCPT. Syntax: "RCPT TO:" ("<Postmaster@" domain ">" / "<Postmaster>" / Forward-Path) [SP Rcpt-parameters] CRLF Examples: RCPT TO:<<EMAIL>> */ WriteLine("RCPT TO:<" + to + ">"); // Read first line of reply, check if it's ok. string line = ReadLine(); if (!line.StartsWith("250")) { throw new SMTP_ClientException(line); } if (!m_pRecipients.Contains(to)) { m_pRecipients.Add(to); } } /// <summary> /// Starts resetting SMTP session, all state data will be deleted. /// </summary> /// <param name="callback">Callback to call when the asynchronous operation is complete.</param> /// <param name="state">User data.</param> /// <returns>An IAsyncResult that references the asynchronous disconnect.</returns> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when SMTP client is not connected.</exception> public IAsyncResult BeginReset(AsyncCallback callback, object state) { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (!IsConnected) { throw new InvalidOperationException("You must connect first."); } ResetDelegate asyncMethod = Reset; AsyncResultState asyncState = new AsyncResultState(this, asyncMethod, callback, state); asyncState.SetAsyncResult(asyncMethod.BeginInvoke(asyncState.CompletedCallback, null)); return asyncState; } /// <summary> /// Ends a pending asynchronous reset request. /// </summary> /// <param name="asyncResult">An IAsyncResult that stores state information and any user defined data for this asynchronous operation.</param> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="ArgumentNullException">Is raised when <b>asyncResult</b> is null.</exception> /// <exception cref="ArgumentException">Is raised when invalid <b>asyncResult</b> passed to this method.</exception> /// <exception cref="SMTP_ClientException">Is raised when SMTP server returns error.</exception> public void EndReset(IAsyncResult asyncResult) { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (asyncResult == null) { throw new ArgumentNullException("asyncResult"); } AsyncResultState castedAsyncResult = asyncResult as AsyncResultState; if (castedAsyncResult == null || castedAsyncResult.AsyncObject != this) { throw new ArgumentException( "Argument asyncResult was not returned by a call to the BeginReset method."); } if (castedAsyncResult.IsEndCalled) { throw new InvalidOperationException( "BeginReset was previously called for the asynchronous connection."); } castedAsyncResult.IsEndCalled = true; if (castedAsyncResult.AsyncDelegate is ResetDelegate) { ((ResetDelegate) castedAsyncResult.AsyncDelegate).EndInvoke(castedAsyncResult.AsyncResult); } else { throw new ArgumentException( "Argument asyncResult was not returned by a call to the BeginReset method."); } } /// <summary> /// Resets SMTP session, all state data will be deleted. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when SMTP client is not connected.</exception> /// <exception cref="SMTP_ClientException">Is raised when SMTP server returns error.</exception> public void Reset() { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (!IsConnected) { throw new InvalidOperationException("You must connect first."); } /* RFC 2821 4.1.1.5 RESET (RSET). This command specifies that the current mail transaction will be aborted. Any stored sender, recipients, and mail data MUST be discarded, and all buffers and state tables cleared. The receiver MUST send a "250 OK" reply to a RSET command with no arguments. A reset command may be issued by the client at any time. */ WriteLine("RSET"); string line = ReadLine(); if (!line.StartsWith("250")) { throw new SMTP_ClientException(line); } m_MailFrom = null; m_pRecipients.Clear(); } /// <summary> /// Starts sending specified raw message to SMTP server. /// </summary> /// <param name="message">Message stream. Message will be readed from current stream position and to the end of stream.</param> /// <param name="callback">Callback to call when the asynchronous operation is complete.</param> /// <param name="state">User data.</param> /// <returns>An IAsyncResult that references the asynchronous method.</returns> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when SMTP client is not connected.</exception> /// <exception cref="ArgumentNullException">Is raised when <b>message</b> is null.</exception> public IAsyncResult BeginSendMessage(Stream message, AsyncCallback callback, object state) { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (!IsConnected) { throw new InvalidOperationException("You must connect first."); } if (message == null) { throw new ArgumentNullException("message"); } SendMessageDelegate asyncMethod = SendMessage; AsyncResultState asyncState = new AsyncResultState(this, asyncMethod, callback, state); asyncState.SetAsyncResult(asyncMethod.BeginInvoke(message, asyncState.CompletedCallback, null)); return asyncState; } /// <summary> /// Ends a pending asynchronous SendMessage request. /// </summary> /// <param name="asyncResult">An IAsyncResult that stores state information and any user defined data for this asynchronous operation.</param> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="ArgumentNullException">Is raised when <b>asyncResult</b> is null.</exception> /// <exception cref="ArgumentException">Is raised when invalid <b>asyncResult</b> passed to this method.</exception> /// <exception cref="SMTP_ClientException">Is raised when SMTP server returns error.</exception> public void EndSendMessage(IAsyncResult asyncResult) { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (asyncResult == null) { throw new ArgumentNullException("asyncResult"); } AsyncResultState castedAsyncResult = asyncResult as AsyncResultState; if (castedAsyncResult == null || castedAsyncResult.AsyncObject != this) { throw new ArgumentException( "Argument asyncResult was not returned by a call to the BeginSendMessage method."); } if (castedAsyncResult.IsEndCalled) { throw new InvalidOperationException( "BeginSendMessage was previously called for the asynchronous connection."); } castedAsyncResult.IsEndCalled = true; if (castedAsyncResult.AsyncDelegate is SendMessageDelegate) { ((SendMessageDelegate) castedAsyncResult.AsyncDelegate).EndInvoke( castedAsyncResult.AsyncResult); } else { throw new ArgumentException( "Argument asyncResult was not returned by a call to the BeginSendMessage method."); } } /// <summary> /// Sends specified raw message to SMTP server. /// </summary> /// <param name="message">Message stream. Message will be readed from current stream position and to the end of stream.</param> /// <remarks>The stream must contain data in MIME format, other formats normally are rejected by SMTP server.</remarks> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when SMTP client is not connected.</exception> /// <exception cref="ArgumentNullException">Is raised when <b>message</b> is null.</exception> /// <exception cref="SMTP_ClientException">Is raised when SMTP server returns error.</exception> public void SendMessage(Stream message) { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (!IsConnected) { throw new InvalidOperationException("You must connect first."); } if (message == null) { throw new ArgumentNullException("message"); } // See if BDAT supported. bool bdatSupported = false; foreach (string feature in EsmtpFeatures) { if (feature.ToUpper() == SMTP_ServiceExtensions.CHUNKING) { bdatSupported = true; break; } } #region DATA if (!bdatSupported) { /* RFC 2821 4.1.1.4 DATA Notes: Message must be period handled for DATA command. This meas if message line starts with ., additional .(period) must be added. Message send is ended with <CRLF>.<CRLF>. Examples: C: DATA<CRLF> S: 354 Start sending message, end with <crlf>.<crlf><CRLF> C: send_message C: <CRLF>.<CRLF> S: 250 Ok<CRLF> */ WriteLine("DATA"); string line = ReadLine(); if (line.StartsWith("354")) { long writtenCount = TcpStream.WritePeriodTerminated(message); LogAddWrite(writtenCount, "Wrote " + writtenCount + " bytes."); // Read server reply. line = ReadLine(); if (!line.StartsWith("250")) { throw new SMTP_ClientException(line); } } else { throw new SMTP_ClientException(line); } } #endregion #region BDAT else { /* RFC 3030 BDAT Syntax: BDAT<SP>ChunkSize[<SP>LAST]<CRLF> Exapmle: C: BDAT 1000 LAST<CRLF> C: send_1000_byte_message S: 250 OK<CRLF> */ // TODO: Get rid of BDAT 0 LAST, this is valid syntax but many servers can't handle it. // We just read 1 buffer ahead, then you see when source stream has EOS. byte[] buffer1 = new byte[16000]; byte[] buffer2 = new byte[16000]; byte[] currentBuffer = buffer1; byte[] lastBuffer = buffer2; int lastReadedCount = 0; // Buffer first data block. lastReadedCount = message.Read(lastBuffer, 0, lastBuffer.Length); while (true) { // Read data block to free buffer. int readedCount = message.Read(currentBuffer, 0, currentBuffer.Length); // End of stream reached, "last data block" is last one. if (readedCount == 0) { WriteLine("BDAT " + lastReadedCount + " LAST"); TcpStream.Write(lastBuffer, 0, lastReadedCount); LogAddWrite(readedCount, "Wrote " + lastReadedCount + " bytes."); // Read server response. string line = ReadLine(); if (!line.StartsWith("250")) { throw new SMTP_ClientException(line); } // We are done, exit while. break; } // Send last data block, free it up for reuse. else { WriteLine("BDAT " + lastReadedCount); TcpStream.Write(lastBuffer, 0, lastReadedCount); LogAddWrite(readedCount, "Wrote " + lastReadedCount + " bytes."); // Read server response. string line = ReadLine(); if (!line.StartsWith("250")) { throw new SMTP_ClientException(line); } // Mark last buffer as current(free it up), just mark current buffer as last for next while cycle. byte[] tmp = lastBuffer; lastBuffer = currentBuffer; currentBuffer = tmp; } lastReadedCount = readedCount; } } #endregion } #endregion #region Overrides /// <summary> /// This method is called after TCP client has sucessfully connected. /// </summary> protected override void OnConnected() { /* Notes: Greeting may be single or multiline response. Examples: 220<SP>SMTP server ready<CRLF> 220-SMTP server ready<CRLF> 220-Addtitional text<CRLF> 220<SP>final row<CRLF> */ StringBuilder response = new StringBuilder(); string line = ReadLine(); response.AppendLine(line); // Read multiline response. while (line.Length >= 4 && line[3] == '-') { line = ReadLine(); response.AppendLine(line); } if (line.StartsWith("220")) { m_GreetingText = response.ToString(); } else { throw new SMTP_ClientException(response.ToString()); } #region EHLO/HELO // If local host name not specified, get local computer name. string localHostName = m_LocalHostName; if (string.IsNullOrEmpty(localHostName)) { localHostName = Dns.GetHostName(); } // Do EHLO/HELO. WriteLine("EHLO " + localHostName); // Read server response. line = ReadLine(); if (line.StartsWith("250")) { m_IsEsmtpSupported = true; /* RFC 2821 172.16.58.3 EHLO Examples: C: EHLO domain<CRLF> S: 250-domain freeText<CRLF> S: 250-EHLO_keyword<CRLF> S: 250 EHLO_keyword<CRLF> 250<SP> specifies that last EHLO response line. */ // We may have 250- or 250 SP as domain separator. // 250- if (line.StartsWith("250-")) { m_RemoteHostName = line.Substring(4).Split(new[] {' '}, 2)[0]; } // 250 SP else { m_RemoteHostName = line.Split(new[] {' '}, 3)[1]; } m_pEsmtpFeatures = new List<string>(); // Read multiline response, EHLO keywords. while (line.StartsWith("250-")) { line = ReadLine(); if (line.StartsWith("250-")) { m_pEsmtpFeatures.Add(line.Substring(4)); } } } // Probably EHLO not supported, try HELO. else { m_IsEsmtpSupported = false; m_pEsmtpFeatures = new List<string>(); WriteLine("HELO " + localHostName); line = ReadLine(); if (line.StartsWith("250")) { /* Rfc 2821 4.1.1.1 EHLO/HELO Syntax: "HELO" SP Domain CRLF Examples: C: HELO domain<CRLF> S: 250 domain freeText<CRLF> */ m_RemoteHostName = line.Split(new[] {' '}, 3)[1]; } // Server rejects us for some reason. else { throw new SMTP_ClientException(line); } } #endregion m_pRecipients = new List<string>(); } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/MIME/MIME_b_MessageRfc822.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.MIME { #region usings using System; using System.IO; using System.Text; using IO; using Mail; #endregion /// <summary> /// This class represents MIME message/rfc822 body. Defined in RFC 2046 5.2.1. /// </summary> public class MIME_b_MessageRfc822 : MIME_b { #region Members private Mail_Message m_pMessage; #endregion #region Properties /// <summary> /// Gets if body has modified. /// </summary> public override bool IsModified { get { return m_pMessage.IsModified; } } /// <summary> /// Gets embbed mail message. /// </summary> public Mail_Message Message { get { return m_pMessage; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> public MIME_b_MessageRfc822() : base(new MIME_h_ContentType("message/rfc822")) { m_pMessage = new Mail_Message(); } #endregion #region Overrides /// <summary> /// Stores MIME entity body to the specified stream. /// </summary> /// <param name="stream">Stream where to store body data.</param> /// <param name="headerWordEncoder">Header 8-bit words ecnoder. Value null means that words are not encoded.</param> /// <param name="headerParmetersCharset">Charset to use to encode 8-bit header parameters. Value null means parameters not encoded.</param> /// <exception cref="ArgumentNullException">Is raised when <b>stream</b> is null reference.</exception> protected internal override void ToStream(Stream stream, MIME_Encoding_EncodedWord headerWordEncoder, Encoding headerParmetersCharset) { if (stream == null) { throw new ArgumentNullException("stream"); } m_pMessage.ToStream(stream, headerWordEncoder, headerParmetersCharset); } #endregion /// <summary> /// Parses body from the specified stream /// </summary> /// <param name="owner">Owner MIME entity.</param> /// <param name="mediaType">MIME media type. For example: text/plain.</param> /// <param name="stream">Stream from where to read body.</param> /// <returns>Returns parsed body.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>stream</b>, <b>mediaType</b> or <b>stream</b> is null reference.</exception> /// <exception cref="ParseException">Is raised when any parsing errors.</exception> protected new static MIME_b Parse(MIME_Entity owner, string mediaType, SmartStream stream) { if (owner == null) { throw new ArgumentNullException("owner"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } if (stream == null) { throw new ArgumentNullException("stream"); } MIME_b_MessageRfc822 retVal = new MIME_b_MessageRfc822(); if (owner.ContentTransferEncoding != null && owner.ContentTransferEncoding.Equals("base64", StringComparison.OrdinalIgnoreCase)) { Stream decodedDataStream = new MemoryStream(); using (StreamReader reader = new StreamReader(stream)) { byte[] decoded = Convert.FromBase64String(reader.ReadToEnd()); decodedDataStream.Write(decoded, 0, decoded.Length); decodedDataStream.Seek(0, SeekOrigin.Begin); } //Create base64 decoder stream = new SmartStream(decodedDataStream,true); } retVal.m_pMessage = Mail_Message.ParseFromStream(stream); return retVal; } } }<file_sep>/module/ASC.Api/ASC.Api.Mail/MailApi.Tags.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections.Generic; using System.Linq; using System.Threading; using ASC.Api.Attributes; using ASC.Mail.Data.Contracts; using ASC.Mail.Extensions; using ASC.Web.Mail.Resources; namespace ASC.Api.Mail { public partial class MailApi { /// <summary> /// Returns list of the tags used in Mail /// </summary> /// <returns>Tags list. Tags represented as JSON.</returns> /// <short>Get tags list</short> /// <category>Tags</category> [Read(@"tags")] public IEnumerable<MailTagData> GetTags() { return MailEngineFactory.TagEngine.GetTags().ToTagData(); } /// <summary> /// Creates a new tag /// </summary> /// <param name="name">Tag name represented as string</param> /// <param name="style">Style identificator. With postfix will be added to tag css style whe it will represent. Specifies color of tag.</param> /// <param name="addresses">Specifies list of addresses tag associated with.</param> /// <returns>MailTag</returns> /// <short>Create tag</short> /// <category>Tags</category> /// <exception cref="ArgumentException">Exception happens when in parameters is invalid. Text description contains parameter name and text description.</exception> [Create(@"tags")] public MailTagData CreateTag(string name, string style, IEnumerable<string> addresses) { //TODO: Is it necessary? Thread.CurrentThread.CurrentCulture = CurrentCulture; Thread.CurrentThread.CurrentUICulture = CurrentCulture; if (string.IsNullOrEmpty(name)) throw new ArgumentException(MailApiResource.ErrorTagNameCantBeEmpty); if (MailEngineFactory.TagEngine.IsTagExists(name)) throw new ArgumentException(MailApiResource.ErrorTagNameAlreadyExists.Replace("%1", "\"" + name + "\"")); return MailEngineFactory.TagEngine.CreateTag(name, style, addresses).ToTagData(); } /// <summary> /// Updates the selected tag /// </summary> /// <param name="id"></param> /// <param name="name">Tag name represented as string</param> /// <param name="style">Style identificator. With postfix will be added to tag css style whe it will represent. Specifies color of tag.</param> /// <param name="addresses">Specifies list of addresses tag associated with.</param> /// <returns>Updated MailTag</returns> /// <short>Update tag</short> /// <category>Tags</category> /// <exception cref="ArgumentException">Exception happens when in parameters is invalid. Text description contains parameter name and text description.</exception> [Update(@"tags/{id}")] public MailTagData UpdateTag(int id, string name, string style, IEnumerable<string> addresses) { if (id < 0) throw new ArgumentException(@"Invalid tag id", "id"); //TODO: Is it necessary? Thread.CurrentThread.CurrentCulture = CurrentCulture; Thread.CurrentThread.CurrentUICulture = CurrentCulture; if (string.IsNullOrEmpty(name)) throw new ArgumentException(MailApiResource.ErrorTagNameCantBeEmpty); try { var tag = MailEngineFactory.TagEngine.UpdateTag(id, name, style, addresses); return tag.ToTagData(); } catch (ArgumentException ex) { if (ex.Message.Equals("Tag name already exists")) throw new ArgumentException(MailApiResource.ErrorTagNameAlreadyExists.Replace("%1", "\"" + name + "\"")); throw; } } /// <summary> /// Deletes the selected tag from TLMail /// </summary> /// <param name="id">Tag for deleting id</param> /// <returns>Deleted MailTag</returns> /// <short>Delete tag</short> /// <category>Tags</category> /// <exception cref="ArgumentException">Exception happens when in parameters is invalid. Text description contains parameter name and text description.</exception> [Delete(@"tags/{id}")] public int DeleteTag(int id) { if (id < 0) throw new ArgumentException(@"Invalid tag id", "id"); if (!MailEngineFactory.TagEngine.DeleteTag(id)) throw new Exception("DeleteTag failed"); return id; } /// <summary> /// Adds the selected tag to the messages /// </summary> /// <param name="id">Tag for setting id</param> /// <param name="messages">Messages id for setting.</param> /// <returns>Setted MailTag</returns> /// <short>Set tag to messages</short> /// <category>Tags</category> /// <exception cref="ArgumentException">Exception happens when in parameters is invalid. Text description contains parameter name and text description.</exception> [Update(@"tags/{id}/set")] public int SetTag(int id, List<int> messages) { if (!messages.Any()) throw new ArgumentException(@"Messages are empty", "messages"); MailEngineFactory.TagEngine.SetMessagesTag(messages, id); return id; } /// <summary> /// Removes the specified tag from messages /// </summary> /// <param name="id">Tag for removing id</param> /// <param name="messages">Messages id for removing.</param> /// <returns>Removed mail tag</returns> /// <short>Remove tag from messages</short> /// <category>Tags</category> /// <exception cref="ArgumentException">Exception happens when parameters are invalid. Text description contains parameter name and text description.</exception> [Update(@"tags/{id}/unset")] public int UnsetTag(int id, List<int> messages) { if (!messages.Any()) throw new ArgumentException(@"Messages are empty", "messages"); MailEngineFactory.TagEngine.UnsetMessagesTag(messages, id); return id; } } } <file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/RTP/RTCP_Packet_BYE.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.RTP { #region usings using System; using System.Text; #endregion /// <summary> /// This class represents BYE: Goodbye RTCP Packet. /// </summary> public class RTCP_Packet_BYE : RTCP_Packet { #region Members private string m_LeavingReason = ""; private uint[] m_Sources; private int m_Version = 2; #endregion #region Properties /// <summary> /// Gets RTCP version. /// </summary> public override int Version { get { return m_Version; } } /// <summary> /// Gets RTCP packet type. /// </summary> public override int Type { get { return RTCP_PacketType.BYE; } } /// <summary> /// Gets or sets SSRC/CSRC identifiers included in this BYE packet. /// </summary> /// <exception cref="ArgumentException">Is raised when invalid value is passed.</exception> public uint[] Sources { get { return m_Sources; } set { if (value.Length > 31) { throw new ArgumentException("Property 'Sources' can accomodate only 31 entries."); } m_Sources = value; } } /// <summary> /// Gets leaving reason. /// </summary> public string LeavingReason { get { return m_LeavingReason; } set { m_LeavingReason = value; } } /// <summary> /// Gets number of bytes needed for this packet. /// </summary> public override int Size { get { int size = 4; if (m_Sources != null) { size += 4*m_Sources.Length; } if (!string.IsNullOrEmpty(m_LeavingReason)) { size += Encoding.UTF8.GetByteCount(m_LeavingReason); } return size; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> internal RTCP_Packet_BYE() {} #endregion #region Methods /// <summary> /// Stores BYE packet to the specified buffer. /// </summary> /// <param name="buffer">Buffer where to store BYE packet.</param> /// <param name="offset">Offset in buffer.</param> /// <exception cref="ArgumentNullException">Is raised when <b>buffer</b> is null.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> public override void ToByte(byte[] buffer, ref int offset) { /* RFC 3550.6.6 BYE: Goodbye RTCP Packet. 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |V=2|P| SC | PT=BYE=203 | length | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | SSRC/CSRC | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ : ... : +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ (opt) | length | reason for leaving ... +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ if (buffer == null) { throw new ArgumentNullException("buffer"); } if (offset < 0) { throw new ArgumentException("Argument 'offset' value must be >= 0."); } // Calculate packet body size in bytes. int length = 0; length += m_Sources.Length*4; if (!string.IsNullOrEmpty(m_LeavingReason)) { length += Encoding.UTF8.GetByteCount(m_LeavingReason); } // V=2 P SC buffer[offset++] = (byte) (2 << 6 | 0 << 5 | m_Sources.Length & 0x1F); // PT=BYE=203 buffer[offset++] = 203; // length buffer[offset++] = (byte) ((length >> 8) & 0xFF); buffer[offset++] = (byte) (length & 0xFF); // SSRC/CSRC's foreach (int source in m_Sources) { buffer[offset++] = (byte) ((source & 0xFF000000) >> 24); buffer[offset++] = (byte) ((source & 0x00FF0000) >> 16); buffer[offset++] = (byte) ((source & 0x0000FF00) >> 8); buffer[offset++] = (byte) ((source & 0x000000FF)); } // reason for leaving if (!string.IsNullOrEmpty(m_LeavingReason)) { byte[] reasonBytes = Encoding.UTF8.GetBytes(m_LeavingReason); buffer[offset++] = (byte) reasonBytes.Length; Array.Copy(reasonBytes, 0, buffer, offset, reasonBytes.Length); offset += reasonBytes.Length; } } #endregion #region Overrides /// <summary> /// Parses BYE packet from raw byte[] bye packet. /// </summary> /// <param name="buffer">Buffer what contains BYE packet.</param> /// <param name="offset">Offset in buffer.</param> /// <exception cref="ArgumentNullException">Is raised when <b>buffer</b> is null.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> protected override void ParseInternal(byte[] buffer, ref int offset) { /* RFC 3550.6.6 BYE: Goodbye RTCP Packet. 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |V=2|P| SC | PT=BYE=203 | length | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | SSRC/CSRC | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ : ... : +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ (opt) | length | reason for leaving ... +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ if (buffer == null) { throw new ArgumentNullException("buffer"); } if (offset < 0) { throw new ArgumentException("Argument 'offset' value must be >= 0."); } m_Version = buffer[offset] >> 6; bool isPadded = Convert.ToBoolean((buffer[offset] >> 5) & 0x1); int sourceCount = buffer[offset++] & 0x1F; int type = buffer[offset++]; int length = buffer[offset++] << 8 | buffer[offset++]; if (isPadded) { PaddBytesCount = buffer[offset + length]; } m_Sources = new uint[sourceCount]; for (int i = 0; i < sourceCount; i++) { m_Sources[i] = (uint) (buffer[offset++] << 24 | buffer[offset++] << 16 | buffer[offset++] << 8 | buffer[offset++]); } // See if we have optional reason text. if (length > m_Sources.Length*4) { int reasonLength = buffer[offset++]; m_LeavingReason = Encoding.UTF8.GetString(buffer, offset, reasonLength); offset += reasonLength; } } #endregion } }<file_sep>/module/ASC.AuditTrail/Mappers/AuditActionMapper.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections.Generic; using ASC.MessagingSystem; using System.Linq; namespace ASC.AuditTrail.Mappers { public class AuditActionMapper { private static readonly Dictionary<MessageAction, MessageMaps> actions; static AuditActionMapper() { actions = new Dictionary<MessageAction, MessageMaps>(); actions = actions .Union(LoginActionsMapper.GetMaps()) .Union(ProjectsActionsMapper.GetMaps()) .Union(CrmActionMapper.GetMaps()) .Union(PeopleActionMapper.GetMaps()) .Union(DocumentsActionMapper.GetMaps()) .Union(SettingsActionsMapper.GetMaps()) .Union(OthersActionsMapper.GetMaps()) .ToDictionary(x => x.Key, x => x.Value); } public static string GetActionText(AuditEvent evt) { var action = (MessageAction)evt.Action; if (!actions.ContainsKey(action)) { //log.Error(string.Format("There is no action text for \"{0}\" type of event", action)); return string.Empty; } try { var actionText = actions[(MessageAction)evt.Action].GetActionText(); if (evt.Description == null || !evt.Description.Any()) return actionText; var description = evt.Description .Select(t => t.Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries)) .Select(split => string.Join(", ", split.Select(ToLimitedText))).ToArray(); return string.Format(actionText, description); } catch { //log.Error(string.Format("Error while building action text for \"{0}\" type of event", action)); return string.Empty; } } public static string GetActionText(LoginEvent evt) { var action = (MessageAction)evt.Action; if (!actions.ContainsKey(action)) { //log.Error(string.Format("There is no action text for \"{0}\" type of event", action)); return string.Empty; } try { var actionText = actions[(MessageAction)evt.Action].GetActionText(); if (evt.Description == null || !evt.Description.Any()) return actionText; var description = evt.Description .Select(t => t.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)) .Select(split => string.Join(", ", split.Select(ToLimitedText))).ToArray(); return string.Format(actionText, description); } catch { //log.Error(string.Format("Error while building action text for \"{0}\" type of event", action)); return string.Empty; } } public static string GetActionTypeText(AuditEvent evt) { var action = (MessageAction)evt.Action; return !actions.ContainsKey(action) ? string.Empty : actions[(MessageAction)evt.Action].GetActionTypeText(); } public static string GetProductText(AuditEvent evt) { var action = (MessageAction)evt.Action; return !actions.ContainsKey(action) ? string.Empty : actions[(MessageAction)evt.Action].GetProduct(); } public static string GetModuleText(AuditEvent evt) { var action = (MessageAction)evt.Action; return !actions.ContainsKey(action) ? string.Empty : actions[(MessageAction)evt.Action].GetModule(); } private static string ToLimitedText(string text) { if (text == null) return null; return text.Length < 50 ? text : string.Format("{0}...", text.Substring(0, 47)); } } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/Mail/Mail_h_DispositionNotificationOptions.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.Mail { #region usings using System; using System.Text; using MIME; #endregion /// <summary> /// Represents "Disposition-Notification-Options:" header. Defined in RFC 2298 2.2. /// </summary> public class Mail_h_DispositionNotificationOptions : MIME_h { /* Disposition-Notification-Options = "Disposition-Notification-Options" ":" disposition-notification-parameters disposition-notification-parameters = parameter *(";" parameter) parameter = attribute "=" importance "," 1#value importance = "required" / "optional" */ #region Properties /// <summary> /// Gets if this header field is modified since it has loaded. /// </summary> /// <remarks>All new added header fields has <b>IsModified = true</b>.</remarks> /// <exception cref="ObjectDisposedException">Is riased when this class is disposed and this property is accessed.</exception> public override bool IsModified { get { return true; } //m_pAddresses.IsModified; } } /// <summary> /// Gets header field name. For example "Sender". /// </summary> public override string Name { get { return "Disposition-Notification-Options"; } } /// <summary> /// Gets or sets mailbox address. /// </summary> public string Address { get { return "TODO:"; } } #endregion #region Methods /// <summary> /// Returns header field as string. /// </summary> /// <param name="wordEncoder">8-bit words ecnoder. Value null means that words are not encoded.</param> /// <param name="parmetersCharset">Charset to use to encode 8-bit characters. Value null means parameters not encoded.</param> /// <returns>Returns header field as string.</returns> public override string ToString(MIME_Encoding_EncodedWord wordEncoder, Encoding parmetersCharset) { return "TODO:"; } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/TCP/TCP_Client.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.TCP { #region usings using System; using System.Diagnostics; using System.Net; using System.Net.Security; using System.Net.Sockets; using System.Security.Cryptography.X509Certificates; using System.Text.RegularExpressions; using IO; using Log; #endregion /// <summary> /// This class implements generic TCP client. /// </summary> public class TCP_Client : TCP_Session { #region Delegates /// <summary> /// Internal helper method for asynchronous Connect method. /// </summary> /// <param name="localEP">Local IP end point to use for connect.</param> /// <param name="remoteEP">Remote IP end point where to connect.</param> /// <param name="ssl">Specifies if connects to SSL end point.</param> private delegate void BeginConnectEPDelegate(IPEndPoint localEP, IPEndPoint remoteEP, bool ssl); /// <summary> /// Internal helper method for asynchronous Connect method. /// </summary> /// <param name="host">Host name or IP address.</param> /// <param name="port">Port to connect.</param> /// <param name="ssl">Specifies if connects to SSL end point.</param> private delegate void BeginConnectHostDelegate(string host, int port, bool ssl); /// <summary> /// Internal helper method for asynchronous Disconnect method. /// </summary> private delegate void DisconnectDelegate(); #endregion #region Members private static readonly Regex IpRegexp = new Regex(@"^(([01]?\d\d?|2[0-4]\d|25[0-5])\.){3}([01]?\d\d?|25[0-5]|2[0-4]\d)$", RegexOptions.Compiled | RegexOptions.IgnoreCase); private DateTime m_ConnectTime; private string m_ID = ""; private bool m_IsConnected; private bool m_IsDisposed; private bool m_IsSecure; private RemoteCertificateValidationCallback m_pCertificateCallback; private IPEndPoint m_pLocalEP; private Logger m_pLogger; private IPEndPoint m_pRemoteEP; private SmartStream m_pTcpStream; private Socket socket; #endregion #region Properties /// <summary> /// Gets the time when session was connected. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when TCP client is not connected.</exception> public override DateTime ConnectTime { get { if (m_IsDisposed) { throw new ObjectDisposedException("TCP_Client"); } if (!IsConnected) { throw new InvalidOperationException("TCP client is not connected."); } return m_ConnectTime; } } /// <summary> /// Gets session ID. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when TCP client is not connected.</exception> public override string ID { get { if (m_IsDisposed) { throw new ObjectDisposedException("TCP_Client"); } if (!IsConnected) { throw new InvalidOperationException("TCP client is not connected."); } return m_ID; } } /// <summary> /// Gets if TCP client is connected. /// </summary> public override bool IsConnected { get { if (Socket != null) { return Socket.Connected; } return m_IsConnected; } } /// <summary> /// Gets if this object is disposed. /// </summary> public bool IsDisposed { get { return m_IsDisposed; } } /// <summary> /// Gets if this session TCP connection is secure connection. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when TCP client is not connected.</exception> public override bool IsSecureConnection { get { if (m_IsDisposed) { throw new ObjectDisposedException("TCP_Client"); } if (!IsConnected) { throw new InvalidOperationException("TCP client is not connected."); } return m_IsSecure; } } /// <summary> /// Gets the last time when data was sent or received. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when TCP client is not connected.</exception> public override DateTime LastActivity { get { if (m_IsDisposed) { throw new ObjectDisposedException("TCP_Client"); } if (!IsConnected) { throw new InvalidOperationException("TCP client is not connected."); } return m_pTcpStream.LastActivity; } } /// <summary> /// Gets session local IP end point. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when TCP client is not connected.</exception> public override IPEndPoint LocalEndPoint { get { if (m_IsDisposed) { throw new ObjectDisposedException("TCP_Client"); } if (!IsConnected) { throw new InvalidOperationException("TCP client is not connected."); } return m_pLocalEP; } } /// <summary> /// Gets or sets TCP client logger. Value null means no logging. /// </summary> public Logger Logger { get { return m_pLogger; } set { m_pLogger = value; } } /// <summary> /// Gets session remote IP end point. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when TCP client is not connected.</exception> public override IPEndPoint RemoteEndPoint { get { if (m_IsDisposed) { throw new ObjectDisposedException("TCP_Client"); } if (!IsConnected) { throw new InvalidOperationException("TCP client is not connected."); } return m_pRemoteEP; } } /// <summary> /// Gets TCP stream which must be used to send/receive data through this session. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when TCP client is not connected.</exception> public override SmartStream TcpStream { get { if (m_IsDisposed) { throw new ObjectDisposedException("TCP_Client"); } if (!IsConnected) { throw new InvalidOperationException("TCP client is not connected."); } return m_pTcpStream; } } /// <summary> /// Gets or stes remote callback which is called when remote server certificate needs to be validated. /// Value null means not sepcified. /// </summary> public RemoteCertificateValidationCallback ValidateCertificateCallback { get { return m_pCertificateCallback; } set { m_pCertificateCallback = value; } } public Socket Socket { get { return socket; } set { socket = value; } } #endregion #region Methods /// <summary> /// Cleans up any resources being used. This method is thread-safe. /// </summary> public override void Dispose() { lock (this) { Debug.Print("TCP client disposed"); if (m_IsDisposed) { return; } try { if (IsConnected) { Disconnect(); } } catch {} m_IsDisposed = true; } } /// <summary> /// Starts connection to the specified host. /// </summary> /// <param name="host">Host name or IP address.</param> /// <param name="port">Port to connect.</param> /// <param name="callback">Callback to call when the connect operation is complete.</param> /// <param name="state">User data.</param> /// <returns>An IAsyncResult that references the asynchronous connection.</returns> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when TCP client is already connected.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> public IAsyncResult BeginConnect(string host, int port, AsyncCallback callback, object state) { return BeginConnect(host, port, false, callback, state); } /// <summary> /// Starts connection to the specified host. /// </summary> /// <param name="host">Host name or IP address.</param> /// <param name="port">Port to connect.</param> /// <param name="ssl">Specifies if connects to SSL end point.</param> /// <param name="callback">Callback to call when the connect operation is complete.</param> /// <param name="state">User data.</param> /// <returns>An IAsyncResult that references the asynchronous connection.</returns> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when TCP client is already connected.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> public IAsyncResult BeginConnect(string host, int port, bool ssl, AsyncCallback callback, object state) { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (IsConnected) { throw new InvalidOperationException("TCP client is already connected."); } if (string.IsNullOrEmpty(host)) { throw new ArgumentException("Argument 'host' value may not be null or empty."); } if (port < 1) { throw new ArgumentException("Argument 'port' value must be >= 1."); } BeginConnectHostDelegate asyncMethod = Connect; AsyncResultState asyncState = new AsyncResultState(this, asyncMethod, callback, state); asyncState.SetAsyncResult(asyncMethod.BeginInvoke(host, port, ssl, asyncState.CompletedCallback, null)); return asyncState; } /// <summary> /// Starts connection to the specified remote end point. /// </summary> /// <param name="remoteEP">Remote IP end point where to connect.</param> /// <param name="ssl">Specifies if connects to SSL end point.</param> /// <param name="callback">Callback to call when the connect operation is complete.</param> /// <param name="state">User data.</param> /// <returns>An IAsyncResult that references the asynchronous connection.</returns> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when TCP client is already connected.</exception> /// <exception cref="ArgumentNullException">Is raised when <b>remoteEP</b> is null.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> public IAsyncResult BeginConnect(IPEndPoint remoteEP, bool ssl, AsyncCallback callback, object state) { return BeginConnect(null, remoteEP, ssl, callback, state); } /// <summary> /// Starts connection to the specified remote end point. /// </summary> /// <param name="localEP">Local IP end point to use for connect.</param> /// <param name="remoteEP">Remote IP end point where to connect.</param> /// <param name="ssl">Specifies if connects to SSL end point.</param> /// <param name="callback">Callback to call when the connect operation is complete.</param> /// <param name="state">User data.</param> /// <returns>An IAsyncResult that references the asynchronous connection.</returns> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when TCP client is already connected.</exception> /// <exception cref="ArgumentNullException">Is raised when <b>remoteEP</b> is null.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> public IAsyncResult BeginConnect(IPEndPoint localEP, IPEndPoint remoteEP, bool ssl, AsyncCallback callback, object state) { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (IsConnected) { throw new InvalidOperationException("TCP client is already connected."); } if (remoteEP == null) { throw new ArgumentNullException("remoteEP"); } BeginConnectEPDelegate asyncMethod = Connect; AsyncResultState asyncState = new AsyncResultState(this, asyncMethod, callback, state); asyncState.SetAsyncResult(asyncMethod.BeginInvoke(localEP, remoteEP, ssl, asyncState.CompletedCallback, null)); return asyncState; } /// <summary> /// Ends a pending asynchronous connection request. /// </summary> /// <param name="asyncResult">An IAsyncResult that stores state information and any user defined data for this asynchronous operation.</param> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="ArgumentNullException">Is raised when <b>asyncResult</b> is null.</exception> /// <exception cref="ArgumentException">Is raised when argument <b>asyncResult</b> was not returned by a call to the <b>BeginConnect</b> method.</exception> /// <exception cref="InvalidOperationException">Is raised when <b>EndConnect</b> was previously called for the asynchronous connection.</exception> public void EndConnect(IAsyncResult asyncResult) { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (asyncResult == null) { throw new ArgumentNullException("asyncResult"); } AsyncResultState castedAsyncResult = asyncResult as AsyncResultState; if (castedAsyncResult == null || castedAsyncResult.AsyncObject != this) { throw new ArgumentException( "Argument asyncResult was not returned by a call to the BeginConnect method."); } if (castedAsyncResult.IsEndCalled) { throw new InvalidOperationException( "EndConnect was previously called for the asynchronous operation."); } castedAsyncResult.IsEndCalled = true; if (castedAsyncResult.AsyncDelegate is BeginConnectHostDelegate) { ((BeginConnectHostDelegate) castedAsyncResult.AsyncDelegate).EndInvoke( castedAsyncResult.AsyncResult); } else if (castedAsyncResult.AsyncDelegate is BeginConnectEPDelegate) { ((BeginConnectEPDelegate) castedAsyncResult.AsyncDelegate).EndInvoke( castedAsyncResult.AsyncResult); } else { throw new ArgumentException( "Argument asyncResult was not returned by a call to the BeginConnect method."); } } /// <summary> /// Connects to the specified host. If the hostname resolves to more than one IP address, /// all IP addresses will be tried for connection, until one of them connects. /// </summary> /// <param name="host">Host name or IP address.</param> /// <param name="port">Port to connect.</param> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when TCP client is already connected.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> public void Connect(string host, int port) { Connect(host, port, false); } /// <summary> /// Connects to the specified host. If the hostname resolves to more than one IP address, /// all IP addresses will be tried for connection, until one of them connects. /// </summary> /// <param name="host">Host name or IP address.</param> /// <param name="port">Port to connect.</param> /// <param name="ssl">Specifies if connects to SSL end point.</param> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when TCP client is already connected.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> public void Connect(string host, int port, bool ssl) { Connect(host, port, ssl, 30000); } /// <summary> /// Connects to the specified host. If the hostname resolves to more than one IP address, /// all IP addresses will be tried for connection, until one of them connects. /// </summary> /// <param name="host">Host name or IP address.</param> /// <param name="port">Port to connect.</param> /// <param name="ssl">Specifies if connects to SSL end point.</param> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when TCP client is already connected.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> public void Connect(string host, int port, bool ssl, int timeout) { if (m_IsDisposed) { throw new ObjectDisposedException("TCP_Client"); } if (IsConnected) { throw new InvalidOperationException("TCP client is already connected."); } if (string.IsNullOrEmpty(host)) { throw new ArgumentException("Argument 'host' value may not be null or empty."); } if (port < 1) { throw new ArgumentException("Argument 'port' value must be >= 1."); } //Check ip IPAddress[] ips = Dns.GetHostAddresses(host); for (int i = 0; i < ips.Length; i++) { try { Connect(null, new IPEndPoint(ips[i], port), ssl, timeout); break; } catch (Exception x) { if (IsConnected) { throw x; } // Connect failed for specified IP address, if there are some more IPs left, try next, otherwise forward exception. else if (i == (ips.Length - 1)) { throw x; } } } } /// <summary> /// Connects to the specified remote end point. /// </summary> /// <param name="remoteEP">Remote IP end point where to connect.</param> /// <param name="ssl">Specifies if connects to SSL end point.</param> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when TCP client is already connected.</exception> /// <exception cref="ArgumentNullException">Is raised when <b>remoteEP</b> is null.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> public void Connect(IPEndPoint remoteEP, bool ssl) { Connect(null, remoteEP, ssl); } /// <summary> /// Connects to the specified remote end point. /// </summary> /// <param name="localEP">Local IP end point to use for connet.</param> /// <param name="remoteEP">Remote IP end point where to connect.</param> /// <param name="ssl">Specifies if connects to SSL end point.</param> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when TCP client is already connected.</exception> /// <exception cref="ArgumentNullException">Is raised when <b>remoteEP</b> is null.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> public void Connect(IPEndPoint localEP, IPEndPoint remoteEP, bool ssl) { Connect(localEP, remoteEP, ssl, 30000); } /// <summary> /// Connects to the specified remote end point. /// </summary> /// <param name="localEP">Local IP end point to use for connet.</param> /// <param name="remoteEP">Remote IP end point where to connect.</param> /// <param name="ssl">Specifies if connects to SSL end point.</param> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when TCP client is already connected.</exception> /// <exception cref="ArgumentNullException">Is raised when <b>remoteEP</b> is null.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> public void Connect(IPEndPoint localEP, IPEndPoint remoteEP, bool ssl, int timeout) { Debug.Print("TCP client connect"); if (m_IsDisposed) { throw new ObjectDisposedException("TCP_Client"); } if (IsConnected) { throw new InvalidOperationException("TCP client is already connected."); } if (remoteEP == null) { throw new ArgumentNullException("remoteEP"); } if (Socket != null && Socket.Connected) { Socket.Disconnect(false); Socket.Shutdown(SocketShutdown.Both); } Socket = null; if (remoteEP.AddressFamily == AddressFamily.InterNetwork) { Socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); } else if (remoteEP.AddressFamily == AddressFamily.InterNetworkV6) { Socket = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp); } else { throw new ArgumentException("Remote end point has invalid AddressFamily."); } try { Socket.SendTimeout = timeout; Socket.ReceiveTimeout = timeout; if (localEP != null) { Socket.Bind(localEP); } LogAddText("Connecting to " + remoteEP + "."); Socket.Connect(remoteEP); m_IsConnected = true; m_ID = Guid.NewGuid().ToString(); m_ConnectTime = DateTime.Now; m_pLocalEP = (IPEndPoint) Socket.LocalEndPoint; m_pRemoteEP = (IPEndPoint) Socket.RemoteEndPoint; m_pTcpStream = new SmartStream(new NetworkStream(Socket, true), true); LogAddText("Connected, localEP='" + m_pLocalEP + "'; remoteEP='" + remoteEP + "'."); if (ssl) { SwitchToSecure(); } } catch (Exception x) { LogAddException("Exception: " + x.Message, x); // Switching to secure failed. if (IsConnected) { Disconnect(); } // Bind or connect failed. else { Socket.Close(); } OnError(x); throw x; } OnConnected(); } /// <summary> /// Disconnects connection. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when TCP client is not connected.</exception> public override void Disconnect() { Debug.Print("TCP client disconect"); if (m_IsDisposed) { throw new ObjectDisposedException("TCP_Client"); } if (!IsConnected) { throw new InvalidOperationException("TCP client is not connected."); } try { m_pLocalEP = null; m_pRemoteEP = null; m_pTcpStream.Dispose(); LogAddText("Socket disconnecting"); m_IsSecure = false; } catch (Exception) { } } private void DisconnectCallback(IAsyncResult ar) { try { Socket.EndDisconnect(ar); Socket.Close(); m_IsConnected = false; LogAddText("Disconnected."); } catch (Exception) { } } /// <summary> /// Starts disconnecting connection. /// </summary> /// <param name="callback">Callback to call when the asynchronous operation is complete.</param> /// <param name="state">User data.</param> /// <returns>An IAsyncResult that references the asynchronous disconnect.</returns> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when TCP client is not connected.</exception> public IAsyncResult BeginDisconnect(AsyncCallback callback, object state) { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (!IsConnected) { throw new InvalidOperationException("TCP client is not connected."); } DisconnectDelegate asyncMethod = Disconnect; AsyncResultState asyncState = new AsyncResultState(this, asyncMethod, callback, state); asyncState.SetAsyncResult(asyncMethod.BeginInvoke(asyncState.CompletedCallback, null)); return asyncState; } /// <summary> /// Ends a pending asynchronous disconnect request. /// </summary> /// <param name="asyncResult">An IAsyncResult that stores state information and any user defined data for this asynchronous operation.</param> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="ArgumentNullException">Is raised when <b>asyncResult</b> is null.</exception> /// <exception cref="ArgumentException">Is raised when argument <b>asyncResult</b> was not returned by a call to the <b>BeginDisconnect</b> method.</exception> /// <exception cref="InvalidOperationException">Is raised when <b>EndDisconnect</b> was previously called for the asynchronous connection.</exception> public void EndDisconnect(IAsyncResult asyncResult) { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (asyncResult == null) { throw new ArgumentNullException("asyncResult"); } AsyncResultState castedAsyncResult = asyncResult as AsyncResultState; if (castedAsyncResult == null || castedAsyncResult.AsyncObject != this) { throw new ArgumentException( "Argument asyncResult was not returned by a call to the BeginDisconnect method."); } if (castedAsyncResult.IsEndCalled) { throw new InvalidOperationException( "EndDisconnect was previously called for the asynchronous connection."); } castedAsyncResult.IsEndCalled = true; if (castedAsyncResult.AsyncDelegate is DisconnectDelegate) { ((DisconnectDelegate) castedAsyncResult.AsyncDelegate).EndInvoke(castedAsyncResult.AsyncResult); } else { throw new ArgumentException( "Argument asyncResult was not returned by a call to the BeginDisconnect method."); } } #endregion #region Virtual methods /// <summary> /// This method is called after TCP client has sucessfully connected. /// </summary> protected virtual void OnConnected() {} #endregion #region Utility methods private bool RemoteCertificateValidationCallback(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { // User will handle it. if (m_pCertificateCallback != null) { return m_pCertificateCallback(sender, certificate, chain, sslPolicyErrors); } else { if (sslPolicyErrors == SslPolicyErrors.None || sslPolicyErrors == SslPolicyErrors.RemoteCertificateNameMismatch) { return true; } // Do not allow this client to communicate with unauthenticated servers. return false; } } #endregion /// <summary> /// Switches session to secure connection. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when TCP client is not connected or is already secure.</exception> protected void SwitchToSecure() { if (m_IsDisposed) { throw new ObjectDisposedException("TCP_Client"); } if (!IsConnected) { throw new InvalidOperationException("TCP client is not connected."); } if (m_IsSecure) { throw new InvalidOperationException("TCP client is already secure."); } LogAddText("Switching to SSL."); // FIX ME: if ssl switching fails, it closes source stream or otherwise if ssl successful, source stream leaks. SslStream sslStream = new SslStream(m_pTcpStream.SourceStream, true, RemoteCertificateValidationCallback); sslStream.AuthenticateAsClient(""); // Close old stream, but leave source stream open. m_pTcpStream.IsOwner = false; m_pTcpStream.Dispose(); m_IsSecure = true; m_pTcpStream = new SmartStream(sslStream, true); } // Do we need it ? /// <summary> /// This must be called when unexpected error happens. When inheriting <b>TCP_Client</b> class, be sure that you call <b>OnError</b> /// method for each unexpected error. /// </summary> /// <param name="x">Exception happened.</param> protected void OnError(Exception x) { try { if (m_pLogger != null) { //m_pLogger.AddException(x); } } catch {} } /// <summary> /// Reads and logs specified line from connected host. /// </summary> /// <returns>Returns readed line.</returns> protected string ReadLine() { SmartStream.ReadLineAsyncOP args = new SmartStream.ReadLineAsyncOP(new byte[Workaround.Definitions.MaxStreamLineLength], SizeExceededAction. JunkAndThrowException); TcpStream.ReadLine(args, false); if (args.Error != null) { throw args.Error; } string line = args.LineUtf8; if (args.BytesInBuffer > 0) { LogAddRead(args.BytesInBuffer, line); } else { LogAddText("Remote host closed connection."); } return line; } /// <summary> /// Sends and logs specified line to connected host. /// </summary> /// <param name="line">Line to send.</param> protected void WriteLine(string line) { if (line == null) { throw new ArgumentNullException("line"); } int countWritten = TcpStream.WriteLine(line); LogAddWrite(countWritten, line); } /// <summary> /// Logs read operation. /// </summary> /// <param name="size">Number of bytes readed.</param> /// <param name="text">Log text.</param> protected void LogAddRead(long size, string text) { try { if (m_pLogger != null) { m_pLogger.AddRead(ID, AuthenticatedUserIdentity, size, text, LocalEndPoint, RemoteEndPoint); } } catch { // We skip all logging errors, normally there shouldn't be any. } } /// <summary> /// Logs write operation. /// </summary> /// <param name="size">Number of bytes written.</param> /// <param name="text">Log text.</param> protected void LogAddWrite(long size, string text) { try { if (m_pLogger != null) { m_pLogger.AddWrite(ID, AuthenticatedUserIdentity, size, text, LocalEndPoint, RemoteEndPoint); } } catch { // We skip all logging errors, normally there shouldn't be any. } } /// <summary> /// Logs free text entry. /// </summary> /// <param name="text">Log text.</param> protected void LogAddText(string text) { try { if (m_pLogger != null) { m_pLogger.AddText(IsConnected ? ID : "", IsConnected ? AuthenticatedUserIdentity : null, text, IsConnected ? LocalEndPoint : null, IsConnected ? RemoteEndPoint : null); } } catch { // We skip all logging errors, normally there shouldn't be any. } } /// <summary> /// Logs exception. /// </summary> /// <param name="text">Log text.</param> /// <param name="x">Exception happened.</param> protected void LogAddException(string text, Exception x) { try { if (m_pLogger != null) { m_pLogger.AddException(IsConnected ? ID : "", IsConnected ? AuthenticatedUserIdentity : null, text, IsConnected ? LocalEndPoint : null, IsConnected ? RemoteEndPoint : null, x); } } catch { // We skip all logging errors, normally there shouldn't be any. } } } }<file_sep>/web/studio/ASC.Web.Studio/Products/Files/Warmup.aspx.cs  using System.Collections.Generic; using ASC.Web.Core; namespace ASC.Web.Files { public partial class Warmup : WarmupPage { protected override List<string> Exclude { get { return new List<string>(3) { "DocEditor.aspx", "App.aspx", "Share.aspx" }; } } } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/SIP/Message/SIP_t_AcceptRange.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.SIP.Message { #region usings using System; using System.Text; #endregion /// <summary> /// Implements SIP "accept-range" value. Defined in RFC 3261. /// </summary> /// <remarks> /// <code> /// RFC 3261 Syntax: /// accept-range = media-range [ accept-params ] /// media-range = ("*//*" / (m-type SLASH "*") / (m-type SLASH m-subtype)) *(SEMI m-parameter) /// accept-params = SEMI "q" EQUAL qvalue *(SEMI generic-param) /// </code> /// </remarks> public class SIP_t_AcceptRange : SIP_t_Value { #region Members private readonly SIP_ParameterCollection m_pMediaParameters; private readonly SIP_ParameterCollection m_pParameters; private string m_MediaType = ""; #endregion #region Properties /// <summary> /// Gets or sets media type. Value *(STAR) means all values. Syntax: mediaType / mediaSubType. /// Examples: */*,video/*,text/html. /// </summary> public string MediaType { get { return m_MediaType; } set { if (string.IsNullOrEmpty(value)) { throw new ArgumentException("Property MediaType value can't be null or empty !"); } if (value.IndexOf('/') == -1) { throw new ArgumentException( "Invalid roperty MediaType value, syntax: mediaType / mediaSubType !"); } m_MediaType = value; } } /// <summary> /// Gets media parameters collection. /// </summary> /// <returns></returns> public SIP_ParameterCollection MediaParameters { get { return m_pMediaParameters; } } /// <summary> /// Gets accept value parameters. /// </summary> public SIP_ParameterCollection Parameters { get { return m_pParameters; } } /// <summary> /// Gets or sets qvalue parameter. Targets are processed from highest qvalue to lowest. /// This value must be between 0.0 and 1.0. Value -1 means that value not specified. /// </summary> public double QValue { get { SIP_Parameter parameter = Parameters["qvalue"]; if (parameter != null) { return Convert.ToDouble(parameter.Value); } else { return -1; } } set { if (value < 0 || value > 1) { throw new ArgumentException("Property QValue value must be between 0.0 and 1.0 !"); } if (value < 0) { Parameters.Remove("qvalue"); } else { Parameters.Set("qvalue", value.ToString()); } } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> public SIP_t_AcceptRange() { m_pMediaParameters = new SIP_ParameterCollection(); m_pParameters = new SIP_ParameterCollection(); } #endregion #region Methods /// <summary> /// Parses "accept-range" from specified value. /// </summary> /// <param name="value">SIP "accept-range" value.</param> /// <exception cref="ArgumentNullException">Raised when <b>value</b> is null.</exception> /// <exception cref="SIP_ParseException">Raised when invalid SIP message.</exception> public void Parse(string value) { if (value == null) { throw new ArgumentNullException("value"); } Parse(new StringReader(value)); } /// <summary> /// Parses "accept-range" from specified reader. /// </summary> /// <param name="reader">Reader from where to parse.</param> /// <exception cref="ArgumentNullException">Raised when <b>reader</b> is null.</exception> /// <exception cref="SIP_ParseException">Raised when invalid SIP message.</exception> public override void Parse(StringReader reader) { /* accept-range = media-range [ accept-params ] media-range = ("*/ /*" / (m-type SLASH "*") / (m-type SLASH m-subtype)) *(SEMI m-parameter) accept-params = SEMI "q" EQUAL qvalue *(SEMI generic-param) */ if (reader == null) { throw new ArgumentNullException("reader"); } // Parse m-type string word = reader.ReadWord(); if (word == null) { throw new SIP_ParseException("Invalid 'accept-range' value, m-type is missing !"); } MediaType = word; // Parse media and accept parameters !!! thats confusing part, RFC invalid. bool media_accept = true; while (reader.Available > 0) { reader.ReadToFirstChar(); // We have 'next' value, so we are done here. if (reader.SourceString.StartsWith(",")) { break; } // We have parameter else if (reader.SourceString.StartsWith(";")) { reader.ReadSpecifiedLength(1); string paramString = reader.QuotedReadToDelimiter(new[] {';', ','}, false); if (paramString != "") { string[] name_value = paramString.Split(new[] {'='}, 2); string name = name_value[0].Trim(); string value = ""; if (name_value.Length == 2) { value = name_value[1]; } // If q, then accept parameters begin if (name.ToLower() == "q") { media_accept = false; } if (media_accept) { MediaParameters.Add(name, value); } else { Parameters.Add(name, value); } } } // Unknown data else { throw new SIP_ParseException("SIP_t_AcceptRange unexpected prarameter value !"); } } } /// <summary> /// Converts this to valid "accept-range" value. /// </summary> /// <returns>Returns "accept-range" value.</returns> public override string ToStringValue() { /* Accept = "Accept" HCOLON [ accept-range *(COMMA accept-range) ] accept-range = media-range [ accept-params ] media-range = ("*/ /*" / (m-type SLASH "*") / (m-type SLASH m-subtype)) *(SEMI m-parameter) accept-params = SEMI "q" EQUAL qvalue *(SEMI generic-param) */ StringBuilder retVal = new StringBuilder(); retVal.Append(m_MediaType); foreach (SIP_Parameter parameter in m_pMediaParameters) { if (parameter.Value != null) { retVal.Append(";" + parameter.Name + "=" + parameter.Value); } else { retVal.Append(";" + parameter.Name); } } foreach (SIP_Parameter parameter in m_pParameters) { if (parameter.Value != null) { retVal.Append(";" + parameter.Name + "=" + parameter.Value); } else { retVal.Append(";" + parameter.Name); } } return retVal.ToString(); } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/RTP/RTCP_Packet_APP.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.RTP { #region usings using System; #endregion /// <summary> /// This class represents Application-Defined RTCP Packet. /// </summary> public class RTCP_Packet_APP : RTCP_Packet { #region Members private byte[] m_Data; private string m_Name = ""; private uint m_Source; private int m_SubType; private int m_Version = 2; #endregion #region Properties /// <summary> /// Gets RTCP version. /// </summary> public override int Version { get { return m_Version; } } /// <summary> /// Gets RTCP packet type. /// </summary> public override int Type { get { return RTCP_PacketType.APP; } } /// <summary> /// Gets subtype value. /// </summary> public int SubType { get { return m_SubType; } } /// <summary> /// Gets sender synchronization(SSRC) or contributing(CSRC) source identifier. /// </summary> public uint Source { get { return m_Source; } set { m_Source = value; } } /// <summary> /// Gets 4 ASCII char packet name. /// </summary> public string Name { get { return m_Name; } } /// <summary> /// Gets application-dependent data. /// </summary> public byte[] Data { get { return m_Data; } } /// <summary> /// Gets number of bytes needed for this packet. /// </summary> public override int Size { get { return 12 + m_Data.Length; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> internal RTCP_Packet_APP() { m_Name = "xxxx"; m_Data = new byte[0]; } #endregion #region Methods /// <summary> /// Stores APP packet to the specified buffer. /// </summary> /// <param name="buffer">Buffer where to store APP packet.</param> /// <param name="offset">Offset in buffer.</param> /// <exception cref="ArgumentNullException">Is raised when <b>buffer</b> is null.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> public override void ToByte(byte[] buffer, ref int offset) { /* RFC 3550 6.7 APP: Application-Defined RTCP Packet. 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |V=2|P| subtype | PT=APP=204 | length | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | SSRC/CSRC | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | name (ASCII) | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | application-dependent data ... +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ if (buffer == null) { throw new ArgumentNullException("buffer"); } if (offset < 0) { throw new ArgumentException("Argument 'offset' value must be >= 0."); } int length = 8 + m_Data.Length; // V P subtype buffer[offset++] = (byte) (2 << 6 | 0 << 5 | m_SubType & 0x1F); // PT=APP=204 buffer[offset++] = 204; // length buffer[offset++] = (byte) ((length >> 8) | 0xFF); buffer[offset++] = (byte) ((length) | 0xFF); // SSRC/CSRC buffer[offset++] = (byte) ((m_Source >> 24) | 0xFF); buffer[offset++] = (byte) ((m_Source >> 16) | 0xFF); buffer[offset++] = (byte) ((m_Source >> 8) | 0xFF); buffer[offset++] = (byte) ((m_Source) | 0xFF); // name buffer[offset++] = (byte) m_Name[0]; buffer[offset++] = (byte) m_Name[1]; buffer[offset++] = (byte) m_Name[2]; buffer[offset++] = (byte) m_Name[2]; // application-dependent data Array.Copy(m_Data, 0, buffer, offset, m_Data.Length); offset += m_Data.Length; } #endregion #region Overrides /// <summary> /// Parses APP packet from the specified buffer. /// </summary> /// <param name="buffer">Buffer what conatins APP packet.</param> /// <param name="offset">Offset in buffer.</param> /// <exception cref="ArgumentNullException">Is raised when <b>buffer</b> is null.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> protected override void ParseInternal(byte[] buffer, ref int offset) { /* RFC 3550 6.7 APP: Application-Defined RTCP Packet. 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |V=2|P| subtype | PT=APP=204 | length | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | SSRC/CSRC | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | name (ASCII) | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | application-dependent data ... +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ if (buffer == null) { throw new ArgumentNullException("buffer"); } if (offset < 0) { throw new ArgumentException("Argument 'offset' value must be >= 0."); } m_Version = buffer[offset++] >> 6; bool isPadded = Convert.ToBoolean((buffer[offset] >> 5) & 0x1); int subType = buffer[offset++] & 0x1F; int type = buffer[offset++]; int length = buffer[offset++] << 8 | buffer[offset++]; if (isPadded) { PaddBytesCount = buffer[offset + length]; } m_SubType = subType; m_Source = (uint) (buffer[offset++] << 24 | buffer[offset++] << 16 | buffer[offset++] << 8 | buffer[offset++]); m_Name = ((char) buffer[offset++]) + ((char) buffer[offset++]).ToString() + ((char) buffer[offset++]) + ((char) buffer[offset++]); m_Data = new byte[length - 8]; Array.Copy(buffer, offset, m_Data, 0, m_Data.Length); } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/_Obsolete/SocketLogger.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net { #region usings using System; using System.Collections.Generic; using System.Net; using System.Net.Sockets; #endregion /// <summary> /// Socket logger. /// </summary> public class SocketLogger { #if (DEBUG) private const int logDumpCount = 1; #else private const int logDumpCount = 100; #endif #region Members private readonly List<SocketLogEntry> m_pEntries; private readonly LogEventHandler m_pLogHandler; private readonly Socket m_pSocket; private bool m_FirstLogPart = true; private IPEndPoint m_pLoaclEndPoint; private IPEndPoint m_pRemoteEndPoint; private string m_SessionID = ""; private string m_UserName = ""; #endregion #region Properties /// <summary> /// Gets or sets session ID. /// </summary> public string SessionID { get { return m_SessionID; } set { m_SessionID = value; } } /// <summary> /// Gets or sets authenticated user name. /// </summary> public string UserName { get { return m_UserName; } set { m_UserName = value; } } /// <summary> /// Gets current cached log entries. /// </summary> public SocketLogEntry[] LogEntries { get { return m_pEntries.ToArray(); } } /// <summary> /// Gets local endpoint. /// </summary> public IPEndPoint LocalEndPoint { get { return m_pLoaclEndPoint; } } /// <summary> /// Gets remote endpoint. /// </summary> public IPEndPoint RemoteEndPoint { get { return m_pRemoteEndPoint; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="socket"></param> /// <param name="logHandler"></param> public SocketLogger(Socket socket, LogEventHandler logHandler) { m_pSocket = socket; m_pLogHandler = logHandler; m_pEntries = new List<SocketLogEntry>(); } #endregion #region Methods /// <summary> /// Converts log entries to string. /// </summary> /// <param name="logger">Socket logger.</param> /// <param name="firstLogPart">Specifies if first log part of multipart log.</param> /// <param name="lastLogPart">Specifies if last log part (logging ended).</param> /// <returns></returns> public static string LogEntriesToString(SocketLogger logger, bool firstLogPart, bool lastLogPart) { string logText = "//----- Sys: 'Session:'" + logger.SessionID + " added " + DateTime.Now + "\r\n"; if (!firstLogPart) { logText = "//----- Sys: 'Session:'" + logger.SessionID + " partial log continues " + DateTime.Now + "\r\n"; } foreach (SocketLogEntry entry in logger.LogEntries) { if (entry.Type == SocketLogEntryType.ReadFromRemoteEP) { logText += CreateEntry(logger, entry.Text, ">>>"); } else if (entry.Type == SocketLogEntryType.SendToRemoteEP) { logText += CreateEntry(logger, entry.Text, "<<<"); } else { logText += CreateEntry(logger, entry.Text, "---"); } } if (lastLogPart) { logText += "//----- Sys: 'Session:'" + logger.SessionID + " removed " + DateTime.Now + "\r\n"; } else { logText += "//----- Sys: 'Session:'" + logger.SessionID + " partial log " + DateTime.Now + "\r\n"; } return logText; } /// <summary> /// Adds data read(from remoteEndpoint) entry. /// </summary> /// <param name="text">Log text.</param> /// <param name="size">Readed text size.</param> public void AddReadEntry(string text, long size) { if (m_pLoaclEndPoint == null || m_pRemoteEndPoint == null) { m_pLoaclEndPoint = (IPEndPoint) m_pSocket.LocalEndPoint; m_pRemoteEndPoint = (IPEndPoint) m_pSocket.RemoteEndPoint; } m_pEntries.Add(new SocketLogEntry(text, size, SocketLogEntryType.ReadFromRemoteEP)); OnEntryAdded(); } /// <summary> /// Adds data send(to remoteEndpoint) entry. /// </summary> /// <param name="text">Log text.</param> /// <param name="size">Sent text size.</param> public void AddSendEntry(string text, long size) { if (m_pLoaclEndPoint == null || m_pRemoteEndPoint == null) { m_pLoaclEndPoint = (IPEndPoint) m_pSocket.LocalEndPoint; m_pRemoteEndPoint = (IPEndPoint) m_pSocket.RemoteEndPoint; } m_pEntries.Add(new SocketLogEntry(text, size, SocketLogEntryType.SendToRemoteEP)); OnEntryAdded(); } /// <summary> /// Adds free text entry. /// </summary> /// <param name="text">Log text.</param> public void AddTextEntry(string text) { m_pEntries.Add(new SocketLogEntry(text, 0, SocketLogEntryType.FreeText)); OnEntryAdded(); } /// <summary> /// Requests to write all in memory log entries to log log file. /// </summary> public void Flush() { if (m_pLogHandler != null) { m_pLogHandler(this, new Log_EventArgs(this, m_FirstLogPart, true)); } } #endregion #region Utility methods private static string CreateEntry(SocketLogger logger, string text, string prefix) { string retVal = ""; if (text.EndsWith("\r\n")) { text = text.Substring(0, text.Length - 2); } string remIP = "xxx.xxx.xxx.xxx"; try { if (logger.RemoteEndPoint != null) { remIP = (logger.RemoteEndPoint).Address.ToString(); } } catch {} string[] lines = text.Replace("\r\n", "\n").Split('\n'); foreach (string line in lines) { retVal += "SessionID: " + logger.SessionID + " RemIP: " + remIP + " " + prefix + " '" + line + "'\r\n"; } return retVal; } /// <summary> /// This method is called when new loge entry has added. /// </summary> private void OnEntryAdded() { // Ask to server to write partial log if (m_pEntries.Count > logDumpCount) { if (m_pLogHandler != null) { m_pLogHandler(this, new Log_EventArgs(this, m_FirstLogPart, false)); } m_pEntries.Clear(); m_FirstLogPart = false; } } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/IMAP/Server/IMAP_eArgs_Search.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; namespace LumiSoft.Net.IMAP.Server { /// <summary> /// Provides data from IMAP Search command. /// </summary> public class IMAP_eArgs_Search { private IMAP_Session m_pSession = null; private string m_Folder = ""; private IMAP_Messages m_pMessages = null; private IMAP_SearchMatcher m_pMatcher = null; /// <summary> /// Default constructor. /// </summary> /// <param name="session">IMAP session what calls this search.</param> /// <param name="folder">IMAP folder name which messages to search.</param> /// <param name="matcher">Matcher what must be used to check if message matches searching criterial.</param> public IMAP_eArgs_Search(IMAP_Session session,string folder,IMAP_SearchMatcher matcher) { m_pSession = session; m_Folder = folder; m_pMatcher = matcher; m_pMessages = new IMAP_Messages(folder); } #region Properties Implementation /// <summary> /// Gets current session. /// </summary> public IMAP_Session Session { get{ return m_pSession; } } /// <summary> /// Gets folder name which messages to search. /// </summary> public string Folder { get{ return m_Folder; } } /// <summary> /// Gets or sets messges what match searching criterial. /// </summary> public IMAP_Messages MatchingMessages { get{ return m_pMessages; } } /// <summary> /// Gets matcher what must be used to check if message matches searching criterial. /// </summary> public IMAP_SearchMatcher Matcher { get{ return m_pMatcher; } } #endregion } } <file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/IMAP/Server/_FetchHelper.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.IMAP.Server { #region usings using System; using System.IO; using System.Text; using Mime; #endregion /// <summary> /// FETCH command helper methods. /// </summary> internal class FetchHelper { #region Methods /// <summary> /// Returns requested header fields lines. /// Note: Header terminator blank line is included. /// </summary> /// <param name="fieldsStr">Header fields to get.</param> /// <param name="entity">Entity which header field lines to get.</param> /// <returns></returns> public static byte[] ParseHeaderFields(string fieldsStr, MimeEntity entity) { return ParseHeaderFields(fieldsStr, Encoding.Default.GetBytes(entity.HeaderString)); } /// <summary> /// Returns requested header fields lines. /// Note: Header terminator blank line is included. /// </summary> /// <param name="fieldsStr">Header fields to get.</param> /// <param name="data">Message data.</param> /// <returns></returns> public static byte[] ParseHeaderFields(string fieldsStr, byte[] data) { fieldsStr = fieldsStr.Trim(); if (fieldsStr.StartsWith("(")) { fieldsStr = fieldsStr.Substring(1, fieldsStr.Length - 1); } if (fieldsStr.EndsWith(")")) { fieldsStr = fieldsStr.Substring(0, fieldsStr.Length - 1); } string retVal = ""; string[] fields = fieldsStr.Split(' '); using (MemoryStream mStrm = new MemoryStream(data)) { TextReader r = new StreamReader(mStrm); string line = r.ReadLine(); bool fieldFound = false; // Loop all header lines while (line != null) { // End of header if (line.Length == 0) { break; } // Field continues if (fieldFound && line.StartsWith("\t")) { retVal += line + "\r\n"; } else { fieldFound = false; // Check if wanted field foreach (string field in fields) { if (line.Trim().ToLower().StartsWith(field.Trim().ToLower())) { retVal += line + "\r\n"; fieldFound = true; } } } line = r.ReadLine(); } } // Add header terminating blank line retVal += "\r\n"; return Encoding.ASCII.GetBytes(retVal); } /// <summary> /// Returns header fields lines except requested. /// Note: Header terminator blank line is included. /// </summary> /// <param name="fieldsStr">Header fields to skip.</param> /// <param name="entity">Entity which header field lines to get.</param> /// <returns></returns> public static byte[] ParseHeaderFieldsNot(string fieldsStr, MimeEntity entity) { return ParseHeaderFieldsNot(fieldsStr, Encoding.Default.GetBytes(entity.HeaderString)); } /// <summary> /// Returns header fields lines except requested. /// Note: Header terminator blank line is included. /// </summary> /// <param name="fieldsStr">Header fields to skip.</param> /// <param name="data">Message data.</param> /// <returns></returns> public static byte[] ParseHeaderFieldsNot(string fieldsStr, byte[] data) { fieldsStr = fieldsStr.Trim(); if (fieldsStr.StartsWith("(")) { fieldsStr = fieldsStr.Substring(1, fieldsStr.Length - 1); } if (fieldsStr.EndsWith(")")) { fieldsStr = fieldsStr.Substring(0, fieldsStr.Length - 1); } string retVal = ""; string[] fields = fieldsStr.Split(' '); using (MemoryStream mStrm = new MemoryStream(data)) { TextReader r = new StreamReader(mStrm); string line = r.ReadLine(); bool fieldFound = false; // Loop all header lines while (line != null) { // End of header if (line.Length == 0) { break; } // Filed continues if (fieldFound && line.StartsWith("\t")) { retVal += line + "\r\n"; } else { fieldFound = false; // Check if wanted field foreach (string field in fields) { if (line.Trim().ToLower().StartsWith(field.Trim().ToLower())) { fieldFound = true; } } if (!fieldFound) { retVal += line + "\r\n"; } } line = r.ReadLine(); } } return Encoding.ASCII.GetBytes(retVal); } /// <summary> /// Gets specified mime entity. Returns null if specified mime entity doesn't exist. /// </summary> /// <param name="parser">Reference to mime parser.</param> /// <param name="mimeEntitySpecifier">Mime entity specifier. Nested mime entities are pointed by '.'. /// For example: 1,1.1,2.1, ... .</param> /// <returns></returns> public static MimeEntity GetMimeEntity(Mime parser, string mimeEntitySpecifier) { // TODO: nested rfc 822 message // For single part message there is only one entity with value 1. // Example: // header // entity -> 1 // For multipart message, entity counting starts from MainEntity.ChildEntities // Example: // header // multipart/mixed // entity1 -> 1 // entity2 -> 2 // ... // Single part if ((parser.MainEntity.ContentType & MediaType_enum.Multipart) == 0) { if (mimeEntitySpecifier.Length == 1 && Convert.ToInt32(mimeEntitySpecifier) == 1) { return parser.MainEntity; } else { return null; } } // multipart else { MimeEntity entity = parser.MainEntity; string[] parts = mimeEntitySpecifier.Split('.'); foreach (string part in parts) { int mEntryNo = Convert.ToInt32(part) - 1; // Enitites are zero base, mimeEntitySpecifier is 1 based. if (mEntryNo > -1 && mEntryNo < entity.ChildEntities.Count) { entity = entity.ChildEntities[mEntryNo]; } else { return null; } } return entity; } } /// <summary> /// Gets specified mime entity header. /// Note: Header terminator blank line is included. /// </summary> /// <param name="entity">Mime entity.</param> /// <returns></returns> public static byte[] GetMimeEntityHeader(MimeEntity entity) { return Encoding.ASCII.GetBytes(entity.HeaderString + "\r\n"); } /// <summary> /// Gets requested mime entity header. Returns null if specified mime entity doesn't exist. /// Note: Header terminator blank line is included. /// </summary> /// <param name="parser">Reference to mime parser.</param> /// <param name="mimeEntitySpecifier">Mime entity specifier. Nested mime entities are pointed by '.'. /// For example: 1,1.1,2.1, ... .</param> /// <returns>Returns requested mime entity data or NULL if requested entry doesn't exist.</returns> public static byte[] GetMimeEntityHeader(Mime parser, string mimeEntitySpecifier) { MimeEntity mEntry = GetMimeEntity(parser, mimeEntitySpecifier); if (mEntry != null) { return GetMimeEntityHeader(mEntry); } else { return null; } } /// <summary> /// Gets requested mime entity data. Returns null if specified mime entity doesn't exist. /// </summary> /// <param name="parser">Reference to mime parser.</param> /// <param name="mimeEntitySpecifier">Mime entity specifier. Nested mime entities are pointed by '.'. /// For example: 1,1.1,2.1, ... .</param> /// <returns>Returns requested mime entity data or NULL if requested entry doesn't exist.</returns> public static byte[] GetMimeEntityData(Mime parser, string mimeEntitySpecifier) { MimeEntity entity = GetMimeEntity(parser, mimeEntitySpecifier); if (entity != null) { return entity.DataEncoded; } else { return null; } } #endregion #region Utility methods private static string Escape(string text) { text = text.Replace("\\", "\\\\"); text = text.Replace("\"", "\\\""); return text; } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/SIP/Proxy/SIP_B2BUA.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.SIP.Proxy { #region usings using System; using System.Collections.Generic; using AUTH; using Message; using Stack; #endregion /// <summary> /// This class implements SIP b2bua(back to back user agent). Defined in RFC 3261. /// </summary> public class SIP_B2BUA : IDisposable { #region Events /// <summary> /// Is called when new call is created. /// </summary> public event EventHandler CallCreated = null; /// <summary> /// Is called when call has terminated. /// </summary> public event EventHandler CallTerminated = null; #endregion #region Members private readonly List<SIP_B2BUA_Call> m_pCalls; private readonly SIP_ProxyCore m_pProxy; private bool m_IsDisposed; #endregion #region Properties /// <summary> /// Gets B2BUA owner SIP stack. /// </summary> public SIP_Stack Stack { get { return m_pProxy.Stack; } } /// <summary> /// Gets active calls. /// </summary> public SIP_B2BUA_Call[] Calls { get { return m_pCalls.ToArray(); } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="owner">Onwer SIP proxy.</param> internal SIP_B2BUA(SIP_ProxyCore owner) { m_pProxy = owner; m_pCalls = new List<SIP_B2BUA_Call>(); } #endregion #region Methods /// <summary> /// Cleans up any resources being used. /// </summary> public void Dispose() { if (m_IsDisposed) { return; } m_IsDisposed = true; // Terminate all calls. foreach (SIP_B2BUA_Call call in m_pCalls) { call.Terminate(); } } /// <summary> /// Gets call by call ID. /// </summary> /// <param name="callID">Call ID.</param> /// <returns>Returns call with specified ID or null if no call with specified ID.</returns> public SIP_B2BUA_Call GetCallByID(string callID) { foreach (SIP_B2BUA_Call call in m_pCalls.ToArray()) { if (call.CallID == callID) { return call; } } return null; } #endregion #region Internal methods /// <summary> /// This method is called when new request is received. /// </summary> /// <param name="e">Request event arguments.</param> internal void OnRequestReceived(SIP_RequestReceivedEventArgs e) { SIP_Request request = e.Request; if (request.RequestLine.Method == SIP_Methods.CANCEL) { /* RFC 3261 9.2. If the UAS did not find a matching transaction for the CANCEL according to the procedure above, it SHOULD respond to the CANCEL with a 481 (Call Leg/Transaction Does Not Exist). Regardless of the method of the original request, as long as the CANCEL matched an existing transaction, the UAS answers the CANCEL request itself with a 200 (OK) response. */ SIP_ServerTransaction trToCancel = m_pProxy.Stack.TransactionLayer.MatchCancelToTransaction(e.Request); if (trToCancel != null) { trToCancel.Cancel(); //e.ServerTransaction.SendResponse(request.CreateResponse(SIP_ResponseCodes.x200_Ok)); } else { //e.ServerTransaction.SendResponse(request.CreateResponse(SIP_ResponseCodes.x481_Call_Transaction_Does_Not_Exist)); } } // We never should ge BYE here, because transport layer must match it to dialog. else if (request.RequestLine.Method == SIP_Methods.BYE) { /* RFC 3261 15.1.2. If the BYE does not match an existing dialog, the UAS core SHOULD generate a 481 (Call/Transaction Does Not Exist) response and pass that to the server transaction. */ //e.ServerTransaction.SendResponse(request.CreateResponse(SIP_ResponseCodes.x481_Call_Transaction_Does_Not_Exist)); } // We never should ge ACK here, because transport layer must match it to dialog. else if (request.RequestLine.Method == SIP_Methods.ACK) { // ACK is response less request, so we may not return error to it. } // B2BUA must respond to OPTIONS request, not to forward it. else if (request.RequestLine.Method == SIP_Methods.OPTIONS) { /* SIP_Response response = e.Request.CreateResponse(SIP_ResponseCodes.x200_Ok); // Add Allow to non ACK response. if(e.Request.RequestLine.Method != SIP_Methods.ACK){ response.Allow.Add("INVITE,ACK,OPTIONS,CANCEL,BYE,PRACK,MESSAGE,UPDATE"); } // Add Supported to 2xx non ACK response. if(response.StatusCodeType == SIP_StatusCodeType.Success && e.Request.RequestLine.Method != SIP_Methods.ACK){ response.Supported.Add("100rel,timer"); } e.ServerTransaction.SendResponse(response);*/ } // We never should get PRACK here, because transport layer must match it to dialog. else if (request.RequestLine.Method == SIP_Methods.PRACK) { //e.ServerTransaction.SendResponse(request.CreateResponse(SIP_ResponseCodes.x481_Call_Transaction_Does_Not_Exist)); } // We never should get UPDATE here, because transport layer must match it to dialog. else if (request.RequestLine.Method == SIP_Methods.UPDATE) { //e.ServerTransaction.SendResponse(request.CreateResponse(SIP_ResponseCodes.x481_Call_Transaction_Does_Not_Exist)); } else { /* draft-marjou-sipping-b2bua-00 4.1.3. When the UAS of the B2BUA receives an upstream SIP request, its associated UAC generates a new downstream SIP request with its new Via, Max-Forwards, Call-Id, CSeq, and Contact header fields. Route header fields of the upstream request are copied in the downstream request, except the first Route header if it is under the responsibility of the B2BUA. Record-Route header fields of the upstream request are not copied in the new downstream request, as Record-Route is only meaningful for the upstream dialog. The UAC SHOULD copy other header fields and body from the upstream request into this downstream request before sending it. */ SIP_Request b2buaRequest = e.Request.Copy(); b2buaRequest.Via.RemoveAll(); b2buaRequest.MaxForwards = 70; b2buaRequest.CallID = SIP_t_CallID.CreateCallID().CallID; b2buaRequest.CSeq.SequenceNumber = 1; b2buaRequest.Contact.RemoveAll(); // b2buaRequest.Contact.Add(m_pProxy.CreateContact(b2buaRequest.To.Address).ToStringValue()); if (b2buaRequest.Route.Count > 0 && m_pProxy.IsLocalRoute( SIP_Uri.Parse(b2buaRequest.Route.GetTopMostValue().Address.Uri.ToString()))) { b2buaRequest.Route.RemoveTopMostValue(); } b2buaRequest.RecordRoute.RemoveAll(); // Remove our Authorization header if it's there. foreach ( SIP_SingleValueHF<SIP_t_Credentials> header in b2buaRequest.ProxyAuthorization.HeaderFields) { try { Auth_HttpDigest digest = new Auth_HttpDigest(header.ValueX.AuthData, b2buaRequest.RequestLine.Method); if (m_pProxy.Stack.Realm == digest.Realm) { b2buaRequest.ProxyAuthorization.Remove(header); } } catch { // We don't care errors here. This can happen if remote server xxx auth method here and // we don't know how to parse it, so we leave it as is. } } //--- Add/replace default fields. ------------------------------------------ b2buaRequest.Allow.RemoveAll(); b2buaRequest.Supported.RemoveAll(); // Accept to non ACK,BYE request. if (request.RequestLine.Method != SIP_Methods.ACK && request.RequestLine.Method != SIP_Methods.BYE) { b2buaRequest.Allow.Add("INVITE,ACK,OPTIONS,CANCEL,BYE,PRACK"); } // Supported to non ACK request. if (request.RequestLine.Method != SIP_Methods.ACK) { b2buaRequest.Supported.Add("100rel,timer"); } // Remove Require: header. b2buaRequest.Require.RemoveAll(); // RFC 4028 7.4. For re-INVITE and UPDATE we need to add Session-Expires and Min-SE: headers. if (request.RequestLine.Method == SIP_Methods.INVITE || request.RequestLine.Method == SIP_Methods.UPDATE) { b2buaRequest.SessionExpires = new SIP_t_SessionExpires(m_pProxy.Stack.SessionExpries, "uac"); b2buaRequest.MinSE = new SIP_t_MinSE(m_pProxy.Stack.MinimumSessionExpries); } // Forward request. m_pProxy.ForwardRequest(true, e, b2buaRequest, false); } } /// <summary> /// This method is called when new response is received. /// </summary> /// <param name="e">Response event arguments.</param> internal void OnResponseReceived(SIP_ResponseReceivedEventArgs e) { // If we get response here, that means we have stray response, just do nothing. // All reponses must match to transactions, so we never should reach here. } /// <summary> /// Adds specified call to calls list. /// </summary> /// <param name="caller">Caller side dialog.</param> /// <param name="calee">Calee side dialog.</param> internal void AddCall(SIP_Dialog caller, SIP_Dialog calee) { lock (m_pCalls) { SIP_B2BUA_Call call = new SIP_B2BUA_Call(this, caller, calee); m_pCalls.Add(call); OnCallCreated(call); } } /// <summary> /// Removes specified call from calls list. /// </summary> /// <param name="call">Call to remove.</param> internal void RemoveCall(SIP_B2BUA_Call call) { m_pCalls.Remove(call); OnCallTerminated(call); } #endregion /// <summary> /// Raises CallCreated event. /// </summary> /// <param name="call">Call created.</param> protected void OnCallCreated(SIP_B2BUA_Call call) { if (CallCreated != null) { CallCreated(call, new EventArgs()); } } /// <summary> /// Raises CallTerminated event. /// </summary> /// <param name="call">Call terminated.</param> protected internal void OnCallTerminated(SIP_B2BUA_Call call) { if (CallTerminated != null) { CallTerminated(call, new EventArgs()); } } } }<file_sep>/module/ASC.Api/ASC.Api.MailServer/MailServerApi.WebDomain.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System.Collections.Generic; using System.Linq; using ASC.Api.Attributes; using ASC.Core; using ASC.Mail.Core.Engine.Operations.Base; using ASC.Mail.Data.Contracts; // ReSharper disable InconsistentNaming namespace ASC.Api.MailServer { public partial class MailServerApi { /// <summary> /// Returns list of the web domains associated with tenant /// </summary> /// <returns>List of WebDomainData for current tenant</returns> /// <short>Get tenant web domain list</short> /// <category>Domains</category> [Read(@"domains/get")] public List<ServerDomainData> GetDomains() { var listDomainData = MailEngineFactory.ServerDomainEngine.GetDomains(); if (CoreContext.Configuration.Standalone) { //Skip common domain listDomainData = listDomainData.Where(d => !d.IsSharedDomain).ToList(); } return listDomainData; } /// <summary> /// Returns the common web domain /// </summary> /// <returns>WebDomainData for common web domain</returns> /// <short>Get common web domain</short> /// <category>Domains</category> [Read(@"domains/common")] public ServerDomainData GetCommonDomain() { var commonDomain = MailEngineFactory.ServerDomainEngine.GetCommonDomain(); return commonDomain; } /// <summary> /// Associate a web domain with tenant /// </summary> /// <param name="name">web domain name</param> /// <param name="id_dns"></param> /// <returns>WebDomainData associated with tenant</returns> /// <short>Add domain to mail server</short> /// <category>Domains</category> [Create(@"domains/add")] public ServerDomainData AddDomain(string name, int id_dns) { var domain = MailEngineFactory.ServerDomainEngine.AddDomain(name, id_dns); return domain; } /// <summary> /// Deletes the selected web domain /// </summary> /// <param name="id">id of web domain</param> /// <returns>MailOperationResult object</returns> /// <short>Remove domain from mail server</short> /// <category>Domains</category> [Delete(@"domains/remove/{id}")] public MailOperationStatus RemoveDomain(int id) { var status = MailEngineFactory.ServerDomainEngine.RemoveDomain(id); return status; } /// <summary> /// Returns dns records associated with domain /// </summary> /// <param name="id">id of domain</param> /// <returns>Dns records associated with domain</returns> /// <short>Returns dns records</short> /// <category>DnsRecords</category> [Read(@"domains/dns/get")] public ServerDomainDnsData GetDnsRecords(int id) { var dns = MailEngineFactory.ServerDomainEngine.GetDnsData(id); return dns; } /// <summary> /// Check web domain name existance /// </summary> /// <param name="name">web domain name</param> /// <returns>True if domain name already exists.</returns> /// <short>Is domain name exists.</short> /// <category>Domains</category> [Read(@"domains/exists")] public bool IsDomainExists(string name) { var isExists = MailEngineFactory.ServerDomainEngine.IsDomainExists(name); return isExists; } /// <summary> /// Check web domain name ownership over txt record in dns /// </summary> /// <param name="name">web domain name</param> /// <returns>True if user is owner of this domain.</returns> /// <short>Check domain ownership.</short> /// <category>Domains</category> [Read(@"domains/ownership/check")] public bool CheckDomainOwnership(string name) { var isOwnershipProven = MailEngineFactory.ServerEngine.CheckDomainOwnership(name); return isOwnershipProven; } } } <file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/POP3/Server/POP3_MessageCollection.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.POP3.Server { #region usings using System.Collections; using System.Collections.Generic; #endregion /// <summary> /// POP3 messages info collection. /// </summary> public class POP3_MessageCollection : IEnumerable { #region Members private readonly List<POP3_Message> m_pMessages; #endregion #region Properties /// <summary> /// Gets number of messages in the collection. /// </summary> public int Count { get { return m_pMessages.Count; } } /// <summary> /// Gets a POP3_Message object in the collection by index number. /// </summary> /// <param name="index">An Int32 value that specifies the position of the POP3_Message object in the POP3_MessageCollection collection.</param> public POP3_Message this[int index] { get { return m_pMessages[index]; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> public POP3_MessageCollection() { m_pMessages = new List<POP3_Message>(); } #endregion #region Methods /// <summary> /// Adds new message info to the collection. /// </summary> /// <param name="id">Message ID.</param> /// <param name="uid">Message UID.</param> /// <param name="size">Message size in bytes.</param> public POP3_Message Add(string id, string uid, long size) { return Add(id, uid, size, null); } /// <summary> /// Adds new message info to the collection. /// </summary> /// <param name="id">Message ID.</param> /// <param name="uid">Message UID.</param> /// <param name="size">Message size in bytes.</param> /// <param name="tag">Message user data.</param> public POP3_Message Add(string id, string uid, long size, object tag) { POP3_Message message = new POP3_Message(this, id, uid, size); m_pMessages.Add(message); message.Tag = tag; return message; } /// <summary> /// Removes specified message from the collection. /// </summary> /// <param name="message">Message to remove.</param> public void Remove(POP3_Message message) { m_pMessages.Remove(message); } /// <summary> /// Gets if collection contains message with the specified UID. /// </summary> /// <param name="uid">Message UID to check.</param> /// <returns></returns> public bool ContainsUID(string uid) { foreach (POP3_Message message in m_pMessages) { if (message.UID.ToLower() == uid.ToLower()) { return true; } } return false; } /// <summary> /// Removes all messages from the collection. /// </summary> public void Clear() { m_pMessages.Clear(); } /// <summary> /// Checks if message exists. NOTE marked for delete messages returns false. /// </summary> /// <param name="sequenceNo">Message 1 based sequence number.</param> /// <returns></returns> public bool MessageExists(int sequenceNo) { if (sequenceNo > 0 && sequenceNo <= m_pMessages.Count) { if (!m_pMessages[sequenceNo - 1].MarkedForDelete) { return true; } } return false; } /// <summary> /// Gets messages total sizes. NOTE messages marked for deletion is excluded. /// </summary> /// <returns></returns> public long GetTotalMessagesSize() { long totalSize = 0; foreach (POP3_Message msg in m_pMessages) { if (!msg.MarkedForDelete) { totalSize += msg.Size; } } return totalSize; } /// <summary> /// Resets deleted flags on all messages. /// </summary> public void ResetDeletedFlag() { foreach (POP3_Message msg in m_pMessages) { msg.MarkedForDelete = false; } } /// <summary> /// Gets enumerator. /// </summary> /// <returns></returns> public IEnumerator GetEnumerator() { return m_pMessages.GetEnumerator(); } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/IO/QuotedPrintableStream.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.IO { #region usings using System; using System.Globalization; using System.IO; #endregion /// <summary> /// Implements RFC 2045 6.7. Quoted-Printable stream. /// </summary> public class QuotedPrintableStream : Stream { #region Members private readonly FileAccess m_AccessMode = FileAccess.ReadWrite; private readonly byte[] m_pDecodedBuffer; private readonly byte[] m_pEncodedBuffer; private readonly SmartStream m_pStream; private int m_DecodedCount; private int m_DecodedOffset; private int m_EncodedCount; private byte[] line_buf; #endregion #region Properties /// <summary> /// Gets a value indicating whether the current stream supports reading. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> public override bool CanRead { get { return (m_AccessMode & FileAccess.Read) != 0; } } /// <summary> /// Gets a value indicating whether the current stream supports seeking. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> public override bool CanSeek { get { return false; } } /// <summary> /// Gets a value indicating whether the current stream supports writing. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> public override bool CanWrite { get { return (m_AccessMode & FileAccess.Write) != 0; } } /// <summary> /// Gets the length in bytes of the stream. This method is not supported and always throws a NotSupportedException. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> /// <exception cref="NotSupportedException">Is raised when this property is accessed.</exception> public override long Length { get { throw new NotSupportedException(); } } /// <summary> /// Gets or sets the position within the current stream. This method is not supported and always throws a NotSupportedException. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> /// <exception cref="NotSupportedException">Is raised when this property is accessed.</exception> public override long Position { get { throw new NotSupportedException(); } set { throw new NotSupportedException(); } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="stream">Source stream.</param> /// <param name="access">Specifies stream access mode.</param> /// <exception cref="ArgumentNullException">Is raised when <b>stream</b> is null reference.</exception> public QuotedPrintableStream(SmartStream stream, FileAccess access) { if (stream == null) { throw new ArgumentNullException("stream"); } m_pStream = stream; m_AccessMode = access; m_pDecodedBuffer = new byte[Workaround.Definitions.MaxStreamLineLength]; m_pEncodedBuffer = new byte[78]; line_buf = new byte[Workaround.Definitions.MaxStreamLineLength]; } #endregion #region Methods /// <summary> /// Clears all buffers for this stream and causes any buffered data to be written to the underlying device. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> public override void Flush() { if (m_EncodedCount > 0) { m_pStream.Write(m_pEncodedBuffer, 0, m_EncodedCount); m_EncodedCount = 0; } } /// <summary> /// Sets the position within the current stream. This method is not supported and always throws a NotSupportedException. /// </summary> /// <param name="offset">A byte offset relative to the <b>origin</b> parameter.</param> /// <param name="origin">A value of type SeekOrigin indicating the reference point used to obtain the new position.</param> /// <returns>The new position within the current stream.</returns> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="NotSupportedException">Is raised when this method is accessed.</exception> public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(); } /// <summary> /// Sets the length of the current stream. This method is not supported and always throws a NotSupportedException. /// </summary> /// <param name="value">The desired length of the current stream in bytes.</param> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="NotSupportedException">Is raised when this method is accessed.</exception> public override void SetLength(long value) { throw new NotSupportedException(); } /// <summary> /// Reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read. /// </summary> /// <param name="buffer">An array of bytes. When this method returns, the buffer contains the specified byte array with the values between offset and (offset + count - 1) replaced by the bytes read from the current source.</param> /// <param name="offset">The zero-based byte offset in buffer at which to begin storing the data read from the current stream.</param> /// <param name="count">The maximum number of bytes to be read from the current stream.</param> /// <returns>The total number of bytes read into the buffer. This can be less than the number of bytes requested if that many bytes are not currently available, or zero (0) if the end of the stream has been reached.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>buffer</b> is null reference.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> /// <exception cref="NotSupportedException">Is raised when reading not supported.</exception> public override int Read(byte[] buffer, int offset, int count) { if (buffer == null) { throw new ArgumentNullException("buffer"); } if (offset < 0 || offset > buffer.Length) { throw new ArgumentException("Invalid argument 'offset' value."); } if (offset + count > buffer.Length) { throw new ArgumentException("Invalid argument 'count' value."); } if ((m_AccessMode & FileAccess.Read) == 0) { throw new NotSupportedException(); } while (true) { // Read next quoted-printable line and decode it. if (m_DecodedOffset >= m_DecodedCount) { m_DecodedOffset = 0; m_DecodedCount = 0; SmartStream.ReadLineAsyncOP readLineOP = new SmartStream.ReadLineAsyncOP(line_buf, SizeExceededAction . ThrowException); m_pStream.ReadLine(readLineOP, false); // IO error reading line. if (readLineOP.Error != null) { throw readLineOP.Error; } // We reached end of stream. else if (readLineOP.BytesInBuffer == 0) { return 0; } // Decode quoted-printable line. else { // Process bytes. bool softLineBreak = false; int lineLength = readLineOP.LineBytesInBuffer; for (int i = 0; i < readLineOP.LineBytesInBuffer; i++) { byte b = readLineOP.Buffer[i]; // We have soft line-break. if (b == '=' && i == (lineLength - 1)) { softLineBreak = true; } // We should have =XX char. else if (b == '=') { byte b1 = readLineOP.Buffer[++i]; byte b2 = readLineOP.Buffer[++i]; string b1b2 = ((char)b1).ToString() + (char)b2; byte b1b2_num; if (byte.TryParse(b1b2, NumberStyles.HexNumber, null, out b1b2_num)) { m_pDecodedBuffer[m_DecodedCount++] = b1b2_num; } else { m_pDecodedBuffer[m_DecodedCount++] = b; m_pDecodedBuffer[m_DecodedCount++] = b1; m_pDecodedBuffer[m_DecodedCount++] = b2; } } // Normal char. else { m_pDecodedBuffer[m_DecodedCount++] = b; } } if (!softLineBreak) { m_pDecodedBuffer[m_DecodedCount++] = (byte) '\r'; m_pDecodedBuffer[m_DecodedCount++] = (byte) '\n'; } } } // We some decoded data, return it. if (m_DecodedOffset < m_DecodedCount) { int countToCopy = Math.Min(count, m_DecodedCount - m_DecodedOffset); Array.Copy(m_pDecodedBuffer, m_DecodedOffset, buffer, offset, countToCopy); m_DecodedOffset += countToCopy; return countToCopy; } } } /// <summary> /// Encodes a sequence of bytes, writes to the current stream and advances the current position within this stream by the number of bytes written. /// </summary> /// <param name="buffer">An array of bytes. This method copies count bytes from buffer to the current stream.</param> /// <param name="offset">The zero-based byte offset in buffer at which to begin copying bytes to the current stream.</param> /// <param name="count">The number of bytes to be written to the current stream.</param> /// <exception cref="ArgumentNullException">Is raised when <b>buffer</b> is null reference.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> /// <exception cref="NotSupportedException">Is raised when reading not supported.</exception> public override void Write(byte[] buffer, int offset, int count) { if (buffer == null) { throw new ArgumentNullException("buffer"); } if (offset < 0 || offset > buffer.Length) { throw new ArgumentException("Invalid argument 'offset' value."); } if (offset + count > buffer.Length) { throw new ArgumentException("Invalid argument 'count' value."); } if ((m_AccessMode & FileAccess.Write) == 0) { throw new NotSupportedException(); } // Process bytes. for (int i = 0; i < count; i++) { byte b = buffer[offset + i]; // We don't need to encode byte. if ((b >= 33 && b <= 60) || (b >= 62 && b <= 126)) { // Maximum allowed quoted-printable line length reached, do soft line break. if (m_EncodedCount >= 75) { m_pEncodedBuffer[m_EncodedCount++] = (byte) '='; m_pEncodedBuffer[m_EncodedCount++] = (byte) '\r'; m_pEncodedBuffer[m_EncodedCount++] = (byte) '\n'; // Write encoded data to underlying stream. Flush(); } m_pEncodedBuffer[m_EncodedCount++] = b; } // We need to encode byte. else { // Maximum allowed quote-printable line length reached, do soft line break. if (m_EncodedCount >= 73) { m_pEncodedBuffer[m_EncodedCount++] = (byte) '='; m_pEncodedBuffer[m_EncodedCount++] = (byte) '\r'; m_pEncodedBuffer[m_EncodedCount++] = (byte) '\n'; // Write encoded data to underlying stream. Flush(); } // Encode byte. m_pEncodedBuffer[m_EncodedCount++] = (byte) '='; m_pEncodedBuffer[m_EncodedCount++] = (byte) (b >> 4).ToString("x")[0]; m_pEncodedBuffer[m_EncodedCount++] = (byte) (b & 0xF).ToString("x")[0]; } } } #endregion } }<file_sep>/module/ASC.Api/ASC.Api.Mail/MailApi.Attachments.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.IO; using System.Web; using ASC.Api.Attributes; using ASC.Mail.Core.Engine; using ASC.Mail.Data.Contracts; using ASC.Mail.Utils; using ASC.Mail.Core.Engine.Operations.Base; using System.Threading; // ReSharper disable InconsistentNaming namespace ASC.Api.Mail { public partial class MailApi { /// <summary> /// Export all message's attachments to MyDocuments /// </summary> /// <param name="id_message">Id of any message</param> /// <param name="id_folder" optional="true">Id of Documents folder (if empty then @My)</param> /// <returns>Count of exported attachments</returns> /// <category>Messages</category> [Update(@"messages/attachments/export")] public int ExportAttachmentsToDocuments(int id_message, string id_folder = null) { if (id_message < 1) throw new ArgumentException(@"Invalid message id", "id_message"); if (string.IsNullOrEmpty(id_folder)) id_folder = DocumentsEngine.MY_DOCS_FOLDER_ID; var scheme = HttpContext.Current == null ? Uri.UriSchemeHttp : HttpContext.Current.Request.GetUrlRewriter().Scheme; var documentsDal = new DocumentsEngine(TenantId, Username, scheme); var savedAttachmentsList = documentsDal.StoreAttachmentsToDocuments(id_message, id_folder); return savedAttachmentsList.Count; } /// <summary> /// Export attachment to MyDocuments /// </summary> /// <param name="id_attachment">Id of any attachment from the message</param> /// <param name="id_folder" optional="true">Id of Documents folder (if empty then @My)</param> /// <returns>Id document in My Documents</returns> /// <category>Messages</category> [Update(@"messages/attachment/export")] public object ExportAttachmentToDocuments(int id_attachment, string id_folder = null) { if (id_attachment < 1) throw new ArgumentException(@"Invalid attachment id", "id_attachment"); if (string.IsNullOrEmpty(id_folder)) id_folder = DocumentsEngine.MY_DOCS_FOLDER_ID; var scheme = HttpContext.Current == null ? Uri.UriSchemeHttp : HttpContext.Current.Request.GetUrlRewriter().Scheme; var documentsDal = new DocumentsEngine(TenantId, Username, scheme); var documentId = documentsDal.StoreAttachmentToDocuments(id_attachment, id_folder); return documentId; } /// <summary> /// Add attachment to draft /// </summary> /// <param name="id_message">Id of any message</param> /// <param name="name">File name</param> /// <param name="file">File stream</param> /// <param name="content_type">File content type</param> /// <returns>MailAttachment</returns> /// <category>Messages</category> [Create(@"messages/attachment/add")] public MailAttachmentData AddAttachment(int id_message, string name, Stream file, string content_type) { var attachment = MailEngineFactory.AttachmentEngine .AttachFileToDraft(TenantId, Username, id_message, name, file, file.Length, content_type); return attachment; } /// <summary> /// Add attachment to draft /// </summary> /// <param name="id_message">Id of any message</param> /// <param name="ical_body">File name</param> /// <returns>MailAttachment</returns> /// <category>Messages</category> [Create(@"messages/calendarbody/add")] public MailAttachmentData AddCalendarBody(int id_message, string ical_body) { if (string.IsNullOrEmpty(ical_body)) throw new ArgumentException(@"Empty calendar body", "ical_body"); var calendar = MailUtil.ParseValidCalendar(ical_body, _log); if (calendar == null) throw new ArgumentException(@"Invalid calendar body", "ical_body"); using (var ms = new MemoryStream()) { using (var writer = new StreamWriter(ms)) { writer.Write(ical_body); writer.Flush(); ms.Position = 0; var attachment = MailEngineFactory.AttachmentEngine .AttachFileToDraft(TenantId, Username, id_message, calendar.Method.ToLowerInvariant() + ".ics", ms, ms.Length, "text/calendar"); return attachment; } } } /// <summary> /// Download all attachments from message /// </summary> /// <short> /// Download all attachments from message /// </short> /// <param name="messageId">Id of message</param> /// <returns>Attachment Archive</returns> [Update(@"messages/attachment/downloadall/{messageId}")] public MailOperationStatus DownloadAllAttachments(int messageId) { Thread.CurrentThread.CurrentCulture = CurrentCulture; Thread.CurrentThread.CurrentUICulture = CurrentCulture; return MailEngineFactory.OperationEngine.DownloadAllAttachments(messageId, TranslateMailOperationStatus); } } } <file_sep>/common/ASC.Core.Common/Notify/PushSenderSink.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections.Generic; using System.Linq; using ASC.Common.Logging; using ASC.Core.Common.Notify.Push; using ASC.Core.Configuration; using ASC.Notify.Messages; using ASC.Notify.Sinks; namespace ASC.Core.Common.Notify { class PushSenderSink : Sink { private readonly ILog _log = LogManager.GetLogger("ASC"); private bool configured = true; public override SendResponse ProcessMessage(INoticeMessage message) { try { var notification = new PushNotification { Module = GetTagValue<PushModule>(message, PushConstants.PushModuleTagName), Action = GetTagValue<PushAction>(message, PushConstants.PushActionTagName), Item = GetTagValue<PushItem>(message, PushConstants.PushItemTagName), ParentItem = GetTagValue<PushItem>(message, PushConstants.PushParentItemTagName), Message = message.Body, ShortMessage = message.Subject }; if (configured) { try { using (var pushClient = new PushServiceClient()) { pushClient.EnqueueNotification( CoreContext.TenantManager.GetCurrentTenant().TenantId, message.Recipient.ID, notification, new List<string>()); } } catch (InvalidOperationException) { configured = false; _log.Debug("push sender endpoint is not configured!"); } } else { _log.Debug("push sender endpoint is not configured!"); } return new SendResponse(message, Constants.NotifyPushSenderSysName, SendResult.OK); } catch (Exception error) { return new SendResponse(message, Constants.NotifyPushSenderSysName, error); } } private T GetTagValue<T>(INoticeMessage message, string tagName) { var tag = message.Arguments.FirstOrDefault(arg => arg.Tag == tagName); return tag != null ? (T)tag.Value : default(T); } } } <file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Autoreply/AddressParsers/CommentAddressParser.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using ASC.Core.Tenants; using ASC.Mail.Autoreply.ParameterResolvers; namespace ASC.Mail.Autoreply.AddressParsers { internal class CommentAddressParser : AddressParser { protected readonly string[] CommunityTypes = new[] {"blog", @"forum\.topic", "event", "wiki", "bookmark"}; protected readonly string[] ProjectsTypes = new[] {@"project\.milestone", @"project\.task", @"project\.message"}; protected readonly string[] FilesTypes = new[] {"file"}; private Regex _routeRegex; protected override Regex GetRouteRegex() { if (_routeRegex == null) { var regex = new StringBuilder(); regex.Append("^reply_(?'type'"); regex.Append(string.Join("|", CommunityTypes)); regex.Append("|"); regex.Append(string.Join("|", ProjectsTypes)); regex.Append("|"); regex.Append(string.Join("|", FilesTypes)); regex.Append(")_(?'postId'[-0-9a-zA-Z]+)_(?'parentId'[-0-9a-zA-Z]*)$"); _routeRegex = new Regex(regex.ToString(), RegexOptions.Compiled); } return _routeRegex; } protected override ApiRequest ParseRequestInfo(IDictionary<string, string> groups, Tenant t) { ApiRequest requestInfo; if (groups["type"] == @"forum.topic") { requestInfo = new ApiRequest(string.Format("community/{0}/{1}", groups["type"].Replace(@"\", "").Replace('.', '/'), groups["postId"])) { Parameters = new List<RequestParameter> { new RequestParameter("subject", new TitleResolver()), new RequestParameter("content", new HtmlContentResolver()) } }; if (!string.IsNullOrEmpty(groups["parentId"])) { requestInfo.Parameters.Add(new RequestParameter("parentPostId", groups["parentId"])); } } else { requestInfo = new ApiRequest(string.Format("{0}/{1}/comment", groups["type"].Replace(@"\", "").Replace('.', '/'), groups["postId"])) { Parameters = new List<RequestParameter> { new RequestParameter("content", new HtmlContentResolver()) } }; if (!string.IsNullOrEmpty(groups["parentId"])) { requestInfo.Parameters.Add(new RequestParameter("parentId", groups["parentId"])); } } if (CommunityTypes.Contains(groups["type"])) { requestInfo.Url = "community/" + requestInfo.Url; } return requestInfo; } } } <file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/Data/DbFile.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Data.lsDB { #region usings using System; using System.Collections; using System.IO; using System.Threading; using Net; #endregion /// <summary> /// LumiSoft database file. /// </summary> public class DbFile : IDisposable { #region Members private readonly LDB_DataColumnCollection m_pColumns; private int m_DataPageDataAreaSize = 1000; private long m_DatapagesStartOffset = -1; private string m_DbFileName = ""; private long m_FileLength; private long m_FilePosition; private LDB_Record m_pCurrentRecord; private FileStream m_pDbFile; private bool m_TableLocked; #endregion #region Properties /// <summary> /// Gets if there is active database file. /// </summary> public bool IsDatabaseOpen { get { return m_pDbFile != null; } } /// <summary> /// Gets open database file name. Throws exception if database isn't open. /// </summary> public string FileName { get { if (!IsDatabaseOpen) { throw new Exception("Database isn't open, please open database first !"); } return m_DbFileName; } } /// <summary> /// Gets table columns. Throws exception if database isn't open. /// </summary> public LDB_DataColumnCollection Columns { get { if (!IsDatabaseOpen) { throw new Exception("Database isn't open, please open database first !"); } return m_pColumns; } } /// <summary> /// Gets current record. Returns null if there isn't current record. /// </summary> public LDB_Record CurrentRecord { get { return m_pCurrentRecord; } } /// <summary> /// Gets table is locked. /// </summary> public bool TableLocked { get { return m_TableLocked; } } /// <summary> /// Gets how much data data page can store. /// </summary> public int DataPageDataAreaSize { get { return m_DataPageDataAreaSize; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> public DbFile() { m_pColumns = new LDB_DataColumnCollection(this); } #endregion #region Methods /// <summary> /// Clean up any resources being used. /// </summary> public void Dispose() { Close(); } /// <summary> /// Opens specified data file. /// </summary> /// <param name="fileName">File name.</param> public void Open(string fileName) { Open(fileName, 0); } /// <summary> /// Opens specified data file. /// </summary> /// <param name="fileName">File name.</param> /// <param name="waitTime">If data base file is exclusively locked, then how many seconds to wait file to unlock before raising a error.</param> public void Open(string fileName, int waitTime) { DateTime lockExpireTime = DateTime.Now.AddSeconds(waitTime); while (true) { try { m_pDbFile = File.Open(fileName, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite); break; } catch (IOException x) { // Make this because to get rid of "The variable 'x' is declared but never used" string dummy = x.Message; Thread.Sleep(15); // Lock wait time timed out if (DateTime.Now > lockExpireTime) { throw new Exception("Database file is locked and lock wait time expired !"); } } } /* Table structure: 50 bytes - version 2 bytes - CRLF 8 bytes - free datapages count 2 bytes - CRLF 4 bytes - datapage data area size 2 bytes - CRLF 100 x 500 bytes - 100 columns info store 2 bytes - CRLF ... data pages */ m_DbFileName = fileName; StreamLineReader r = new StreamLineReader(m_pDbFile); // TODO: check if LDB file // Read version line (50 bytes + CRLF) byte[] version = r.ReadLine(); // Skip free data pages count byte[] freeDataPagesCount = new byte[10]; m_pDbFile.Read(freeDataPagesCount, 0, freeDataPagesCount.Length); // 4 bytes datapage data area size + CRLF byte[] dataPageDataAreaSize = new byte[6]; m_pDbFile.Read(dataPageDataAreaSize, 0, dataPageDataAreaSize.Length); m_DataPageDataAreaSize = ldb_Utils.ByteToInt(dataPageDataAreaSize, 0); // Read 100 column lines (500 + CRLF bytes each) for (int i = 0; i < 100; i++) { byte[] columnInfo = r.ReadLine(); if (columnInfo == null) { throw new Exception("Invalid columns data area length !"); } if (columnInfo[0] != '\0') { m_pColumns.Parse(columnInfo); } } // Header terminator \0 m_pDbFile.Position++; // No we have rows start offset m_DatapagesStartOffset = m_pDbFile.Position; // Store file length and position m_FileLength = m_pDbFile.Length; m_FilePosition = m_pDbFile.Position; } /// <summary> /// Closes database file. /// </summary> public void Close() { if (m_pDbFile != null) { m_pDbFile.Close(); m_pDbFile = null; m_DbFileName = ""; m_FileLength = 0; m_FilePosition = 0; } } /// <summary> /// Creates new database file. /// </summary> /// <param name="fileName">File name.</param> public void Create(string fileName) { Create(fileName, 1000); } /// <summary> /// Creates new database file. /// </summary> /// <param name="fileName">File name.</param> /// <param name="dataPageDataAreaSize">Specifies how many data can data page store.</param> public void Create(string fileName, int dataPageDataAreaSize) { m_pDbFile = new FileStream(fileName, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.None); /* Table structure: 50 bytes - version 2 bytes - CRLF 8 bytes - free datapages count 2 bytes - CRLF 4 bytes - datapage data area size 2 bytes - CRLF 100 x 500 bytes - 100 columns info store 2 bytes - CRLF ... data pages */ // Version 50 + CRLF bytes byte[] versionData = new byte[52]; versionData[0] = (byte) '1'; versionData[1] = (byte) '.'; versionData[2] = (byte) '0'; versionData[50] = (byte) '\r'; versionData[51] = (byte) '\n'; m_pDbFile.Write(versionData, 0, versionData.Length); // 8 bytes free data pages count + CRLF byte[] freeDataPagesCount = new byte[10]; freeDataPagesCount[8] = (byte) '\r'; freeDataPagesCount[9] = (byte) '\n'; m_pDbFile.Write(freeDataPagesCount, 0, freeDataPagesCount.Length); // 4 bytes datapage data area size + CRLF byte[] dataPageDataAreaSizeB = new byte[6]; Array.Copy(ldb_Utils.IntToByte(dataPageDataAreaSize), 0, dataPageDataAreaSizeB, 0, 4); dataPageDataAreaSizeB[4] = (byte) '\r'; dataPageDataAreaSizeB[5] = (byte) '\n'; m_pDbFile.Write(dataPageDataAreaSizeB, 0, dataPageDataAreaSizeB.Length); // 100 x 100 + CRLF bytes header lines for (int i = 0; i < 100; i++) { byte[] data = new byte[100]; m_pDbFile.Write(data, 0, data.Length); m_pDbFile.Write(new byte[] {(int) '\r', (int) '\n'}, 0, 2); } // Headers terminator char(0) m_pDbFile.WriteByte((int) '\0'); // Data pages start pointer m_DatapagesStartOffset = m_pDbFile.Position - 1; m_DbFileName = fileName; m_DataPageDataAreaSize = dataPageDataAreaSize; // Store file length and position m_FileLength = m_pDbFile.Length; m_FilePosition = m_pDbFile.Position; } /// <summary> /// Locks table. /// </summary> /// <param name="waitTime">If table is locked, then how many sconds to wait table to unlock, before teturning error.</param> public void LockTable(int waitTime) { if (!IsDatabaseOpen) { throw new Exception("Database isn't open, please open database first !"); } // Table is locked already, just skip locking if (m_TableLocked) { return; } DateTime lockExpireTime = DateTime.Now.AddSeconds(waitTime); while (true) { try { // We just lock first byte m_pDbFile.Lock(0, 1); m_TableLocked = true; break; } // Catch the IOException generated if the // specified part of the file is locked. catch (IOException x) { // Make this because to get rid of "The variable 'x' is declared but never used" string dummy = x.Message; Thread.Sleep(15); // Lock wait time timed out if (DateTime.Now > lockExpireTime) { throw new Exception("Table is locked and lock wait time expired !"); } } } } /// <summary> /// Unlock table. /// </summary> public void UnlockTable() { if (!IsDatabaseOpen) { throw new Exception("Database isn't open, please open database first !"); } if (m_TableLocked) { // We just unlock first byte m_pDbFile.Unlock(0, 1); } } /* /// <summary> /// Locks current record. /// </summary> public void LockRecord() { if(!this.IsDatabaseOpen){ throw new Exception("Database isn't open, please open database first !"); } } */ /* /// <summary> /// Unlocks current record. /// </summary> public void UnlockRecord() { if(!this.IsDatabaseOpen){ throw new Exception("Database isn't open, please open database first !"); } } */ /// <summary> /// Gets next record. Returns true if end of file reached and there are no more records. /// </summary> /// <returns>Returns true if end of file reached and there are no more records.</returns> public bool NextRecord() { if (!IsDatabaseOpen) { throw new Exception("Database isn't open, please open database first !"); } //--- Find next record ---------------------------------------------------// long nextRowStartOffset = 0; if (m_pCurrentRecord == null) { nextRowStartOffset = m_DatapagesStartOffset; } else { nextRowStartOffset = m_pCurrentRecord.DataPage.Pointer + m_DataPageDataAreaSize + 33; } while (true) { if (m_FileLength > nextRowStartOffset) { DataPage dataPage = new DataPage(m_DataPageDataAreaSize, this, nextRowStartOffset); // We want datapage with used space if (dataPage.Used && dataPage.OwnerDataPagePointer < 1) { m_pCurrentRecord = new LDB_Record(this, dataPage); break; } } else { return true; } nextRowStartOffset += m_DataPageDataAreaSize + 33; } //-------------------------------------------------------------------------// return false; } /// <summary> /// Appends new record to table. /// </summary> public void AppendRecord(object[] values) { if (!IsDatabaseOpen) { throw new Exception("Database isn't open, please open database first !"); } if (m_pColumns.Count != values.Length) { throw new Exception("Each column must have corresponding value !"); } bool unlock = true; // Table is already locked, don't lock it if (TableLocked) { unlock = false; } else { LockTable(15); } // Construct record data byte[] record = LDB_Record.CreateRecord(this, values); // Get free data pages DataPage[] dataPages = GetDataPages(0, (int) Math.Ceiling(record.Length/(double) m_DataPageDataAreaSize)); StoreDataToDataPages(m_DataPageDataAreaSize, record, dataPages); if (unlock) { UnlockTable(); } } /// <summary> /// Deletes current record. /// </summary> public void DeleteCurrentRecord() { if (!IsDatabaseOpen) { throw new Exception("Database isn't open, please open database first !"); } if (m_pCurrentRecord == null) { throw new Exception("There is no current record !"); } bool unlock = true; // Table is already locked, don't lock it if (TableLocked) { unlock = false; } else { LockTable(15); } // Release all data pages hold by this row DataPage[] dataPages = m_pCurrentRecord.DataPages; for (int i = 0; i < dataPages.Length; i++) { DataPage p = dataPages[i]; byte[] dataPage = DataPage.CreateDataPage(m_DataPageDataAreaSize, false, 0, 0, 0, new byte[m_DataPageDataAreaSize]); SetFilePosition(p.Pointer); WriteToFile(dataPage, 0, dataPage.Length); } // Increase free data pages count info in table header byte[] freeDataPagesCount = new byte[8]; SetFilePosition(52); ReadFromFile(freeDataPagesCount, 0, freeDataPagesCount.Length); freeDataPagesCount = ldb_Utils.LongToByte(ldb_Utils.ByteToLong(freeDataPagesCount, 0) + dataPages.Length); SetFilePosition(52); WriteToFile(freeDataPagesCount, 0, freeDataPagesCount.Length); if (unlock) { UnlockTable(); } // Activate next record **** Change it ??? NextRecord(); } #endregion #region Utility methods /// <summary> /// Moves position to the end of file. /// </summary> private void GoToFileEnd() { m_pDbFile.Position = m_pDbFile.Length; m_FileLength = m_pDbFile.Length; m_FilePosition = m_FileLength; } #endregion #region Internal methods /// <summary> /// Stores data to specified data pages. /// </summary> /// <param name="dataPageDataAreaSize">Data page data area size.</param> /// <param name="data">Data to store.</param> /// <param name="dataPages">Data pages where to store data.</param> internal static void StoreDataToDataPages(int dataPageDataAreaSize, byte[] data, DataPage[] dataPages) { if ((int) Math.Ceiling(data.Length/(double) dataPageDataAreaSize) > dataPages.Length) { throw new Exception("There isn't enough data pages to store data ! Data needs '" + (int) Math.Ceiling(data.Length/(double) dataPageDataAreaSize) + "' , but available '" + dataPages.Length + "'."); } //--- Store data to data page(s) -----------------------// long position = 0; for (int i = 0; i < dataPages.Length; i++) { if ((data.Length - position) > dataPageDataAreaSize) { byte[] d = new byte[dataPageDataAreaSize]; Array.Copy(data, position, d, 0, d.Length); dataPages[i].WriteData(d); position += dataPageDataAreaSize; } else { byte[] d = new byte[data.Length - position]; Array.Copy(data, position, d, 0, d.Length); dataPages[i].WriteData(d); } } //------------------------------------------------------// } /// <summary> /// Gets specified number of free data pages. If free data pages won't exist, creates new ones. /// Data pages are marked as used and OwnerDataPagePointer and NextDataPagePointer is set as needed. /// </summary> /// <param name="ownerDataPagePointer">Owner data page pointer that own first requested data page. If no owner then this value is 0.</param> /// <param name="count">Number of data pages wanted.</param> internal DataPage[] GetDataPages(long ownerDataPagePointer, int count) { if (!TableLocked) { throw new Exception("Table must be locked to acess GetDataPages() method !"); } ArrayList freeDataPages = new ArrayList(); // Get free data pages count from table header byte[] freeDataPagesCount = new byte[8]; SetFilePosition(52); ReadFromFile(freeDataPagesCount, 0, freeDataPagesCount.Length); long nFreeDataPages = ldb_Utils.ByteToLong(freeDataPagesCount, 0); // We have plenty free data pages and enough for count requested, find requested count free data pages if (nFreeDataPages > 1000 && nFreeDataPages > count) { long nextDataPagePointer = m_DatapagesStartOffset + 1; while (freeDataPages.Count < count) { DataPage dataPage = new DataPage(m_DataPageDataAreaSize, this, nextDataPagePointer); if (!dataPage.Used) { dataPage.Used = true; freeDataPages.Add(dataPage); } nextDataPagePointer += m_DataPageDataAreaSize + 33; } // Decrease free data pages count in table header SetFilePosition(52); ReadFromFile(ldb_Utils.LongToByte(nFreeDataPages - count), 0, 8); } // Just create new data pages else { for (int i = 0; i < count; i++) { byte[] dataPage = DataPage.CreateDataPage(m_DataPageDataAreaSize, true, 0, 0, 0, new byte[m_DataPageDataAreaSize]); GoToFileEnd(); long dataPageStartPointer = GetFilePosition(); WriteToFile(dataPage, 0, dataPage.Length); freeDataPages.Add(new DataPage(m_DataPageDataAreaSize, this, dataPageStartPointer)); } } // Relate data pages (chain) for (int i = 0; i < freeDataPages.Count; i++) { // First data page if (i == 0) { // Owner data page poitner specified for first data page if (ownerDataPagePointer > 0) { ((DataPage) freeDataPages[i]).OwnerDataPagePointer = ownerDataPagePointer; } // There is continuing data page if (freeDataPages.Count > 1) { ((DataPage) freeDataPages[i]).NextDataPagePointer = ((DataPage) freeDataPages[i + 1]).Pointer; } } // Last data page else if (i == (freeDataPages.Count - 1)) { ((DataPage) freeDataPages[i]).OwnerDataPagePointer = ((DataPage) freeDataPages[i - 1]).Pointer; } // Middle range data page else { ((DataPage) freeDataPages[i]).OwnerDataPagePointer = ((DataPage) freeDataPages[i - 1]).Pointer; ((DataPage) freeDataPages[i]).NextDataPagePointer = ((DataPage) freeDataPages[i + 1]).Pointer; } } DataPage[] retVal = new DataPage[freeDataPages.Count]; freeDataPages.CopyTo(retVal); return retVal; } /// <summary> /// Adds column to db file. /// </summary> /// <param name="column"></param> internal void AddColumn(LDB_DataColumn column) { // Find free column data area // Set position over version, free data pages count and data page data area size m_pDbFile.Position = 68; long freeColumnPosition = -1; StreamLineReader r = new StreamLineReader(m_pDbFile); // Loop all columns data areas, see it there any free left for (int i = 0; i < 100; i++) { byte[] columnInfo = r.ReadLine(); if (columnInfo == null) { throw new Exception("Invalid columns data area length !"); } // We found unused column data area if (columnInfo[0] == '\0') { freeColumnPosition = m_pDbFile.Position; break; } } m_FilePosition = m_pDbFile.Position; if (freeColumnPosition != -1) { // TODO: If there is data ??? // Move to row start SetFilePosition(GetFilePosition() - 102); // Store column byte[] columnData = column.ToColumnInfo(); WriteToFile(columnData, 0, columnData.Length); } else { throw new Exception("Couldn't find free column space ! "); } } /// <summary> /// Removes specified column from database file. /// </summary> /// <param name="column"></param> internal void RemoveColumn(LDB_DataColumn column) { throw new Exception("TODO:"); } /// <summary> /// Reads data from file. /// </summary> /// <param name="data">Buffer where to store readed data..</param> /// <param name="offset">Offset in array to where to start storing readed data.</param> /// <param name="count">Number of bytes to read.</param> /// <returns></returns> internal int ReadFromFile(byte[] data, int offset, int count) { int readed = m_pDbFile.Read(data, offset, count); m_FilePosition += readed; return readed; } /// <summary> /// Writes data to file. /// </summary> /// <param name="data">Data to write.</param> /// <param name="offset">Offset in array from where to start writing data.</param> /// <param name="count">Number of bytes to write.</param> /// <returns></returns> internal void WriteToFile(byte[] data, int offset, int count) { m_pDbFile.Write(data, offset, count); m_FilePosition += count; } /// <summary> /// Gets current position in file. /// </summary> /// <returns></returns> internal long GetFilePosition() { return m_FilePosition; } /// <summary> /// Sets file position. /// </summary> /// <param name="position">Position in file.</param> internal void SetFilePosition(long position) { if (m_FilePosition != position) { m_pDbFile.Position = position; m_FilePosition = position; } } #endregion } }<file_sep>/common/ASC.Data.Backup/ZipOperator.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections.Generic; using System.IO; using SharpCompress.Common; using SharpCompress.Readers; using SharpCompress.Writers; namespace ASC.Data.Backup { public class ZipWriteOperator : IDataWriteOperator { private readonly IWriter writer; private readonly Stream file; public ZipWriteOperator(string targetFile) { file = new FileStream(targetFile, FileMode.Create); writer = WriterFactory.Open(file, ArchiveType.Tar, CompressionType.GZip); } public void WriteEntry(string key, string source) { writer.Write(key, source); } public void Dispose() { writer.Dispose(); file.Close(); } } public class ZipReadOperator : IDataReadOperator { private readonly string tmpdir; public List<string> Entries { get; private set; } public ZipReadOperator(string targetFile) { tmpdir = Path.Combine(Path.GetDirectoryName(targetFile), Path.GetFileNameWithoutExtension(targetFile).Replace('>', '_').Replace(':', '_').Replace('?', '_')); Entries = new List<string>(); using (var stream = File.OpenRead(targetFile)) { var reader = ReaderFactory.Open(stream, new ReaderOptions { LookForHeader = true, LeaveStreamOpen = true }); while (reader.MoveToNextEntry()) { if (reader.Entry.IsDirectory) continue; if (reader.Entry.Key == "././@LongLink") { string fullPath; using (var streamReader = new StreamReader(reader.OpenEntryStream())) { fullPath = streamReader.ReadToEnd().TrimEnd(char.MinValue); } fullPath = Path.Combine(tmpdir, fullPath); if (!Directory.Exists(Path.GetDirectoryName(fullPath))) { Directory.CreateDirectory(Path.GetDirectoryName(fullPath)); } reader.MoveToNextEntry(); using (var fileStream = File.Create(fullPath)) using (var entryStream = reader.OpenEntryStream()) { entryStream.StreamCopyTo(fileStream); } } else { try { reader.WriteEntryToDirectory(tmpdir, new ExtractionOptions { ExtractFullPath = true, Overwrite = true }); } catch (ArgumentException) { } } Entries.Add(reader.Entry.Key); } } } public Stream GetEntry(string key) { var filePath = Path.Combine(tmpdir, key); return File.Exists(filePath) ? File.Open(filePath, FileMode.Open, FileAccess.ReadWrite, FileShare.Read) : null; } public void Dispose() { if (Directory.Exists(tmpdir)) { Directory.Delete(tmpdir, true); } } } }<file_sep>/module/ASC.Api/ASC.Api.Settings/SettingsApi.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Configuration; using System.Globalization; using System.Linq; using System.Net; using System.Security; using System.ServiceModel.Security; using System.Web; using System.Web.Optimization; using ASC.Api.Attributes; using ASC.Api.Collections; using ASC.Api.Employee; using ASC.Api.Interfaces; using ASC.Api.Utils; using ASC.Common.Logging; using ASC.Common.Threading; using ASC.Core; using ASC.Core.Billing; using ASC.Core.Common.Configuration; using ASC.Core.Common.Contracts; using ASC.Core.Common.Notify; using ASC.Core.Tenants; using ASC.Core.Users; using ASC.Data.Storage; using ASC.Data.Storage.Configuration; using ASC.Data.Storage.Migration; using ASC.Data.Storage.Encryption; using ASC.IPSecurity; using ASC.MessagingSystem; using ASC.Specific; using ASC.Web.Core; using ASC.Web.Core.Sms; using ASC.Web.Core.Utility; using ASC.Web.Core.Utility.Settings; using ASC.Web.Core.WebZones; using ASC.Web.Core.WhiteLabel; using ASC.Web.Studio.Core; using ASC.Web.Studio.Core.Backup; using ASC.Web.Studio.Core.Notify; using ASC.Web.Studio.Core.Quota; using ASC.Web.Studio.Core.SMS; using ASC.Web.Studio.Core.Statistic; using ASC.Web.Studio.Core.TFA; using ASC.Web.Studio.Utility; using Resources; using SecurityContext = ASC.Core.SecurityContext; using StorageHelper = ASC.Web.Studio.UserControls.CustomNavigation.StorageHelper; namespace ASC.Api.Settings { ///<summary> /// Portal settings ///</summary> public partial class SettingsApi : IApiEntryPoint { private const int ONE_THREAD = 1; private static readonly DistributedTaskQueue ldapTasks = new DistributedTaskQueue("ldapOperations"); private static readonly DistributedTaskQueue quotaTasks = new DistributedTaskQueue("quotaOperations", ONE_THREAD); private static readonly DistributedTaskQueue smtpTasks = new DistributedTaskQueue("smtpOperations"); public string Name { get { return "settings"; } } private static HttpRequest Request { get { return HttpContext.Current.Request; } } private static int CurrentTenant { get { return CoreContext.TenantManager.GetCurrentTenant().TenantId; } } private static Guid CurrentUser { get { return SecurityContext.CurrentAccount.ID; } } private static DistributedTaskQueue LDAPTasks { get { return ldapTasks; } } private static DistributedTaskQueue SMTPTasks { get { return smtpTasks; } } ///<summary> /// Returns the list of all available portal settings with the current values for each one ///</summary> ///<short> /// Portal settings ///</short> ///<returns>Settings</returns> [Read("")] public SettingsWrapper GetSettings() { var settings = new SettingsWrapper(); var tenant = CoreContext.TenantManager.GetCurrentTenant(); settings.Timezone = tenant.TimeZone.ToSerializedString(); settings.UtcOffset = tenant.TimeZone.GetUtcOffset(DateTime.UtcNow); settings.UtcHoursOffset = tenant.TimeZone.GetUtcOffset(DateTime.UtcNow).TotalHours; settings.TrustedDomains = tenant.TrustedDomains; settings.TrustedDomainsType = tenant.TrustedDomainsType; settings.Culture = tenant.GetCulture().ToString(); return settings; } ///<summary> /// Returns space usage quota for portal with the space usage of each module ///</summary> ///<short> /// Space usage ///</short> ///<returns>Space usage and limits for upload</returns> [Read("quota")] public QuotaWrapper GetQuotaUsed() { return QuotaWrapper.GetCurrent(); } ///<summary> /// Start Recalculate Quota Task ///</summary> ///<short> /// Recalculate Quota ///</short> ///<returns></returns> [Read("recalculatequota")] public void RecalculateQuota() { SecurityContext.DemandPermissions(SecutiryConstants.EditPortalSettings); var operations = quotaTasks.GetTasks() .Where(t => t.GetProperty<int>(QuotaSync.TenantIdKey) == TenantProvider.CurrentTenantID); if (operations.Any(o => o.Status <= DistributedTaskStatus.Running)) { throw new InvalidOperationException(Resource.LdapSettingsTooManyOperations); } var op = new QuotaSync(TenantProvider.CurrentTenantID); quotaTasks.QueueTask(op.RunJob, op.GetDistributedTask()); } ///<summary> /// Check Recalculate Quota Task ///</summary> ///<short> /// Check Recalculate Quota Task ///</short> ///<returns>Check Recalculate Quota Task Status</returns> [Read("checkrecalculatequota")] public bool CheckRecalculateQuota() { SecurityContext.DemandPermissions(SecutiryConstants.EditPortalSettings); var task = quotaTasks.GetTasks().FirstOrDefault(t => t.GetProperty<int>(QuotaSync.TenantIdKey) == TenantProvider.CurrentTenantID); if (task != null && task.Status == DistributedTaskStatus.Completed) { quotaTasks.RemoveTask(task.Id); return false; } return task != null; } /// <summary> /// Get build version /// </summary> /// <visible>false</visible> /// <returns>Current onlyoffice, editor, mailserver versions</returns> [Read("version/build", false, false)] //NOTE: this method doesn't requires auth!!! //NOTE: this method doesn't check payment!!! public BuildVersion GetBuildVersions() { return BuildVersion.GetCurrentBuildVersion(); } /// <summary> /// Get list of availibe portal versions including current version /// </summary> /// <short> /// Portal versions /// </short> /// <visible>false</visible> /// <returns>List of availibe portal versions including current version</returns> [Read("version")] public TenantVersionWrapper GetVersions() { return new TenantVersionWrapper(CoreContext.TenantManager.GetCurrentTenant().Version, CoreContext.TenantManager.GetTenantVersions()); } /// <summary> /// Set current portal version to the one with the ID specified in the request /// </summary> /// <short> /// Change portal version /// </short> /// <param name="versionId">Version ID</param> /// <visible>false</visible> /// <returns>List of availibe portal versions including current version</returns> [Update("version")] public TenantVersionWrapper SetVersion(int versionId) { SecurityContext.DemandPermissions(SecutiryConstants.EditPortalSettings); CoreContext.TenantManager.GetTenantVersions().FirstOrDefault(r => r.Id == versionId).NotFoundIfNull(); var tenant = CoreContext.TenantManager.GetCurrentTenant(false); CoreContext.TenantManager.SetTenantVersion(tenant, versionId); return GetVersions(); } /// <summary> /// Returns security settings about product, module or addons /// </summary> /// <short> /// Get security settings /// </short> /// <param name="ids">Module ID list</param> /// <returns></returns> [Read("security")] public IEnumerable<SecurityWrapper> GetWebItemSecurityInfo(IEnumerable<string> ids) { if (ids == null || !ids.Any()) { ids = WebItemManager.Instance.GetItemsAll().Select(i => i.ID.ToString()); } var subItemList = WebItemManager.Instance.GetItemsAll().Where(item => item.IsSubItem()).Select(i => i.ID.ToString()); return ids.Select(WebItemSecurity.GetSecurityInfo) .Select(i => new SecurityWrapper { WebItemId = i.WebItemId, Enabled = i.Enabled, Users = i.Users.Select(EmployeeWraper.Get), Groups = i.Groups.Select(g => new GroupWrapperSummary(g)), IsSubItem = subItemList.Contains(i.WebItemId), }).ToList(); } [Read("security/{id}")] public bool GetWebItemSecurityInfo(Guid id) { var module = WebItemManager.Instance[id]; return module != null && !module.IsDisabled(); } /// <summary> /// Return list of enabled modules /// </summary> /// <short> /// Enabled modules /// </short> /// <visible>false</visible> [Read("security/modules")] public object GetEnabledModules() { var EnabledModules = WebItemManager.Instance.GetItems(WebZoneType.All, ItemAvailableState.Normal) .Where(item => !item.IsSubItem() && item.Visible) .ToList() .Select(item => new { id = item.ProductClassName.HtmlEncode(), title = item.Name.HtmlEncode() }); return EnabledModules; } /// <summary> /// Get portal password settings /// </summary> /// <short> /// Password settings /// </short> [Read("security/password")] public object GetPasswordSettings() { var UserPasswordSettings = PasswordSettings.Load(); return UserPasswordSettings; } /// <summary> /// Set security settings for product, module or addons /// </summary> /// <short> /// Set security settings /// </short> /// <param name="id">Module ID</param> /// <param name="enabled">Enabled</param> /// <param name="subjects">User (Group) ID list</param> [Update("security")] public IEnumerable<SecurityWrapper> SetWebItemSecurity(string id, bool enabled, IEnumerable<Guid> subjects) { SecurityContext.DemandPermissions(SecutiryConstants.EditPortalSettings); WebItemSecurity.SetSecurity(id, enabled, subjects != null ? subjects.ToArray() : null); var securityInfo = GetWebItemSecurityInfo(new List<string> { id }); if (subjects == null) return securityInfo; var productName = GetProductName(new Guid(id)); if (!subjects.Any()) { MessageService.Send(Request, MessageAction.ProductAccessOpened, productName); } else { foreach (var info in securityInfo) { if (info.Groups.Any()) { MessageService.Send(Request, MessageAction.GroupsOpenedProductAccess, productName, info.Groups.Select(x => x.Name)); } if (info.Users.Any()) { MessageService.Send(Request, MessageAction.UsersOpenedProductAccess, productName, info.Users.Select(x => HttpUtility.HtmlDecode(x.DisplayName))); } } } return securityInfo; } /// <summary> /// Set access to products, modules or addons /// </summary> /// <short> /// Set access /// </short> /// <param name="items"></param> [Update("security/access")] public IEnumerable<SecurityWrapper> SetAccessToWebItems(IEnumerable<ItemKeyValuePair<String, Boolean>> items) { SecurityContext.DemandPermissions(SecutiryConstants.EditPortalSettings); var itemList = new ItemDictionary<String, Boolean>(); foreach (ItemKeyValuePair<String, Boolean> item in items) { if (!itemList.ContainsKey(item.Key)) itemList.Add(item.Key, item.Value); } var defaultPageSettings = StudioDefaultPageSettings.Load(); foreach (var item in itemList) { Guid[] subjects = null; var productId = new Guid(item.Key); if (item.Value) { var webItem = WebItemManager.Instance[productId] as IProduct; if (webItem != null || productId == WebItemManager.MailProductID) { var productInfo = WebItemSecurity.GetSecurityInfo(item.Key); var selectedGroups = productInfo.Groups.Select(group => group.ID).ToList(); var selectedUsers = productInfo.Users.Select(user => user.ID).ToList(); selectedUsers.AddRange(selectedGroups); if (selectedUsers.Count > 0) { subjects = selectedUsers.ToArray(); } } } else if (productId == defaultPageSettings.DefaultProductID) { ((StudioDefaultPageSettings)defaultPageSettings.GetDefault()).Save(); } WebItemSecurity.SetSecurity(item.Key, item.Value, subjects); } MessageService.Send(Request, MessageAction.ProductsListUpdated); return GetWebItemSecurityInfo(itemList.Keys.ToList()); } [Read("security/administrator/{productid}")] public IEnumerable<EmployeeWraper> GetProductAdministrators(Guid productid) { return WebItemSecurity.GetProductAdministrators(productid) .Select(EmployeeWraper.Get) .ToList(); } [Read("security/administrator")] public object IsProductAdministrator(Guid productid, Guid userid) { var result = WebItemSecurity.IsProductAdministrator(productid, userid); return new { ProductId = productid, UserId = userid, Administrator = result, }; } [Update("security/administrator")] public object SetProductAdministrator(Guid productid, Guid userid, bool administrator) { SecurityContext.DemandPermissions(SecutiryConstants.EditPortalSettings); WebItemSecurity.SetProductAdministrator(productid, userid, administrator); var admin = CoreContext.UserManager.GetUsers(userid); if (productid == Guid.Empty) { var messageAction = administrator ? MessageAction.AdministratorOpenedFullAccess : MessageAction.AdministratorDeleted; MessageService.Send(Request, messageAction, MessageTarget.Create(admin.ID), admin.DisplayUserName(false)); } else { var messageAction = administrator ? MessageAction.ProductAddedAdministrator : MessageAction.ProductDeletedAdministrator; MessageService.Send(Request, messageAction, MessageTarget.Create(admin.ID), GetProductName(productid), admin.DisplayUserName(false)); } return new { ProductId = productid, UserId = userid, Administrator = administrator }; } /// <summary> /// Get portal logo image URL /// </summary> /// <short> /// Portal logo /// </short> /// <returns>Portal logo image URL</returns> [Read("logo")] public string GetLogo() { return TenantInfoSettings.Load().GetAbsoluteCompanyLogoPath(); } ///<visible>false</visible> [Create("whitelabel/save")] public void SaveWhiteLabelSettings(string logoText, IEnumerable<ItemKeyValuePair<int, string>> logo, bool isDefault) { SecurityContext.DemandPermissions(SecutiryConstants.EditPortalSettings); if (!TenantLogoManager.WhiteLabelEnabled || !TenantLogoManager.WhiteLabelPaid) { throw new BillingException(Resource.ErrorNotAllowedOption, "WhiteLabel"); } if (isDefault) { DemandRebrandingPermission(); SaveWhiteLabelSettingsForDefaultTenant(logoText, logo); } else { SaveWhiteLabelSettingsForCurrentTenant(logoText, logo); } } private void SaveWhiteLabelSettingsForCurrentTenant(string logoText, IEnumerable<ItemKeyValuePair<int, string>> logo) { var settings = TenantWhiteLabelSettings.Load(); SaveWhiteLabelSettingsForTenant(settings, null, TenantProvider.CurrentTenantID, logoText, logo); } private void SaveWhiteLabelSettingsForDefaultTenant(string logoText, IEnumerable<ItemKeyValuePair<int, string>> logo) { var settings = TenantWhiteLabelSettings.LoadForDefaultTenant(); var storage = StorageFactory.GetStorage(string.Empty, "static_partnerdata"); SaveWhiteLabelSettingsForTenant(settings, storage, Tenant.DEFAULT_TENANT, logoText, logo); } private static void SaveWhiteLabelSettingsForTenant(TenantWhiteLabelSettings settings, IDataStore storage, int tenantId, string logoText, IEnumerable<ItemKeyValuePair<int, string>> logo) { if (logo != null) { var logoDict = new Dictionary<int, string>(); logo.ToList().ForEach(n => logoDict.Add(n.Key, n.Value)); settings.SetLogo(logoDict, storage); } settings.LogoText = logoText; settings.Save(tenantId); } ///<visible>false</visible> [Create("whitelabel/savefromfiles")] public void SaveWhiteLabelSettingsFromFiles(IEnumerable<HttpPostedFileBase> attachments, bool isDefault) { SecurityContext.DemandPermissions(SecutiryConstants.EditPortalSettings); if (!TenantLogoManager.WhiteLabelEnabled || !TenantLogoManager.WhiteLabelPaid) { throw new BillingException(Resource.ErrorNotAllowedOption, "WhiteLabel"); } if (attachments == null || !attachments.Any()) { throw new InvalidOperationException("No input files"); } if (isDefault) { DemandRebrandingPermission(); SaveWhiteLabelSettingsFromFilesForDefaultTenant(attachments); } else { SaveWhiteLabelSettingsFromFilesForCurrentTenant(attachments); } } public void SaveWhiteLabelSettingsFromFilesForCurrentTenant(IEnumerable<HttpPostedFileBase> attachments) { var settings = TenantWhiteLabelSettings.Load(); SaveWhiteLabelSettingsFromFilesForTenant(settings, null, TenantProvider.CurrentTenantID, attachments); } public void SaveWhiteLabelSettingsFromFilesForDefaultTenant(IEnumerable<HttpPostedFileBase> attachments) { var settings = TenantWhiteLabelSettings.LoadForDefaultTenant(); var storage = StorageFactory.GetStorage(string.Empty, "static_partnerdata"); SaveWhiteLabelSettingsFromFilesForTenant(settings, storage, Tenant.DEFAULT_TENANT, attachments); } public void SaveWhiteLabelSettingsFromFilesForTenant(TenantWhiteLabelSettings settings, IDataStore storage, int tenantId, IEnumerable<HttpPostedFileBase> attachments) { foreach (var f in attachments) { var parts = f.FileName.Split('.'); var logoType = (WhiteLabelLogoTypeEnum) (Convert.ToInt32(parts[0])); var fileExt = parts[1]; settings.SetLogoFromStream(logoType, fileExt, f.InputStream, storage); } settings.Save(tenantId); } ///<visible>false</visible> [Read("whitelabel/sizes")] public object GetWhiteLabelSizes() { SecurityContext.DemandPermissions(SecutiryConstants.EditPortalSettings); if (!TenantLogoManager.WhiteLabelEnabled) { throw new BillingException(Resource.ErrorNotAllowedOption, "WhiteLabel"); } return new[] { new {type = (int)WhiteLabelLogoTypeEnum.LightSmall, name = WhiteLabelLogoTypeEnum.LightSmall.ToString(), height = TenantWhiteLabelSettings.logoLightSmallSize.Height, width = TenantWhiteLabelSettings.logoLightSmallSize.Width}, new {type = (int)WhiteLabelLogoTypeEnum.Dark, name = WhiteLabelLogoTypeEnum.Dark.ToString(), height = TenantWhiteLabelSettings.logoDarkSize.Height, width = TenantWhiteLabelSettings.logoDarkSize.Width}, new {type = (int)WhiteLabelLogoTypeEnum.Favicon, name = WhiteLabelLogoTypeEnum.Favicon.ToString(), height = TenantWhiteLabelSettings.logoFaviconSize.Height, width = TenantWhiteLabelSettings.logoFaviconSize.Width}, new {type = (int)WhiteLabelLogoTypeEnum.DocsEditor, name = WhiteLabelLogoTypeEnum.DocsEditor.ToString(), height = TenantWhiteLabelSettings.logoDocsEditorSize.Height, width = TenantWhiteLabelSettings.logoDocsEditorSize.Width} }; } ///<visible>false</visible> [Read("whitelabel/logos")] public Dictionary<int, string> GetWhiteLabelLogos(bool retina, bool isDefault) { SecurityContext.DemandPermissions(SecutiryConstants.EditPortalSettings); if (!TenantLogoManager.WhiteLabelEnabled) { throw new BillingException(Resource.ErrorNotAllowedOption, "WhiteLabel"); } var result = new Dictionary<int, string>(); if (isDefault) { DemandRebrandingPermission(); result.Add((int)WhiteLabelLogoTypeEnum.LightSmall, CommonLinkUtility.GetFullAbsolutePath(TenantWhiteLabelSettings.GetAbsoluteDefaultLogoPath(WhiteLabelLogoTypeEnum.LightSmall, !retina))); result.Add((int)WhiteLabelLogoTypeEnum.Dark, CommonLinkUtility.GetFullAbsolutePath(TenantWhiteLabelSettings.GetAbsoluteDefaultLogoPath(WhiteLabelLogoTypeEnum.Dark, !retina))); result.Add((int)WhiteLabelLogoTypeEnum.Favicon, CommonLinkUtility.GetFullAbsolutePath(TenantWhiteLabelSettings.GetAbsoluteDefaultLogoPath(WhiteLabelLogoTypeEnum.Favicon, !retina))); result.Add((int)WhiteLabelLogoTypeEnum.DocsEditor, CommonLinkUtility.GetFullAbsolutePath(TenantWhiteLabelSettings.GetAbsoluteDefaultLogoPath(WhiteLabelLogoTypeEnum.DocsEditor, !retina))); } else { var settings = TenantWhiteLabelSettings.Load(); result.Add((int)WhiteLabelLogoTypeEnum.LightSmall, CommonLinkUtility.GetFullAbsolutePath(settings.GetAbsoluteLogoPath(WhiteLabelLogoTypeEnum.LightSmall, !retina))); result.Add((int)WhiteLabelLogoTypeEnum.Dark, CommonLinkUtility.GetFullAbsolutePath(settings.GetAbsoluteLogoPath(WhiteLabelLogoTypeEnum.Dark, !retina))); result.Add((int)WhiteLabelLogoTypeEnum.Favicon, CommonLinkUtility.GetFullAbsolutePath(settings.GetAbsoluteLogoPath(WhiteLabelLogoTypeEnum.Favicon, !retina))); result.Add((int)WhiteLabelLogoTypeEnum.DocsEditor, CommonLinkUtility.GetFullAbsolutePath(settings.GetAbsoluteLogoPath(WhiteLabelLogoTypeEnum.DocsEditor, !retina))); } return result; } ///<visible>false</visible> [Read("whitelabel/logotext")] public string GetWhiteLabelLogoText(bool isDefault) { if (!TenantLogoManager.WhiteLabelEnabled) { throw new BillingException(Resource.ErrorNotAllowedOption, "WhiteLabel"); } if (isDefault) { DemandRebrandingPermission(); } var settings = isDefault ? TenantWhiteLabelSettings.LoadForDefaultTenant() : TenantWhiteLabelSettings.Load(); return settings.LogoText ?? TenantWhiteLabelSettings.DefaultLogoText; } ///<visible>false</visible> [Update("whitelabel/restore")] public void RestoreWhiteLabelOptions(bool isDefault) { SecurityContext.DemandPermissions(SecutiryConstants.EditPortalSettings); if (!TenantLogoManager.WhiteLabelEnabled || !TenantLogoManager.WhiteLabelPaid) { throw new BillingException(Resource.ErrorNotAllowedOption, "WhiteLabel"); } if (isDefault) { DemandRebrandingPermission(); RestoreWhiteLabelOptionsForDefaultTenant(); } else { RestoreWhiteLabelOptionsForCurrentTenant(); } } public void RestoreWhiteLabelOptionsForCurrentTenant() { var settings = TenantWhiteLabelSettings.Load(); RestoreWhiteLabelOptionsForTenant(settings, null, TenantProvider.CurrentTenantID); var tenantInfoSettings = TenantInfoSettings.Load(); tenantInfoSettings.RestoreDefaultLogo(); tenantInfoSettings.Save(); } public void RestoreWhiteLabelOptionsForDefaultTenant() { var settings = TenantWhiteLabelSettings.LoadForDefaultTenant(); var storage = StorageFactory.GetStorage(string.Empty, "static_partnerdata"); RestoreWhiteLabelOptionsForTenant(settings, storage, Tenant.DEFAULT_TENANT); } public void RestoreWhiteLabelOptionsForTenant(TenantWhiteLabelSettings settings, IDataStore storage, int tenantId) { settings.RestoreDefault(tenantId, storage); } /// <summary> /// Get portal ip restrictions /// </summary> /// <returns></returns> [Read("/iprestrictions")] public IEnumerable<IPRestriction> GetIpRestrictions() { SecurityContext.DemandPermissions(SecutiryConstants.EditPortalSettings); return IPRestrictionsService.Get(CurrentTenant); } /// <summary> /// save new portal ip restrictions /// </summary> /// <param name="ips">ip restrictions</param> /// <returns></returns> [Update("iprestrictions")] public IEnumerable<string> SaveIpRestrictions(IEnumerable<string> ips) { SecurityContext.DemandPermissions(SecutiryConstants.EditPortalSettings); return IPRestrictionsService.Save(ips, CurrentTenant); } /// <summary> /// update ip restrictions settings /// </summary> /// <param name="enable">enable ip restrictions settings</param> /// <returns></returns> [Update("iprestrictions/settings")] public IPRestrictionsSettings UpdateIpRestrictionsSettings(bool enable) { SecurityContext.DemandPermissions(SecutiryConstants.EditPortalSettings); var settings = new IPRestrictionsSettings { Enable = enable }; settings.Save(); return settings; } /// <summary> /// update tips settings /// </summary> /// <param name="show">show tips for user</param> /// <returns></returns> [Update("tips")] public TipsSettings UpdateTipsSettings(bool show) { var settings = new TipsSettings { Show = show }; settings.SaveForCurrentUser(); if (!show && !string.IsNullOrEmpty(SetupInfo.TipsAddress)) { try { using (var client = new WebClient()) { var data = new NameValueCollection(); data["userId"] = CurrentUser.ToString(); data["tenantId"] = CurrentTenant.ToString(CultureInfo.InvariantCulture); client.UploadValues(string.Format("{0}/tips/deletereaded", SetupInfo.TipsAddress), data); } } catch (Exception e) { LogManager.GetLogger("ASC").Error(e.Message, e); } } return settings; } /// <summary> /// change tips&amp;tricks subscription /// </summary> /// <returns>subscription state</returns> [Update("tips/change/subscription")] public bool UpdateTipsSubscription() { return StudioPeriodicNotify.ChangeSubscription(SecurityContext.CurrentAccount.ID); } /// <summary> /// Complete Wizard /// </summary> /// <returns>WizardSettings</returns> /// <visible>false</visible> [Update("wizard/complete")] public WizardSettings CompleteWizard() { SecurityContext.DemandPermissions(SecutiryConstants.EditPortalSettings); var settings = WizardSettings.Load(); if (settings.Completed) return settings; settings.Completed = true; settings.Save(); return settings; } /// <summary> /// Update two-factor authentication settings /// </summary> /// <param name="type">sms, app or none</param> /// <returns>true if success</returns> [Update("tfaapp")] public bool TfaSettings(string type) { SecurityContext.DemandPermissions(SecutiryConstants.EditPortalSettings); var result = false; MessageAction action; switch (type) { case "sms": if (!StudioSmsNotificationSettings.IsVisibleSettings) throw new Exception(Resource.SmsNotAvailable); if (!SmsProviderManager.Enabled()) throw new MethodAccessException(); StudioSmsNotificationSettings.Enable = true; action = MessageAction.TwoFactorAuthenticationEnabledBySms; if (TfaAppAuthSettings.Enable) { TfaAppAuthSettings.Enable = false; } result = true; break; case "app": if (!TfaAppAuthSettings.IsVisibleSettings) { throw new Exception(Resource.TfaAppNotAvailable); } TfaAppAuthSettings.Enable = true; action = MessageAction.TwoFactorAuthenticationEnabledByTfaApp; if (StudioSmsNotificationSettings.IsVisibleSettings && StudioSmsNotificationSettings.Enable) { StudioSmsNotificationSettings.Enable = false; } result = true; break; default: if (TfaAppAuthSettings.Enable) { TfaAppAuthSettings.Enable = false; } if (StudioSmsNotificationSettings.IsVisibleSettings && StudioSmsNotificationSettings.Enable) { StudioSmsNotificationSettings.Enable = false; } action = MessageAction.TwoFactorAuthenticationDisabled; break; } if (result) { CookiesManager.ResetTenantCookie(); } MessageService.Send(Request, action); return result; } ///<visible>false</visible> [Read("tfaappcodes")] public IEnumerable<object> TfaAppGetCodes() { var currentUser = CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID); if (!TfaAppAuthSettings.IsVisibleSettings || !TfaAppUserSettings.EnableForUser(currentUser.ID)) throw new Exception(Resource.TfaAppNotAvailable); if (currentUser.IsVisitor() || currentUser.IsOutsider()) throw new NotSupportedException("Not available."); return TfaAppUserSettings.LoadForCurrentUser().CodesSetting.Select(r => new { r.IsUsed, r.Code }).ToList(); } /// <summary> /// Requests new backup codes for two-factor application /// </summary> /// <returns>New backup codes</returns> [Update("tfaappnewcodes")] public IEnumerable<object> TfaAppRequestNewCodes() { var currentUser = CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID); if (!TfaAppAuthSettings.IsVisibleSettings || !TfaAppUserSettings.EnableForUser(currentUser.ID)) throw new Exception(Resource.TfaAppNotAvailable); if (currentUser.IsVisitor() || currentUser.IsOutsider()) throw new NotSupportedException("Not available."); var codes = currentUser.GenerateBackupCodes().Select(r => new { r.IsUsed, r.Code }).ToList(); MessageService.Send(HttpContext.Current.Request, MessageAction.UserConnectedTfaApp, MessageTarget.Create(currentUser.ID), currentUser.DisplayUserName(false)); return codes; } /// <summary> /// Unlinks current two-factor auth application /// </summary> /// <returns>Login url</returns> [Update("tfaappnewapp")] public string TfaAppNewApp(Guid id) { var isMe = id.Equals(Guid.Empty); var user = CoreContext.UserManager.GetUsers(isMe ? SecurityContext.CurrentAccount.ID : id); if (!isMe && !SecurityContext.CheckPermissions(new UserSecurityProvider(user.ID), Core.Users.Constants.Action_EditUser)) throw new SecurityAccessDeniedException(Resource.ErrorAccessDenied); if (!TfaAppAuthSettings.IsVisibleSettings || !TfaAppUserSettings.EnableForUser(user.ID)) throw new Exception(Resource.TfaAppNotAvailable); if (user.IsVisitor() || user.IsOutsider()) throw new NotSupportedException("Not available."); TfaAppUserSettings.DisableForUser(user.ID); MessageService.Send(HttpContext.Current.Request, MessageAction.UserDisconnectedTfaApp, MessageTarget.Create(user.ID), user.DisplayUserName(false)); if (isMe) { return CommonLinkUtility.GetConfirmationUrl(user.Email, ConfirmType.TfaActivation); } StudioNotifyService.Instance.SendMsgTfaReset(user); return string.Empty; } /// <visible>false</visible> /// <summary> /// Gets a link that will connect TelegramBot to your account /// </summary> /// <returns>url</returns> [Read("telegramlink")] public string TelegramLink() { var currentLink = TelegramHelper.Instance.CurrentRegistrationLink(CurrentUser, CurrentTenant); if (string.IsNullOrEmpty(currentLink)) { return TelegramHelper.Instance.RegisterUser(CurrentUser, CurrentTenant); } else { return currentLink; } } /// <summary> /// Checks if user has connected TelegramBot /// </summary> /// <returns>0 - not connected, 1 - connected, 2 - awaiting confirmation</returns> [Read("telegramisconnected")] public int TelegramIsConnected() { return (int)TelegramHelper.Instance.UserIsConnected(CurrentUser, CurrentTenant); } /// <summary> /// Unlinks TelegramBot from your account /// </summary> [Delete("telegramdisconnect")] public void TelegramDisconnect() { TelegramHelper.Instance.Disconnect(CurrentUser, CurrentTenant); } ///<visible>false</visible> [Update("welcome/close")] public void CloseWelcomePopup() { var currentUser = CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID); var collaboratorPopupSettings = CollaboratorSettings.LoadForCurrentUser(); if (!(currentUser.IsVisitor() && collaboratorPopupSettings.FirstVisit && !currentUser.IsOutsider())) throw new NotSupportedException("Not available."); collaboratorPopupSettings.FirstVisit = false; collaboratorPopupSettings.SaveForCurrentUser(); } ///<visible>false</visible> [Update("colortheme")] public void SaveColorTheme(string theme) { SecurityContext.DemandPermissions(SecutiryConstants.EditPortalSettings); ColorThemesSettings.SaveColorTheme(theme); MessageService.Send(HttpContext.Current.Request, MessageAction.ColorThemeChanged); } ///<visible>false</visible> [Update("timeandlanguage")] public string TimaAndLanguage(string lng, string timeZoneID) { SecurityContext.DemandPermissions(SecutiryConstants.EditPortalSettings); var tenant = CoreContext.TenantManager.GetCurrentTenant(); var culture = CultureInfo.GetCultureInfo(lng); var changelng = false; if (SetupInfo.EnabledCultures.Find(c => String.Equals(c.Name, culture.Name, StringComparison.InvariantCultureIgnoreCase)) != null) { if (!String.Equals(tenant.Language, culture.Name, StringComparison.InvariantCultureIgnoreCase)) { tenant.Language = culture.Name; changelng = true; } } var oldTimeZone = tenant.TimeZone; var timeZones = TimeZoneInfo.GetSystemTimeZones().ToList(); if (timeZones.All(tz => tz.Id != "UTC")) { timeZones.Add(TimeZoneInfo.Utc); } tenant.TimeZone = timeZones.FirstOrDefault(tz => tz.Id == timeZoneID) ?? TimeZoneInfo.Utc; CoreContext.TenantManager.SaveTenant(tenant); if (!tenant.TimeZone.Id.Equals(oldTimeZone.Id) || changelng) { if (!tenant.TimeZone.Id.Equals(oldTimeZone.Id)) { MessageService.Send(HttpContext.Current.Request, MessageAction.TimeZoneSettingsUpdated); } if (changelng) { MessageService.Send(HttpContext.Current.Request, MessageAction.LanguageSettingsUpdated); } } return Resource.SuccessfullySaveSettingsMessage; } ///<visible>false</visible> [Update("defaultpage")] public string SaveDefaultPageSettings(string defaultProductID) { SecurityContext.DemandPermissions(SecutiryConstants.EditPortalSettings); new StudioDefaultPageSettings { DefaultProductID = new Guid(defaultProductID) }.Save(); MessageService.Send(HttpContext.Current.Request, MessageAction.DefaultStartPageSettingsUpdated); return Resource.SuccessfullySaveSettingsMessage; } private static string GetProductName(Guid productId) { var product = WebItemManager.Instance[productId]; return productId == Guid.Empty ? "All" : product != null ? product.Name : productId.ToString(); } /// <summary> /// Refresh license /// </summary> /// <visible>false</visible> [Read("license/refresh")] public bool RefreshLicense() { if (!CoreContext.Configuration.Standalone) return false; LicenseReader.RefreshLicense(); return true; } /// <summary> /// Get Custom Navigation Items /// </summary> /// <returns>CustomNavigationItem List</returns> [Read("customnavigation/getall")] public List<CustomNavigationItem> GetCustomNavigationItems() { return CustomNavigationSettings.Load().Items; } /// <summary> /// Get Custom Navigation Items Sample /// </summary> /// <returns>CustomNavigationItem Sample</returns> [Read("customnavigation/getsample")] public CustomNavigationItem GetCustomNavigationItemSample() { return CustomNavigationItem.GetSample(); } /// <summary> /// Get Custom Navigation Item by Id /// </summary> /// <param name="id">Item id</param> /// <returns>CustomNavigationItem</returns> [Read("customnavigation/get/{id}")] public CustomNavigationItem GetCustomNavigationItem(Guid id) { return CustomNavigationSettings.Load().Items.FirstOrDefault(item => item.Id == id); } /// <summary> /// Add Custom Navigation Item /// </summary> /// <param name="item">Item</param> /// <returns>CustomNavigationItem</returns> [Create("customnavigation/create")] public CustomNavigationItem CreateCustomNavigationItem(CustomNavigationItem item) { SecurityContext.DemandPermissions(SecutiryConstants.EditPortalSettings); var settings = CustomNavigationSettings.Load(); var exist = false; foreach (var existItem in settings.Items) { if (existItem.Id != item.Id) continue; existItem.Label = item.Label; existItem.Url = item.Url; existItem.ShowInMenu = item.ShowInMenu; existItem.ShowOnHomePage = item.ShowOnHomePage; if (existItem.SmallImg != item.SmallImg) { StorageHelper.DeleteLogo(existItem.SmallImg); existItem.SmallImg = StorageHelper.SaveTmpLogo(item.SmallImg); } if (existItem.BigImg != item.BigImg) { StorageHelper.DeleteLogo(existItem.BigImg); existItem.BigImg = StorageHelper.SaveTmpLogo(item.BigImg); } exist = true; break; } if (!exist) { item.Id = Guid.NewGuid(); item.SmallImg = StorageHelper.SaveTmpLogo(item.SmallImg); item.BigImg = StorageHelper.SaveTmpLogo(item.BigImg); settings.Items.Add(item); } settings.Save(); MessageService.Send(HttpContext.Current.Request, MessageAction.CustomNavigationSettingsUpdated); return item; } /// <summary> /// Delete Custom Navigation Item by Id /// </summary> /// <param name="id">Item id</param> [Delete("customnavigation/delete/{id}")] public void DeleteCustomNavigationItem(Guid id) { SecurityContext.DemandPermissions(SecutiryConstants.EditPortalSettings); var settings = CustomNavigationSettings.Load(); var terget = settings.Items.FirstOrDefault(item => item.Id == id); if (terget == null) return; StorageHelper.DeleteLogo(terget.SmallImg); StorageHelper.DeleteLogo(terget.BigImg); settings.Items.Remove(terget); settings.Save(); MessageService.Send(HttpContext.Current.Request, MessageAction.CustomNavigationSettingsUpdated); } /// <summary> /// update email activation settings /// </summary> /// <param name="show">show email activation panel for user</param> /// <returns></returns> [Update("emailactivation")] public EmailActivationSettings UpdateEmailActivationSettings(bool show) { var settings = new EmailActivationSettings { Show = show }; settings.SaveForCurrentUser(); return settings; } ///<visible>false</visible> [Read("companywhitelabel")] public List<CompanyWhiteLabelSettings> GetLicensorData() { var result = new List<CompanyWhiteLabelSettings>(); var instance = CompanyWhiteLabelSettings.Instance; result.Add(instance); if (!instance.IsDefault && !instance.IsLicensor) { result.Add(instance.GetDefault() as CompanyWhiteLabelSettings); } return result; } /// <summary> /// Get WebItem Space Usage Statistics /// </summary> /// <param name="id">WebItem id</param> /// <returns>UsageSpaceStatItemWrapper List</returns> [Read("statistics/spaceusage/{id}")] public List<UsageSpaceStatItemWrapper> GetSpaceUsageStatistics(Guid id) { SecurityContext.DemandPermissions(SecutiryConstants.EditPortalSettings); var webtem = WebItemManager.Instance.GetItems(Web.Core.WebZones.WebZoneType.All, ItemAvailableState.All) .FirstOrDefault(item => item != null && item.ID == id && item.Context != null && item.Context.SpaceUsageStatManager != null); if (webtem == null) return new List<UsageSpaceStatItemWrapper>(); return webtem.Context.SpaceUsageStatManager.GetStatData() .ConvertAll(it => new UsageSpaceStatItemWrapper { Name = it.Name.HtmlEncode(), Icon = it.ImgUrl, Disabled = it.Disabled, Size = FileSizeComment.FilesSizeToString(it.SpaceUsage), Url = it.Url }); } /// <summary> /// Get User Visit Statistics /// </summary> /// <param name="fromDate">From Date</param> /// <param name="toDate">To Date</param> /// <returns>ChartPointWrapper List</returns> [Read("statistics/visit")] public List<ChartPointWrapper> GetVisitStatistics(ApiDateTime fromDate, ApiDateTime toDate) { SecurityContext.DemandPermissions(SecutiryConstants.EditPortalSettings); var from = TenantUtil.DateTimeFromUtc(fromDate); var to = TenantUtil.DateTimeFromUtc(toDate); var points = new List<ChartPointWrapper>(); if (from.CompareTo(to) >= 0) return points; for (var d = new DateTime(from.Ticks); d.Date.CompareTo(to.Date) <= 0; d = d.AddDays(1)) { points.Add(new ChartPointWrapper { DisplayDate = d.Date.ToShortDateString(), Date = d.Date, Hosts = 0, Hits = 0 }); } var hits = StatisticManager.GetHitsByPeriod(TenantProvider.CurrentTenantID, from, to); var hosts = StatisticManager.GetHostsByPeriod(TenantProvider.CurrentTenantID, from, to); if (hits.Count == 0 || hosts.Count == 0) return points; hits.Sort((x, y) => x.VisitDate.CompareTo(y.VisitDate)); hosts.Sort((x, y) => x.VisitDate.CompareTo(y.VisitDate)); for (int i = 0, n = points.Count, hitsNum = 0, hostsNum = 0; i < n; i++) { while (hitsNum < hits.Count && points[i].Date.CompareTo(hits[hitsNum].VisitDate.Date) == 0) { points[i].Hits += hits[hitsNum].VisitCount; hitsNum++; } while (hostsNum < hosts.Count && points[i].Date.CompareTo(hosts[hostsNum].VisitDate.Date) == 0) { points[i].Hosts++; hostsNum++; } } return points; } /// <summary> /// Get Storage /// </summary> /// <returns>Consumer</returns> [Read("storage")] public List<StorageWrapper> GetAllStorages() { SecurityContext.DemandPermissions(SecutiryConstants.EditPortalSettings); TenantExtra.DemandControlPanelPermission(); var current = StorageSettings.Load(); var consumers = ConsumerFactory.GetAll<DataStoreConsumer>().ToList(); return consumers.Select(consumer => new StorageWrapper(consumer, current)).ToList(); } /// <summary> /// Get Storage /// </summary> /// <returns>Consumer</returns> [Read("storage/progress", checkPayment: false)] public double GetStorageProgress() { SecurityContext.DemandPermissions(SecutiryConstants.EditPortalSettings); if (!CoreContext.Configuration.Standalone) return -1; using (var migrateClient = new ServiceClient()) { return migrateClient.GetProgress(CoreContext.TenantManager.GetCurrentTenant().TenantId); } } /// <summary> /// Get Storage /// </summary> /// <returns>Consumer</returns> [Update("storage")] public StorageSettings UpdateStorage(string module, IEnumerable<ItemKeyValuePair<string, string>> props) { try { LogManager.GetLogger("ASC").Debug("UpdateStorage"); SecurityContext.DemandPermissions(SecutiryConstants.EditPortalSettings); if (!CoreContext.Configuration.Standalone) return null; TenantExtra.DemandControlPanelPermission(); var consumer = ConsumerFactory.GetByName(module); if (!consumer.IsSet) throw new ArgumentException("module"); var settings = StorageSettings.Load(); if (settings.Module == module) return settings; settings.Module = module; settings.Props = props.ToDictionary(r => r.Key, b => b.Value); StartMigrate(settings); return settings; } catch (Exception e) { LogManager.GetLogger("ASC").Error("UpdateStorage", e); throw; } } [Delete("storage")] public void ResetStorageToDefault() { try { LogManager.GetLogger("ASC").Debug("ResetStorageToDefault"); SecurityContext.DemandPermissions(SecutiryConstants.EditPortalSettings); if (!CoreContext.Configuration.Standalone) return; TenantExtra.DemandControlPanelPermission(); var settings = StorageSettings.Load(); settings.Module = null; settings.Props = null; StartMigrate(settings); } catch (Exception e) { LogManager.GetLogger("ASC").Error("ResetStorageToDefault", e); throw; } } /// <summary> /// Get Storage /// </summary> /// <returns>Consumer</returns> [Read("storage/cdn")] public List<StorageWrapper> GetAllCdnStorages() { SecurityContext.DemandPermissions(SecutiryConstants.EditPortalSettings); if (!CoreContext.Configuration.Standalone) return null; TenantExtra.DemandControlPanelPermission(); var current = CdnStorageSettings.Load(); var consumers = ConsumerFactory.GetAll<DataStoreConsumer>().Where(r => r.Cdn != null).ToList(); return consumers.Select(consumer => new StorageWrapper(consumer, current)).ToList(); } /// <summary> /// Get Storage /// </summary> /// <returns>Consumer</returns> [Update("storage/cdn")] public CdnStorageSettings UpdateCdn(string module, IEnumerable<ItemKeyValuePair<string, string>> props) { SecurityContext.DemandPermissions(SecutiryConstants.EditPortalSettings); if (!CoreContext.Configuration.Standalone) return null; TenantExtra.DemandControlPanelPermission(); var consumer = ConsumerFactory.GetByName(module); if (!consumer.IsSet) throw new ArgumentException("module"); var settings = CdnStorageSettings.Load(); if (settings.Module == module) return settings; settings.Module = module; settings.Props = props.ToDictionary(r => r.Key, b => b.Value); try { using (var migrateClient = new ServiceClient()) { migrateClient.UploadCdn(CoreContext.TenantManager.GetCurrentTenant().TenantId, "/", HttpContext.Current.Server.MapPath("~/"), settings); } BundleTable.Bundles.Clear(); } catch (Exception e) { LogManager.GetLogger("ASC").Error("UpdateCdn", e); throw; } return settings; } [Delete("storage/cdn")] public void ResetCdnToDefault() { SecurityContext.DemandPermissions(SecutiryConstants.EditPortalSettings); if (!CoreContext.Configuration.Standalone) return; TenantExtra.DemandControlPanelPermission(); CdnStorageSettings.Load().Clear(); } /// <summary> /// Get Storage /// </summary> /// <returns>Consumer</returns> [Read("storage/backup")] public List<StorageWrapper> GetAllBackupStorages() { SecurityContext.DemandPermissions(SecutiryConstants.EditPortalSettings); if (CoreContext.Configuration.Standalone) { TenantExtra.DemandControlPanelPermission(); } var schedule = new BackupAjaxHandler().GetSchedule(); var current = new StorageSettings(); if (schedule != null && schedule.StorageType == Core.Common.Contracts.BackupStorageType.ThirdPartyConsumer) { current = new StorageSettings { Module = schedule.StorageParams["module"], Props = schedule.StorageParams.Where(r => r.Key != "module").ToDictionary(r => r.Key, r => r.Value) }; } var consumers = ConsumerFactory.GetAll<DataStoreConsumer>().ToList(); return consumers.Select(consumer => new StorageWrapper(consumer, current)).ToList(); } private void StartMigrate(StorageSettings settings) { using (var migrateClient = new ServiceClient()) { migrateClient.Migrate(CoreContext.TenantManager.GetCurrentTenant().TenantId, settings); } var tenant = CoreContext.TenantManager.GetCurrentTenant(); tenant.SetStatus(TenantStatus.Migrating); CoreContext.TenantManager.SaveTenant(tenant); } [Read("socket")] public object GetSocketSettings() { var hubUrl = ConfigurationManagerExtension.AppSettings["web.hub"] ?? string.Empty; if (hubUrl != string.Empty) { if (!hubUrl.EndsWith("/")) { hubUrl += "/"; } } return new { Url = hubUrl }; } ///<visible>false</visible> [Read("controlpanel")] public TenantControlPanelSettings GetTenantControlPanelSettings() { return TenantControlPanelSettings.Instance; } ///<visible>false</visible> [Create("rebranding/company")] public void SaveCompanyWhiteLabelSettings(CompanyWhiteLabelSettings settings) { if (settings == null) throw new ArgumentNullException("settings"); DemandRebrandingPermission(); settings.IsLicensor = false; //TODO: CoreContext.TenantManager.GetTenantQuota(TenantProvider.CurrentTenantID).Branding && settings.IsLicensor settings.SaveForDefaultTenant(); } ///<visible>false</visible> [Read("rebranding/company")] public CompanyWhiteLabelSettings GetCompanyWhiteLabelSettings() { return CompanyWhiteLabelSettings.Instance; } ///<visible>false</visible> [Delete("rebranding/company")] public CompanyWhiteLabelSettings DeleteCompanyWhiteLabelSettings() { DemandRebrandingPermission(); var defaultSettings = (CompanyWhiteLabelSettings) CompanyWhiteLabelSettings.Instance.GetDefault(); defaultSettings.SaveForDefaultTenant(); return defaultSettings; } ///<visible>false</visible> [Create("rebranding/additional")] public void SaveAdditionalWhiteLabelSettings(AdditionalWhiteLabelSettings settings) { if (settings == null) throw new ArgumentNullException("settings"); DemandRebrandingPermission(); settings.SaveForDefaultTenant(); } ///<visible>false</visible> [Read("rebranding/additional")] public AdditionalWhiteLabelSettings GetAdditionalWhiteLabelSettings() { return AdditionalWhiteLabelSettings.Instance; } ///<visible>false</visible> [Delete("rebranding/additional")] public AdditionalWhiteLabelSettings DeleteAdditionalWhiteLabelSettings() { DemandRebrandingPermission(); var defaultSettings = (AdditionalWhiteLabelSettings)AdditionalWhiteLabelSettings.Instance.GetDefault(); defaultSettings.SaveForDefaultTenant(); return defaultSettings; } ///<visible>false</visible> [Create("rebranding/mail")] public void SaveMailWhiteLabelSettings(MailWhiteLabelSettings settings) { if (settings == null) throw new ArgumentNullException("settings"); DemandRebrandingPermission(); settings.SaveForDefaultTenant(); } ///<visible>false</visible> [Update("rebranding/mail")] public void UpdateMailWhiteLabelSettings(bool footerEnabled) { DemandRebrandingPermission(); var settings = MailWhiteLabelSettings.Instance; settings.FooterEnabled = footerEnabled; settings.SaveForDefaultTenant(); } ///<visible>false</visible> [Read("rebranding/mail")] public MailWhiteLabelSettings GetMailWhiteLabelSettings() { return MailWhiteLabelSettings.Instance; } ///<visible>false</visible> [Delete("rebranding/mail")] public MailWhiteLabelSettings DeleteMailWhiteLabelSettings() { DemandRebrandingPermission(); var defaultSettings = (MailWhiteLabelSettings)MailWhiteLabelSettings.Instance.GetDefault(); defaultSettings.SaveForDefaultTenant(); return defaultSettings; } private static void DemandRebrandingPermission() { TenantExtra.DemandControlPanelPermission(); if (!CoreContext.TenantManager.GetTenantQuota(TenantProvider.CurrentTenantID).SSBranding) { throw new BillingException(Resource.ErrorNotAllowedOption, "SSBranding"); } if (CoreContext.Configuration.CustomMode) { throw new SecurityException(); } } /// <summary> /// Get storage encryption settings /// </summary> /// <returns>EncryptionSettings</returns> /// <visible>false</visible> [Read("encryption/settings")] public EncryptionSettings GetStorageEncryptionSettings() { try { if (!SetupInfo.IsVisibleSettings<EncryptionSettings>()) { throw new NotSupportedException(); } if (!CoreContext.Configuration.Standalone) { throw new NotSupportedException(Resource.ErrorServerEditionMethod); } SecurityContext.DemandPermissions(SecutiryConstants.EditPortalSettings); TenantExtra.DemandControlPanelPermission(); if (!CoreContext.TenantManager.GetTenantQuota(TenantProvider.CurrentTenantID).DiscEncryption) { throw new BillingException(Resource.ErrorNotAllowedOption, "DiscEncryption"); } var settings = EncryptionSettings.Load(); settings.Password = string.Empty; // Don't show password return settings; } catch (Exception e) { LogManager.GetLogger("ASC").Error("GetStorageEncryptionSettings", e); return null; } } /// <summary> /// Get storage encryption progress /// </summary> /// <returns>Progress</returns> /// <visible>false</visible> [Read("encryption/progress", checkPayment: false)] public double GetStorageEncryptionProgress() { if (!SetupInfo.IsVisibleSettings<EncryptionSettings>()) { throw new NotSupportedException(); } if (!CoreContext.Configuration.Standalone) { throw new NotSupportedException(Resource.ErrorServerEditionMethod); } if (!CoreContext.TenantManager.GetTenantQuota(TenantProvider.CurrentTenantID).DiscEncryption) { throw new BillingException(Resource.ErrorNotAllowedOption, "DiscEncryption"); } using (var encryptionClient = new EncryptionServiceClient()) { return encryptionClient.GetProgress(); } } public static readonly object Locker = new object(); /// <summary> /// Start storage encryption process /// </summary> /// <returns></returns> /// <visible>false</visible> [Create("encryption/start")] public void StartStorageEncryption(bool notifyUsers) { lock (Locker) { var activeTenants = CoreContext.TenantManager.GetTenants(); if (activeTenants.Any()) { StartEncryption(notifyUsers); } } } private void StartEncryption(bool notifyUsers) { if (!SetupInfo.IsVisibleSettings<EncryptionSettings>()) { throw new NotSupportedException(); } if (!CoreContext.Configuration.Standalone) { throw new NotSupportedException(Resource.ErrorServerEditionMethod); } SecurityContext.DemandPermissions(SecutiryConstants.EditPortalSettings); TenantExtra.DemandControlPanelPermission(); if (!CoreContext.TenantManager.GetTenantQuota(TenantProvider.CurrentTenantID).DiscEncryption) { throw new BillingException(Resource.ErrorNotAllowedOption, "DiscEncryption"); } var storages = GetAllStorages(); if (storages.Any(s => s.Current)) { throw new NotSupportedException(Resource.ErrorDefaultStorageMethod); } var cdnStorages = GetAllCdnStorages(); if (cdnStorages.Any(s => s.Current)) { throw new NotSupportedException(Resource.ErrorDefaultStorageMethod); } var tenants = CoreContext.TenantManager.GetTenants(); using (var service = new BackupServiceClient()) { foreach (var tenant in tenants) { var progress = service.GetBackupProgress(tenant.TenantId); if (progress != null && progress.IsCompleted == false) { throw new Exception(Resource.ErrorWaitForBackupProcessComplete); } } foreach (var tenant in tenants) { service.DeleteSchedule(tenant.TenantId); } } var settings = EncryptionSettings.Load(); settings.NotifyUsers = notifyUsers; if (settings.Status == EncryprtionStatus.Decrypted) { settings.Status = EncryprtionStatus.EncryptionStarted; settings.Password = EncryptionSettings.GeneratePassword(32, 16); } else if (settings.Status == EncryprtionStatus.Encrypted) { settings.Status = EncryprtionStatus.DecryptionStarted; } MessageService.Send(HttpContext.Current.Request, settings.Status == EncryprtionStatus.EncryptionStarted ? MessageAction.StartStorageEncryption : MessageAction.StartStorageDecryption); var serverRootPath = CommonLinkUtility.GetFullAbsolutePath("~").TrimEnd('/'); foreach (var tenant in tenants) { CoreContext.TenantManager.SetCurrentTenant(tenant); if (notifyUsers) { if (settings.Status == EncryprtionStatus.EncryptionStarted) { StudioNotifyService.Instance.SendStorageEncryptionStart(serverRootPath); } else { StudioNotifyService.Instance.SendStorageDecryptionStart(serverRootPath); } } tenant.SetStatus(TenantStatus.Encryption); CoreContext.TenantManager.SaveTenant(tenant); } settings.Save(); using (var encryptionClient = new EncryptionServiceClient()) { encryptionClient.Start(settings, serverRootPath); } } } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/IMAP/Client/IMAP_Client.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.IMAP.Client { #region usings using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Security.Principal; using System.Timers; using IO; using Server; using TCP; using StringReader=StringReader; using System.Text; #endregion /// <summary> /// IMAP client. /// </summary> /// <example> /// <code> /// using(IMAP_Client c = new IMAP_Client()){ /// c.Connect("ivx",143); /// c.Authenticate("test","test"); /// /// c.SelectFolder("Inbox"); /// /// IMAP_SequenceSet sequence_set = new IMAP_SequenceSet(); /// // First message /// sequence_set.Parse("1"); /// // All messages /// // sequence_set.Parse("1:*"); /// // Messages 1,3,6 and 100 to last /// // sequence_set.Parse("1,3,6,100:*"); /// /// // Get messages flags and header /// IMAP_FetchItem msgsInfo = c.FetchMessages(sequence_set,IMAP_FetchItem_Flags.MessageFlags | IMAP_FetchItem_Flags.Header,true,false); /// /// // Do your suff /// } /// </code> /// </example> public class IMAP_Client : TCP_Client { private const int NoopInterval = 60000; private const int NoopDelay = 5000; #region Members //private readonly TimerEx m_Timer = new TimerEx(NoopInterval); private int m_CmdNumber; private int m_MsgCount; private int m_NewMsgCount; private char m_PathSeparator = '\0'; private GenericIdentity m_pAuthdUserIdentity; private string m_SelectedFolder = ""; private long m_UIDNext; private long m_UIDValidity; #endregion #region Properties /// <summary> /// Gets session authenticated user identity, returns null if not authenticated. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when this property is accessed and POP3 client is not connected.</exception> public override GenericIdentity AuthenticatedUserIdentity { get { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (!IsConnected) { throw new InvalidOperationException("You must connect first."); } return m_pAuthdUserIdentity; } } /// <summary> /// Gets IMAP server path separator char. /// </summary> public char PathSeparator { get { // Get separator if (m_PathSeparator == '\0') { m_PathSeparator = GetFolderSeparator()[0]; } return m_PathSeparator; } } /// <summary> /// Gets selected folder. /// </summary> public string SelectedFolder { get { return m_SelectedFolder; } } /// <summary> /// Gets folder UID. /// </summary> public long UIDValidity { get { return m_UIDValidity; } } /// <summary> /// Gets next predicted message UID. /// </summary> public long UIDNext { get { return m_UIDNext; } } /// <summary> /// Gets numbers of recent(not accessed messages) in selected folder. /// </summary> public int RecentMessagesCount { get { return NewMsgCount; } } /// <summary> /// Gets numbers of messages in selected folder. /// </summary> public int MessagesCount { get { return MsgCount; } } ///<summary> /// ///</summary> public bool HasNewMessages { get; set; } private int MsgCount { get { return m_MsgCount; } set { if (value > m_MsgCount) { HasNewMessages = true; m_NewMsgCount = value - m_MsgCount; } m_MsgCount = value; } } private int NewMsgCount { get { return m_NewMsgCount; } set { HasNewMessages = m_NewMsgCount < value; m_NewMsgCount = value; } } public List<string> Capabilities { get { return capabilities; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> public IMAP_Client() { //m_Timer.AutoReset = true; //m_Timer.Elapsed += Timer_Elapsed; //m_Timer.Enabled = true; } #endregion #region Methods /// <summary> /// Clean up any resources being used. /// </summary> public override void Dispose() { Debug.Print("IMAP client disposed"); //m_Timer.Enabled = false; //m_Timer.Dispose(); base.Dispose(); } /// <summary> /// Closes connection to POP3 server. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when POP3 client is not connected.</exception> public override void Disconnect() { Debug.Print("IMAP client disconect"); if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (!IsConnected) { throw new InvalidOperationException("IMAP client is not connected."); } try { // Send LOGOUT command to server. int countWritten = TcpStream.WriteLine("a1 LOGOUT"); LogAddWrite(countWritten, "a1 LOGOUT"); string line = ""; while (true) { line = ReadLine(); if (string.IsNullOrEmpty(line)) { break; } if (line.StartsWith("a1 OK")) { break; } } } catch {} try { base.Disconnect(); } catch {} } private List<string> capabilities = new List<string>(); private void GetCapabilities() { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (!IsConnected) { throw new Exception("You must connect first !"); } string line = GetNextCmdTag() + " CAPABILITY"; int countWritten = TcpStream.WriteLine(line); LogAddWrite(countWritten, line); Capabilities.Clear(); while (true) { line = ReadLine(); // We have un-tagged resposne. if (line.StartsWith("*")) { ProcessCapsResponse(line); } else { break; } } if (!RemoveCmdTag(line).ToUpper().StartsWith("OK")) { throw new IMAP_ClientException(line); } } private void ProcessCapsResponse(string line) { if (line.IndexOf("CAPABILITY") > -1) { string[] idsLine = line.Substring(line.IndexOf(' ', line.IndexOf("CAPABILITY"))).Split( new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); Capabilities.AddRange(idsLine); } } /// <summary> /// Switches IMAP connection to SSL. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when IMAP client is not connected or is authenticated or is already secure connection.</exception> public void StartTLS() { /* RFC 2595 3. IMAP STARTTLS extension. Example: C: a001 CAPABILITY S: * CAPABILITY IMAP4rev1 STARTTLS LOGINDISABLED S: a001 OK CAPABILITY completed C: a002 STARTTLS S: a002 OK Begin TLS negotiation now <TLS negotiation, further commands are under TLS layer> */ if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (!IsConnected) { throw new InvalidOperationException("You must connect first."); } if (IsAuthenticated) { throw new InvalidOperationException( "The STARTTLS command is only valid in non-authenticated state !"); } if (IsSecureConnection) { throw new InvalidOperationException("Connection is already secure."); } string line = GetNextCmdTag() + " STARTTLS"; int countWritten = TcpStream.WriteLine(line); LogAddWrite(countWritten, line); SmartStream.ReadLineAsyncOP args = new SmartStream.ReadLineAsyncOP(new byte[Workaround.Definitions.MaxStreamLineLength], SizeExceededAction. JunkAndThrowException); TcpStream.ReadLine(args, false); if (args.Error != null) { throw args.Error; } line = args.LineUtf8; LogAddRead(args.BytesInBuffer, line); line = RemoveCmdTag(line); if (!line.ToUpper().StartsWith("OK")) { throw new IMAP_ClientException(line); } SwitchToSecure(); } /// <summary> /// Authenticates user. /// </summary> /// <param name="userName">User name.</param> /// <param name="password"><PASSWORD>.</param> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when IMAP client is not connected or is already authenticated.</exception> public void Authenticate(string userName, string password) { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (!IsConnected) { throw new InvalidOperationException("You must connect first."); } if (IsAuthenticated) { throw new InvalidOperationException("Session is already authenticated."); } string line = GetNextCmdTag() + " LOGIN " + TextUtils.QuoteString(userName) + " " + TextUtils.QuoteString(password); int countWritten = TcpStream.WriteLine(line); LogAddWrite(countWritten, string.IsNullOrEmpty(password) ? line : line.Replace(password, "<***REMOVED***>")); SmartStream.ReadLineAsyncOP args = new SmartStream.ReadLineAsyncOP(new byte[Workaround.Definitions.MaxStreamLineLength], SizeExceededAction. JunkAndThrowException); TcpStream.ReadLine(args, false); if (args.Error != null) { throw args.Error; } line = args.LineUtf8; LogAddRead(args.BytesInBuffer, line); line = RemoveCmdTag(line); if (line.ToUpper().StartsWith("OK")) { m_pAuthdUserIdentity = new GenericIdentity(userName, "login"); } else { throw new IMAP_ClientException(line); } } /// <summary> /// Creates specified folder. /// </summary> /// <param name="folderName">Folder name. Eg. test, Inbox/SomeSubFolder. NOTE: use GetFolderSeparator() to get right folder separator.</param> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when IMAP client is not connected and authenticated.</exception> public void CreateFolder(string folderName) { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (!IsConnected) { throw new InvalidOperationException("You must connect first."); } if (!IsAuthenticated) { throw new InvalidOperationException("The CREATE command is only valid in authenticated state."); } // Ensure that we send right separator to server, we accept both \ and /. folderName = folderName.Replace('\\', PathSeparator).Replace('/', PathSeparator); string line = GetNextCmdTag() + " CREATE " + TextUtils.QuoteString(Core.Encode_IMAP_UTF7_String(folderName)); int countWritten = TcpStream.WriteLine(line); LogAddWrite(countWritten, line); SmartStream.ReadLineAsyncOP args = new SmartStream.ReadLineAsyncOP(new byte[Workaround.Definitions.MaxStreamLineLength], SizeExceededAction. JunkAndThrowException); TcpStream.ReadLine(args, false); if (args.Error != null) { throw args.Error; } line = args.LineUtf8; LogAddRead(args.BytesInBuffer, line); line = RemoveCmdTag(line); if (!line.ToUpper().StartsWith("OK")) { throw new IMAP_ClientException(line); } } /// <summary> /// Deletes specified folder. /// </summary> /// <param name="folderName">Folder name.</param> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when IMAP client is not connected and authenticated.</exception> public void DeleteFolder(string folderName) { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (!IsConnected) { throw new InvalidOperationException("You must connect first."); } if (!IsAuthenticated) { throw new InvalidOperationException("The DELETE command is only valid in authenticated state."); } string line = GetNextCmdTag() + " DELETE " + TextUtils.QuoteString(Core.Encode_IMAP_UTF7_String(folderName)); int countWritten = TcpStream.WriteLine(line); LogAddWrite(countWritten, line); SmartStream.ReadLineAsyncOP args = new SmartStream.ReadLineAsyncOP(new byte[Workaround.Definitions.MaxStreamLineLength], SizeExceededAction. JunkAndThrowException); TcpStream.ReadLine(args, false); if (args.Error != null) { throw args.Error; } line = args.LineUtf8; LogAddRead(args.BytesInBuffer, line); line = RemoveCmdTag(line); if (!line.ToUpper().StartsWith("OK")) { throw new IMAP_ClientException(line); } } /// <summary> /// Renames specified folder. /// </summary> /// <param name="sourceFolderName">Source folder name.</param> /// <param name="destinationFolderName">Destination folder name.</param> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when IMAP client is not connected and authenticated.</exception> public void RenameFolder(string sourceFolderName, string destinationFolderName) { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (!IsConnected) { throw new InvalidOperationException("You must connect first."); } if (!IsAuthenticated) { throw new InvalidOperationException("The RENAME command is only valid in authenticated state."); } string line = GetNextCmdTag() + " RENAME " + TextUtils.QuoteString(Core.Encode_IMAP_UTF7_String(sourceFolderName)) + " " + TextUtils.QuoteString(Core.Encode_IMAP_UTF7_String(destinationFolderName)); int countWritten = TcpStream.WriteLine(line); LogAddWrite(countWritten, line); SmartStream.ReadLineAsyncOP args = new SmartStream.ReadLineAsyncOP(new byte[Workaround.Definitions.MaxStreamLineLength], SizeExceededAction. JunkAndThrowException); TcpStream.ReadLine(args, false); if (args.Error != null) { throw args.Error; } line = args.LineUtf8; LogAddRead(args.BytesInBuffer, line); line = RemoveCmdTag(line); if (!line.ToUpper().StartsWith("OK")) { throw new IMAP_ClientException(line); } } /// <summary> /// Gets all available folders. /// </summary> /// <returns>Returns user folders.</returns> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when IMAP client is not connected and authenticated.</exception> public string[] GetFolders() { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (!IsConnected) { throw new InvalidOperationException("You must connect first."); } if (!IsAuthenticated) { throw new InvalidOperationException("The LIST command is only valid in authenticated state."); } List<string> list = new List<string>(); string line = GetNextCmdTag() + " LIST \"\" \"*\""; int countWritten = TcpStream.WriteLine(line); LogAddWrite(countWritten, line); // Must get lines with * and cmdTag + OK or cmdTag BAD/NO. while (true) { line = ReadLine(); if (line.StartsWith("*")) { // don't show not selectable folders if (line.ToLower().IndexOf("\\noselect") == -1) { line = line.Substring(line.IndexOf(")") + 1).Trim(); // Remove * LIST(..) line = line.Substring(line.IndexOf(" ")).Trim(); // Remove Folder separator list.Add(TextUtils.UnQuoteString(Core.Decode_IMAP_UTF7_String(line.Trim()))); } } else { break; } } line = RemoveCmdTag(line); if (!line.ToUpper().StartsWith("OK")) { throw new IMAP_ClientException(line); } return list.ToArray(); } /// <summary> /// Gets all subscribed folders. /// </summary> /// <returns>Returns user subscribed folders.</returns> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when IMAP client is not connected and authenticated.</exception> public string[] GetSubscribedFolders() { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (!IsConnected) { throw new InvalidOperationException("You must connect first."); } if (!IsAuthenticated) { throw new InvalidOperationException("The LSUB command is only valid in authenticated state."); } List<string> list = new List<string>(); string line = GetNextCmdTag() + " LSUB \"\" \"*\""; int countWritten = TcpStream.WriteLine(line); LogAddWrite(countWritten, line); // Must get lines with * and cmdTag + OK or cmdTag BAD/NO. while (true) { line = ReadLine(); if (line.StartsWith("*")) { // don't show not selectable folders if (line.ToLower().IndexOf("\\noselect") == -1) { line = line.Substring(line.IndexOf(")") + 1).Trim(); // Remove * LIST(..) line = line.Substring(line.IndexOf(" ")).Trim(); // Remove Folder separator list.Add(TextUtils.UnQuoteString(Core.Decode_IMAP_UTF7_String(line.Trim()))); } } else { break; } } line = RemoveCmdTag(line); if (!line.ToUpper().StartsWith("OK")) { throw new IMAP_ClientException(line); } return list.ToArray(); } /// <summary> /// Subscribes specified folder. /// </summary> /// <param name="folderName">Folder name.</param> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when IMAP client is not connected and authenticated.</exception> public void SubscribeFolder(string folderName) { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (!IsConnected) { throw new InvalidOperationException("You must connect first."); } if (!IsAuthenticated) { throw new InvalidOperationException( "The SUBSCRIBE command is only valid in authenticated state."); } // Ensure that we send right separator to server, we accept both \ and /. folderName = folderName.Replace('\\', PathSeparator).Replace('/', PathSeparator); string line = GetNextCmdTag() + " SUBSCRIBE " + TextUtils.QuoteString(Core.Encode_IMAP_UTF7_String(folderName)); int countWritten = TcpStream.WriteLine(line); LogAddWrite(countWritten, line); line = ReadLine(); line = RemoveCmdTag(line); if (!line.ToUpper().StartsWith("OK")) { throw new IMAP_ClientException(line); } } /// <summary> /// UnSubscribes specified folder. /// </summary> /// <param name="folderName">Folder name.</param> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when IMAP client is not connected and authenticated.</exception> public void UnSubscribeFolder(string folderName) { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (!IsConnected) { throw new InvalidOperationException("You must connect first."); } if (!IsAuthenticated) { throw new InvalidOperationException( "The UNSUBSCRIBE command is only valid in authenticated state."); } // Ensure that we send right separator to server, we accept both \ and /. folderName = folderName.Replace('\\', PathSeparator).Replace('/', PathSeparator); string line = GetNextCmdTag() + " UNSUBSCRIBE " + TextUtils.QuoteString(Core.Encode_IMAP_UTF7_String(folderName)); int countWritten = TcpStream.WriteLine(line); LogAddWrite(countWritten, line); line = ReadLine(); line = RemoveCmdTag(line); if (!line.ToUpper().StartsWith("OK")) { throw new IMAP_ClientException(line); } } /// <summary> /// Selects specified folder. /// </summary> /// <param name="folderName">Folder name.</param> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when IMAP client is not connected and authenticated.</exception> public void ExamineFolder(string folderName) { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (!IsConnected) { throw new InvalidOperationException("You must connect first."); } if (!IsAuthenticated) { throw new InvalidOperationException("The SELECT command is only valid in authenticated state."); } // Ensure that we send right separator to server, we accept both \ and /. folderName = folderName.Replace('\\', PathSeparator).Replace('/', PathSeparator); string line = GetNextCmdTag() + " EXAMINE " + TextUtils.QuoteString(Core.Encode_IMAP_UTF7_String(folderName)); int countWritten = TcpStream.WriteLine(line); LogAddWrite(countWritten, line); // Must get lines with * and cmdTag + OK or cmdTag BAD/NO. while (true) { line = ReadLine(); if (line.StartsWith("*")) { // Get rid of * line = line.Substring(1).Trim(); if (line.ToUpper().IndexOf("EXISTS") > -1 && line.ToUpper().IndexOf("FLAGS") == -1) { MsgCount = Convert.ToInt32(line.Substring(0, line.IndexOf(" ")).Trim()); } else if (line.ToUpper().IndexOf("RECENT") > -1 && line.ToUpper().IndexOf("FLAGS") == -1) { NewMsgCount = Convert.ToInt32(line.Substring(0, line.IndexOf(" ")).Trim()); } else if (line.ToUpper().IndexOf("UIDNEXT") > -1) { m_UIDNext = Convert.ToInt64(line.Substring(line.ToUpper().IndexOf("UIDNEXT") + 8, line.IndexOf(']') - line.ToUpper().IndexOf("UIDNEXT") - 8)); } else if (line.ToUpper().IndexOf("UIDVALIDITY") > -1) { m_UIDValidity = Convert.ToInt64(line.Substring(line.ToUpper().IndexOf("UIDVALIDITY") + 12, line.IndexOf(']') - line.ToUpper().IndexOf("UIDVALIDITY") - 12)); } } else { break; } } line = RemoveCmdTag(line); if (!line.ToUpper().StartsWith("OK")) { throw new IMAP_ClientException(line); } } /// <summary> /// Selects specified folder. /// </summary> /// <param name="folderName">Folder name.</param> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when IMAP client is not connected and authenticated.</exception> public void SelectFolder(string folderName) { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (!IsConnected) { throw new InvalidOperationException("You must connect first."); } if (!IsAuthenticated) { throw new InvalidOperationException("The SELECT command is only valid in authenticated state."); } // Ensure that we send right separator to server, we accept both \ and /. folderName = folderName.Replace('\\', PathSeparator).Replace('/', PathSeparator); string line = GetNextCmdTag() + " SELECT " + TextUtils.QuoteString(Core.Encode_IMAP_UTF7_String(folderName)); int countWritten = TcpStream.WriteLine(line); LogAddWrite(countWritten, line); // Must get lines with * and cmdTag + OK or cmdTag BAD/NO. while (true) { line = ReadLine(); if (line.StartsWith("*")) { // Get rid of * line = line.Substring(1).Trim(); if (line.ToUpper().IndexOf("EXISTS") > -1 && line.ToUpper().IndexOf("FLAGS") == -1) { MsgCount = Convert.ToInt32(line.Substring(0, line.IndexOf(" ")).Trim()); } else if (line.ToUpper().IndexOf("RECENT") > -1 && line.ToUpper().IndexOf("FLAGS") == -1) { NewMsgCount = Convert.ToInt32(line.Substring(0, line.IndexOf(" ")).Trim()); } else if (line.ToUpper().IndexOf("UIDNEXT") > -1) { m_UIDNext = Convert.ToInt64(line.Substring(line.ToUpper().IndexOf("UIDNEXT") + 8, line.IndexOf(']') - line.ToUpper().IndexOf("UIDNEXT") - 8)); } else if (line.ToUpper().IndexOf("UIDVALIDITY") > -1) { m_UIDValidity = Convert.ToInt64(line.Substring(line.ToUpper().IndexOf("UIDVALIDITY") + 12, line.IndexOf(']') - line.ToUpper().IndexOf("UIDVALIDITY") - 12)); } } else { break; } } line = RemoveCmdTag(line); if (!line.ToUpper().StartsWith("OK")) { throw new IMAP_ClientException(line); } m_SelectedFolder = folderName; } /// <summary> /// Gets specified folder quota info. Throws Exception if server doesn't support QUOTA. /// </summary> /// <param name="folder">Folder name.</param> /// <returns>Returns specified folder quota info.</returns> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when IMAP client is not connected and authenticated.</exception> public IMAP_Quota GetFolderQuota(string folder) { /* RFC 2087 4.3. GETQUOTAROOT Command Arguments: mailbox name Data: untagged responses: QUOTAROOT, QUOTA Result: OK - getquota completed NO - getquota error: no such mailbox, permission denied BAD - command unknown or arguments invalid The GETQUOTAROOT command takes the name of a mailbox and returns the list of quota roots for the mailbox in an untagged QUOTAROOT response. For each listed quota root, it also returns the quota root's resource usage and limits in an untagged QUOTA response. Example: C: A003 GETQUOTAROOT INBOX S: * QUOTAROOT INBOX "" S: * QUOTA "" (STORAGE 10 512) S: A003 OK Getquota completed */ if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (!IsConnected) { throw new InvalidOperationException("You must connect first."); } if (!IsAuthenticated) { throw new InvalidOperationException("The command is only valid in authenticated state."); } IMAP_Quota retVal = null; // Ensure that we send right separator to server, we accept both \ and /. folder = folder.Replace('\\', PathSeparator).Replace('/', PathSeparator); string line = GetNextCmdTag() + " GETQUOTAROOT " + TextUtils.QuoteString(Core.Encode_IMAP_UTF7_String(folder)); int countWritten = TcpStream.WriteLine(line); LogAddWrite(countWritten, line); // Must get lines with * and cmdTag + OK or cmdTag BAD/NO. while (true) { line = ReadLine(); if (line.StartsWith("*")) { // Get rid of * line = line.Substring(1).Trim(); if (line.ToUpper().StartsWith("QUOTAROOT")) { // Skip QUOTAROOT } else if (line.ToUpper().StartsWith("QUOTA")) { StringReader r = new StringReader(line); // Skip QUOTA word r.ReadWord(); string qoutaRootName = r.ReadWord(); long storage = -1; long maxStorage = -1; long messages = -1; long maxMessages = -1; string limits = r.ReadParenthesized(); r = new StringReader(limits); while (r.Available > 0) { string limitName = r.ReadWord(); // STORAGE usedBytes maximumAllowedBytes if (limitName.ToUpper() == "STORAGE") { storage = Convert.ToInt64(r.ReadWord()); maxStorage = Convert.ToInt64(r.ReadWord()); } // STORAGE messagesCount maximumAllowedMessages else if (limitName.ToUpper() == "MESSAGE") { messages = Convert.ToInt64(r.ReadWord()); maxMessages = Convert.ToInt64(r.ReadWord()); } } retVal = new IMAP_Quota(qoutaRootName, messages, maxMessages, storage, maxStorage); } } else { break; } } line = RemoveCmdTag(line); if (!line.ToUpper().StartsWith("OK")) { throw new IMAP_ClientException(line); } return retVal; } /// <summary> /// Gets IMAP server namespaces info. /// </summary> /// <returns>Returns user namespaces.</returns> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when IMAP client is not connected and authenticated.</exception> public IMAP_NamespacesInfo GetNamespacesInfo() { /* RFC 2342 5. NAMESPACE Command. Arguments: none Response: an untagged NAMESPACE response that contains the prefix and hierarchy delimiter to the server's Personal Namespace(s), Other Users' Namespace(s), and Shared Namespace(s) that the server wishes to expose. The response will contain a NIL for any namespace class that is not available. Namespace_Response_Extensions MAY be included in the response. Namespace_Response_Extensions which are not on the IETF standards track, MUST be prefixed with an "X-". Result: OK - Command completed NO - Error: Can't complete command BAD - argument invalid Example: < A server that supports a single personal namespace. No leading prefix is used on personal mailboxes and "/" is the hierarchy delimiter.> C: A001 NAMESPACE S: * NAMESPACE (("" "/")) NIL NIL S: A001 OK NAMESPACE command completed */ if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (!IsConnected) { throw new InvalidOperationException("You must connect first."); } if (!IsAuthenticated) { throw new InvalidOperationException( "The NAMESPACE command is only valid in authenticated state."); } string line = GetNextCmdTag() + " NAMESPACE"; int countWritten = TcpStream.WriteLine(line); LogAddWrite(countWritten, line); IMAP_NamespacesInfo namespacesInfo = new IMAP_NamespacesInfo(null, null, null); while (true) { line = ReadLine(); if (line.StartsWith("*")) { line = RemoveCmdTag(line); if (line.ToUpper().StartsWith("NAMESPACE")) { namespacesInfo = IMAP_NamespacesInfo.Parse(line); } } else { break; } } line = RemoveCmdTag(line); if (!line.ToUpper().StartsWith("OK")) { throw new IMAP_ClientException(line); } return namespacesInfo; } /// <summary> /// Gets specified folder ACL entries. /// </summary> /// <param name="folderName">Folder which ACL entries to get.</param> /// <returns>Returns specified folder ACL entries.</returns> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when IMAP client is not connected and authenticated.</exception> public IMAP_Acl[] GetFolderACL(string folderName) { /* RFC 2086 4.3. GETACL Arguments: mailbox name Data: untagged responses: ACL Result: OK - getacl completed NO - getacl failure: can't get acl BAD - command unknown or arguments invalid The GETACL command returns the access control list for mailbox in an untagged ACL reply. Example: C: A002 GETACL INBOX S: * ACL INBOX Fred rwipslda S: A002 OK Getacl complete .... Multiple users S: * ACL INBOX Fred rwipslda test rwipslda .... No acl flags for Fred S: * ACL INBOX Fred "" test rwipslda */ if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (!IsConnected) { throw new InvalidOperationException("You must connect first."); } if (!IsAuthenticated) { throw new InvalidOperationException("The GETACL command is only valid in authenticated state."); } // Ensure that we send right separator to server, we accept both \ and /. folderName = folderName.Replace('\\', PathSeparator).Replace('/', PathSeparator); string line = GetNextCmdTag() + " GETACL " + TextUtils.QuoteString(Core.Encode_IMAP_UTF7_String(folderName)); int countWritten = TcpStream.WriteLine(line); LogAddWrite(countWritten, line); List<IMAP_Acl> retVal = new List<IMAP_Acl>(); while (true) { line = ReadLine(); if (line.StartsWith("*")) { line = RemoveCmdTag(line); if (line.ToUpper().StartsWith("ACL")) { retVal.Add(IMAP_Acl.Parse(line)); } } else { break; } } line = RemoveCmdTag(line); if (!line.ToUpper().StartsWith("OK")) { throw new IMAP_ClientException(line); } return retVal.ToArray(); } /// <summary> /// Sets specified user ACL permissions for specified folder. /// </summary> /// <param name="folderName">Folder name which ACL to set.</param> /// <param name="userName">User name who's ACL to set.</param> /// <param name="acl">ACL permissions to set.</param> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when IMAP client is not connected and authenticated.</exception> public void SetFolderACL(string folderName, string userName, IMAP_ACL_Flags acl) { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (!IsConnected) { throw new InvalidOperationException("You must connect first."); } if (!IsAuthenticated) { throw new InvalidOperationException("The SETACL command is only valid in authenticated state."); } // Ensure that we send right separator to server, we accept both \ and /. folderName = folderName.Replace('\\', PathSeparator).Replace('/', PathSeparator); string line = GetNextCmdTag() + " SETACL " + TextUtils.QuoteString(Core.Encode_IMAP_UTF7_String(folderName)) + " " + TextUtils.QuoteString(userName) + " " + IMAP_Utils.ACL_to_String(acl); int countWritten = TcpStream.WriteLine(line); LogAddWrite(countWritten, line); line = ReadLine(); line = RemoveCmdTag(line); if (!line.ToUpper().StartsWith("OK")) { throw new IMAP_ClientException(line); } } /// <summary> /// Deletes specified user access to specified folder. /// </summary> /// <param name="folderName">Folder which ACL to remove.</param> /// <param name="userName">User name who's ACL to remove.</param> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when IMAP client is not connected and authenticated.</exception> public void DeleteFolderACL(string folderName, string userName) { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (!IsConnected) { throw new InvalidOperationException("You must connect first."); } if (!IsAuthenticated) { throw new InvalidOperationException( "The DELETEACL command is only valid in authenticated state."); } // Ensure that we send right separator to server, we accept both \ and /. folderName = folderName.Replace('\\', PathSeparator).Replace('/', PathSeparator); string line = GetNextCmdTag() + " DELETEACL " + TextUtils.QuoteString(Core.Encode_IMAP_UTF7_String(folderName)) + " " + TextUtils.QuoteString(userName); int countWritten = TcpStream.WriteLine(line); LogAddWrite(countWritten, line); line = ReadLine(); line = RemoveCmdTag(line); if (!line.ToUpper().StartsWith("OK")) { throw new IMAP_ClientException(line); } } /// <summary> /// Gets myrights to specified folder. /// </summary> /// <param name="folderName">Folder which my rifgts to get.</param> /// <returns>Returns myrights to specified folder.</returns> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when IMAP client is not connected and authenticated.</exception> public IMAP_ACL_Flags GetFolderMyrights(string folderName) { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (!IsConnected) { throw new InvalidOperationException("You must connect first."); } if (!IsAuthenticated) { throw new InvalidOperationException( "The MYRIGHTS command is only valid in authenticated state."); } // Ensure that we send right separator to server, we accept both \ and /. folderName = folderName.Replace('\\', PathSeparator).Replace('/', PathSeparator); string line = GetNextCmdTag() + " MYRIGHTS " + TextUtils.QuoteString(Core.Encode_IMAP_UTF7_String(folderName)); int countWritten = TcpStream.WriteLine(line); LogAddWrite(countWritten, line); IMAP_ACL_Flags aclFlags = IMAP_ACL_Flags.None; // Must get lines with * and cmdTag + OK or cmdTag BAD/NO. while (true) { line = ReadLine(); if (line.StartsWith("*")) { line = RemoveCmdTag(line); if (line.ToUpper().IndexOf("MYRIGHTS") > -1) { aclFlags = IMAP_Utils.ACL_From_String(line.Substring(0, line.IndexOf(" ")).Trim()); } } else { break; } } line = RemoveCmdTag(line); if (!line.ToUpper().StartsWith("OK")) { throw new IMAP_ClientException(line); } return aclFlags; } /// <summary> /// Copies specified messages to specified folder. /// </summary> /// <param name="sequence_set">IMAP sequence-set.</param> /// <param name="destFolder">Destination folder name.</param> /// <param name="uidCopy">Specifies if UID COPY or COPY. /// For UID COPY all sequence_set numers must be message UID values and for normal COPY message numbers.</param> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when IMAP client is not connected,not authenticated and folder not selected.</exception> public void CopyMessages(IMAP_SequenceSet sequence_set, string destFolder, bool uidCopy) { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (!IsConnected) { throw new InvalidOperationException("You must connect first."); } if (!IsAuthenticated) { throw new InvalidOperationException("The COPY command is only valid in authenticated state."); } if (m_SelectedFolder.Length == 0) { throw new InvalidOperationException("The COPY command is only valid in selected state."); } // Ensure that we send right separator to server, we accept both \ and /. destFolder = destFolder.Replace('\\', PathSeparator).Replace('/', PathSeparator); string line = ""; if (uidCopy) { line = GetNextCmdTag() + " UID COPY " + sequence_set.ToSequenceSetString() + " " + TextUtils.QuoteString(Core.Encode_IMAP_UTF7_String(destFolder)); } else { line = GetNextCmdTag() + " COPY " + sequence_set.ToSequenceSetString() + " " + TextUtils.QuoteString(Core.Encode_IMAP_UTF7_String(destFolder)); } int countWritten = TcpStream.WriteLine(line); LogAddWrite(countWritten, line); // Read un-tagged response lines while we get final response line. while (true) { line = ReadLine(); // We have un-tagged resposne. if (line.StartsWith("*")) { ProcessStatusResponse(line); } else { break; } } if (!RemoveCmdTag(line).ToUpper().StartsWith("OK")) { throw new IMAP_ClientException(line); } } /// <summary> /// Moves specified messages to specified folder. /// </summary> /// <param name="sequence_set">IMAP sequence-set.</param> /// <param name="destFolder">Folder where to copy messages.</param> /// <param name="uidMove">Specifies if sequence-set contains message UIDs or message numbers.</param> public void MoveMessages(IMAP_SequenceSet sequence_set, string destFolder, bool uidMove) { if (!IsConnected) { throw new Exception("You must connect first !"); } if (!IsAuthenticated) { throw new Exception("You must authenticate first !"); } if (m_SelectedFolder.Length == 0) { throw new Exception("You must select folder first !"); } CopyMessages(sequence_set, destFolder, uidMove); DeleteMessages(sequence_set, uidMove); } /// <summary> /// Deletes specified messages. /// </summary> /// <param name="sequence_set">IMAP sequence-set.</param> /// <param name="uidDelete">Specifies if sequence-set contains message UIDs or message numbers.</param> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when IMAP client is not connected,not authenticated and folder not selected.</exception> public void DeleteMessages(IMAP_SequenceSet sequence_set, bool uidDelete) { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (!IsConnected) { throw new InvalidOperationException("You must connect first."); } if (!IsAuthenticated) { throw new InvalidOperationException("The command is only valid in authenticated state."); } if (m_SelectedFolder.Length == 0) { throw new InvalidOperationException("The command is only valid in selected state."); } // 1) Set deleted flag // 2) Delete messages with EXPUNGE command string line = ""; if (uidDelete) { line = GetNextCmdTag() + " UID STORE " + sequence_set.ToSequenceSetString() + " " + "+FLAGS.SILENT (\\Deleted)"; } else { line = GetNextCmdTag() + " STORE " + sequence_set.ToSequenceSetString() + " " + "+FLAGS.SILENT (\\Deleted)"; } int countWritten = TcpStream.WriteLine(line); LogAddWrite(countWritten, line); // Read un-tagged response lines while we get final response line. while (true) { line = ReadLine(); // We have un-tagged resposne. if (line.StartsWith("*")) { ProcessStatusResponse(line); } else { break; } } if (!RemoveCmdTag(line).ToUpper().StartsWith("OK")) { throw new IMAP_ClientException(line); } line = GetNextCmdTag() + " EXPUNGE"; countWritten = TcpStream.WriteLine(line); LogAddWrite(countWritten, line); // Read un-tagged response lines while we get final response line. while (true) { line = ReadLine(); // We have un-tagged resposne. if (line.StartsWith("*")) { ProcessStatusResponse(line); } else { break; } } if (!RemoveCmdTag(line).ToUpper().StartsWith("OK")) { throw new IMAP_ClientException(line); } } /// <summary> /// Stores message to specified folder. /// </summary> /// <param name="folderName">Folder where to store message.</param> /// <param name="data">Message data which to store.</param> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when IMAP client is not connected,not authenticated and folder not selected.</exception> public void StoreMessage(string folderName, byte[] data) { StoreMessage(folderName, IMAP_MessageFlags.Seen, DateTime.Now, data); } /// <summary> /// Stores message to specified folder. /// </summary> /// <param name="folderName">Folder where to store message.</param> /// <param name="messageFlags">Message flags what are stored for message.</param> /// <param name="inernalDate">Internal date value what are stored for message.</param> /// <param name="data">Message data which to store.</param> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when IMAP client is not connected,not authenticated and folder not selected.</exception> public void StoreMessage(string folderName, IMAP_MessageFlags messageFlags, DateTime inernalDate, byte[] data) { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (!IsConnected) { throw new InvalidOperationException("You must connect first."); } if (!IsAuthenticated) { throw new InvalidOperationException("The command is only valid in authenticated state."); } // Ensure that we send right separator to server, we accept both \ and /. folderName = folderName.Replace('\\', PathSeparator).Replace('/', PathSeparator); string line = GetNextCmdTag() + " APPEND " + TextUtils.QuoteString(Core.Encode_IMAP_UTF7_String(folderName)) + " (" + IMAP_Utils.MessageFlagsToString(messageFlags) + ") \"" + IMAP_Utils.DateTimeToString(inernalDate) + "\" {" + data.Length + "}"; int countWritten = TcpStream.WriteLine(line); LogAddWrite(countWritten, line); // Read un-tagged response lines while we get final response line or + send data. while (true) { line = ReadLine(); // We have un-tagged resposne. if (line.StartsWith("*")) { ProcessStatusResponse(line); } // Send data. else if (line.StartsWith("+")) { // Send message. TcpStream.Write(data, 0, data.Length); LogAddWrite(data.Length, "Wrote " + data.Length + " bytes."); // Send CRLF, ends splitted command line. TcpStream.Write(new[] {(byte) '\r', (byte) '\n'}, 0, 2); LogAddWrite(data.Length, "Wrote CRLF."); } else { break; } } if (!RemoveCmdTag(line).ToUpper().StartsWith("OK")) { throw new IMAP_ClientException(line); } } public int[] Search(string searchPattern, bool uidSearch) { if (!IsConnected) { throw new Exception("You must connect first !"); } if (!IsAuthenticated) { throw new Exception("You must authenticate first !"); } if (m_SelectedFolder.Length == 0) { throw new Exception("You must select folder first !"); } string line = GetNextCmdTag() + (uidSearch ? " UID" : "") + " SEARCH " + Core.Encode_IMAP_UTF7_String(searchPattern); int countWritten = TcpStream.WriteLine(line); LogAddWrite(countWritten, line); List<int> messageIDs = new List<int>(); // Read un-tagged response lines while we get final response line or + send data. while (true) { line = ReadLine(); // We have un-tagged resposne. if (line.StartsWith("*")) { ProcessSearchResponse(line, messageIDs); } else { break; } } if (!RemoveCmdTag(line).ToUpper().StartsWith("OK")) { throw new IMAP_ClientException(line); } return messageIDs.ToArray(); } public int[] SearchText(string textToFind, bool uidSearch, Encoding charset) { if (!IsConnected) { throw new Exception("You must connect first !"); } if (!IsAuthenticated) { throw new Exception("You must authenticate first !"); } if (m_SelectedFolder.Length == 0) { throw new Exception("You must select folder first !"); } string line = GetNextCmdTag() + (uidSearch ? " UID" : "") + " SEARCH " + (charset==null?"":string.Format("CHARSET {0} ", charset.WebName.ToUpper()))+string.Format("TEXT {0}", (charset==null?string.Format("\"{0}\"",Core.Encode_IMAP_UTF7_String(textToFind)):string.Format("{{{0}}}", textToFind.Length))); int countWritten = TcpStream.WriteLine(line); LogAddWrite(countWritten, line); if (charset != null) { line = ReadLine(); if (line.StartsWith("+")) { countWritten = TcpStream.WriteLine(textToFind); LogAddWrite(countWritten, textToFind); } } List<int> messageIDs = new List<int>(); // Read un-tagged response lines while we get final response line or + send data. while (true) { line = ReadLine(); // We have un-tagged resposne. if (line.StartsWith("*")) { ProcessSearchResponse(line, messageIDs); } else { break; } } if (!RemoveCmdTag(line).ToUpper().StartsWith("OK")) { throw new IMAP_ClientException(line); } return messageIDs.ToArray(); } /// <summary> /// Fetches specifes messages specified fetch items. /// </summary> /// <param name="sequence_set">IMAP sequence-set.</param> /// <param name="fetchFlags">Specifies what data to fetch from IMAP server.</param> /// <param name="setSeenFlag">If true message seen flag is setted.</param> /// <param name="uidFetch">Specifies if sequence-set contains message UIDs or message numbers.</param> /// <returns>Returns requested fetch items.</returns> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when IMAP client is not connected,not authenticated and folder not selected.</exception> public IMAP_FetchItem[] FetchMessages(IMAP_SequenceSet sequence_set, IMAP_FetchItem_Flags fetchFlags, bool setSeenFlag, bool uidFetch) { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (!IsConnected) { throw new InvalidOperationException("You must connect first."); } if (!IsAuthenticated) { throw new InvalidOperationException("The command is only valid in authenticated state."); } if (m_SelectedFolder.Length == 0) { throw new InvalidOperationException("The command is only valid in selected state."); } List<IMAP_FetchItem> fetchItems = new List<IMAP_FetchItem>(); //--- Construct FETCH command line -----------------------------------------------------------------------// string fetchCmdLine = GetNextCmdTag(); if (uidFetch) { fetchCmdLine += " UID"; } fetchCmdLine += " FETCH " + sequence_set.ToSequenceSetString() + " (UID"; // FLAGS if ((fetchFlags & IMAP_FetchItem_Flags.MessageFlags) != 0) { fetchCmdLine += " FLAGS"; } // RFC822.SIZE if ((fetchFlags & IMAP_FetchItem_Flags.Size) != 0) { fetchCmdLine += " RFC822.SIZE"; } // INTERNALDATE if ((fetchFlags & IMAP_FetchItem_Flags.InternalDate) != 0) { fetchCmdLine += " INTERNALDATE"; } // ENVELOPE if ((fetchFlags & IMAP_FetchItem_Flags.Envelope) != 0) { fetchCmdLine += " ENVELOPE"; } // BODYSTRUCTURE if ((fetchFlags & IMAP_FetchItem_Flags.BodyStructure) != 0) { fetchCmdLine += " BODYSTRUCTURE"; } // BODY[] or BODY.PEEK[] if ((fetchFlags & IMAP_FetchItem_Flags.Message) != 0) { if (setSeenFlag) { fetchCmdLine += " BODY[]"; } else { fetchCmdLine += " BODY.PEEK[]"; } } // BODY[HEADER] or BODY.PEEK[HEADER] ---> This needed only if full message isn't requested. if ((fetchFlags & IMAP_FetchItem_Flags.Message) == 0 && (fetchFlags & IMAP_FetchItem_Flags.Header) != 0) { if (setSeenFlag) { fetchCmdLine += " BODY[HEADER]"; } else { fetchCmdLine += " BODY.PEEK[HEADER]"; } } //--------------------------------------------------------------------------------------------------------// fetchCmdLine += ")"; // Send fetch command line to server. int countWritten = TcpStream.WriteLine(fetchCmdLine); LogAddWrite(countWritten, fetchCmdLine); // Read un-tagged response lines while we get final response line. byte[] lineBuffer = new byte[Workaround.Definitions.MaxStreamLineLength]; string line = ""; while (true) { SmartStream.ReadLineAsyncOP args = new SmartStream.ReadLineAsyncOP(lineBuffer, SizeExceededAction. JunkAndThrowException); TcpStream.ReadLine(args, false); if (args.Error != null) { throw args.Error; } line = args.LineUtf8; LogAddRead(args.BytesInBuffer, line); // We have un-tagged resposne. if (line.StartsWith("*")) { if (IsStatusResponse(line)) { ProcessStatusResponse(line); } else { int no = 0; int uid = 0; int size = 0; byte[] data = null; IMAP_MessageFlags flags = IMAP_MessageFlags.Recent; string envelope = ""; string bodystructure = ""; string internalDate = ""; // Remove * line = RemoveCmdTag(line); // Get message number no = Convert.ToInt32(line.Substring(0, line.IndexOf(" "))); // Get rid of FETCH and parse params. Reply:* 1 FETCH (UID 12 BODY[] ...) line = line.Substring(line.IndexOf("FETCH (") + 7); StringReader r = new StringReader(line); // Loop fetch result fields while (r.Available > 0) { r.ReadToFirstChar(); // Fetch command closing ) parenthesis if (r.SourceString == ")") { break; } #region UID <value> // UID <value> else if (r.StartsWith("UID", false)) { // Remove UID word from reply r.ReadSpecifiedLength("UID".Length); r.ReadToFirstChar(); // Read <value> string word = r.ReadWord(); if (word == null) { throw new Exception("IMAP server didn't return UID <value> !"); } else { uid = Convert.ToInt32(word); } } #endregion #region RFC822.SIZE <value> // RFC822.SIZE <value> else if (r.StartsWith("RFC822.SIZE", false)) { // Remove RFC822.SIZE word from reply r.ReadSpecifiedLength("RFC822.SIZE".Length); r.ReadToFirstChar(); // Read <value> string word = r.ReadWord(); if (word == null) { throw new Exception("IMAP server didn't return RFC822.SIZE <value> !"); } else { try { size = Convert.ToInt32(word); } catch { throw new Exception( "IMAP server returned invalid RFC822.SIZE <value> '" + word + "' !"); } } } #endregion #region INTERNALDATE <value> // INTERNALDATE <value> else if (r.StartsWith("INTERNALDATE", false)) { // Remove INTERNALDATE word from reply r.ReadSpecifiedLength("INTERNALDATE".Length); r.ReadToFirstChar(); // Read <value> string word = r.ReadWord(); if (word == null) { throw new Exception("IMAP server didn't return INTERNALDATE <value> !"); } else { internalDate = word; } } #endregion #region ENVELOPE (<envelope-string>) else if (r.StartsWith("ENVELOPE", false)) { // Remove ENVELOPE word from reply r.ReadSpecifiedLength("ENVELOPE".Length); r.ReadToFirstChar(); /* Handle string literals {count-to-read}<CRLF>data(length = count-to-read). (string can be quoted string or literal) Loop while get envelope,invalid response or timeout. */ while (true) { try { envelope = r.ReadParenthesized(); break; } catch (Exception x) { string s = r.ReadToEnd(); /* partial_envelope {count-to-read} Example: ENVELOPE ("Mon, 03 Apr 2006 10:10:10 GMT" {35} */ if (s.EndsWith("}")) { // Get partial envelope and append it back to reader r.AppenString(s.Substring(0, s.LastIndexOf('{'))); // Read remaining envelope and append it to reader. int countToRead = Convert.ToInt32(s.Substring(s.LastIndexOf('{') + 1, s.LastIndexOf('}') - s.LastIndexOf('{') - 1)); string reply = TcpStream.ReadFixedCountString(countToRead); LogAddRead(countToRead, reply); r.AppenString(TextUtils.QuoteString(reply)); // Read fetch continuing line. TcpStream.ReadLine(args, false); if (args.Error != null) { throw args.Error; } line = args.LineUtf8; LogAddRead(args.BytesInBuffer, line); r.AppenString(line); } // Unexpected response else { throw x; } } } } #endregion #region BODYSTRUCTURE (<bodystructure-string>) else if (r.StartsWith("BODYSTRUCTURE", false)) { // Remove BODYSTRUCTURE word from reply r.ReadSpecifiedLength("BODYSTRUCTURE".Length); r.ReadToFirstChar(); bodystructure = r.ReadParenthesized(); } #endregion #region BODY[] or BODY[HEADER] // BODY[] or BODY[HEADER] else if (r.StartsWith("BODY", false)) { if (r.StartsWith("BODY[]", false)) { // Remove BODY[] r.ReadSpecifiedLength("BODY[]".Length); } else if (r.StartsWith("BODY[HEADER]", false)) { // Remove BODY[HEADER] r.ReadSpecifiedLength("BODY[HEADER]".Length); } else { throw new Exception("Invalid FETCH response: " + r.SourceString); } r.ReadToFirstChar(); // We must now have {<size-to-read>}, or there is error if (!r.StartsWith("{")) { throw new Exception("Invalid FETCH BODY[] or BODY[HEADER] response: " + r.SourceString); } // Read <size-to-read> int dataLength = Convert.ToInt32(r.ReadParenthesized()); // Read data MemoryStream storeStrm = new MemoryStream(dataLength); TcpStream.ReadFixedCount(storeStrm, dataLength); LogAddRead(dataLength, "Readed " + dataLength + " bytes."); data = storeStrm.ToArray(); // Read fetch continuing line. TcpStream.ReadLine(args, false); if (args.Error != null) { throw args.Error; } line = args.LineUtf8; LogAddRead(args.BytesInBuffer, line); r.AppenString(line); } #endregion #region FLAGS (<flags-list>) // FLAGS (<flags-list>) else if (r.StartsWith("FLAGS", false)) { // Remove FLAGS word from reply r.ReadSpecifiedLength("FLAGS".Length); r.ReadToFirstChar(); // Read (<flags-list>) string flagsList = r.ReadParenthesized(); if (flagsList == null) { throw new Exception("IMAP server didn't return FLAGS (<flags-list>) !"); } else { flags = IMAP_Utils.ParseMessageFlags(flagsList); } } #endregion else { throw new Exception("Not supported fetch reply: " + r.SourceString); } } fetchItems.Add(new IMAP_FetchItem(no, uid, size, data, flags, internalDate, envelope, bodystructure, fetchFlags)); } } else { break; } } if (!RemoveCmdTag(line).ToUpper().StartsWith("OK")) { throw new IMAP_ClientException(line); } return fetchItems.ToArray(); } /// <summary> /// Gets specified message from server and stores to specified stream. /// </summary> /// <param name="uid">Message UID which to get.</param> /// <param name="storeStream">Stream where to store message.</param> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when IMAP client is not connected,not authenticated and folder not selected.</exception> public void FetchMessage(int uid, Stream storeStream) { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (!IsConnected) { throw new InvalidOperationException("You must connect first."); } if (!IsAuthenticated) { throw new InvalidOperationException("The command is only valid in authenticated state."); } if (m_SelectedFolder.Length == 0) { throw new InvalidOperationException("The command is only valid in selected state."); } // Send fetch command line to server. string line = GetNextCmdTag() + " UID FETCH " + uid + " BODY[]"; int countWritten = TcpStream.WriteLine(line); LogAddWrite(countWritten, line); // Read un-tagged response lines while we get final response line. while (true) { line = ReadLine(); // We have un-tagged resposne. if (line.StartsWith("*")) { if (IsStatusResponse(line)) { ProcessStatusResponse(line); } else if (line.ToUpper().IndexOf("BODY[") > - 1) { if (line.IndexOf('{') > -1) { StringReader r = new StringReader(line); while (r.Available > 0 && !r.StartsWith("{")) { r.ReadSpecifiedLength(1); } int sizeOfData = Convert.ToInt32(r.ReadParenthesized()); TcpStream.ReadFixedCount(storeStream, sizeOfData); LogAddRead(sizeOfData, "Readed " + sizeOfData + " bytes."); line = ReadLine(); } } } else { break; } } if (!RemoveCmdTag(line).ToUpper().StartsWith("OK")) { throw new IMAP_ClientException(line); } } /// <summary> /// Stores specified message flags to specified messages. /// </summary> /// <param name="sequence_set">IMAP sequence-set.</param> /// <param name="msgFlags">Message flags.</param> /// <param name="uidStore">Specifies if UID STORE or STORE. /// For UID STORE all sequence_set numers must be message UID values and for normal STORE message numbers.</param> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when IMAP client is not connected,not authenticated and folder not selected.</exception> public void StoreMessageFlags(IMAP_SequenceSet sequence_set, IMAP_MessageFlags msgFlags, bool uidStore) { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (!IsConnected) { throw new InvalidOperationException("You must connect first."); } if (!IsAuthenticated) { throw new InvalidOperationException("The command is only valid in authenticated state."); } if (m_SelectedFolder.Length == 0) { throw new InvalidOperationException("The command is only valid in selected state."); } string line = ""; if (uidStore) { line = GetNextCmdTag() + " UID STORE " + sequence_set.ToSequenceSetString() + " FLAGS (" + IMAP_Utils.MessageFlagsToString(msgFlags) + ")"; } else { line = GetNextCmdTag() + " STORE " + sequence_set.ToSequenceSetString() + " FLAGS (" + IMAP_Utils.MessageFlagsToString(msgFlags) + ")"; } int countWritten = TcpStream.WriteLine(line); LogAddWrite(countWritten, line); // Read un-tagged response lines while we get final response line. while (true) { line = ReadLine(); // We have un-tagged resposne. if (line.StartsWith("*")) { ProcessStatusResponse(line); } else { break; } } if (!RemoveCmdTag(line).ToUpper().StartsWith("OK")) { throw new IMAP_ClientException(line); } } public void AddMessageFlags(IMAP_SequenceSet sequence_set, IMAP_MessageFlags msgFlags, bool uidStore) { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (!IsConnected) { throw new InvalidOperationException("You must connect first."); } if (!IsAuthenticated) { throw new InvalidOperationException("The command is only valid in authenticated state."); } if (m_SelectedFolder.Length == 0) { throw new InvalidOperationException("The command is only valid in selected state."); } string line = ""; if (uidStore) { line = GetNextCmdTag() + " UID STORE " + sequence_set.ToSequenceSetString() + " +FLAGS.SILENT (" + IMAP_Utils.MessageFlagsToString(msgFlags) + ")"; } else { line = GetNextCmdTag() + " STORE " + sequence_set.ToSequenceSetString() + " +FLAGS.SILENT (" + IMAP_Utils.MessageFlagsToString(msgFlags) + ")"; } int countWritten = TcpStream.WriteLine(line); LogAddWrite(countWritten, line); // Read un-tagged response lines while we get final response line. while (true) { line = ReadLine(); // We have un-tagged resposne. if (line.StartsWith("*")) { ProcessStatusResponse(line); } else { break; } } if (!RemoveCmdTag(line).ToUpper().StartsWith("OK")) { throw new IMAP_ClientException(line); } } public void RemoveMessageFlags(IMAP_SequenceSet sequence_set, IMAP_MessageFlags msgFlags, bool uidStore) { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (!IsConnected) { throw new InvalidOperationException("You must connect first."); } if (!IsAuthenticated) { throw new InvalidOperationException("The command is only valid in authenticated state."); } if (m_SelectedFolder.Length == 0) { throw new InvalidOperationException("The command is only valid in selected state."); } string line = ""; if (uidStore) { line = GetNextCmdTag() + " UID STORE " + sequence_set.ToSequenceSetString() + " -FLAGS.SILENT (" + IMAP_Utils.MessageFlagsToString(msgFlags) + ")"; } else { line = GetNextCmdTag() + " STORE " + sequence_set.ToSequenceSetString() + " -FLAGS.SILENT (" + IMAP_Utils.MessageFlagsToString(msgFlags) + ")"; } int countWritten = TcpStream.WriteLine(line); LogAddWrite(countWritten, line); // Read un-tagged response lines while we get final response line. while (true) { line = ReadLine(); // We have un-tagged resposne. if (line.StartsWith("*")) { ProcessStatusResponse(line); } else { break; } } if (!RemoveCmdTag(line).ToUpper().StartsWith("OK")) { throw new IMAP_ClientException(line); } } /// <summary> /// Gets messages total size in selected folder. /// </summary> /// <returns>Returns messages total size in selected folder.</returns> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when IMAP client is not connected,not authenticated and folder not selected.</exception> public int GetMessagesTotalSize() { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (!IsConnected) { throw new InvalidOperationException("You must connect first."); } if (!IsAuthenticated) { throw new InvalidOperationException("The command is only valid in authenticated state."); } if (m_SelectedFolder.Length == 0) { throw new InvalidOperationException("The command is only valid in selected state."); } int totalSize = 0; string line = GetNextCmdTag() + " FETCH 1:* (RFC822.SIZE)"; int countWritten = TcpStream.WriteLine(line); LogAddWrite(countWritten, line); // Read un-tagged response lines while we get final response line. while (true) { line = ReadLine(); // We have un-tagged resposne. if (line.StartsWith("*")) { if (IsStatusResponse(line)) { ProcessStatusResponse(line); } else { // Get rid of * 1 FETCH and parse params. Reply:* 1 FETCH (UID 12 BODY[] ...) line = line.Substring(line.IndexOf("FETCH (") + 7); // RFC822.SIZE field if (line.ToUpper().StartsWith("RFC822.SIZE")) { line = line.Substring(11).Trim(); // Remove RFC822.SIZE word from reply totalSize += Convert.ToInt32(line.Substring(0, line.Length - 1).Trim()); // Remove ending ')' } } } else { break; } } if (!RemoveCmdTag(line).ToUpper().StartsWith("OK")) { throw new IMAP_ClientException(line); } return totalSize; } /// <summary> /// Gets unseen messages count in selected folder. /// </summary> /// <returns>Returns number of unseen messages.</returns> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when IMAP client is not connected,not authenticated and folder not selected.</exception> public int GetUnseenMessagesCount() { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (!IsConnected) { throw new InvalidOperationException("You must connect first."); } if (!IsAuthenticated) { throw new InvalidOperationException("The command is only valid in authenticated state."); } if (m_SelectedFolder.Length == 0) { throw new InvalidOperationException("The command is only valid in selected state."); } int count = 0; string line = GetNextCmdTag() + " FETCH 1:* (FLAGS)"; int countWritten = TcpStream.WriteLine(line); LogAddWrite(countWritten, line); // Read un-tagged response lines while we get final response line. while (true) { line = ReadLine(); // We have un-tagged resposne. if (line.StartsWith("*")) { if (IsStatusResponse(line)) { ProcessStatusResponse(line); } else { // Get rid of * 1 FETCH and parse params. Reply:* 1 FETCH (UID 12 BODY[] ...) line = line.Substring(line.IndexOf("FETCH (") + 7); if (line.ToUpper().IndexOf("\\SEEN") == -1) { count++; } } } else { break; } } if (!RemoveCmdTag(line).ToUpper().StartsWith("OK")) { throw new IMAP_ClientException(line); } return count; } /// <summary> /// Gets IMAP server folder separator char. /// </summary> /// <returns>Returns IMAP server folder separator char.</returns> public string GetFolderSeparator() { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (!IsConnected) { throw new InvalidOperationException("You must connect first."); } if (!IsAuthenticated) { throw new InvalidOperationException("The command is only valid in authenticated state."); } string folderSeparator = ""; string line = GetNextCmdTag() + " LIST \"\" \"\""; int countWritten = TcpStream.WriteLine(line); LogAddWrite(countWritten, line); // Read un-tagged response lines while we get final response line. while (true) { line = ReadLine(); // We have un-tagged resposne. if (line.StartsWith("*")) { if (IsStatusResponse(line)) { ProcessStatusResponse(line); } else { line = line.Substring(line.IndexOf(")") + 1).Trim(); // Remove * LIST(..) // get folder separator folderSeparator = line.Substring(0, line.IndexOf(" ")).Trim(); } } else { break; } } if (!RemoveCmdTag(line).ToUpper().StartsWith("OK")) { throw new IMAP_ClientException(line); } return folderSeparator.Replace("\"", ""); } #endregion #region Overrides /// <summary> /// This method is called after TCP client has sucessfully connected. /// </summary> protected override void OnConnected() { SmartStream.ReadLineAsyncOP args = new SmartStream.ReadLineAsyncOP(new byte[Workaround.Definitions.MaxStreamLineLength], SizeExceededAction. JunkAndThrowException); TcpStream.ReadLine(args, false); if (args.Error != null) { throw args.Error; } string line = args.LineUtf8; LogAddRead(args.BytesInBuffer, line); line = RemoveCmdTag(line); if (line.ToUpper().StartsWith("OK")) { // Clear path separator, so next access will get it. m_PathSeparator = '\0'; } else { throw new Exception("Server returned: " + line); } GetCapabilities(); if (Capabilities.Contains("STARTTLS") && Capabilities.Contains("LOGINDISABLED")) { //Switch to ssl StartTLS(); //get caps again GetCapabilities(); } } #endregion #region Event handlers private void Timer_Elapsed(object sender, ElapsedEventArgs e) { if (IsConnected && IsAuthenticated && !IsDisposed) { if ((DateTime.Now - LastActivity) > TimeSpan.FromMilliseconds(NoopInterval)) { //Send noop //SendNoop();//No noop } } } #endregion #region Utility methods private DateTime lastStatus; public void SendNoop() { SendNoop(false); } public void SendNoop(bool bForce) { if (IsConnected && IsAuthenticated && !IsDisposed) { if (((DateTime.Now - lastStatus).TotalMilliseconds > NoopDelay)||bForce) { string cmdTag = GetNextCmdTag(); string line = cmdTag + " NOOP"; int countWritten = TcpStream.WriteLine(line); LogAddWrite(countWritten, line); while (true) { line = ReadLine(); if (line.StartsWith("*")) { ProcessStatusResponse(line); } else { break; } } line = RemoveCmdTag(line); if (!line.ToUpper().StartsWith("OK")) { throw new IMAP_ClientException(line); } lastStatus = DateTime.Now; } } } private void ProcessSearchResponse(string line, List<int> ds) { if (line.IndexOf("SEARCH") > -1 && !line.Equals("* SEARCH")/*empty responce*/) { string[] idsLine = line.Substring(line.IndexOf(' ', line.IndexOf("SEARCH"))).Split( new[] {' '}, StringSplitOptions.RemoveEmptyEntries); foreach (string num in idsLine) { int number; if (int.TryParse(num, NumberStyles.Integer, CultureInfo.InvariantCulture, out number)) { ds.Add(number); } } } } /// <summary> /// Removes command tag from response line. /// </summary> /// <param name="responseLine">Response line with command tag.</param> /// <returns></returns> private string RemoveCmdTag(string responseLine) { return responseLine.Substring(responseLine.IndexOf(" ")).Trim(); } /// <summary> /// Processes IMAP STATUS response and updates this class status info. /// </summary> /// <param name="statusResponse">IMAP STATUS response line.</param> private void ProcessStatusResponse(string statusResponse) { /* RFC 3501 7.3.1. EXISTS Response Example: S: * 23 EXISTS */ /* RFC 3501 7.3.2. RECENT Response Example: S: * 5 RECENT */ statusResponse = statusResponse.ToUpper(); // Get rid of * statusResponse = statusResponse.Substring(1).Trim(); if (statusResponse.IndexOf("EXISTS") > -1 && statusResponse.IndexOf("FLAGS") == -1) { MsgCount = Convert.ToInt32(statusResponse.Substring(0, statusResponse.IndexOf(" ")).Trim()); lastStatus = DateTime.Now; } else if (statusResponse.IndexOf("RECENT") > -1 && statusResponse.IndexOf("FLAGS") == -1) { NewMsgCount = Convert.ToInt32(statusResponse.Substring(0, statusResponse.IndexOf(" ")).Trim()); lastStatus = DateTime.Now; } else if (statusResponse.IndexOf("EXPUNGE") > -1 && statusResponse.IndexOf("FLAGS") == -1) { //Dec number by 1 MsgCount--; lastStatus = DateTime.Now; } } /// <summary> /// Gets if specified line is STATUS response. /// </summary> /// <param name="line"></param> /// <returns></returns> private bool IsStatusResponse(string line) { if (!line.StartsWith("*")) { return false; } // Remove * line = line.Substring(1).TrimStart(); // RFC 3951 7.1.2. NO Response (untagged) if (line.ToUpper().StartsWith("NO")) { return true; } // RFC 3951 7.1.3. BAD Response (untagged) else if (line.ToUpper().StartsWith("BAD")) { return true; } // * 1 EXISTS // * 1 RECENT // * 1 EXPUNGE if (line.ToLower().IndexOf("exists") > -1) { return true; } if (line.ToLower().IndexOf("recent") > -1 && line.ToLower().IndexOf("flags") == -1) { return true; } else if (line.ToLower().IndexOf("expunge") > -1) { return true; } return false; } /// <summary> /// Gets next command tag. /// </summary> /// <returns>Returns next command tag.</returns> private string GetNextCmdTag() { m_CmdNumber++; return "ls" + m_CmdNumber; } #endregion public byte[] GetFilters() { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (!IsConnected) { throw new InvalidOperationException("You must connect first."); } if (!IsAuthenticated) { throw new InvalidOperationException("The command is only valid in authenticated state."); } if (m_SelectedFolder.Length == 0) { throw new InvalidOperationException("The command is only valid in selected state."); } // Send fetch command line to server. string line = GetNextCmdTag() + " X-GET-FILTER "; int countWritten = TcpStream.WriteLine(line); LogAddWrite(countWritten, line); using (MemoryStream store = new MemoryStream()) { // Read un-tagged response lines while we get final response line. while (true) { line = ReadLine(); // We have un-tagged resposne. if (line.StartsWith("*")) { if (IsStatusResponse(line)) { ProcessStatusResponse(line); } else if (line.ToUpper().IndexOf("FILTER") > -1) { if (line.IndexOf('{') > -1) { StringReader r = new StringReader(line); while (r.Available > 0 && !r.StartsWith("{")) { r.ReadSpecifiedLength(1); } int sizeOfData = Convert.ToInt32(r.ReadParenthesized()); TcpStream.ReadFixedCount(store, sizeOfData); LogAddRead(sizeOfData, "Readed " + sizeOfData + " bytes."); line = ReadLine(); } } } else { break; } } if (!RemoveCmdTag(line).ToUpper().StartsWith("OK")) { throw new IMAP_ClientException(line); } byte[] buffer = store.GetBuffer(); if (buffer.Length>0) { return Convert.FromBase64String(Encoding.UTF8.GetString(buffer)); } else { return null; } } } public void SetFilters(byte[] bufferRaw) { if (bufferRaw == null) { throw new ArgumentNullException("bufferRaw"); } if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (!IsConnected) { throw new InvalidOperationException("You must connect first."); } if (!IsAuthenticated) { throw new InvalidOperationException("The command is only valid in authenticated state."); } // Ensure that we send right separator to server, we accept both \ and /. byte[] buffer = Encoding.UTF8.GetBytes(Convert.ToBase64String(bufferRaw)); string line = string.Format("{0} X-SET-FILTER {{{1}}}", GetNextCmdTag(), buffer.Length); int countWritten = TcpStream.WriteLine(line); LogAddWrite(countWritten, line); // Read un-tagged response lines while we get final response line or + send data. while (true) { line = ReadLine(); // We have un-tagged resposne. if (line.StartsWith("*")) { ProcessStatusResponse(line); } // Send data. else if (line.StartsWith("+")) { // Send message. TcpStream.Write(buffer, 0, buffer.Length); LogAddWrite(buffer.Length, "Wrote " + buffer.Length + " bytes."); // Send CRLF, ends splitted command line. TcpStream.Write(new[] { (byte)'\r', (byte)'\n' }, 0, 2); LogAddWrite(buffer.Length, "Wrote CRLF."); } else { break; } } if (!RemoveCmdTag(line).ToUpper().StartsWith("OK")) { throw new IMAP_ClientException(line); } } } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/URI/UriSchemes.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net { /// <summary> /// This class represents well known URI schemes. /// </summary> public class UriSchemes { #region Constants /// <summary> /// HTTP Extensions for Distributed Authoring (WebDAV). /// </summary> public const string dav = "dav"; /// <summary> /// Addressing files on local or network file systems. /// </summary> public const string file = "file"; /// <summary> /// FTP resources. /// </summary> public const string ftp = "ftp"; /// <summary> /// HTTP resources. /// </summary> public const string http = "http"; /// <summary> /// HTTP connections secured using SSL/TLS. /// </summary> public const string https = "https"; /// <summary> /// SMTP e-mail addresses and default content. /// </summary> public const string mailto = "mailto"; /// <summary> /// Session Initiation Protocol (SIP). /// </summary> public const string sip = "sip"; /// <summary> /// Session Initiation Protocol (SIP) using TLS. /// </summary> public const string sips = "sips"; /// <summary> /// Telephone numbers. /// </summary> public const string tel = "tel"; #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/ServersCore/SocketBufferedWriter.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net { #region usings using System; using System.Text; #endregion /// <summary> /// Implements buffered writer for socket. /// </summary> public class SocketBufferedWriter { #region Members private readonly byte[] m_Buffer; private readonly SocketEx m_pSocket; private int m_AvailableInBuffer; private int m_BufferSize = 8000; #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="socket">Socket where to write data.</param> public SocketBufferedWriter(SocketEx socket) { m_pSocket = socket; m_Buffer = new byte[m_BufferSize]; } #endregion #region Methods /// <summary> /// Forces to send all data in buffer to destination host. /// </summary> public void Flush() { if (m_AvailableInBuffer > 0) { m_pSocket.Write(m_Buffer, 0, m_AvailableInBuffer); m_AvailableInBuffer = 0; } } /// <summary> /// Queues specified data to write buffer. If write buffer is full, buffered data will be sent to detination host. /// </summary> /// <param name="data">Data to queue.</param> public void Write(string data) { Write(Encoding.UTF8.GetBytes(data)); } /// <summary> /// Queues specified data to write buffer. If write buffer is full, buffered data will be sent to detination host. /// </summary> /// <param name="data">Data to queue.</param> public void Write(byte[] data) { // There is no room to accomodate data to buffer if ((m_AvailableInBuffer + data.Length) > m_BufferSize) { // Send buffer data m_pSocket.Write(m_Buffer, 0, m_AvailableInBuffer); m_AvailableInBuffer = 0; // Store new data to buffer if (data.Length < m_BufferSize) { Array.Copy(data, m_Buffer, data.Length); m_AvailableInBuffer = data.Length; } // Buffer is smaller than data, send it directly else { m_pSocket.Write(data); } } // Store data to buffer else { Array.Copy(data, 0, m_Buffer, m_AvailableInBuffer, data.Length); m_AvailableInBuffer += data.Length; } } #endregion } }<file_sep>/module/ASC.AuditTrail/Mappers/ProjectsActionMapper.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System.Collections.Generic; using ASC.MessagingSystem; namespace ASC.AuditTrail.Mappers { internal class ProjectsActionsMapper { public static Dictionary<MessageAction, MessageMaps> GetMaps() { return new Dictionary<MessageAction, MessageMaps> { #region projects { MessageAction.ProjectCreated, new MessageMaps { ActionTypeTextResourceName = "CreateActionType", ActionTextResourceName = "ProjectCreated", ProductResourceName = "ProjectsProduct", ModuleResourceName = "ProjectsModule" } }, { MessageAction.ProjectCreatedFromTemplate, new MessageMaps { ActionTypeTextResourceName = "CreateActionType", ActionTextResourceName = "ProjectCreatedFromTemplate", ProductResourceName = "ProjectsProduct", ModuleResourceName = "ProjectsModule" } }, { MessageAction.ProjectUpdated, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "ProjectUpdated", ProductResourceName = "ProjectsProduct", ModuleResourceName = "ProjectsModule" } }, { MessageAction.ProjectUpdatedStatus, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "ProjectUpdatedStatus", ProductResourceName = "ProjectsProduct", ModuleResourceName = "ProjectsModule" } }, { MessageAction.ProjectFollowed, new MessageMaps { ActionTypeTextResourceName = "FollowActionType", ActionTextResourceName = "ProjectFollowed", ProductResourceName = "ProjectsProduct", ModuleResourceName = "ProjectsModule" } }, { MessageAction.ProjectUnfollowed, new MessageMaps { ActionTypeTextResourceName = "UnfollowActionType", ActionTextResourceName = "ProjectUnfollowed", ProductResourceName = "ProjectsProduct", ModuleResourceName = "ProjectsModule" } }, { MessageAction.ProjectDeleted, new MessageMaps { ActionTypeTextResourceName = "DeleteActionType", ActionTextResourceName = "ProjectDeleted", ProductResourceName = "ProjectsProduct", ModuleResourceName = "ProjectsModule" } }, #endregion #region team { MessageAction.ProjectDeletedMember, new MessageMaps { ActionTypeTextResourceName = "DeleteActionType", ActionTextResourceName = "ProjectDeletedMember", ProductResourceName = "ProjectsProduct", ModuleResourceName = "ProjectsModule" } }, { MessageAction.ProjectUpdatedTeam, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "ProjectUpdatedTeam", ProductResourceName = "ProjectsProduct", ModuleResourceName = "ProjectsModule" } }, { MessageAction.ProjectUpdatedMemberRights, new MessageMaps { ActionTypeTextResourceName = "UpdateAccessActionType", ActionTextResourceName = "ProjectUpdatedMemberRights", ProductResourceName = "ProjectsProduct", ModuleResourceName = "ProjectsModule" } }, #endregion #region contacts { MessageAction.ProjectLinkedCompany, new MessageMaps { ActionTypeTextResourceName = "LinkActionType", ActionTextResourceName = "ProjectLinkedCompany", ProductResourceName = "ProjectsProduct", ModuleResourceName = "ProjectsModule" } }, { MessageAction.ProjectUnlinkedCompany, new MessageMaps { ActionTypeTextResourceName = "UnlinkActionType", ActionTextResourceName = "ProjectUnlinkedCompany", ProductResourceName = "ProjectsProduct", ModuleResourceName = "ProjectsModule" } }, { MessageAction.ProjectLinkedPerson, new MessageMaps { ActionTypeTextResourceName = "LinkActionType", ActionTextResourceName = "ProjectLinkedPerson", ProductResourceName = "ProjectsProduct", ModuleResourceName = "ProjectsModule" } }, { MessageAction.ProjectUnlinkedPerson, new MessageMaps { ActionTypeTextResourceName = "UnlinkActionType", ActionTextResourceName = "ProjectUnlinkedPerson", ProductResourceName = "ProjectsProduct", ModuleResourceName = "ProjectsModule" } }, { MessageAction.ProjectLinkedContacts, new MessageMaps { ActionTypeTextResourceName = "LinkActionType", ActionTextResourceName = "ProjectLinkedContacts", ProductResourceName = "ProjectsProduct", ModuleResourceName = "ProjectsModule" } }, #endregion #region milestones { MessageAction.MilestoneCreated, new MessageMaps { ActionTypeTextResourceName = "CreateActionType", ActionTextResourceName = "MilestoneCreated", ProductResourceName = "ProjectsProduct", ModuleResourceName = "MilestonesModule" } }, { MessageAction.MilestoneUpdated, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "MilestoneUpdated", ProductResourceName = "ProjectsProduct", ModuleResourceName = "MilestonesModule" } }, { MessageAction.MilestoneUpdatedStatus, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "MilestoneUpdatedStatus", ProductResourceName = "ProjectsProduct", ModuleResourceName = "MilestonesModule" } }, { MessageAction.MilestoneDeleted, new MessageMaps { ActionTypeTextResourceName = "DeleteActionType", ActionTextResourceName = "MilestoneDeleted", ProductResourceName = "ProjectsProduct", ModuleResourceName = "MilestonesModule" } }, #endregion #region tasks { MessageAction.TaskCreated, new MessageMaps { ActionTypeTextResourceName = "CreateActionType", ActionTextResourceName = "TaskCreated", ProductResourceName = "ProjectsProduct", ModuleResourceName = "TasksModule" } }, { MessageAction.TaskCreatedFromDiscussion, new MessageMaps { ActionTypeTextResourceName = "CreateActionType", ActionTextResourceName = "TaskCreatedFromDiscussion", ProductResourceName = "ProjectsProduct", ModuleResourceName = "TasksModule" } }, { MessageAction.TaskUpdated, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "TaskUpdated", ProductResourceName = "ProjectsProduct", ModuleResourceName = "TasksModule" } }, { MessageAction.TaskUpdatedStatus, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "TaskUpdatedStatus", ProductResourceName = "ProjectsProduct", ModuleResourceName = "TasksModule" } }, { MessageAction.TaskMovedToMilestone, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "TaskMovedToMilestone", ProductResourceName = "ProjectsProduct", ModuleResourceName = "TasksModule" } }, { MessageAction.TaskUnlinkedMilestone, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "TaskUnlinkedMilestone", ProductResourceName = "ProjectsProduct", ModuleResourceName = "TasksModule" } }, { MessageAction.TaskUpdatedFollowing, new MessageMaps { ActionTypeTextResourceName = "FollowActionType", ActionTextResourceName = "TaskUpdatedFollowing", ProductResourceName = "ProjectsProduct", ModuleResourceName = "TasksModule" } }, { MessageAction.TaskAttachedFiles, new MessageMaps { ActionTypeTextResourceName = "AttachActionType", ActionTextResourceName = "TaskAttachedFiles", ProductResourceName = "ProjectsProduct", ModuleResourceName = "TasksModule" } }, { MessageAction.TaskDetachedFile, new MessageMaps { ActionTypeTextResourceName = "DetachActionType", ActionTextResourceName = "TaskDetachedFile", ProductResourceName = "ProjectsProduct", ModuleResourceName = "TasksModule" } }, { MessageAction.TasksLinked, new MessageMaps { ActionTypeTextResourceName = "LinkActionType", ActionTextResourceName = "TasksLinked", ProductResourceName = "ProjectsProduct", ModuleResourceName = "TasksModule" } }, { MessageAction.TasksUnlinked, new MessageMaps { ActionTypeTextResourceName = "UnlinkActionType", ActionTextResourceName = "TasksUnlinked", ProductResourceName = "ProjectsProduct", ModuleResourceName = "TasksModule" } }, { MessageAction.TaskDeleted, new MessageMaps { ActionTypeTextResourceName = "DeleteActionType", ActionTextResourceName = "TaskDeleted", ProductResourceName = "ProjectsProduct", ModuleResourceName = "TasksModule" } }, { MessageAction.TaskCommentCreated, new MessageMaps { ActionTypeTextResourceName = "CreateActionType", ActionTextResourceName = "TaskCommentCreated", ProductResourceName = "ProjectsProduct", ModuleResourceName = "TasksModule" } }, { MessageAction.TaskCommentUpdated, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "TaskCommentUpdated", ProductResourceName = "ProjectsProduct", ModuleResourceName = "TasksModule" } }, { MessageAction.TaskCommentDeleted, new MessageMaps { ActionTypeTextResourceName = "DeleteActionType", ActionTextResourceName = "TaskCommentDeleted", ProductResourceName = "ProjectsProduct", ModuleResourceName = "TasksModule" } }, #endregion #region subtasks { MessageAction.SubtaskCreated, new MessageMaps { ActionTypeTextResourceName = "CreateActionType", ActionTextResourceName = "SubtaskCreated", ProductResourceName = "ProjectsProduct", ModuleResourceName = "TasksModule" } }, { MessageAction.SubtaskUpdated, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "SubtaskUpdated", ProductResourceName = "ProjectsProduct", ModuleResourceName = "TasksModule" } }, { MessageAction.SubtaskUpdatedStatus, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "SubtaskUpdatedStatus", ProductResourceName = "ProjectsProduct", ModuleResourceName = "TasksModule" } }, { MessageAction.SubtaskDeleted, new MessageMaps { ActionTypeTextResourceName = "DeleteActionType", ActionTextResourceName = "SubtaskDeleted", ProductResourceName = "ProjectsProduct", ModuleResourceName = "TasksModule" } }, #endregion #region discussions { MessageAction.DiscussionCreated, new MessageMaps { ActionTypeTextResourceName = "CreateActionType", ActionTextResourceName = "DiscussionCreated", ProductResourceName = "ProjectsProduct", ModuleResourceName = "DiscussionsModule" } }, { MessageAction.DiscussionUpdated, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "DiscussionUpdated", ProductResourceName = "ProjectsProduct", ModuleResourceName = "DiscussionsModule" } }, { MessageAction.DiscussionUpdatedFollowing, new MessageMaps { ActionTypeTextResourceName = "FollowActionType", ActionTextResourceName = "DiscussionUpdatedFollowing", ProductResourceName = "ProjectsProduct", ModuleResourceName = "DiscussionsModule" } }, { MessageAction.DiscussionAttachedFiles, new MessageMaps { ActionTypeTextResourceName = "AttachActionType", ActionTextResourceName = "DiscussionAttachedFiles", ProductResourceName = "ProjectsProduct", ModuleResourceName = "DiscussionsModule" } }, { MessageAction.DiscussionDetachedFile, new MessageMaps { ActionTypeTextResourceName = "DetachActionType", ActionTextResourceName = "DiscussionDetachedFile", ProductResourceName = "ProjectsProduct", ModuleResourceName = "DiscussionsModule" } }, { MessageAction.DiscussionDeleted, new MessageMaps { ActionTypeTextResourceName = "DeleteActionType", ActionTextResourceName = "DiscussionDeleted", ProductResourceName = "ProjectsProduct", ModuleResourceName = "DiscussionsModule" } }, { MessageAction.DiscussionCommentCreated, new MessageMaps { ActionTypeTextResourceName = "CreateActionType", ActionTextResourceName = "DiscussionCommentCreated", ProductResourceName = "ProjectsProduct", ModuleResourceName = "DiscussionsModule" } }, { MessageAction.DiscussionCommentUpdated, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "DiscussionCommentUpdated", ProductResourceName = "ProjectsProduct", ModuleResourceName = "DiscussionsModule" } }, { MessageAction.DiscussionCommentDeleted, new MessageMaps { ActionTypeTextResourceName = "DeleteActionType", ActionTextResourceName = "DiscussionCommentDeleted", ProductResourceName = "ProjectsProduct", ModuleResourceName = "DiscussionsModule" } }, #endregion #region time tracking { MessageAction.TaskTimeCreated, new MessageMaps { ActionTypeTextResourceName = "CreateActionType", ActionTextResourceName = "TaskTimeCreated", ProductResourceName = "ProjectsProduct", ModuleResourceName = "TimeTrackingModule" } }, { MessageAction.TaskTimeUpdated, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "TaskTimeUpdated", ProductResourceName = "ProjectsProduct", ModuleResourceName = "TimeTrackingModule" } }, { MessageAction.TaskTimesUpdatedStatus, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "TaskTimesUpdatedStatus", ProductResourceName = "ProjectsProduct", ModuleResourceName = "TimeTrackingModule" } }, { MessageAction.TaskTimesDeleted, new MessageMaps { ActionTypeTextResourceName = "DeleteActionType", ActionTextResourceName = "TaskTimesDeleted", ProductResourceName = "ProjectsProduct", ModuleResourceName = "TimeTrackingModule" } }, #endregion #region reports { MessageAction.ReportTemplateCreated, new MessageMaps { ActionTypeTextResourceName = "CreateActionType", ActionTextResourceName = "ReportTemplateCreated", ProductResourceName = "ProjectsProduct", ModuleResourceName = "ReportsModule" } }, { MessageAction.ReportTemplateUpdated, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "ReportTemplateUpdated", ProductResourceName = "ProjectsProduct", ModuleResourceName = "ReportsModule" } }, { MessageAction.ReportTemplateDeleted, new MessageMaps { ActionTypeTextResourceName = "DeleteActionType", ActionTextResourceName = "ReportTemplateDeleted", ProductResourceName = "ProjectsProduct", ModuleResourceName = "ReportsModule" } }, #endregion #region settings { MessageAction.ProjectTemplateCreated, new MessageMaps { ActionTypeTextResourceName = "CreateActionType", ActionTextResourceName = "ProjectTemplateCreated", ProductResourceName = "ProjectsProduct", ModuleResourceName = "ProjectsSettingsModule" } }, { MessageAction.ProjectTemplateUpdated, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "ProjectTemplateUpdated", ProductResourceName = "ProjectsProduct", ModuleResourceName = "ProjectsSettingsModule" } }, { MessageAction.ProjectTemplateDeleted, new MessageMaps { ActionTypeTextResourceName = "DeleteActionType", ActionTextResourceName = "ProjectTemplateDeleted", ProductResourceName = "ProjectsProduct", ModuleResourceName = "ProjectsSettingsModule" } }, { MessageAction.ProjectsImportedFromBasecamp, new MessageMaps { ActionTypeTextResourceName = "ImportActionType", ActionTextResourceName = "ProjectsImportedFromBasecamp", ProductResourceName = "ProjectsProduct", ModuleResourceName = "ProjectsModule" } }, #endregion }; } } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Autoreply/AddressParsers/FileAddressParser.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System.Collections.Generic; using System.Text.RegularExpressions; using ASC.Core.Tenants; namespace ASC.Mail.Autoreply.AddressParsers { internal class FileAddressParser : AddressParser { protected override Regex GetRouteRegex() { return new Regex(@"^file_(?'folder'my|common|share|\d+)$", RegexOptions.Compiled); } protected override ApiRequest ParseRequestInfo(IDictionary<string,string> groups, Tenant t) { var folder = groups["folder"]; int id; if (!int.TryParse(folder, out id)) { folder = '@' + folder; } return new ApiRequest(string.Format("files/{0}/upload", folder)) {FilesToPost = new List<RequestFileInfo>()}; } } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/POP3/Server/POP3_eArgs_GetMessageStream.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.POP3.Server { #region usings using System; using System.IO; #endregion /// <summary> /// Provides data to POP3 server event GetMessageStream. /// </summary> public class POP3_eArgs_GetMessageStream { #region Members private readonly POP3_Message m_pMessageInfo; private readonly POP3_Session m_pSession; private bool m_CloseMessageStream = true; private bool m_MessageExists = true; private long m_MessageStartOffset; private Stream m_MessageStream; #endregion #region Properties /// <summary> /// Gets reference to current POP3 session. /// </summary> public POP3_Session Session { get { return m_pSession; } } /// <summary> /// Gets message info what message stream to get. /// </summary> public POP3_Message MessageInfo { get { return m_pMessageInfo; } } /// <summary> /// Gets or sets if message stream is closed automatically if all actions on it are completed. /// Default value is true. /// </summary> public bool CloseMessageStream { get { return m_CloseMessageStream; } set { m_CloseMessageStream = value; } } /// <summary> /// Gets or sets message stream. When setting this property Stream position must be where message begins. /// </summary> public Stream MessageStream { get { if (m_MessageStream != null) { m_MessageStream.Position = m_MessageStartOffset; } return m_MessageStream; } set { if (value == null) { throw new ArgumentNullException("Property MessageStream value can't be null !"); } if (!value.CanSeek) { throw new Exception("Stream must support seeking !"); } m_MessageStream = value; m_MessageStartOffset = m_MessageStream.Position; } } /// <summary> /// Gets message size in bytes. /// </summary> public long MessageSize { get { if (m_MessageStream == null) { throw new Exception("You must set MessageStream property first to use this property !"); } else { return m_MessageStream.Length - m_MessageStream.Position; } } } /// <summary> /// Gets or sets if message exists. Set this false, if message actually doesn't exist any more. /// </summary> public bool MessageExists { get { return m_MessageExists; } set { m_MessageExists = value; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="session">Reference to current POP3 session.</param> /// <param name="messageInfo">Message info what message items to get.</param> public POP3_eArgs_GetMessageStream(POP3_Session session, POP3_Message messageInfo) { m_pSession = session; m_pMessageInfo = messageInfo; } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/TCP/TCP_ServerSession.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.TCP { #region usings using System; using System.Collections.Generic; using System.Diagnostics; using System.Net; using System.Net.Security; using System.Net.Sockets; using System.Security.Cryptography.X509Certificates; using IO; #endregion /// <summary> /// This class implements generic TCP server session. /// </summary> public class TCP_ServerSession : TCP_Session { #region Events /// <summary> /// This event is raised when session has disconnected and will be disposed soon. /// </summary> public event EventHandler Disonnected = null; /// <summary> /// This event is raised when session has disposed. /// </summary> public event EventHandler Disposed = null; /// <summary> /// This event is raised when TCP server session has unknown unhandled error. /// </summary> public event ErrorEventHandler Error = null; /// <summary> /// This event is raised when session idle(no activity) timeout reached. /// </summary> public event EventHandler IdleTimeout = null; #endregion #region Members private DateTime m_ConnectTime; private string m_ID = ""; private bool m_IsDisposed; private bool m_IsSecure; private bool m_IsTerminated; private string m_LocalHostName = ""; private X509Certificate m_pCertificate; private IPEndPoint m_pLocalEP; private IPEndPoint m_pRemoteEP; private object m_pServer; private Dictionary<string, object> m_pTags; private SmartStream m_pTcpStream; #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> public TCP_ServerSession() { m_pTags = new Dictionary<string, object>(); } #endregion #region Properties /// <summary> /// Gets session certificate. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> public X509Certificate Certificate { get { if (m_IsDisposed) { throw new ObjectDisposedException("TCP_ServerSession"); } return m_pCertificate; } } /// <summary> /// Gets the time when session was connected. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> public override DateTime ConnectTime { get { if (m_IsDisposed) { throw new ObjectDisposedException("TCP_ServerSession"); } return m_ConnectTime; } } /// <summary> /// Gets session ID. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> public override string ID { get { if (m_IsDisposed) { throw new ObjectDisposedException("TCP_ServerSession"); } return m_ID; } } /// <summary> /// Gets if session is connected. /// </summary> public override bool IsConnected { get { return true; } } /// <summary> /// Gets if TCP server session is disposed. /// </summary> public bool IsDisposed { get { return m_IsDisposed; } } /// <summary> /// Gets if this session TCP connection is secure connection. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> public override bool IsSecureConnection { get { if (m_IsDisposed) { throw new ObjectDisposedException("TCP_ServerSession"); } return m_IsSecure; } } /// <summary> /// Gets the last time when data was sent or received. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> public override DateTime LastActivity { get { if (m_IsDisposed) { throw new ObjectDisposedException("TCP_ServerSession"); } return m_pTcpStream.LastActivity; } } /// <summary> /// Gets session local IP end point. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> public override IPEndPoint LocalEndPoint { get { if (m_IsDisposed) { throw new ObjectDisposedException("TCP_ServerSession"); } return m_pLocalEP; } } /// <summary> /// Gets local host name. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> public string LocalHostName { get { if (m_IsDisposed) { throw new ObjectDisposedException("TCP_ServerSession"); } return m_LocalHostName; } } /// <summary> /// Gets session remote IP end point. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> public override IPEndPoint RemoteEndPoint { get { if (m_IsDisposed) { throw new ObjectDisposedException("TCP_ServerSession"); } return m_pRemoteEP; } } /// <summary> /// Gets owner TCP server. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> public object Server { get { if (m_IsDisposed) { throw new ObjectDisposedException("TCP_ServerSession"); } return m_pServer; } } /// <summary> /// Gets or sets user data. /// </summary> public object Tag { get; set; } /// <summary> /// Gets user data items collection. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> public Dictionary<string, object> Tags { get { if (m_IsDisposed) { throw new ObjectDisposedException("TCP_ServerSession"); } return m_pTags; } } /// <summary> /// Gets TCP stream which must be used to send/receive data through this session. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> public override SmartStream TcpStream { get { if (m_IsDisposed) { throw new ObjectDisposedException("TCP_ServerSession"); } return m_pTcpStream; } } #endregion #region Methods /// <summary> /// Cleans up any resources being used. /// </summary> public override void Dispose() { if (m_IsDisposed) { return; } if (!m_IsTerminated) { try { Disconnect(); } catch { // Skip disconnect errors. } } m_IsDisposed = true; // We must call disposed event before we release events. try { OnDisposed(); } catch { // We never should get exception here, user should handle it, just skip it. } m_pLocalEP = null; m_pRemoteEP = null; m_pCertificate = null; try { //_socket.Shutdown(SocketShutdown.Both);//Stop coms m_pTcpStream.Dispose(); } catch (Exception) { } m_pTcpStream = null; m_pTags = null; // Release events. IdleTimeout = null; Disonnected = null; Disposed = null; } /// <summary> /// Switches session to secure connection. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when connection is already secure or when SSL certificate is not specified.</exception> public void SwitchToSecure() { if (m_IsDisposed) { throw new ObjectDisposedException("TCP_ServerSession"); } if (m_IsSecure) { throw new InvalidOperationException("Session is already SSL/TLS."); } if (m_pCertificate == null) { throw new InvalidOperationException("There is no certificate specified."); } // FIX ME: if ssl switching fails, it closes source stream or otherwise if ssl successful, source stream leaks. SslStream sslStream = new SslStream(m_pTcpStream.SourceStream); sslStream.AuthenticateAsServer(m_pCertificate); // Close old stream, but leave source stream open. m_pTcpStream.IsOwner = false; m_pTcpStream.Dispose(); m_IsSecure = true; m_pTcpStream = new SmartStream(sslStream, true); } /// <summary> /// Disconnects session. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> public override void Disconnect() { Disconnect(null); } /// <summary> /// Disconnects session. /// </summary> /// <param name="text">Text what is sent to connected host before disconnecting.</param> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> public void Disconnect(string text) { if (m_IsDisposed) { throw new ObjectDisposedException("TCP_ServerSession"); } if (m_IsTerminated) { return; } m_IsTerminated = true; if (!string.IsNullOrEmpty(text)) { try { m_pTcpStream.Write(text); } catch (Exception x) { OnError(x); } } try { OnDisonnected(); } catch (Exception x) { // We never should get exception here, user should handle it. OnError(x); } Dispose(); } #endregion #region Virtual methods /// <summary> /// This method is called from TCP server when session should start processing incoming connection. /// </summary> protected internal virtual void Start() {} /// <summary> /// This method is called when specified session times out. /// </summary> /// <remarks> /// This method allows inhereted classes to report error message to connected client. /// Session will be disconnected after this method completes. /// </remarks> protected virtual void OnTimeout() {} /// <summary> /// Just calls <b>OnTimeout</b> method. /// </summary> internal virtual void OnTimeoutI() { OnTimeout(); } /// <summary> /// Raises <b>Error</b> event. /// </summary> /// <param name="x">Exception happened.</param> protected virtual void OnError(Exception x) { if (Error != null) { Error(this, new Error_EventArgs(x, new StackTrace())); } } #endregion #region Internal methods private Socket _socket; /// <summary> /// Initializes session. This method is called from TCP_Server when new session created. /// </summary> /// <param name="server">Owner TCP server.</param> /// <param name="socket">Connected socket.</param> /// <param name="hostName">Local host name.</param> /// <param name="ssl">Specifies if session should switch to SSL.</param> /// <param name="certificate">SSL certificate.</param> internal void Init(object server, Socket socket, string hostName, bool ssl, X509Certificate certificate) { // NOTE: We may not raise any event here ! _socket = socket; m_pServer = server; m_LocalHostName = hostName; m_ID = Guid.NewGuid().ToString(); m_ConnectTime = DateTime.Now; m_pLocalEP = (IPEndPoint) socket.LocalEndPoint; m_pRemoteEP = (IPEndPoint) socket.RemoteEndPoint; m_pCertificate = certificate; socket.ReceiveBufferSize = Workaround.Definitions.MaxStreamLineLength; socket.SendBufferSize = Workaround.Definitions.MaxStreamLineLength; socket.ReceiveTimeout = 30000; socket.SendTimeout = 10000;//10 sec if (ssl) { SwitchToSecure(); } else { m_pTcpStream = new SmartStream(new NetworkStream(socket, true), true); } } #endregion #region Utility methods /// <summary> /// Raises <b>IdleTimeout</b> event. /// </summary> private void OnIdleTimeout() { if (IdleTimeout != null) { IdleTimeout(this, new EventArgs()); } } /// <summary> /// Raises <b>Disonnected</b> event. /// </summary> private void OnDisonnected() { if (Disonnected != null) { Disonnected(this, new EventArgs()); } } /// <summary> /// Raises <b>Disposed</b> event. /// </summary> private void OnDisposed() { if (Disposed != null) { Disposed(this, new EventArgs()); } } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/MIME/MIME_b_Message.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.MIME { #region usings using System; using IO; #endregion /// <summary> /// This class represents MIME message/xxx bodies. Defined in RFC 2046 5.2. /// </summary> public class MIME_b_Message : MIME_b_SinglepartBase { #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="mediaType">MIME media type.</param> /// <exception cref="ArgumentNullException">Is raised when <b>mediaType</b> is null reference.</exception> public MIME_b_Message(string mediaType) : base(mediaType) {} #endregion /// <summary> /// Parses body from the specified stream /// </summary> /// <param name="owner">Owner MIME entity.</param> /// <param name="mediaType">MIME media type. For example: text/plain.</param> /// <param name="stream">Stream from where to read body.</param> /// <returns>Returns parsed body.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>stream</b>, <b>mediaType</b> or <b>strean</b> is null reference.</exception> /// <exception cref="ParseException">Is raised when any parsing errors.</exception> protected new static MIME_b Parse(MIME_Entity owner, string mediaType, SmartStream stream) { if (owner == null) { throw new ArgumentNullException("owner"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } if (stream == null) { throw new ArgumentNullException("stream"); } MIME_b_Message retVal = new MIME_b_Message(mediaType); Net_Utils.StreamCopy(stream, retVal.EncodedStream, Workaround.Definitions.MaxStreamLineLength); return retVal; } } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/SMTP/Server/old/MessageStoringCompleted_eArgs.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.IO; using System.Collections.Generic; using System.Text; namespace LumiSoft.Net.SMTP.Server { /// <summary> /// This class provides data for the MessageStoringCompleted event. /// </summary> public class MessageStoringCompleted_eArgs { private SMTP_Session m_pSession = null; private string m_ErrorText = null; //private long m_StoredCount = 0; private Stream m_pMessageStream = null; private SmtpServerReply m_pCustomReply = null; /// <summary> /// Default constructor. /// </summary> /// <param name="session">Reference to calling SMTP session.</param> /// <param name="errorText">Gets errors what happened on storing message or null if no errors.</param> /// <param name="messageStream">Gets message stream where messages was stored. Stream postions is End of Stream, where message storing ended.</param> public MessageStoringCompleted_eArgs(SMTP_Session session,string errorText,Stream messageStream) { m_pSession = session; m_ErrorText = errorText; m_pMessageStream = messageStream; m_pCustomReply = new SmtpServerReply(); } #region Properties Implementation /// <summary> /// Gets reference to smtp session. /// </summary> public SMTP_Session Session { get{ return m_pSession; } } /// <summary> /// Gets errors what happened on storing message or null if no errors. /// </summary> public string ErrorText { get{ return m_ErrorText; } } /* /// <summary> /// Gets count of bytes stored to MessageStream. This value as meaningfull value only if this.ErrorText == null (No errors). /// </summary> public long StoredCount { get{ return m_StoredCount; } }*/ /// <summary> /// Gets message stream where messages was stored. Stream postions is End of Stream, where message storing ended. /// </summary> public Stream MessageStream { get{ return m_pMessageStream; } } /// <summary> /// Gets SMTP server reply info. You can use this property for specifying custom reply text and optionally SMTP reply code. /// </summary> public SmtpServerReply ServerReply { get{ return m_pCustomReply; } } #endregion } } <file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/STUN/Message/STUN_t_ErrorCode.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.STUN.Message { /// <summary> /// This class implements STUN ERROR-CODE. Defined in RFC 3489 11.2.9. /// </summary> public class STUN_t_ErrorCode { #region Members private string m_ReasonText = ""; #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="code">Error code.</param> /// <param name="reasonText">Reason text.</param> public STUN_t_ErrorCode(int code, string reasonText) { Code = code; m_ReasonText = reasonText; } #endregion #region Properties /// <summary> /// Gets or sets error code. /// </summary> public int Code { get; set; } /// <summary> /// Gets reason text. /// </summary> public string ReasonText { get { return m_ReasonText; } set { m_ReasonText = value; } } #endregion } }<file_sep>/common/ASC.Common/Data/Sql/SqlDebugView.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Text; namespace ASC.Common.Data.Sql { class SqlDebugView { private readonly ISqlInstruction instruction; public string Sql { get { return GetSqlWithParameters(); } } public object[] Parameters { get { return instruction.GetParameters(); } } public SqlDebugView(ISqlInstruction instruction) { this.instruction = instruction; } private string GetSqlWithParameters() { var sql = instruction.ToString(); var parameters = instruction.GetParameters(); var sb = new StringBuilder(); var i = 0; foreach (var part in sql.Split('?')) { sb.Append(part); if (i < parameters.Length) { var p = parameters[i]; if (p == null) { sb.Append("null"); } else if (p is string || p is char || p is DateTime || p is Guid) { sb.AppendFormat("'{0}'", p); } else { sb.Append(p); } } i++; } return sb.ToString(); } } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/IMAP/Server/IMAP_SearchGroup.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.IMAP.Server { #region usings using System; using System.Collections; using Mime; #endregion /// <summary> /// IMAP search command grouped(parenthesized) search-key collection. /// </summary> internal class SearchGroup { #region Members private readonly ArrayList m_pSearchKeys; #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> public SearchGroup() { m_pSearchKeys = new ArrayList(); } #endregion #region Methods /// <summary> /// Parses search key from current position. /// </summary> /// <param name="reader"></param> public void Parse(StringReader reader) { //Remove spaces from string start reader.ReadToFirstChar(); if (reader.StartsWith("(")) { reader = new StringReader(reader.ReadParenthesized().Trim()); } //--- Start parsing search keys --------------// while (reader.Available > 0) { object searchKey = ParseSearchKey(reader); if (searchKey != null) { m_pSearchKeys.Add(searchKey); } } //--------------------------------------------// } /// <summary> /// Gets if message Header is needed for matching. /// </summary> /// <returns></returns> public bool IsHeaderNeeded() { foreach (object searchKey in m_pSearchKeys) { if (IsHeaderNeededForKey(searchKey)) { return true; } } return false; } /// <summary> /// Gets if message body text is needed for matching. /// </summary> /// <returns></returns> public bool IsBodyTextNeeded() { foreach (object searchKey in m_pSearchKeys) { if (IsBodyTextNeededForKey(searchKey)) { return true; } } return false; } /// <summary> /// Gets if specified message matches with this class search-key. /// </summary> /// <param name="no">IMAP message sequence number.</param> /// <param name="uid">IMAP message UID.</param> /// <param name="size">IMAP message size in bytes.</param> /// <param name="internalDate">IMAP message INTERNALDATE (dateTime when server stored message).</param> /// <param name="flags">IMAP message flags.</param> /// <param name="mime">Mime message main header only.</param> /// <param name="bodyText">Message body text.</param> /// <returns></returns> public bool Match(long no, long uid, long size, DateTime internalDate, IMAP_MessageFlags flags, Mime mime, string bodyText) { // We must match all keys, if one fails, no need to check others foreach (object searckKey in m_pSearchKeys) { if (!Match_Key_Value(searckKey, no, uid, size, internalDate, flags, mime, bodyText)) { return false; } } return true; } #endregion #region Internal methods /// <summary> /// Parses SearchGroup or SearchItem from reader. If reader starts with (, then parses searchGroup, otherwise SearchItem. /// </summary> /// <param name="reader"></param> /// <returns></returns> internal static object ParseSearchKey(StringReader reader) { //Remove spaces from string start reader.ReadToFirstChar(); // SearchGroup if (reader.StartsWith("(")) { SearchGroup searchGroup = new SearchGroup(); searchGroup.Parse(reader); return searchGroup; } // SearchItem else { return SearchKey.Parse(reader); } } /// <summary> /// Gets if specified message matches to specified search key. /// </summary> /// <param name="searchKey">SearchKey or SearchGroup.</param> /// <param name="no">IMAP message sequence number.</param> /// <param name="uid">IMAP message UID.</param> /// <param name="size">IMAP message size in bytes.</param> /// <param name="internalDate">IMAP message INTERNALDATE (dateTime when server stored message).</param> /// <param name="flags">IMAP message flags.</param> /// <param name="mime">Mime message main header only.</param> /// <param name="bodyText">Message body text.</param> /// <returns></returns> internal static bool Match_Key_Value(object searchKey, long no, long uid, long size, DateTime internalDate, IMAP_MessageFlags flags, Mime mime, string bodyText) { if (searchKey.GetType() == typeof (SearchKey)) { if (!((SearchKey) searchKey).Match(no, uid, size, internalDate, flags, mime, bodyText)) { return false; } } else if (searchKey.GetType() == typeof (SearchGroup)) { if (!((SearchGroup) searchKey).Match(no, uid, size, internalDate, flags, mime, bodyText)) { return false; } } return true; } /// <summary> /// Gets if message header is needed for matching. /// </summary> /// <param name="searchKey"></param> /// <returns></returns> internal static bool IsHeaderNeededForKey(object searchKey) { if (searchKey.GetType() == typeof (SearchKey)) { if (((SearchKey) searchKey).IsHeaderNeeded()) { return true; } } else if (searchKey.GetType() == typeof (SearchGroup)) { if (((SearchGroup) searchKey).IsHeaderNeeded()) { return true; } } return false; } /// <summary> /// Gets if message body text is needed for matching. /// </summary> /// <param name="searchKey"></param> /// <returns></returns> internal static bool IsBodyTextNeededForKey(object searchKey) { if (searchKey.GetType() == typeof (SearchKey)) { if (((SearchKey) searchKey).IsBodyTextNeeded()) { return true; } } else if (searchKey.GetType() == typeof (SearchGroup)) { if (((SearchGroup) searchKey).IsBodyTextNeeded()) { return true; } } return false; } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/vCard/EmailAddressCollection.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.Mime.vCard { #region usings using System.Collections; using System.Collections.Generic; #endregion /// <summary> /// vCard email address collection implementation. /// </summary> public class EmailAddressCollection : IEnumerable { #region Members private readonly List<EmailAddress> m_pCollection; private readonly vCard m_pOwner; #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="owner">Owner vCard.</param> internal EmailAddressCollection(vCard owner) { m_pOwner = owner; m_pCollection = new List<EmailAddress>(); foreach (Item item in owner.Items.Get("EMAIL")) { m_pCollection.Add(EmailAddress.Parse(item)); } } #endregion #region Properties /// <summary> /// Gets number of items in the collection. /// </summary> public int Count { get { return m_pCollection.Count; } } /// <summary> /// Gets item at the specified index. /// </summary> /// <param name="index">Index of item which to get.</param> /// <returns></returns> public EmailAddress this[int index] { get { return m_pCollection[index]; } } #endregion #region Methods /// <summary> /// Add new email address to the collection. /// </summary> /// <param name="type">Email address type. Note: This value can be flagged value !</param> /// <param name="email">Email address.</param> public EmailAddress Add(EmailAddressType_enum type, string email) { Item item = m_pOwner.Items.Add("EMAIL", EmailAddress.EmailTypeToString(type), ""); item.SetDecodedValue(email); EmailAddress emailAddress = new EmailAddress(item, type, email); m_pCollection.Add(emailAddress); return emailAddress; } /// <summary> /// Removes specified item from the collection. /// </summary> /// <param name="item">Item to remove.</param> public void Remove(EmailAddress item) { m_pOwner.Items.Remove(item.Item); m_pCollection.Remove(item); } /// <summary> /// Removes all items from the collection. /// </summary> public void Clear() { foreach (EmailAddress email in m_pCollection) { m_pOwner.Items.Remove(email.Item); } m_pCollection.Clear(); } /// <summary> /// Gets enumerator. /// </summary> /// <returns></returns> public IEnumerator GetEnumerator() { return m_pCollection.GetEnumerator(); } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/RTP/RTCP_CompoundPacket.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.RTP { #region usings using System; using System.Collections.Generic; #endregion /// <summary> /// This class represents RTCP compound packet. /// </summary> public class RTCP_CompoundPacket { #region Members private readonly List<RTCP_Packet> m_pPackets; #endregion #region Properties /// <summary> /// Gets compound packets. /// </summary> public List<RTCP_Packet> Packets { get { return m_pPackets; } } /// <summary> /// Gets total packets size in bytes which is needed for this compound packet. /// </summary> internal int TotalSize { get { int size = 0; foreach (RTCP_Packet packet in m_pPackets) { size += packet.Size; } return size; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> internal RTCP_CompoundPacket() { m_pPackets = new List<RTCP_Packet>(); } #endregion #region Methods /// <summary> /// Parses RTP compound packet. /// </summary> /// <param name="buffer">Data buffer..</param> /// <param name="count">Number of bytes in the <b>buffer</b>.</param> /// <returns>Returns parsed RTP packet.</returns> public static RTCP_CompoundPacket Parse(byte[] buffer, int count) { /* Compound packet stucture: Encryption prefix If and only if the compound packet is to be encrypted, it is prefixed by a random 32-bit quantity redrawn for every compound packet transmitted. SR or RR The first RTCP packet in the compound packet must always be a report packet to facilitate header validation as described in Appendix A.2. This is true even if no data has been sent nor received, in which case an empty RR is sent, and even if the only other RTCP packet in the compound packet is a BYE. Additional RRs If the number of sources for which reception statistics are being reported exceeds 31, the number that will fit into one SR or RR packet, then additional RR packets should follow the initial report packet. SDES An SDES packet containing a CNAME item must be included in each compound RTCP packet. Other source description items may optionally be included if required by a particular application, subject to bandwidth constraints (see Section 6.2.2). BYE or APP Other RTCP packet types, including those yet to be defined, may follow in any order, except that BYE should be the last packet sent with a given SSRC/CSRC. Packet types may appear more than once. */ int offset = 0; RTCP_CompoundPacket packet = new RTCP_CompoundPacket(); while (offset < count) { try { packet.m_pPackets.Add(RTCP_Packet.Parse(buffer, ref offset)); } catch { // Skip invalid or unknown packets. } } return packet; } /// <summary> /// Gets RTCP compound packet as raw byte data. /// </summary> /// <returns>Returns compound packet as raw byte data.</returns> public byte[] ToByte() { byte[] retVal = new byte[TotalSize]; int offset = 0; ToByte(retVal, ref offset); return retVal; } /// <summary> /// Stores this compund packet to specified buffer. /// </summary> /// <param name="buffer">Buffer where to store data.</param> /// <param name="offset">Offset in buffer.</param> /// <exception cref="ArgumentNullException">Is raised when <b>buffer</b> is null.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> public void ToByte(byte[] buffer, ref int offset) { if (buffer == null) { throw new ArgumentNullException("buffer"); } if (offset < 0) { throw new ArgumentException("Argument 'offset' value must be >= 0."); } foreach (RTCP_Packet packet in m_pPackets) { packet.ToByte(buffer, ref offset); } } /// <summary> /// Validates RTCP compound packet. /// </summary> /// <exception cref="ArgumentException">Is raised when invalid RTCP compound packet.</exception> public void Validate() { /* RFC 3550 A.2 RTCP Header Validity Checks. The following checks should be applied to RTCP packets. o RTP version field must equal 2. o The payload type field of the first RTCP packet in a compound packet must be equal to SR or RR. o The padding bit (P) should be zero for the first packet of a compound RTCP packet because padding should only be applied, if it is needed, to the last packet. o The length fields of the individual RTCP packets must add up to the overall length of the compound RTCP packet as received. This is a fairly strong check. */ if (m_pPackets.Count == 0) { throw new ArgumentException("No RTCP packets."); } // Check version and padding. for (int i = 0; i < m_pPackets.Count; i++) { RTCP_Packet packet = m_pPackets[i]; if (packet.Version != 2) { throw new ArgumentException("RTP version field must equal 2."); } if (i < (m_pPackets.Count - 1) && packet.IsPadded) { throw new ArgumentException("Only the last packet in RTCP compound packet may be padded."); } } // The first RTCP packet in a compound packet must be equal to SR or RR. if (m_pPackets[0].Type != RTCP_PacketType.SR || m_pPackets[0].Type != RTCP_PacketType.RR) { throw new ArgumentException( "The first RTCP packet in a compound packet must be equal to SR or RR."); } } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/SIP/Proxy/SIP_ProxyContext.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.SIP.Proxy { #region usings using System; using System.Collections.Generic; using System.Net; using System.Timers; using Message; using Stack; #endregion /// <summary> /// Implements SIP 'proxy context'. Defined in RFC 3261. /// </summary> /// <remarks>Proxy context is bridge between caller and calee. /// Proxy context job is to forward request to contact(s) and send received responses back to caller.</remarks> public class SIP_ProxyContext : IDisposable { #region Nested type: TargetHandler /// <summary> /// This class is responsible for sending <b>request</b> to target(HOPs) and processing responses. /// </summary> private class TargetHandler : IDisposable { #region Members private readonly bool m_AddRecordRoute = true; private readonly bool m_IsRecursed; private readonly SIP_Flow m_pFlow; private readonly object m_pLock = new object(); private bool m_HasReceivedResponse; private bool m_IsCompleted; private bool m_IsDisposed; private bool m_IsStarted; private Queue<SIP_Hop> m_pHops; private SIP_ProxyContext m_pOwner; private SIP_Request m_pRequest; private SIP_Uri m_pTargetUri; private TimerEx m_pTimerC; private SIP_ClientTransaction m_pTransaction; #endregion #region Properties /// <summary> /// Gets if this object is disposed. /// </summary> public bool IsDisposed { get { return m_IsDisposed; } } /// <summary> /// Gets if this target processing has been started. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and and this property is accessed.</exception> public bool IsStarted { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_IsStarted; } } /// <summary> /// Gets if request sender has completed. /// </summary> public bool IsCompleted { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_IsCompleted; } } /// <summary> /// Gets SIP request what this <b>Target</b> is sending. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and and this property is accessed.</exception> public SIP_Request Request { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_pRequest; } } /// <summary> /// Gets target URI where request is being sent. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and and this property is accessed.</exception> public SIP_Uri TargetUri { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_pTargetUri; } } /// <summary> /// Gets if this target is recording routing(By adding Record-Route header field to forwarded requests). /// </summary> public bool IsRecordingRoute { get { return m_AddRecordRoute; } } /// <summary> /// Gets if this target is redirected by proxy context. /// </summary> public bool IsRecursed { get { return m_IsRecursed; } } /// <summary> /// Gets if this handler has received any response from target. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and and this property is accessed.</exception> public bool HasReceivedResponse { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_HasReceivedResponse; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="owner">Owner proxy context.</param> /// <param name="flow">Data flow to use for sending. Value null means system will choose it.</param> /// <param name="targetUri">Target URI where to send request.</param> /// <param name="addRecordRoute">If true, handler will add Record-Route header to forwarded message.</param> /// <param name="isRecursed">If true then this target is redirected by proxy context.</param> /// <exception cref="ArgumentNullException">Is raised when <b>owner</b> or <b>targetURI</b> is null reference.</exception> public TargetHandler(SIP_ProxyContext owner, SIP_Flow flow, SIP_Uri targetUri, bool addRecordRoute, bool isRecursed) { if (owner == null) { throw new ArgumentNullException("owner"); } if (targetUri == null) { throw new ArgumentNullException("targetUri"); } m_pOwner = owner; m_pFlow = flow; m_pTargetUri = targetUri; m_AddRecordRoute = addRecordRoute; m_IsRecursed = isRecursed; m_pHops = new Queue<SIP_Hop>(); } #endregion #region Methods /// <summary> /// Cleans up any resources being used. /// </summary> public void Dispose() { lock (m_pLock) { if (m_IsDisposed) { return; } m_IsDisposed = true; m_pOwner.TargetHandler_Disposed(this); m_pOwner = null; m_pRequest = null; m_pTargetUri = null; m_pHops = null; if (m_pTransaction != null) { m_pTransaction.Dispose(); m_pTransaction = null; } if (m_pTimerC != null) { m_pTimerC.Dispose(); m_pTimerC = null; } } } /// <summary> /// Starts target processing. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and and this method is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when <b>Start</b> method is already called and this method is called.</exception> public void Start() { lock (m_pLock) { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (m_IsStarted) { throw new InvalidOperationException("Start has already called."); } m_IsStarted = true; Init(); // No hops for target. Invalid target domain name,dns server down,target won't support needed target. if (m_pHops.Count == 0) { m_pOwner.ProcessResponse(this, m_pTransaction, m_pOwner.Proxy.Stack.CreateResponse( SIP_ResponseCodes.x503_Service_Unavailable + ": No hop(s) for target.", m_pTransaction.Request)); Dispose(); return; } else { if (m_pFlow != null) { SendToFlow(m_pFlow, m_pRequest.Copy()); } else { SendToNextHop(); } } } } /// <summary> /// Cancels target processing. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and and this method is accessed.</exception> public void Cancel() { lock (m_pLock) { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (m_IsStarted) { m_pTransaction.Cancel(); } else { Dispose(); } } } #endregion #region Event handlers /// <summary> /// Is called when client transactions receives response. /// </summary> /// <param name="sender">Sender.</param> /// <param name="e">Event data.</param> private void ClientTransaction_ResponseReceived(object sender, SIP_ResponseReceivedEventArgs e) { lock (m_pLock) { m_HasReceivedResponse = true; /* RFC 3261 16.7 Response Processing. 1. Find the appropriate response context 2. Update timer C for provisional responses Steps 3 - 10 done in ProxyContext.ProcessResponse method. */ #region 1. Find Context // Done, m_pOwner is it. #endregion #region 2. Update timer C for provisional responses /* For an INVITE transaction, if the response is a provisional response with status codes 101 to 199 inclusive (i.e., anything but 100), the proxy MUST reset timer C for that client transaction. The timer MAY be reset to a different value, but this value MUST be greater than 3 minutes. */ if (m_pTimerC != null && e.Response.StatusCode >= 101 && e.Response.StatusCode <= 199) { m_pTimerC.Interval = 3*60*1000; } #endregion /* // If 401 or 407 (Authentication required), see i we have specified realm(s) credentials, // if so try to authenticate. if(e.Response.StatusCode == 401 || e.Response.StatusCode == 407){ SIP_t_Challenge[] challanges = null; if(e.Response.StatusCode == 401){ challanges = e.Response.WWWAuthenticate.GetAllValues(); } else{ challanges = e.Response.ProxyAuthenticate.GetAllValues(); } // TODO: Porbably we need to auth only if we can provide authentication data to all realms ? SIP_Request request = m_pServerTransaction.Request.Copy(); request.CSeq.SequenceNumber++; bool hasAny = false; foreach(SIP_t_Challenge challange in challanges){ Auth_HttpDigest authDigest = new Auth_HttpDigest(challange.AuthData,m_pServerTransaction.Request.Method); NetworkCredential credential = GetCredential(authDigest.Realm); if(credential != null){ // Don't authenticate again, if we tried already once and failed. // FIX ME: if user passed authorization, then works wrong. if(e.ClientTransaction.Request.Authorization.Count == 0 && e.ClientTransaction.Request.ProxyAuthorization.Count == 0){ authDigest.RequestMethod = m_pServerTransaction.Request.Method; authDigest.Uri = e.ClientTransaction.Request.Uri; authDigest.Realm = credential.Domain; authDigest.UserName = credential.UserName; authDigest.Password = <PASSWORD>; authDigest.CNonce = Auth_HttpDigest.CreateNonce(); authDigest.Qop = authDigest.Qop; authDigest.Opaque = authDigest.Opaque; authDigest.Algorithm = authDigest.Algorithm; if(e.Response.StatusCode == 401){ request.Authorization.Add(authDigest.ToAuthorization()); } else{ request.ProxyAuthorization.Add(authDigest.ToAuthorization()); } hasAny = true; } } } if(hasAny){ // CreateClientTransaction((SIP_Target)e.ClientTransaction.Tag,request); return; } }*/ if (e.Response.StatusCodeType != SIP_StatusCodeType.Provisional) { m_IsCompleted = true; } m_pOwner.ProcessResponse(this, m_pTransaction, e.Response); } } /// <summary> /// Is called when client transaction has timed out. /// </summary> /// <param name="sender">Sender.</param> /// <param name="e">Event data.</param> private void ClientTransaction_TimedOut(object sender, EventArgs e) { lock (m_pLock) { /* RFC 3263 4.3. For SIP requests, failure occurs if the transaction layer reports a 503 error response or a transport failure of some sort (generally, due to fatal ICMP errors in UDP or connection failures in TCP). Failure also occurs if the transaction layer times out without ever having received any response, provisional or final (i.e., timer B or timer F in RFC 3261 [1] fires). If a failure occurs, the client SHOULD create a new request, which is identical to the previous, but has a different value of the Via branch ID than the previous (and therefore constitutes a new SIP transaction). That request is sent to the next element in the list as specified by RFC 2782. */ if (m_pHops.Count > 0) { CleanUpActiveHop(); SendToNextHop(); } /* RFC 3161 16.6.7. If the ordered set is exhausted, the request cannot be forwarded to this element in the target set. The proxy does not need to place anything in the response context, but otherwise acts as if this element of the target set returned a 408 (Request Timeout) final response. */ else { m_IsCompleted = true; m_pOwner.ProcessResponse(this, m_pTransaction, m_pOwner.Proxy.Stack.CreateResponse( SIP_ResponseCodes.x408_Request_Timeout, m_pTransaction.Request)); Dispose(); } } } /// <summary> /// Is called when client transaction encountered transport error. /// </summary> /// <param name="sender">Sender.</param> /// <param name="e">Event data.</param> private void ClientTransaction_TransportError(object sender, ExceptionEventArgs e) { lock (m_pLock) { /* RFC 3263 4.3. For SIP requests, failure occurs if the transaction layer reports a 503 error response or a transport failure of some sort (generally, due to fatal ICMP errors in UDP or connection failures in TCP). Failure also occurs if the transaction layer times out without ever having received any response, provisional or final (i.e., timer B or timer F in RFC 3261 [1] fires). If a failure occurs, the client SHOULD create a new request, which is identical to the previous, but has a different value of the Via branch ID than the previous (and therefore constitutes a new SIP transaction). That request is sent to the next element in the list as specified by RFC 2782. */ if (m_pHops.Count > 0) { CleanUpActiveHop(); SendToNextHop(); } /* RFC 3161 16.6.7. If the ordered set is exhausted, the request cannot be forwarded to this element in the target set. The proxy does not need to place anything in the response context, but otherwise acts as if this element of the target set returned a 408 (Request Timeout) final response. */ else { m_IsCompleted = true; m_pOwner.ProcessResponse(this, m_pTransaction, m_pOwner.Proxy.Stack.CreateResponse( SIP_ResponseCodes.x408_Request_Timeout, m_pTransaction.Request)); Dispose(); } } } /// <summary> /// This method is called when client transaction has disposed. /// </summary> /// <param name="sender">Sender.</param> /// <param name="e">Event data.</param> private void m_pTransaction_Disposed(object sender, EventArgs e) { lock (m_pLock) { if (m_IsDisposed) { return; } // If we have got any response from any client transaction, then all done. if (HasReceivedResponse) { Dispose(); } } } private void m_pTimerC_Elapsed(object sender, ElapsedEventArgs e) { lock (m_pLock) { /* RFC 3261 16.8 Processing Timer C. If the client transaction has received a provisional response, the proxy MUST generate a CANCEL request matching that transaction. If the client transaction has not received a provisional response, the proxy MUST behave as if the transaction received a 408 (Request Timeout) response. */ if (m_pTransaction.HasProvisionalResponse) { m_pTransaction.Cancel(); } else { m_pOwner.ProcessResponse(this, m_pTransaction, m_pOwner.Proxy.Stack.CreateResponse( SIP_ResponseCodes.x408_Request_Timeout, m_pTransaction.Request)); Dispose(); } } } #endregion #region Utility methods /// <summary> /// Initializes target. /// </summary> private void Init() { /* RFC 3261 16.6 Request Forwarding. For each target, the proxy forwards the request following these steps: 1. Make a copy of the received request 2. Update the Request-URI 3. Update the Max-Forwards header field 4. Optionally add a Record-route header field value 5. Optionally add additional header fields 6. Postprocess routing information 7. Determine the next-hop address, port, and transport */ bool isStrictRoute = false; #region 1. Make a copy of the received request. // 1. Make a copy of the received request. m_pRequest = m_pOwner.Request.Copy(); #endregion #region 2. Update the Request-URI. // 2. Update the Request-URI. m_pRequest.RequestLine.Uri = m_pTargetUri; #endregion #region 3. Update the Max-Forwards header field. // 3. Update the Max-Forwards header field. m_pRequest.MaxForwards--; #endregion #region 5. Optionally add additional header fields. // 5. Optionally add additional header fields. // Skip. #endregion #region 6. Postprocess routing information. /* 6. Postprocess routing information. If the copy contains a Route header field, the proxy MUST inspect the URI in its first value. If that URI does not contain an lr parameter, the proxy MUST modify the copy as follows: - The proxy MUST place the Request-URI into the Route header field as the last value. - The proxy MUST then place the first Route header field value into the Request-URI and remove that value from the Route header field. */ if (m_pRequest.Route.GetAllValues().Length > 0 && !m_pRequest.Route.GetTopMostValue().Parameters.Contains("lr")) { m_pRequest.Route.Add(m_pRequest.RequestLine.Uri.ToString()); m_pRequest.RequestLine.Uri = SIP_Utils.UriToRequestUri(m_pRequest.Route.GetTopMostValue().Address.Uri); m_pRequest.Route.RemoveTopMostValue(); isStrictRoute = true; } #endregion #region 7. Determine the next-hop address, port, and transport. /* 7. Determine the next-hop address, port, and transport. The proxy MAY have a local policy to send the request to a specific IP address, port, and transport, independent of the values of the Route and Request-URI. Such a policy MUST NOT be used if the proxy is not certain that the IP address, port, and transport correspond to a server that is a loose router. However, this mechanism for sending the request through a specific next hop is NOT RECOMMENDED; instead a Route header field should be used for that purpose as described above. In the absence of such an overriding mechanism, the proxy applies the procedures listed in [4] as follows to determine where to send the request. If the proxy has reformatted the request to send to a strict-routing element as described in step 6 above, the proxy MUST apply those procedures to the Request-URI of the request. Otherwise, the proxy MUST apply the procedures to the first value in the Route header field, if present, else the Request-URI. The procedures will produce an ordered set of (address, port, transport) tuples. Independently of which URI is being used as input to the procedures of [4], if the Request-URI specifies a SIPS resource, the proxy MUST follow the procedures of [4] as if the input URI were a SIPS URI. As described in [4], the proxy MUST attempt to deliver the message to the first tuple in that set, and proceed through the set in order until the delivery attempt succeeds. For each tuple attempted, the proxy MUST format the message as appropriate for the tuple and send the request using a new client transaction as detailed in steps 8 through 10. Since each attempt uses a new client transaction, it represents a new branch. Thus, the branch parameter provided with the Via header field inserted in step 8 MUST be different for each attempt. If the client transaction reports failure to send the request or a timeout from its state machine, the proxy continues to the next address in that ordered set. If the ordered set is exhausted, the request cannot be forwarded to this element in the target set. The proxy does not need to place anything in the response context, but otherwise acts as if this element of the target set returned a 408 (Request Timeout) final response. */ SIP_Uri uri = null; if (isStrictRoute) { uri = (SIP_Uri) m_pRequest.RequestLine.Uri; } else if (m_pRequest.Route.GetTopMostValue() != null) { uri = (SIP_Uri) m_pRequest.Route.GetTopMostValue().Address.Uri; } else { uri = (SIP_Uri) m_pRequest.RequestLine.Uri; } // Queue hops. foreach ( SIP_Hop hop in m_pOwner.Proxy.Stack.GetHops(uri, m_pRequest.ToByteData().Length, ((SIP_Uri) m_pRequest.RequestLine.Uri).IsSecure)) { m_pHops.Enqueue(hop); } #endregion #region 4. Optionally add a Record-route header field value. // We need to do step 4 after step 7, because then transport in known. // Each transport can have own host-name, otherwise we don't know what to put into Record-Route. /* If the Request-URI contains a SIPS URI, or the topmost Route header field value (after the post processing of bullet 6) contains a SIPS URI, the URI placed into the Record-Route header field MUST be a SIPS URI. Furthermore, if the request was not received over TLS, the proxy MUST insert a Record-Route header field. In a similar fashion, a proxy that receives a request over TLS, but generates a request without a SIPS URI in the Request-URI or topmost Route header field value (after the post processing of bullet 6), MUST insert a Record-Route header field that is not a SIPS URI. */ // NOTE: ACK don't add Record-route header. if (m_pHops.Count > 0 && m_AddRecordRoute && m_pRequest.RequestLine.Method != SIP_Methods.ACK) { string recordRoute = m_pOwner.Proxy.Stack.TransportLayer.GetRecordRoute(m_pHops.Peek().Transport); if (recordRoute != null) { m_pRequest.RecordRoute.Add(recordRoute); } } #endregion } /// <summary> /// Starts sending request to next hop in queue. /// </summary> /// <exception cref="InvalidOperationException">Is raised when no next hop available(m_pHops.Count == 0) and this method is accessed.</exception> private void SendToNextHop() { if (m_pHops.Count == 0) { throw new InvalidOperationException("No more hop(s)."); } SIP_Hop hop = m_pHops.Dequeue(); SendToFlow( m_pOwner.Proxy.Stack.TransportLayer.GetOrCreateFlow(hop.Transport, null, hop.EndPoint), m_pRequest.Copy()); } /// <summary> /// Sends specified request to the specified data flow. /// </summary> /// <param name="flow">SIP data flow.</param> /// <param name="request">SIP request to send.</param> /// <exception cref="ArgumentNullException">Is raised when <b>flow</b> or <b>request</b> is null reference.</exception> private void SendToFlow(SIP_Flow flow, SIP_Request request) { if (flow == null) { throw new ArgumentNullException("flow"); } if (request == null) { throw new ArgumentNullException("request"); } /* NAT traversal. When we do record routing, store request sender flow info and request target flow info. Now the tricky part, how proxy later which flow is target (because both sides can send requests). Sender-flow will store from-tag to flow and target-flow will store flowID only (Because we don't know to-tag). Later if request to-tag matches(incoming request), use that flow, otherwise(outgoing request) other flow. flowInfo: sender-flow "/" target-flow sender-flow = from-tag ":" flowID target-flow = flowID */ if (m_AddRecordRoute && request.From.Tag != null) { string flowInfo = request.From.Tag + ":" + m_pOwner.ServerTransaction.Flow.ID + "/" + flow.ID; ((SIP_Uri) request.RecordRoute.GetTopMostValue().Address.Uri).Parameters.Add("flowInfo", flowInfo); } /* RFC 3261 16.6 Request Forwarding. Common Steps 1 - 7 are done in target Init(). 8. Add a Via header field value 9. Add a Content-Length header field if necessary 10. Forward the new request 11. Set timer C */ #region 8. Add a Via header field value // Skip, Client transaction will add it. #endregion #region 9. Add a Content-Length header field if necessary // Skip, our SIP_Message class is smart and do it when ever it's needed. #endregion #region 10. Forward the new request m_pTransaction = m_pOwner.Proxy.Stack.TransactionLayer.CreateClientTransaction(flow, request, true); m_pTransaction.ResponseReceived += ClientTransaction_ResponseReceived; m_pTransaction.TimedOut += ClientTransaction_TimedOut; m_pTransaction.TransportError += ClientTransaction_TransportError; m_pTransaction.Disposed += m_pTransaction_Disposed; // Start transaction processing. m_pTransaction.Start(); #endregion #region 11. Set timer C /* 11. Set timer C In order to handle the case where an INVITE request never generates a final response, the TU uses a timer which is called timer C. Timer C MUST be set for each client transaction when an INVITE request is proxied. The timer MUST be larger than 3 minutes. Section 16.7 bullet 2 discusses how this timer is updated with provisional responses, and Section 16.8 discusses processing when it fires. */ if (request.RequestLine.Method == SIP_Methods.INVITE) { m_pTimerC = new TimerEx(); m_pTimerC.AutoReset = false; m_pTimerC.Interval = 3*60*1000; m_pTimerC.Elapsed += m_pTimerC_Elapsed; } #endregion } /// <summary> /// Cleans up acitve hop resources. /// </summary> private void CleanUpActiveHop() { if (m_pTimerC != null) { m_pTimerC.Dispose(); m_pTimerC = null; } if (m_pTransaction != null) { m_pTransaction.Dispose(); m_pTransaction = null; } } #endregion } #endregion #region Members private readonly bool m_AddRecordRoute; private readonly DateTime m_CreateTime; private readonly SIP_ForkingMode m_ForkingMode = SIP_ForkingMode.Parallel; private readonly string m_ID = ""; private readonly bool m_IsB2BUA = true; private readonly bool m_NoCancel; private readonly bool m_NoRecurse = true; private readonly List<NetworkCredential> m_pCredentials; private readonly object m_pLock = new object(); private readonly SIP_Request m_pRequest; private bool m_IsDisposed; private bool m_IsFinalResponseSent; private bool m_IsStarted; private SIP_ProxyCore m_pProxy; private List<SIP_Response> m_pResponses; private SIP_ServerTransaction m_pServerTransaction; private Queue<TargetHandler> m_pTargets; private List<TargetHandler> m_pTargetsHandlers; #endregion #region Properties /// <summary> /// Gets if this object is disposed. /// </summary> public bool IsDisposed { get { return m_IsDisposed; } } /// <summary> /// Gets owner SIP proxy server. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and and this property is accessed.</exception> public SIP_ProxyCore Proxy { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_pProxy; } } /// <summary> /// Gets proxy context ID. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and and this property is accessed.</exception> public string ID { get { if (m_IsDisposed) { throw new ObjectDisposedException("SIP_ProxyContext"); } return m_ID; } } /// <summary> /// Gets time when proxy context was created. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and and this property is accessed.</exception> public DateTime CreateTime { get { if (m_IsDisposed) { throw new ObjectDisposedException("SIP_ProxyContext"); } return m_CreateTime; } } /// <summary> /// Gets forking mode used by this 'proxy context'. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and and this property is accessed.</exception> public SIP_ForkingMode ForkingMode { get { if (m_IsDisposed) { throw new ObjectDisposedException("SIP_ProxyContext"); } return m_ForkingMode; } } /// <summary> /// Gets if proxy cancels forked requests what are not needed any more. If true, /// requests not canceled, otherwise canceled. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and and this property is accessed.</exception> public bool NoCancel { get { if (m_IsDisposed) { throw new ObjectDisposedException("SIP_ProxyContext"); } return m_NoCancel; } } /// <summary> /// Gets what proxy server does when it gets 3xx response. If true proxy will forward /// request to new specified address if false, proxy will return 3xx response to caller. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and and this property is accessed.</exception> public bool Recurse { get { if (m_IsDisposed) { throw new ObjectDisposedException("SIP_ProxyContext"); } return !m_NoRecurse; } } /// <summary> /// Gets server transaction what is responsible for sending responses to caller. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public SIP_ServerTransaction ServerTransaction { get { if (m_IsDisposed) { throw new ObjectDisposedException("SIP_ProxyContext"); } return m_pServerTransaction; } } /// <summary> /// Gets request what is forwarded by proxy context. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and and this property is accessed.</exception> public SIP_Request Request { get { if (m_IsDisposed) { throw new ObjectDisposedException("SIP_ProxyContext"); } return m_pRequest; } } /* /// <summary> /// Gets active client transactions that will handle forward request. /// There may be more than 1 active client transaction if parallel forking. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public SIP_ClientTransaction[] ClientTransactions { get{ if(m_IsDisposed){ throw new ObjectDisposedException("SIP_ProxyContext"); } return m_pClientTransactions.ToArray(); } } */ /// <summary> /// Gets all responses what proxy context has received. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception> public SIP_Response[] Responses { get { if (m_IsDisposed) { throw new ObjectDisposedException("SIP_ProxyContext"); } return m_pResponses.ToArray(); } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="proxy">Owner proxy.</param> /// <param name="transaction">Server transaction what is used to send SIP responses back to caller.</param> /// <param name="request">Request to forward.</param> /// <param name="addRecordRoute">If true, Record-Route header field will be added.</param> /// <param name="forkingMode">Specifies how proxy context must handle forking.</param> /// <param name="isB2BUA">Specifies if proxy context is in B2BUA or just transaction satefull mode.</param> /// <param name="noCancel">Specifies if proxy should not send Cancel to forked requests.</param> /// <param name="noRecurse">Specifies what proxy server does when it gets 3xx response. If true proxy will forward /// request to new specified address if false, proxy will return 3xx response to caller.</param> /// <param name="targets">Possible remote targets. NOTE: These values must be in priority order !</param> /// <param name="credentials">Target set credentials.</param> /// <exception cref="ArgumentNullException">Is raised when any of the reference type prameters is null.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> internal SIP_ProxyContext(SIP_ProxyCore proxy, SIP_ServerTransaction transaction, SIP_Request request, bool addRecordRoute, SIP_ForkingMode forkingMode, bool isB2BUA, bool noCancel, bool noRecurse, SIP_ProxyTarget[] targets, NetworkCredential[] credentials) { if (proxy == null) { throw new ArgumentNullException("proxy"); } if (transaction == null) { throw new ArgumentNullException("transaction"); } if (request == null) { throw new ArgumentNullException("request"); } if (targets == null) { throw new ArgumentNullException("targets"); } if (targets.Length == 0) { throw new ArgumentException("Argumnet 'targets' must contain at least 1 value."); } m_pProxy = proxy; m_pServerTransaction = transaction; m_pServerTransaction.Canceled += m_pServerTransaction_Canceled; m_pServerTransaction.Disposed += m_pServerTransaction_Disposed; m_pRequest = request; m_AddRecordRoute = addRecordRoute; m_ForkingMode = forkingMode; m_IsB2BUA = isB2BUA; m_NoCancel = noCancel; m_NoRecurse = noRecurse; m_pTargetsHandlers = new List<TargetHandler>(); m_pResponses = new List<SIP_Response>(); m_ID = Guid.NewGuid().ToString(); m_CreateTime = DateTime.Now; // Queue targets up, higest to lowest. m_pTargets = new Queue<TargetHandler>(); foreach (SIP_ProxyTarget target in targets) { m_pTargets.Enqueue(new TargetHandler(this, target.Flow, target.TargetUri, m_AddRecordRoute, false)); } m_pCredentials = new List<NetworkCredential>(); m_pCredentials.AddRange(credentials); /* RFC 3841 9.1. The Request-Disposition header field specifies caller preferences for how a server should process a request. Override SIP proxy default value. */ foreach (SIP_t_Directive directive in request.RequestDisposition.GetAllValues()) { if (directive.Directive == SIP_t_Directive.DirectiveType.NoFork) { m_ForkingMode = SIP_ForkingMode.None; } else if (directive.Directive == SIP_t_Directive.DirectiveType.Parallel) { m_ForkingMode = SIP_ForkingMode.Parallel; } else if (directive.Directive == SIP_t_Directive.DirectiveType.Sequential) { m_ForkingMode = SIP_ForkingMode.Sequential; } else if (directive.Directive == SIP_t_Directive.DirectiveType.NoCancel) { m_NoCancel = true; } else if (directive.Directive == SIP_t_Directive.DirectiveType.NoRecurse) { m_NoRecurse = true; } } m_pProxy.Stack.Logger.AddText("ProxyContext(id='" + m_ID + "') created."); } #endregion #region Methods /// <summary> /// Cleans up any resources being used. /// </summary> public void Dispose() { lock (m_pLock) { if (m_IsDisposed) { return; } m_IsDisposed = true; m_pProxy.Stack.Logger.AddText("ProxyContext(id='" + m_ID + "') disposed."); m_pProxy.m_pProxyContexts.Remove(this); m_pProxy = null; m_pServerTransaction = null; m_pTargetsHandlers = null; m_pResponses = null; m_pTargets = null; } } /// <summary> /// Starts processing. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and and this method is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when this method is called more than once.</exception> public void Start() { lock (m_pLock) { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (m_IsStarted) { throw new InvalidOperationException("Start has already called."); } m_IsStarted = true; // Only use destination with the highest q value. // We already have ordered highest to lowest, so just get first destination. if (m_ForkingMode == SIP_ForkingMode.None) { TargetHandler handler = m_pTargets.Dequeue(); m_pTargetsHandlers.Add(handler); handler.Start(); } // Use all destinations at same time. else if (m_ForkingMode == SIP_ForkingMode.Parallel) { // NOTE: If target count == 1 and transport exception, target may Dispose proxy context., so we need to handle it. while (!m_IsDisposed && m_pTargets.Count > 0) { TargetHandler handler = m_pTargets.Dequeue(); m_pTargetsHandlers.Add(handler); handler.Start(); } } // Start processing destinations with highest q value to lowest. else if (m_ForkingMode == SIP_ForkingMode.Sequential) { TargetHandler handler = m_pTargets.Dequeue(); m_pTargetsHandlers.Add(handler); handler.Start(); } } } /// <summary> /// Cancels proxy context processing. All client transactions and owner server transaction will be canceled, /// proxy context will be disposed. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and and this method is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when <b>Start</b> method is not called and this method is accessed.</exception> public void Cancel() { lock (m_pLock) { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (!m_IsStarted) { throw new InvalidOperationException("Start method is not called, nothing to cancel."); } m_pServerTransaction.Cancel(); // Server transaction raised Cancled event, we dispose active targets there. } } #endregion #region Event handlers /// <summary> /// Is called when server transaction has canceled. /// </summary> /// <param name="sender">Sender.</param> /// <param name="e">Event data.</param> private void m_pServerTransaction_Canceled(object sender, EventArgs e) { lock (m_pLock) { CancelAllTargets(); // We dont need to Dispose proxy context, server transaction will call Terminated event // after cancel, there we dispose it. } } /// <summary> /// This method is called when server transaction has disposed. /// </summary> /// <param name="sender">Sender.</param> /// <param name="e">Event data.</param> private void m_pServerTransaction_Disposed(object sender, EventArgs e) { // All done, just dispose proxy context. Dispose(); } #endregion #region Utility methods /// <summary> /// This method is called when specified target handler has disposed. /// </summary> /// <param name="handler">TargetHandler what disposed.</param> private void TargetHandler_Disposed(TargetHandler handler) { lock (m_pLock) { m_pTargetsHandlers.Remove(handler); // All targets are processed. if (m_pTargets.Count == 0 && m_pTargetsHandlers.Count == 0) { Dispose(); } } } /// <summary> /// Processes received response. /// </summary> /// <param name="handler">Target handler what received response.</param> /// <param name="transaction">Client transaction what response it is.</param> /// <param name="response">Response received.</param> /// <exception cref="ArgumentNullException">Is raised when <b>handler</b>,<b>transaction</b> or <b>response</b> is null reference.</exception> private void ProcessResponse(TargetHandler handler, SIP_ClientTransaction transaction, SIP_Response response) { if (handler == null) { throw new ArgumentNullException("handler"); } if (transaction == null) { throw new ArgumentNullException("transaction"); } if (response == null) { throw new ArgumentNullException("response"); } /* RFC 3261 16.7 Response Processing. Steps 1 - 2 handled in TargetHandler. 3. Remove the topmost Via 4. Add the response to the response context 5. Check to see if this response should be forwarded immediately 6. When necessary, choose the best final response from the response context. If no final response has been forwarded after every client transaction associated with the response context has been terminated, the proxy must choose and forward the "best" response from those it has seen so far. The following processing MUST be performed on each response that is forwarded. It is likely that more than one response to each request will be forwarded: at least each provisional and one final response. 7. Aggregate authorization header field values if necessary 8. Optionally rewrite Record-Route header field values 9. Forward the response 10. Generate any necessary CANCEL requests */ bool forwardResponse = false; lock (m_pLock) { #region 3. Remove the topmost Via /* The proxy removes the topmost Via header field value from the response. If no Via header field values remain in the response, the response was meant for this element and MUST NOT be forwarded. The remainder of the processing described in this section is not performed on this message, the UAC processing rules described in Section 8.1.3 are followed instead (transport layer processing has already occurred). This will happen, for instance, when the element generates CANCEL requests as described in Section 10. NOTE: We MAY NOT do it for B2BUA, skip it for B2BUA */ if (!m_IsB2BUA) { response.Via.RemoveTopMostValue(); if (response.Via.GetAllValues().Length == 0) { return; } } #endregion #region 4. Add the response to the response context /* Final responses received are stored in the response context until a final response is generated on the server transaction associated with this context. The response may be a candidate for the best final response to be returned on that server transaction. Information from this response may be needed in forming the best response, even if this response is not chosen. If the proxy chooses to recurse on any contacts in a 3xx response by adding them to the target set, it MUST remove them from the response before adding the response to the response context. However, a proxy SHOULD NOT recurse to a non-SIPS URI if the Request-URI of the original request was a SIPS URI. If the proxy recurses on all of the contacts in a 3xx response, the proxy SHOULD NOT add the resulting contactless response to the response context. Removing the contact before adding the response to the response context prevents the next element upstream from retrying a location this proxy has already attempted. 3xx responses may contain a mixture of SIP, SIPS, and non-SIP URIs. A proxy may choose to recurse on the SIP and SIPS URIs and place the remainder into the response context to be returned, potentially in the final response. */ if (response.StatusCodeType == SIP_StatusCodeType.Redirection && !m_NoRecurse && !handler.IsRecursed) { // Get SIP contacts and remove them from response. SIP_t_ContactParam[] contacts = response.Contact.GetAllValues(); // Remove all contacts from response, we add non-SIP URIs back. response.Contact.RemoveAll(); foreach (SIP_t_ContactParam contact in contacts) { // SIP URI add it to fork list. if (contact.Address.IsSipOrSipsUri) { m_pTargets.Enqueue(new TargetHandler(this, null, (SIP_Uri) contact.Address.Uri, m_AddRecordRoute, true)); } // Add specified URI back to response. else { response.Contact.Add(contact.ToStringValue()); } } // There are remaining non-SIP contacts, so we need to add the response to reponses collection. if (response.Contact.GetAllValues().Length > 0) { m_pResponses.Add(response); } // Handle forking if (m_pTargets.Count > 0) { if (m_ForkingMode == SIP_ForkingMode.Parallel) { while (m_pTargets.Count > 0) { TargetHandler h = m_pTargets.Dequeue(); m_pTargetsHandlers.Add(handler); h.Start(); } } // Just fork next. else { TargetHandler h = m_pTargets.Dequeue(); m_pTargetsHandlers.Add(handler); h.Start(); } // Because we forked request to new target(s), we don't need to do steps 5 - 10. return; } } // Not 3xx response or recursing disabled. else { m_pResponses.Add(response); } #endregion #region 5. Check to see if this response should be forwarded immediately /* Until a final response has been sent on the server transaction, the following responses MUST be forwarded immediately: - Any provisional response other than 100 (Trying) - Any 2xx response If a 6xx response is received, it is not immediately forwarded, but the stateful proxy SHOULD cancel all client pending transactions as described in Section 10, and it MUST NOT create any new branches in this context. After a final response has been sent on the server transaction, the following responses MUST be forwarded immediately: - Any 2xx response to an INVITE request */ if (!m_IsFinalResponseSent) { if (response.StatusCodeType == SIP_StatusCodeType.Provisional && response.StatusCode != 100) { forwardResponse = true; } else if (response.StatusCodeType == SIP_StatusCodeType.Success) { forwardResponse = true; } else if (response.StatusCodeType == SIP_StatusCodeType.GlobalFailure) { CancelAllTargets(); } } else { if (response.StatusCodeType == SIP_StatusCodeType.Success && m_pServerTransaction.Request.RequestLine.Method == SIP_Methods.INVITE) { forwardResponse = true; } } #endregion #region x. Handle sequential forking /* Sequential Search: In a sequential search, a proxy server attempts each contact address in sequence, proceeding to the next one only after the previous has generated a final response. A 2xx or 6xx class final response always terminates a sequential search. */ if (m_ForkingMode == SIP_ForkingMode.Sequential && response.StatusCodeType != SIP_StatusCodeType.Provisional) { if (response.StatusCodeType == SIP_StatusCodeType.Success) { // Do nothing, 2xx will be always forwarded and step 10. Cancels all targets. } else if (response.StatusCodeType == SIP_StatusCodeType.GlobalFailure) { // Do nothing, 6xx is already handled in setp 5. } else if (m_pTargets.Count > 0) { TargetHandler h = m_pTargets.Dequeue(); m_pTargetsHandlers.Add(handler); h.Start(); // Skip all next steps, we will get new responses from new target. return; } } #endregion #region 6. When necessary, choose the best final response from the response context /* A stateful proxy MUST send a final response to a response context's server transaction if no final responses have been immediately forwarded by the above rules and all client transactions in this response context have been terminated. The stateful proxy MUST choose the "best" final response among those received and stored in the response context. If there are no final responses in the context, the proxy MUST send a 408 (Request Timeout) response to the server transaction. */ if (!m_IsFinalResponseSent && !forwardResponse && m_pTargets.Count == 0) { bool mustChooseBestFinalResponse = true; // Check if all transactions terminated. foreach (TargetHandler h in m_pTargetsHandlers) { if (!h.IsCompleted) { mustChooseBestFinalResponse = false; break; } } if (mustChooseBestFinalResponse) { response = GetBestFinalResponse(); if (response == null) { response = Proxy.Stack.CreateResponse(SIP_ResponseCodes.x408_Request_Timeout, m_pServerTransaction.Request); } forwardResponse = true; } } #endregion if (forwardResponse) { #region 7. Aggregate authorization header field values if necessary /* If the selected response is a 401 (Unauthorized) or 407 (Proxy Authentication Required), the proxy MUST collect any WWW-Authenticate and Proxy-Authenticate header field values from all other 401 (Unauthorized) and 407 (Proxy Authentication Required) responses received so far in this response context and add them to this response without modification before forwarding. The resulting 401 (Unauthorized) or 407 (Proxy Authentication Required) response could have several WWW-Authenticate AND Proxy-Authenticate header field values. This is necessary because any or all of the destinations the request was forwarded to may have requested credentials. The client needs to receive all of those challenges and supply credentials for each of them when it retries the request. */ if (response.StatusCode == 401 || response.StatusCode == 407) { foreach (SIP_Response resp in m_pResponses.ToArray()) { if (response != resp && (resp.StatusCode == 401 || resp.StatusCode == 407)) { // WWW-Authenticate foreach (SIP_HeaderField hf in resp.WWWAuthenticate.HeaderFields) { resp.WWWAuthenticate.Add(hf.Value); } // Proxy-Authenticate foreach (SIP_HeaderField hf in resp.ProxyAuthenticate.HeaderFields) { resp.ProxyAuthenticate.Add(hf.Value); } } } } #endregion #region 8. Optionally rewrite Record-Route header field values // This is optional so we currently won't do that. #endregion #region 9. Forward the response SendResponse(transaction, response); if (response.StatusCodeType != SIP_StatusCodeType.Provisional) { m_IsFinalResponseSent = true; } #endregion #region 10. Generate any necessary CANCEL requests /* If the forwarded response was a final response, the proxy MUST generate a CANCEL request for all pending client transactions associated with this response context. */ if (response.StatusCodeType != SIP_StatusCodeType.Provisional) { CancelAllTargets(); } #endregion } } } /// <summary> /// Sends SIP response to caller. If proxy context is in B2BUA mode, new response is generated /// as needed. /// </summary> /// <param name="transaction">Client transaction what response it is.</param> /// <param name="response">Response to send.</param> private void SendResponse(SIP_ClientTransaction transaction, SIP_Response response) { if (m_IsB2BUA) { /* draft-marjou-sipping-b2bua-00 4.1.3. When the UAC side of the B2BUA receives the downstream SIP response of a forwarded request, its associated UAS creates an upstream response (except for 100 responses). The creation of the Via, Max- Forwards, Call-Id, CSeq, Record-Route and Contact header fields follows the rules of [2]. The Record-Route header fields of the downstream response are not copied in the new upstream response, as Record-Route is meaningful for the downstream dialog. The UAS SHOULD copy other header fields and body from the downstream response into this upstream response before sending it. */ SIP_Request originalRequest = m_pServerTransaction.Request; // We need to use caller original request to construct response from proxied response. SIP_Response b2buaResponse = response.Copy(); b2buaResponse.Via.RemoveAll(); b2buaResponse.Via.AddToTop(originalRequest.Via.GetTopMostValue().ToStringValue()); b2buaResponse.CallID = originalRequest.CallID; b2buaResponse.CSeq = originalRequest.CSeq; b2buaResponse.Contact.RemoveAll(); //b2buaResponse.Contact.Add(m_pProxy.CreateContact(originalRequest.From.Address).ToStringValue()); b2buaResponse.RecordRoute.RemoveAll(); b2buaResponse.Allow.RemoveAll(); b2buaResponse.Supported.RemoveAll(); // Accept to non ACK,BYE request. if (originalRequest.RequestLine.Method != SIP_Methods.ACK && originalRequest.RequestLine.Method != SIP_Methods.BYE) { b2buaResponse.Allow.Add("INVITE,ACK,OPTIONS,CANCEL,BYE,PRACK"); } // Supported to non ACK request. if (originalRequest.RequestLine.Method != SIP_Methods.ACK) { b2buaResponse.Supported.Add("100rel,timer"); } // Remove Require: header. b2buaResponse.Require.RemoveAll(); m_pServerTransaction.SendResponse(b2buaResponse); // If INVITE 2xx response do call here. if (response.CSeq.RequestMethod.ToUpper() == SIP_Methods.INVITE && response.StatusCodeType == SIP_StatusCodeType.Success) { m_pProxy.B2BUA.AddCall(m_pServerTransaction.Dialog, transaction.Dialog); } } else { m_pServerTransaction.SendResponse(response); } } /// <summary> /// Cancels all targets processing. /// </summary> private void CancelAllTargets() { if (!m_NoCancel) { m_pTargets.Clear(); foreach (TargetHandler target in m_pTargetsHandlers.ToArray()) { target.Cancel(); } } } /// <summary> /// Gets best final response. If no final response in responses collection, null is returned. /// </summary> /// <returns>Resturns best final response or null if no final response.</returns> private SIP_Response GetBestFinalResponse() { // 6xx -> 2xx -> 3xx -> 4xx -> 5xx // 6xx foreach (SIP_Response resp in m_pResponses.ToArray()) { if (resp.StatusCodeType == SIP_StatusCodeType.GlobalFailure) { return resp; } } // 2xx foreach (SIP_Response resp in m_pResponses.ToArray()) { if (resp.StatusCodeType == SIP_StatusCodeType.Success) { return resp; } } // 3xx foreach (SIP_Response resp in m_pResponses.ToArray()) { if (resp.StatusCodeType == SIP_StatusCodeType.Redirection) { return resp; } } // 4xx foreach (SIP_Response resp in m_pResponses.ToArray()) { if (resp.StatusCodeType == SIP_StatusCodeType.RequestFailure) { return resp; } } // 5xx foreach (SIP_Response resp in m_pResponses.ToArray()) { if (resp.StatusCodeType == SIP_StatusCodeType.ServerFailure) { return resp; } } return null; } /// <summary> /// Gets credentials for specified realm. Returns null if none such credentials. /// </summary> /// <param name="realm">Realm which credentials to get.</param> /// <returns>Returns specified realm credentials or null in none.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>realm</b> is null reference.</exception> private NetworkCredential GetCredential(string realm) { if (realm == null) { throw new ArgumentNullException("realm"); } foreach (NetworkCredential c in m_pCredentials) { if (c.Domain.ToLower() == realm.ToLower()) { return c; } } return null; } #endregion } }<file_sep>/module/ASC.Api/ASC.Api.Mail/MailApi.Contacts.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections.Generic; using System.Linq; using System.Web; using ASC.Api.Attributes; using ASC.Mail; using ASC.Mail.Core.Dao.Expressions.Contact; using ASC.Mail.Core.Entities; using ASC.Mail.Data.Contracts; using ASC.Mail.Enums; using ASC.Mail.Extensions; // ReSharper disable InconsistentNaming namespace ASC.Api.Mail { public partial class MailApi { /// <summary> /// Returns the list of the contacts for auto complete feature. /// </summary> /// <param name="term">string part of contact name, lastname or email.</param> /// <returns>Strings list. Strings format: "Name Lastname" email</returns> /// <short>Get contact list for auto complete</short> /// <category>Contacts</category> /// <exception cref="ArgumentException">Exception happens when in parameters is invalid. Text description contains parameter name and text description.</exception> [Read(@"emails/search")] public IEnumerable<string> SearchEmails(string term) { if (string.IsNullOrEmpty(term)) throw new ArgumentException(@"term parameter empty.", "term"); var scheme = HttpContext.Current == null ? Uri.UriSchemeHttp : HttpContext.Current.Request.GetUrlRewriter().Scheme; return MailEngineFactory.ContactEngine.SearchEmails(TenantId, Username, term, MailAutocompleteMaxCountPerSystem, scheme, MailAutocompleteTimeout); } /// <summary> /// Returns lists of mail contacts. /// </summary> /// <param optional="true" name="search">Text to search in contacts name or emails.</param> /// <param optional="true" name="contactType">Type of contacts</param> /// <param optional="true" name="pageSize">Count of contacts on page</param> /// <param optional="true" name="fromIndex">Page number</param> /// <param name="sortorder">Sort order by name. String parameter: "ascending" - ascended, "descending" - descended.</param> /// <returns>List of filtered contacts</returns> /// <short>Gets filtered contacts</short> /// <category>Contacts</category> [Read(@"contacts")] public IEnumerable<MailContactData> GetContacts(string search, int? contactType, int? pageSize, int fromIndex, string sortorder) { var exp = string.IsNullOrEmpty(search) && !contactType.HasValue ? new SimpleFilterContactsExp(TenantId, Username, sortorder == Defines.ASCENDING, fromIndex, pageSize) : new FullFilterContactsExp(TenantId, Username, search, contactType, orderAsc: sortorder == Defines.ASCENDING, startIndex: fromIndex, limit: pageSize); var contacts = MailEngineFactory.ContactEngine.GetContactCards(exp); int totalCount; if (contacts.Any() && contacts.Count() < pageSize) { totalCount = fromIndex + contacts.Count; } else { totalCount = MailEngineFactory.ContactEngine.GetContactCardsCount(exp); } _context.SetTotalCount(totalCount); return contacts.ToMailContactDataList(); } /// <summary> /// Returns lists of mail contacts with contact information /// </summary> /// <param optional="false" name="infoType">infoType</param> /// <param optional="false" name="data">data</param> /// <param optional="true" name="isPrimary">isPrimary</param> /// <returns>List of filtered contacts</returns> /// <short>Gets filtered contacts</short> /// <category>Contacts</category> [Read(@"contacts/bycontactinfo")] public IEnumerable<MailContactData> GetContactsByContactInfo(ContactInfoType infoType, String data, bool? isPrimary) { var exp = new FullFilterContactsExp(TenantId, Username, data, infoType: infoType, isPrimary: isPrimary); var contacts = MailEngineFactory.ContactEngine.GetContactCards(exp); return contacts.ToMailContactDataList(); } /// <summary> /// Create mail contact /// </summary> /// <param name="name">Contact's name</param> /// <param name="description">Description of contact</param> /// <param name="emails">List of emails</param> /// <param name="phoneNumbers">List of phone numbers</param> /// <returns>Information about created contact </returns> /// <short>Create mail contact</short> /// <category>Contacts</category> [Create(@"contact/add")] public MailContactData CreateContact(string name, string description, List<string> emails, List<string> phoneNumbers) { if (!emails.Any()) throw new ArgumentException(@"Invalid list of emails.", "emails"); var contactCard = new ContactCard(0, TenantId, Username, name, description, ContactType.Personal, emails, phoneNumbers); var newContact = MailEngineFactory.ContactEngine.SaveContactCard(contactCard); return newContact.ToMailContactData(); } /// <summary> /// Removes selected mail contacts /// </summary> /// <param name="ids">List of mail contact ids</param> /// <returns>List of removed mail contact ids </returns> /// <short>Remove mail contact </short> /// <category>Contacts</category> [Update(@"contacts/remove")] public IEnumerable<int> RemoveContacts(List<int> ids) { if (!ids.Any()) throw new ArgumentException(@"Empty ids collection", "ids"); MailEngineFactory.ContactEngine.RemoveContacts(ids); return ids; } /// <summary> /// Updates the existing mail contact /// </summary> /// <param name="id">id of mail contact</param> /// <param name="name">Contact's name</param> /// <param name="description">Description of contact</param> /// <param name="emails">List of emails</param> /// <param name="phoneNumbers">List of phone numbers</param> /// <returns>Information about updated contact </returns> /// <short>Update mail contact</short> /// <category>Contacts</category> [Update(@"contact/update")] public MailContactData UpdateContact(int id, string name, string description, List<string> emails, List<string> phoneNumbers) { if (id < 0) throw new ArgumentException(@"Invalid contact id.", "id"); if (!emails.Any()) throw new ArgumentException(@"Invalid list of emails.", "emails"); var contactCard = new ContactCard(id, TenantId, Username, name, description, ContactType.Personal, emails, phoneNumbers); var contact = MailEngineFactory.ContactEngine.UpdateContactCard(contactCard); return contact.ToMailContactData(); } /// <summary> /// Returns list of crm entities linked with chain. Entity: contact, case or opportunity. /// </summary> /// <param name="message_id">Id of message included in the chain. It may be id any of messages included in the chain.</param> /// <returns>List of structures: {entity_id, entity_type, avatar_link, title}</returns> /// <short>Get crm linked entities</short> /// <category>Contacts</category> ///<exception cref="ArgumentException">Exception happens when in parameters is invalid. Text description contains parameter name and text description.</exception> [Read(@"crm/linked/entities")] public IEnumerable<CrmContactData> GetLinkedCrmEntitiesInfo(int message_id) { if(message_id < 0) throw new ArgumentException(@"meesage_id must be positive integer", "message_id"); return MailEngineFactory.CrmLinkEngine.GetLinkedCrmEntitiesId(message_id); } } } <file_sep>/web/studio/ASC.Web.Studio/Products/Community/Modules/Wiki/WikiUC/fckeditor/editor/plugins/quote/lang/es.js  FCKLang.QuoteDlgTitle = "Propiedades de cita"; FCKLang.QuoteBtn = "Insertar cita"; FCKLang.QuoteOwnerAlert = "El campo de nombre está vacío."; FCKLang.QuoteWrote = "escribió:"; FCKLang.QuoteLnkBody = "Cita:";<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/SIP/Message/SIP_t_CallID.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.SIP.Message { #region usings using System; #endregion /// <summary> /// Implements SIP "callid" value. Defined in RFC 3261. /// </summary> /// <remarks> /// <code> /// RFC 3261 Syntax: /// callid = word [ "@" word ] /// </code> /// </remarks> public class SIP_t_CallID : SIP_t_Value { #region Members private string m_CallID = ""; #endregion #region Properties /// <summary> /// Gets or sets call ID. /// </summary> public string CallID { get { return m_CallID; } set { if (string.IsNullOrEmpty(value)) { throw new ArgumentException("Property CallID value may not be null or empty !"); } m_CallID = value; } } #endregion #region Methods /// <summary> /// Creates new call ID value. /// </summary> /// <returns>Returns call ID value.</returns> public static SIP_t_CallID CreateCallID() { SIP_t_CallID callID = new SIP_t_CallID(); callID.CallID = Guid.NewGuid().ToString().Replace("-", ""); return callID; } /// <summary> /// Parses "callid" from specified value. /// </summary> /// <param name="value">SIP "callid" value.</param> /// <exception cref="ArgumentNullException">Raised when <b>value</b> is null.</exception> /// <exception cref="SIP_ParseException">Raised when invalid SIP message.</exception> public void Parse(string value) { if (value == null) { throw new ArgumentNullException("value"); } Parse(new StringReader(value)); } /// <summary> /// Parses "callid" from specified reader. /// </summary> /// <param name="reader">Reader from where to parse.</param> /// <exception cref="ArgumentNullException">Raised when <b>reader</b> is null.</exception> /// <exception cref="SIP_ParseException">Raised when invalid SIP message.</exception> public override void Parse(StringReader reader) { // callid = word [ "@" word ] if (reader == null) { throw new ArgumentNullException("reader"); } // Get Method string word = reader.ReadWord(); if (word == null) { throw new SIP_ParseException("Invalid 'callid' value, callid is missing !"); } m_CallID = word; } /// <summary> /// Converts this to valid "callid" value. /// </summary> /// <returns>Returns "callid" value.</returns> public override string ToStringValue() { return m_CallID; } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/RTP/RTP_SourceState.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.RTP { /// <summary> /// This enum specifies <b>RTP_SyncSource</b> state. /// </summary> public enum RTP_SourceState { /// <summary> /// Source is passive, sending only RTCP packets. /// </summary> Passive = 1, /// <summary> /// Source is active, sending RTP packets. /// </summary> Active = 2, /// <summary> /// Source has disposed. /// </summary> Disposed = 3, } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/MIME/MIME_DispositionTypes .cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.MIME { /// <summary> /// This class holds MIME content disposition types. Defined in RFC 2183. /// </summary> public class MIME_DispositionTypes { #region Members /// <summary> /// Bodyparts can be designated `attachment' to indicate that they are separate from the main body of the mail message, /// and that their display should not be automatic, but contingent upon some further action of the user. /// </summary> public static readonly string Attachment = "attachment"; /// <summary> /// A bodypart should be marked `inline' if it is intended to be displayed automatically upon display of the message. /// Inline bodyparts should be presented in the order in which they occur, subject to the normal semantics of multipart messages. /// </summary> public static readonly string Inline = "inline"; #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/SIP/Stack/SIP_RequestReceivedEventArgs.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.SIP.Stack { #region usings using System; #endregion /// <summary> /// This class provides data for <b>SIP_Dialog.RequestReceived</b> event and <b>SIP_Core.OnRequestReceived</b>> method. /// </summary> public class SIP_RequestReceivedEventArgs : EventArgs { #region Members private readonly SIP_Dialog m_pDialog; private readonly SIP_Flow m_pFlow; private readonly SIP_Request m_pRequest; private readonly SIP_Stack m_pStack; private SIP_ServerTransaction m_pTransaction; #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="stack">Reference to SIP stack.</param> /// <param name="flow">SIP data flow.</param> /// <param name="request">Recieved request.</param> internal SIP_RequestReceivedEventArgs(SIP_Stack stack, SIP_Flow flow, SIP_Request request) : this(stack, flow, request, null, null) {} /// <summary> /// Default constructor. /// </summary> /// <param name="stack">Reference to SIP stack.</param> /// <param name="flow">SIP data flow.</param> /// <param name="request">Recieved request.</param> /// <param name="dialog">SIP dialog which received request.</param> /// <param name="transaction">SIP server transaction which must be used to send response back to request maker.</param> internal SIP_RequestReceivedEventArgs(SIP_Stack stack, SIP_Flow flow, SIP_Request request, SIP_Dialog dialog, SIP_ServerTransaction transaction) { m_pStack = stack; m_pFlow = flow; m_pRequest = request; m_pDialog = dialog; m_pTransaction = transaction; } #endregion #region Properties /// <summary> /// Gets SIP dialog where Request belongs to. Returns null if Request doesn't belong any dialog. /// </summary> public SIP_Dialog Dialog { get { return m_pDialog; } } /// <summary> /// Gets request received by SIP stack. /// </summary> public SIP_Request Request { get { return m_pRequest; } } /// <summary> /// Gets server transaction for that request. Server transaction is created when this property is /// first accessed. If you don't need server transaction for that request, for example statless proxy, /// just don't access this property. For ACK method, this method always return null, because ACK /// doesn't create transaction ! /// </summary> public SIP_ServerTransaction ServerTransaction { get { // ACK never creates transaction. if (m_pRequest.RequestLine.Method == SIP_Methods.ACK) { return null; } // Create server transaction for that request. if (m_pTransaction == null) { m_pTransaction = m_pStack.TransactionLayer.EnsureServerTransaction(m_pFlow, m_pRequest); } return m_pTransaction; } } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/ABNF/ABNF_RuleName.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.ABNF { #region usings using System; using System.IO; using System.Text; #endregion /// <summary> /// This class represent ABNF "rulename". Defined in RFC 5234 4. /// </summary> public class ABNF_RuleName : ABNF_Element { #region Members private readonly string m_RuleName; #endregion #region Properties /// <summary> /// Gets rule name. /// </summary> public string RuleName { get { return m_RuleName; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="ruleName">Rule name.</param> /// <exception cref="ArgumentNullException">Is raised when <b>ruleName</b> is null reference.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> public ABNF_RuleName(string ruleName) { if (ruleName == null) { throw new ArgumentNullException("ruleName"); } if (!ValidateName(ruleName)) { throw new ArgumentException( "Invalid argument 'ruleName' value. Value must be 'rulename = ALPHA *(ALPHA / DIGIT / \"-\")'."); } m_RuleName = ruleName; } #endregion #region Methods /// <summary> /// /// </summary> /// <param name="reader"></param> /// <returns></returns> public static ABNF_RuleName Parse(StringReader reader) { if (reader == null) { throw new ArgumentNullException("reader"); } // RFC 5234 4. // rulename = ALPHA *(ALPHA / DIGIT / "-") if (!char.IsLetter((char) reader.Peek())) { throw new ParseException("Invalid ABNF 'rulename' value '" + reader.ReadToEnd() + "'."); } StringBuilder ruleName = new StringBuilder(); while (true) { // We reached end of string. if (reader.Peek() == -1) { break; } // We have valid rule name char. else if (char.IsLetter((char) reader.Peek()) | char.IsDigit((char) reader.Peek()) | (char) reader.Peek() == '-') { ruleName.Append((char) reader.Read()); } // Not rule name char, probably readed name. else { break; } } return new ABNF_RuleName(ruleName.ToString()); } #endregion #region Utility methods /// <summary> /// Validates 'rulename' value. /// </summary> /// <param name="name">Rule name.</param> /// <returns>Returns true if rule name is valid, otherwise false.</returns> private bool ValidateName(string name) { if (name == null) { return false; } if (name == string.Empty) { return false; } // RFC 5234 4. // rulename = ALPHA *(ALPHA / DIGIT / "-") if (!char.IsLetter(name[0])) { return false; } for (int i = 1; i < name.Length; i++) { char c = name[i]; if (!(char.IsLetter(c) | char.IsDigit(c) | c == '-')) { return false; } } return true; } #endregion } }<file_sep>/common/ASC.Common/Caching/RedisCache.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Configuration; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using ASC.Common.Logging; using Newtonsoft.Json; using Newtonsoft.Json.Serialization; using StackExchange.Redis; using StackExchange.Redis.Extensions.Core; using StackExchange.Redis.Extensions.Core.Extensions; using StackExchange.Redis.Extensions.LegacyConfiguration; namespace ASC.Common.Caching { public class RedisCache : ICache, ICacheNotify { private readonly string CacheId = Guid.NewGuid().ToString(); private readonly StackExchangeRedisCacheClient redis; private readonly ConcurrentDictionary<Type, ConcurrentBag<Action<object, CacheNotifyAction>>> actions = new ConcurrentDictionary<Type, ConcurrentBag<Action<object, CacheNotifyAction>>>(); public RedisCache() { var configuration = ConfigurationManagerExtension.GetSection("redisCacheClient") as RedisCachingSectionHandler; if (configuration == null) throw new ConfigurationErrorsException("Unable to locate <redisCacheClient> section into your configuration file. Take a look https://github.com/imperugo/StackExchange.Redis.Extensions"); var stringBuilder = new StringBuilder(); using (var stream = new StringWriter(stringBuilder)) { var opts = RedisCachingSectionHandler.GetConfig().ConfigurationOptions; opts.SyncTimeout = 60000; var connectionMultiplexer = (IConnectionMultiplexer)ConnectionMultiplexer.Connect(opts, stream); redis = new StackExchangeRedisCacheClient(connectionMultiplexer, new Serializer()); LogManager.GetLogger("ASC").Debug(stringBuilder.ToString()); } } public T Get<T>(string key) where T : class { return redis.Get<T>(key); } public void Insert(string key, object value, TimeSpan sligingExpiration) { redis.Replace(key, value, sligingExpiration); } public void Insert(string key, object value, DateTime absolutExpiration) { redis.Replace(key, value, absolutExpiration == DateTime.MaxValue ? DateTimeOffset.MaxValue : new DateTimeOffset(absolutExpiration)); } public void Remove(string key) { redis.Remove(key); } public void Remove(Regex pattern) { var glob = pattern.ToString().Replace(".*", "*").Replace(".", "?"); var keys = redis.SearchKeys(glob); if (keys.Any()) { redis.RemoveAll(keys); } } public IDictionary<string, T> HashGetAll<T>(string key) { var dic = redis.Database.HashGetAll(key); return dic .Select(e => { var val = default(T); try { val = (string)e.Value != null ? JsonConvert.DeserializeObject<T>(e.Value) : default(T); } catch (Exception ex) { LogManager.GetLogger("ASC").Error("RedisCache HashGetAll", ex); } return new { Key = (string)e.Name, Value = val }; }) .Where(e => e.Value != null && !e.Value.Equals(default(T))) .ToDictionary(e => e.Key, e => e.Value); } public T HashGet<T>(string key, string field) { var value = (string)redis.Database.HashGet(key, field); try { return value != null ? JsonConvert.DeserializeObject<T>(value) : default(T); } catch (Exception ex) { LogManager.GetLogger("ASC").Error("RedisCache HashGet", ex); return default(T); } } public void HashSet<T>(string key, string field, T value) { if (value != null) { redis.Database.HashSet(key, field, JsonConvert.SerializeObject(value)); } else { redis.Database.HashDelete(key, field); } } public void Publish<T>(T obj, CacheNotifyAction action) { redis.Publish("asc:channel:" + typeof(T).FullName, new RedisCachePubSubItem<T>() { CacheId = CacheId, Object = obj, Action = action }); ConcurrentBag<Action<object, CacheNotifyAction>> onchange; actions.TryGetValue(typeof(T), out onchange); if (onchange != null) { onchange.ToArray().ForEach(r => r(obj, action)); } } public void Subscribe<T>(Action<T, CacheNotifyAction> onchange) { redis.Subscribe<RedisCachePubSubItem<T>>("asc:channel:" + typeof(T).FullName, (i) => { if (i.CacheId != CacheId) { onchange(i.Object, i.Action); } }); if (onchange != null) { Action<object, CacheNotifyAction> action = (o, a) => onchange((T)o, a); actions.AddOrUpdate(typeof(T), new ConcurrentBag<Action<object, CacheNotifyAction>> { action }, (type, bag) => { bag.Add(action); return bag; }); } else { ConcurrentBag<Action<object, CacheNotifyAction>> removed; actions.TryRemove(typeof(T), out removed); } } [Serializable] class RedisCachePubSubItem<T> { public string CacheId { get; set; } public T Object { get; set; } public CacheNotifyAction Action { get; set; } } class Serializer : ISerializer { private readonly Encoding enc = Encoding.UTF8; public byte[] Serialize(object item) { try { var s = JsonConvert.SerializeObject(item); return enc.GetBytes(s); } catch (Exception e) { LogManager.GetLogger("ASC").Error("Redis Serialize", e); throw; } } public object Deserialize(byte[] obj) { try { var resolver = new ContractResolver(); var settings = new JsonSerializerSettings { ContractResolver = resolver }; var s = enc.GetString(obj); return JsonConvert.DeserializeObject(s, typeof(object), settings); } catch (Exception e) { LogManager.GetLogger("ASC").Error("Redis Deserialize", e); throw; } } public T Deserialize<T>(byte[] obj) { try { var resolver = new ContractResolver(); var settings = new JsonSerializerSettings { ContractResolver = resolver }; var s = enc.GetString(obj); return JsonConvert.DeserializeObject<T>(s, settings); } catch (Exception e) { LogManager.GetLogger("ASC").Error("Redis Deserialize<T>", e); throw; } } public async Task<byte[]> SerializeAsync(object item) { return await Task.Factory.StartNew(() => Serialize(item)); } public Task<object> DeserializeAsync(byte[] obj) { return Task.Factory.StartNew(() => Deserialize(obj)); } public Task<T> DeserializeAsync<T>(byte[] obj) { return Task.Factory.StartNew(() => Deserialize<T>(obj)); } class ContractResolver : DefaultContractResolver { protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization) { var prop = base.CreateProperty(member, memberSerialization); if (!prop.Writable) { var property = member as PropertyInfo; if (property != null) { var hasPrivateSetter = property.GetSetMethod(true) != null; prop.Writable = hasPrivateSetter; } } return prop; } } } } } <file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/SDP/SDP_ConnectionData.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.SDP { #region usings using System; #endregion /// <summary> /// A SDP_ConnectionData represents an <B>c=</B> SDP message field. Defined in RFC 4566 5.7. Connection Data. /// </summary> public class SDP_ConnectionData { #region Members private string m_Address = ""; private string m_AddressType = ""; private string m_NetType = "IN"; #endregion #region Properties /// <summary> /// Gets net type. Currently it's always IN(Internet). /// </summary> public string NetType { get { return m_NetType; } } /// <summary> /// Gets or sets address type. Currently defined values IP4 or IP6. /// </summary> public string AddressType { get { return m_AddressType; } set { if (string.IsNullOrEmpty(value)) { throw new ArgumentException("Property AddressType can't be null or empty !"); } m_AddressType = value; } } /// <summary> /// Gets or sets connection address. /// </summary> public string Address { get { return m_Address; } set { if (string.IsNullOrEmpty(value)) { throw new ArgumentException("Property Address can't be null or empty !"); } m_Address = value; } } #endregion #region Methods /// <summary> /// Parses media from "c" SDP message field. /// </summary> /// <param name="cValue">"m" SDP message field.</param> /// <returns></returns> public static SDP_ConnectionData Parse(string cValue) { // c=<nettype> <addrtype> <connection-address> SDP_ConnectionData connectionInfo = new SDP_ConnectionData(); // Remove c= StringReader r = new StringReader(cValue); r.QuotedReadToDelimiter('='); //--- <nettype> ------------------------------------------------------------ string word = r.ReadWord(); if (word == null) { throw new Exception("SDP message \"c\" field <nettype> value is missing !"); } connectionInfo.m_NetType = word; //--- <addrtype> ----------------------------------------------------------- word = r.ReadWord(); if (word == null) { throw new Exception("SDP message \"c\" field <addrtype> value is missing !"); } connectionInfo.m_AddressType = word; //--- <connection-address> ------------------------------------------------- word = r.ReadWord(); if (word == null) { throw new Exception("SDP message \"c\" field <connection-address> value is missing !"); } connectionInfo.m_Address = word; return connectionInfo; } /// <summary> /// Converts this to valid connection data stirng. /// </summary> /// <returns></returns> public string ToValue() { // c=<nettype> <addrtype> <connection-address> return "c=" + NetType + " " + AddressType + " " + Address + "\r\n"; } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/SIP/Stack/SIP_RequestSender.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.SIP.Stack { #region usings using System; using System.Collections.Generic; using System.Net; using System.Threading; using AUTH; using Message; #endregion /// <summary> /// This class implements SIP request sender. /// </summary> /// <remarks> /// Request is sent using following methods:<br/> /// *) If there is active data flow, it is used. /// *) Request is sent as described in RFC 3261 [4](RFC 3263). /// </remarks> public class SIP_RequestSender : IDisposable { #region Events /// <summary> /// Is raised when sender has finished processing(got final-response or error). /// </summary> public event EventHandler Completed = null; /// <summary> /// Is raised when this object has disposed. /// </summary> public event EventHandler Disposed = null; /// <summary> /// Is raised when this transaction has got response from target end point. /// </summary> public event EventHandler<SIP_ResponseReceivedEventArgs> ResponseReceived = null; #endregion #region Members private bool m_IsStarted; private List<NetworkCredential> m_pCredentials; private SIP_Flow m_pFlow; private Queue<SIP_Hop> m_pHops; private object m_pLock = new object(); private SIP_Request m_pRequest; private SIP_Stack m_pStack; private SIP_ClientTransaction m_pTransaction; private SIP_RequestSenderState m_State = SIP_RequestSenderState.Initial; #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="stack">Owner stack.</param> /// <param name="request">SIP request.</param> /// <param name="flow">Active data flow what to try before RFC 3261 [4](RFC 3263) methods to use to send request. /// This value can be null.</param> /// <exception cref="ArgumentNullException">Is raised when <b>stack</b> or <b>request</b> is null.</exception> internal SIP_RequestSender(SIP_Stack stack, SIP_Request request, SIP_Flow flow) { if (stack == null) { throw new ArgumentNullException("stack"); } if (request == null) { throw new ArgumentNullException("request"); } m_pStack = stack; m_pRequest = request; m_pFlow = flow; m_pCredentials = new List<NetworkCredential>(); m_pHops = new Queue<SIP_Hop>(); } #endregion #region Properties /// <summary> /// Gets credentials collection. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and and this property is accessed.</exception> public List<NetworkCredential> Credentials { get { if (m_State == SIP_RequestSenderState.Disposed) { throw new ObjectDisposedException(GetType().Name); } return m_pCredentials; } } /// <summary> /// Gets SIP flow what was used to send request or null if request is not sent yet. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and and this property is accessed.</exception> public SIP_Flow Flow { get { if (m_State == SIP_RequestSenderState.Disposed) { throw new ObjectDisposedException(GetType().Name); } return m_pFlow; } } /// <summary> /// Gets if this object is disposed. /// </summary> public bool IsDisposed { get { return m_State == SIP_RequestSenderState.Disposed; } } /// <summary> /// Gets if request sending has been started. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and and this property is accessed.</exception> public bool IsStarted { get { if (m_State == SIP_RequestSenderState.Disposed) { throw new ObjectDisposedException(GetType().Name); } return m_IsStarted; } } /// <summary> /// Gets SIP request. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and and this property is accessed.</exception> public SIP_Request Request { get { if (m_State == SIP_RequestSenderState.Disposed) { throw new ObjectDisposedException(GetType().Name); } return m_pRequest; } } /// <summary> /// Gets owner stack. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and and this property is accessed.</exception> public SIP_Stack Stack { get { if (m_State == SIP_RequestSenderState.Disposed) { throw new ObjectDisposedException(GetType().Name); } return m_pStack; } } #endregion #region Methods /// <summary> /// Cleans up any resources being used. /// </summary> public void Dispose() { lock (m_pLock) { if (m_State == SIP_RequestSenderState.Disposed) { return; } m_State = SIP_RequestSenderState.Disposed; OnDisposed(); ResponseReceived = null; Completed = null; Disposed = null; m_pStack = null; m_pRequest = null; m_pCredentials = null; m_pHops = null; m_pTransaction = null; m_pLock = null; } } /// <summary> /// Starts sending request. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and and this method is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when <b>Start</b> method has alredy called.</exception> /// <exception cref="SIP_TransportException">Is raised when no transport hop(s) for request.</exception> public void Start() { lock (m_pLock) { if (m_State == SIP_RequestSenderState.Disposed) { throw new ObjectDisposedException(GetType().Name); } if (m_IsStarted) { throw new InvalidOperationException("Start method has been already called."); } m_IsStarted = true; m_State = SIP_RequestSenderState.Starting; // Start may take so, process it on thread pool. ThreadPool.QueueUserWorkItem(delegate { lock (m_pLock) { if (m_State == SIP_RequestSenderState.Disposed) { return; } /* RFC 3261 8.1.2 Sending the Request The destination for the request is then computed. Unless there is local policy specifying otherwise, the destination MUST be determined by applying the DNS procedures described in [4] as follows. If the first element in the route set indicated a strict router (resulting in forming the request as described in Section 172.16.58.3), the procedures MUST be applied to the Request-URI of the request. Otherwise, the procedures are applied to the first Route header field value in the request (if one exists), or to the request's Request-URI if there is no Route header field present. These procedures yield an ordered set of address, port, and transports to attempt. Independent of which URI is used as input to the procedures of [4], if the Request-URI specifies a SIPS resource, the UAC MUST follow the procedures of [4] as if the input URI were a SIPS URI. The UAC SHOULD follow the procedures defined in [4] for stateful elements, trying each address until a server is contacted. Each try constitutes a new transaction, and therefore each carries a different topmost Via header field value with a new branch parameter. Furthermore, the transport value in the Via header field is set to whatever transport was determined for the target server. */ // We never use strict, only loose route. bool isStrictRoute = false; SIP_Uri uri = null; if (isStrictRoute) { uri = (SIP_Uri) m_pRequest.RequestLine.Uri; } else if (m_pRequest.Route.GetTopMostValue() != null) { uri = (SIP_Uri) m_pRequest.Route.GetTopMostValue().Address. Uri; } else { uri = (SIP_Uri) m_pRequest.RequestLine.Uri; } //uri.Param_Transport = "TCP"; // Queue hops. foreach (SIP_Hop hop in m_pStack.GetHops(uri, m_pRequest.ToByteData().Length, ((SIP_Uri) m_pRequest.RequestLine.Uri). IsSecure)) { m_pHops.Enqueue(hop); } if (m_pHops.Count == 0) { OnTransportError( new SIP_TransportException("No hops for '" + uri + "'.")); OnCompleted(); } else { m_State = SIP_RequestSenderState.Started; try { if (m_pFlow != null) { SendToFlow(m_pFlow, m_pRequest.Copy()); return; } } catch { // Sending to specified flow failed, probably disposed, just try send to first hop. } SendToNextHop(); } } }); } } /// <summary> /// Cancels current request sending. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and and this method is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when request sending has not been started by <b>Start</b> method.</exception> public void Cancel() { // If sender is in starting state, we must wait that state to complete. while (m_State == SIP_RequestSenderState.Starting) { Thread.Sleep(5); } lock (m_pLock) { if (m_State == SIP_RequestSenderState.Disposed) { throw new ObjectDisposedException(GetType().Name); } if (!m_IsStarted) { throw new InvalidOperationException("Request sending has not started, nothing to cancel."); } if (m_State != SIP_RequestSenderState.Started) { return; } m_pHops.Clear(); } // We may not call m_pTransaction.Cancel() in lock block, because deadlock can happen when transaction get response at same time. // Transaction waits lock for us and we wait lock to transaction. m_pTransaction.Cancel(); } #endregion #region Utility methods /// <summary> /// Is called when client transactions receives response. /// </summary> /// <param name="sender">Sender.</param> /// <param name="e">Event data.</param> private void ClientTransaction_ResponseReceived(object sender, SIP_ResponseReceivedEventArgs e) { lock (m_pLock) { m_pFlow = e.ClientTransaction.Request.Flow; if (e.Response.StatusCode == 401 || e.Response.StatusCode == 407) { // Check if authentication failed(We sent authorization data and it's challenged again, // probably user name or password inccorect) bool hasFailedAuthorization = false; foreach (SIP_t_Challenge challange in e.Response.WWWAuthenticate.GetAllValues()) { foreach (SIP_t_Credentials credentials in m_pTransaction.Request.Authorization.GetAllValues()) { if (new Auth_HttpDigest(challange.AuthData, "").Realm == new Auth_HttpDigest(credentials.AuthData, "").Realm) { hasFailedAuthorization = true; break; } } } foreach (SIP_t_Challenge challange in e.Response.ProxyAuthenticate.GetAllValues()) { foreach (SIP_t_Credentials credentials in m_pTransaction.Request.ProxyAuthorization.GetAllValues()) { if (new Auth_HttpDigest(challange.AuthData, "").Realm == new Auth_HttpDigest(credentials.AuthData, "").Realm) { hasFailedAuthorization = true; break; } } } // Authorization failed, pass response to UA. if (hasFailedAuthorization) { OnResponseReceived(e.Response); } // Try to authorize challanges. else { SIP_Request request = m_pRequest.Copy(); /* RFC 3261 22.2. When a UAC resubmits a request with its credentials after receiving a 401 (Unauthorized) or 407 (Proxy Authentication Required) response, it MUST increment the CSeq header field value as it would normally when sending an updated request. */ request.CSeq = new SIP_t_CSeq(m_pStack.ConsumeCSeq(), request.CSeq.RequestMethod); // All challanges authorized, resend request. if (Authorize(request, e.Response, Credentials.ToArray())) { SIP_Flow flow = m_pTransaction.Flow; CleanUpActiveTransaction(); SendToFlow(flow, request); } // We don't have credentials for one or more challenges. else { OnResponseReceived(e.Response); } } } else { OnResponseReceived(e.Response); if (e.Response.StatusCodeType != SIP_StatusCodeType.Provisional) { OnCompleted(); } } } } /// <summary> /// Is called when client transaction has timed out. /// </summary> /// <param name="sender">Sender.</param> /// <param name="e">Event data.</param> private void ClientTransaction_TimedOut(object sender, EventArgs e) { lock (m_pLock) { /* RFC 3261 8.1.2. The UAC SHOULD follow the procedures defined in [4] for stateful elements, trying each address until a server is contacted. Each try constitutes a new transaction, and therefore each carries a different topmost Via header field value with a new branch parameter. Furthermore, the transport value in the Via header field is set to whatever transport was determined for the target server. */ if (m_pHops.Count > 0) { CleanUpActiveTransaction(); SendToNextHop(); } /* 8.1.3.1 Transaction Layer Errors In some cases, the response returned by the transaction layer will not be a SIP message, but rather a transaction layer error. When a timeout error is received from the transaction layer, it MUST be treated as if a 408 (Request Timeout) status code has been received. If a fatal transport error is reported by the transport layer (generally, due to fatal ICMP errors in UDP or connection failures in TCP), the condition MUST be treated as a 503 (Service Unavailable) status code. */ else { OnResponseReceived(m_pStack.CreateResponse(SIP_ResponseCodes.x408_Request_Timeout, m_pRequest)); OnCompleted(); } } } /// <summary> /// Is called when client transaction encountered transport error. /// </summary> /// <param name="sender">Sender.</param> /// <param name="e">Event data.</param> private void ClientTransaction_TransportError(object sender, EventArgs e) { lock (m_pLock) { /* RFC 3261 8.1.2. The UAC SHOULD follow the procedures defined in [4] for stateful elements, trying each address until a server is contacted. Each try constitutes a new transaction, and therefore each carries a different topmost Via header field value with a new branch parameter. Furthermore, the transport value in the Via header field is set to whatever transport was determined for the target server. */ if (m_pHops.Count > 0) { CleanUpActiveTransaction(); SendToNextHop(); } /* RFC 3261 8.1.3.1 Transaction Layer Errors In some cases, the response returned by the transaction layer will not be a SIP message, but rather a transaction layer error. When a timeout error is received from the transaction layer, it MUST be treated as if a 408 (Request Timeout) status code has been received. If a fatal transport error is reported by the transport layer (generally, due to fatal ICMP errors in UDP or connection failures in TCP), the condition MUST be treated as a 503 (Service Unavailable) status code. */ else { OnResponseReceived( m_pStack.CreateResponse( SIP_ResponseCodes.x503_Service_Unavailable + ": Transport error.", m_pRequest)); OnCompleted(); } } } /// <summary> /// Creates authorization for each challange in <b>response</b>. /// </summary> /// <param name="request">SIP request where to add authorization values.</param> /// <param name="response">SIP response which challanges to authorize.</param> /// <param name="credentials">Credentials for authorization.</param> /// <returns>Returns true if all challanges were authorized. If any of the challanges was not authorized, returns false.</returns> private bool Authorize(SIP_Request request, SIP_Response response, NetworkCredential[] credentials) { if (request == null) { throw new ArgumentNullException("request"); } if (response == null) { throw new ArgumentNullException("response"); } if (credentials == null) { throw new ArgumentNullException("credentials"); } bool allAuthorized = true; #region WWWAuthenticate foreach (SIP_t_Challenge challange in response.WWWAuthenticate.GetAllValues()) { Auth_HttpDigest authDigest = new Auth_HttpDigest(challange.AuthData, request.RequestLine.Method); // Serach credential for the specified challange. NetworkCredential credential = null; foreach (NetworkCredential c in credentials) { if (c.Domain.ToLower() == authDigest.Realm.ToLower()) { credential = c; break; } } // We don't have credential for this challange. if (credential == null) { allAuthorized = false; } // Authorize challange. else { authDigest.UserName = credential.UserName; authDigest.Password = <PASSWORD>; authDigest.CNonce = Auth_HttpDigest.CreateNonce(); request.Authorization.Add(authDigest.ToAuthorization()); } } #endregion #region ProxyAuthenticate foreach (SIP_t_Challenge challange in response.ProxyAuthenticate.GetAllValues()) { Auth_HttpDigest authDigest = new Auth_HttpDigest(challange.AuthData, request.RequestLine.Method); // Serach credential for the specified challange. NetworkCredential credential = null; foreach (NetworkCredential c in credentials) { if (c.Domain.ToLower() == authDigest.Realm.ToLower()) { credential = c; break; } } // We don't have credential for this challange. if (credential == null) { allAuthorized = false; } // Authorize challange. else { authDigest.UserName = credential.UserName; authDigest.Password = <PASSWORD>; authDigest.CNonce = Auth_HttpDigest.CreateNonce(); request.ProxyAuthorization.Add(authDigest.ToAuthorization()); } } #endregion return allAuthorized; } /// <summary> /// Starts sending request to next hop in queue. /// </summary> /// <exception cref="InvalidOperationException">Is raised when no next hop available(m_pHops.Count == 0) and this method is accessed.</exception> private void SendToNextHop() { if (m_pHops.Count == 0) { throw new InvalidOperationException("No more hop(s)."); } SIP_Hop hop = m_pHops.Dequeue(); SendToFlow(m_pStack.TransportLayer.GetOrCreateFlow(hop.Transport, null, hop.EndPoint), m_pRequest.Copy()); } /// <summary> /// Sends specified request to the specified data flow. /// </summary> /// <param name="flow">SIP data flow.</param> /// <param name="request">SIP request to send.</param> /// <exception cref="ArgumentNullException">Is raised when <b>flow</b> or <b>request</b> is null reference.</exception> private void SendToFlow(SIP_Flow flow, SIP_Request request) { if (flow == null) { throw new ArgumentNullException("flow"); } if (request == null) { throw new ArgumentNullException("request"); } #region Contact (RFC 3261 8.1.1.8) /* The Contact header field provides a SIP or SIPS URI that can be used to contact that specific instance of the UA for subsequent requests. The Contact header field MUST be present and contain exactly one SIP or SIPS URI in any request that can result in the establishment of a dialog. For the methods defined in this specification, that includes only the INVITE request. For these requests, the scope of the Contact is global. That is, the Contact header field value contains the URI at which the UA would like to receive requests, and this URI MUST be valid even if used in subsequent requests outside of any dialogs. If the Request-URI or top Route header field value contains a SIPS URI, the Contact header field MUST contain a SIPS URI as well. */ SIP_t_ContactParam contact = request.Contact.GetTopMostValue(); // Add contact header If request-Method can establish dialog and contact header not present. if (SIP_Utils.MethodCanEstablishDialog(request.RequestLine.Method) && contact == null) { SIP_Uri from = (SIP_Uri) request.From.Address.Uri; request.Contact.Add((flow.IsSecure ? "sips:" : "sip:") + from.User + "@" + m_pStack.TransportLayer.GetContactHost(flow)); } // If contact SIP URI and host = auto-allocate, allocate it as needed. else if (contact != null && contact.Address.Uri is SIP_Uri && ((SIP_Uri) contact.Address.Uri).Host == "auto-allocate") { ((SIP_Uri) contact.Address.Uri).Host = m_pStack.TransportLayer.GetContactHost(flow).ToString(); } #endregion m_pTransaction = m_pStack.TransactionLayer.CreateClientTransaction(flow, request, true); m_pTransaction.ResponseReceived += ClientTransaction_ResponseReceived; m_pTransaction.TimedOut += ClientTransaction_TimedOut; m_pTransaction.TransportError += ClientTransaction_TransportError; // Start transaction processing. m_pTransaction.Start(); } /// <summary> /// Cleans up active transaction. /// </summary> private void CleanUpActiveTransaction() { if (m_pTransaction != null) { // Don't dispose transaction, transaction will dispose itself when done. // Otherwise for example failed INVITE won't linger in "Completed" state as it must be. // We just release Events processing, because you don't care about them any more. m_pTransaction.ResponseReceived -= ClientTransaction_ResponseReceived; m_pTransaction.TimedOut -= ClientTransaction_TimedOut; m_pTransaction.TransportError -= ClientTransaction_TransportError; m_pTransaction = null; } } /// <summary> /// Raises ResponseReceived event. /// </summary> /// <param name="response">SIP response received.</param> private void OnResponseReceived(SIP_Response response) { if (ResponseReceived != null) { ResponseReceived(this, new SIP_ResponseReceivedEventArgs(m_pStack, m_pTransaction, response)); } } /// <summary> /// Raises event <b>TransportError</b>. /// </summary> /// <param name="exception">Excption happened.</param> private void OnTransportError(Exception exception) { // TODO: } /// <summary> /// Raises event <b>Completed</b>. /// </summary> private void OnCompleted() { m_State = SIP_RequestSenderState.Completed; if (Completed != null) { Completed(this, new EventArgs()); } } /// <summary> /// Raises <b>Disposed</b> event. /// </summary> private void OnDisposed() { if (Disposed != null) { Disposed(this, new EventArgs()); } } #endregion #region Nested type: SIP_RequestSenderState private enum SIP_RequestSenderState { Initial, Starting, Started, Completed, Disposed } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/RTP/RTP_Participant_Remote.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.RTP { #region usings using System; using System.Text; #endregion /// <summary> /// Implements RTP <b>participant</b>. Defined in RFC 3550. /// </summary> public class RTP_Participant_Remote : RTP_Participant { #region Events /// <summary> /// Is raised when participant data changed. /// </summary> public event EventHandler<RTP_ParticipantEventArgs> Changed = null; #endregion #region Members private string m_Email; private string m_Location; private string m_Name; private string m_Note; private string m_Phone; private string m_Tool; #endregion #region Properties /// <summary> /// Gets the real name, eg. "<NAME>". Value null means not specified. /// </summary> public string Name { get { return m_Name; } } /// <summary> /// Gets email address. For example "<EMAIL>". Value null means not specified. /// </summary> public string Email { get { return m_Email; } } /// <summary> /// Gets phone number. For example "+1 908 555 1212". Value null means not specified. /// </summary> public string Phone { get { return m_Phone; } } /// <summary> /// Gets location string. It may be geographic address or for example chat room name. /// Value null means not specified. /// </summary> public string Location { get { return m_Location; } } /// <summary> /// Gets streaming application name/version. /// Value null means not specified. /// </summary> public string Tool { get { return m_Tool; } } /// <summary> /// Gets note text. The NOTE item is intended for transient messages describing the current state /// of the source, e.g., "on the phone, can't talk". Value null means not specified. /// </summary> public string Note { get { return m_Note; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="cname">Canonical name of participant. For example: <EMAIL>-randomTag.</param> /// <exception cref="ArgumentNullException">Is raised when <b>cname</b> is null reference.</exception> internal RTP_Participant_Remote(string cname) : base(cname) {} #endregion #region Methods /// <summary> /// Returns participant as string. /// </summary> /// <returns>Returns participant as string.</returns> public override string ToString() { StringBuilder retVal = new StringBuilder(); retVal.AppendLine("CNAME: " + CNAME); if (!string.IsNullOrEmpty(m_Name)) { retVal.AppendLine("Name: " + m_Name); } if (!string.IsNullOrEmpty(m_Email)) { retVal.AppendLine("Email: " + m_Email); } if (!string.IsNullOrEmpty(m_Phone)) { retVal.AppendLine("Phone: " + m_Phone); } if (!string.IsNullOrEmpty(m_Location)) { retVal.AppendLine("Location: " + m_Location); } if (!string.IsNullOrEmpty(m_Tool)) { retVal.AppendLine("Tool: " + m_Tool); } if (!string.IsNullOrEmpty(m_Note)) { retVal.AppendLine("Note: " + m_Note); } return retVal.ToString().TrimEnd(); } #endregion // TODO: PRIV #region Utility methods /// <summary> /// Raises <b>Changed</b> event. /// </summary> private void OnChanged() { if (Changed != null) { Changed(this, new RTP_ParticipantEventArgs(this)); } } #endregion #region Internal methods /// <summary> /// Updates participant data from SDES items. /// </summary> /// <param name="sdes">SDES chunk.</param> /// <exception cref="ArgumentNullException">Is raised when <b>sdes</b> is null reference value.</exception> internal void Update(RTCP_Packet_SDES_Chunk sdes) { if (sdes == null) { throw new ArgumentNullException("sdes"); } bool changed = false; if (!string.IsNullOrEmpty(sdes.Name) && !string.Equals(m_Name, sdes.Name)) { m_Name = sdes.Name; changed = true; } if (!string.IsNullOrEmpty(sdes.Email) && !string.Equals(m_Email, sdes.Email)) { m_Email = sdes.Email; changed = true; } if (!string.IsNullOrEmpty(sdes.Phone) && !string.Equals(Phone, sdes.Phone)) { m_Phone = sdes.Phone; changed = true; } if (!string.IsNullOrEmpty(sdes.Location) && !string.Equals(m_Location, sdes.Location)) { m_Location = sdes.Location; changed = true; } if (!string.IsNullOrEmpty(sdes.Tool) && !string.Equals(m_Tool, sdes.Tool)) { m_Tool = sdes.Tool; changed = true; } if (!string.IsNullOrEmpty(sdes.Note) && !string.Equals(m_Note, sdes.Note)) { m_Note = sdes.Note; changed = true; } if (changed) { OnChanged(); } } #endregion } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/SIP/Message/SIP_SingleValueHF.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.SIP.Message { #region usings using System; #endregion /// <summary> /// Implements single value header field. /// Used by header fields like To:,From:,CSeq:, ... . /// </summary> public class SIP_SingleValueHF<T> : SIP_HeaderField where T : SIP_t_Value { #region Members private T m_pValue; #endregion #region Properties /// <summary> /// Gets or sets header field value. /// </summary> public override string Value { get { return ToStringValue(); } set { if (value == null) { throw new ArgumentNullException("Property Value value may not be null !"); } Parse(new StringReader(value)); } } /// <summary> /// Gets or sets header field value. /// </summary> public T ValueX { get { return m_pValue; } set { m_pValue = value; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="name">Header field name.</param> /// <param name="value">Header field value.</param> public SIP_SingleValueHF(string name, T value) : base(name, "") { m_pValue = value; } #endregion #region Methods /// <summary> /// Parses single value from specified reader. /// </summary> /// <param name="reader">Reader what contains </param> public void Parse(StringReader reader) { m_pValue.Parse(reader); } /// <summary> /// Convert this to string value. /// </summary> /// <returns>Returns this as string value.</returns> public string ToStringValue() { return m_pValue.ToStringValue(); } #endregion // FIX ME: Change base class Value property or this to new name } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/IMAP/Server/IMAP_SearchMatcher.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.IMAP.Server { #region usings using System; using Mime; #endregion /// <summary> /// IMAP SEARCH message matcher. You can use this class to see if message values match to search criteria. /// </summary> public class IMAP_SearchMatcher { #region Members private readonly SearchGroup m_pSearchCriteria; #endregion #region Properties /// <summary> /// Gets if header is needed for matching. /// </summary> public bool IsHeaderNeeded { get { return m_pSearchCriteria.IsHeaderNeeded(); } } /// <summary> /// Gets if body text is needed for matching. /// </summary> public bool IsBodyTextNeeded { get { return m_pSearchCriteria.IsBodyTextNeeded(); } } #endregion #region Constructor /// <summary> /// Deault constuctor. /// </summary> /// <param name="mainSearchGroup">SEARCH command main search group.</param> internal IMAP_SearchMatcher(SearchGroup mainSearchGroup) { m_pSearchCriteria = mainSearchGroup; } #endregion #region Methods /// <summary> /// Gets if specified values match search criteria. /// </summary> /// <param name="no">Message sequence number.</param> /// <param name="uid">Message UID.</param> /// <param name="size">Message size in bytes.</param> /// <param name="internalDate">Message INTERNALDATE (dateTime when server stored message).</param> /// <param name="flags">Message flags.</param> /// <param name="header">Message header. This is only needed if this.IsHeaderNeeded is true.</param> /// <param name="bodyText">Message body text (must be decoded unicode text). This is only needed if this.IsBodyTextNeeded is true.</param> /// <returns></returns> public bool Matches(int no, int uid, int size, DateTime internalDate, IMAP_MessageFlags flags, string header, string bodyText) { // Parse header only if it's needed Mime m = null; if (m_pSearchCriteria.IsHeaderNeeded()) { m = new Mime(); m.MainEntity.Header.Parse(header); } return m_pSearchCriteria.Match(no, uid, size, internalDate, flags, m, bodyText); } #endregion } }<file_sep>/redistributable/ShrapBox/Src/AppLimit.CloudComputing.SharpBox/UI/Controler/FileSizeFormat.cs using System; namespace AppLimit.CloudComputing.SharpBox.UI { /// <summary> /// Class to generate file size formatted strings /// </summary> public class FileSizeFormat { /// <summary> /// Size unit /// </summary> public enum FileSizeUnit : long { /// <summary> /// Byte unit /// </summary> B = 1, /// <summary> /// Kilo bytes unit /// </summary> KB = 1024, /// <summary> /// Mega bytes unit /// </summary> MB = 1048576, /// <summary> /// giga bytes unit /// </summary> GB = 1073741824, /// <summary> /// Tera byes unit /// </summary> TB = 1099511627776 } /// <summary> /// Automatically format a size /// </summary> /// <param name="size">The size</param> /// <returns></returns> public static string Format(decimal size) { // return "Unknow" resource string if < 0 if (size < 0) return "N/A"; FileSizeUnit unit = FileSizeUnit.TB; // must be last item of FileSizeUnit enum for (decimal UnitSize = 1024; UnitSize <= (long)FileSizeUnit.TB; UnitSize *= 1024) { if (size < UnitSize) { unit = (FileSizeUnit)(long)(UnitSize / 1024); break; } } return FormatToUnit(size, unit); } /// <summary> /// Format a size to a specific unit /// </summary> /// <param name="size">The size</param> /// <param name="unit">The unit</param> /// <returns></returns> public static string FormatToUnit(decimal size, FileSizeUnit unit) { decimal sizeConverted = ConvertToUnit(size, unit); decimal sizeRounded = 0; if (unit == FileSizeUnit.KB) sizeRounded = Math.Round(sizeConverted, 0); else sizeRounded = Math.Round(sizeConverted, 2); return String.Format("{0} {1}", sizeRounded, unit); } /// <summary> /// Convert bytes to unit (KB or MB...) /// </summary> /// <param name="size">The size</param> /// <param name="unit">The unit</param> /// <returns></returns> public static decimal ConvertToUnit(decimal size, FileSizeUnit unit) { return size / (decimal)unit; } } } <file_sep>/web/studio/ASC.Web.Studio/UserControls/Common/Comments/CommentInfo.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections.Generic; using System.Runtime.Serialization; namespace ASC.Web.Studio.UserControls.Common.Comments { [DataContract] public class Attachment { [DataMember(Name = "FileName")] public string FileName { get; set; } [DataMember(Name = "FilePath")] public string FilePath { get; set; } } [DataContract] public class CommentInfo { [DataMember(Name = "commentID")] public string CommentID { get; set; } [DataMember(Name = "userID")] public Guid UserID { get; set; } [DataMember(Name = "userPost")] public string UserPost { get; set; } [DataMember(Name = "userFullName")] public string UserFullName { get; set; } [DataMember(Name = "userProfileLink")] public string UserProfileLink { get; set; } [DataMember(Name = "userAvatarPath")] public string UserAvatarPath { get; set; } [DataMember(Name = "commentBody")] public string CommentBody { get; set; } [DataMember(Name = "inactive")] public bool Inactive { get; set; } [DataMember(Name = "isRead")] public bool IsRead { get; set; } [DataMember(Name = "isEditPermissions")] public bool IsEditPermissions { get; set; } [DataMember(Name = "isResponsePermissions")] public bool IsResponsePermissions { get; set; } public DateTime TimeStamp { get; set; } [DataMember(Name = "timeStampStr")] public string TimeStampStr { get; set; } [DataMember(Name = "commentList")] public IList<CommentInfo> CommentList { get; set; } [DataMember(Name = "attachments")] public IList<Attachment> Attachments { get; set; } } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/MIME/MIME_b_Text.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.MIME { #region usings using System; using System.IO; using System.Text; using IO; #endregion /// <summary> /// This class represents MIME text/xxx bodies. Defined in RFC 2045. /// </summary> /// <remarks> /// The "text" media type is intended for sending material which is principally textual in form. /// </remarks> public class MIME_b_Text : MIME_b_SinglepartBase { #region Properties /// <summary> /// Gets body decoded text. /// </summary> /// <exception cref="ArgumentException">Is raised when not supported content-type charset or not supported content-transfer-encoding value.</exception> /// <exception cref="NotSupportedException">Is raised when body contains not supported Content-Transfer-Encoding.</exception> public string Text { get { return GetCharset().GetString(Data); } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="mediaType">MIME media type.</param> /// <exception cref="ArgumentNullException">Is raised when <b>mediaSubType</b> is null reference.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> public MIME_b_Text(string mediaType) : base(mediaType) {} #endregion #region Methods /// <summary> /// Sets text. /// </summary> /// <param name="transferEncoding">Content transfer encoding.</param> /// <param name="charset">Charset to use to encode text. If not sure, utf-8 is recommended.</param> /// <param name="text">Text.</param> /// <exception cref="ArgumentNullException">Is raised when <b>transferEncoding</b>, <b>charset</b> or <b>text</b> is null reference.</exception> /// <exception cref="NotSupportedException">Is raised when body contains not supported Content-Transfer-Encoding.</exception> public void SetText(string transferEncoding, Encoding charset, string text) { if (transferEncoding == null) { throw new ArgumentNullException("transferEncoding"); } if (charset == null) { throw new ArgumentNullException("charset"); } if (text == null) { throw new ArgumentNullException("text"); } SetEncodedData(transferEncoding, new MemoryStream(charset.GetBytes(text))); ContentType.Param_Charset = charset.WebName; } #endregion #region Utility methods /// <summary> /// Gets charset from Content-Type. If char set isn't specified, "ascii" is defined as default and it will be returned. /// </summary> /// <returns>Returns content charset.</returns> /// <exception cref="ArgumentException">Is raised when Content-Type has not supported charset parameter value.</exception> private Encoding GetCharset() { // RFC 2046 4.1.2. The default character set, US-ASCII. if (string.IsNullOrEmpty(ContentType.Param_Charset)) { return Encoding.ASCII; } else { return EncodingTools.GetEncodingByCodepageName(ContentType.Param_Charset) ?? Encoding.ASCII; } } #endregion /// <summary> /// Parses body from the specified stream /// </summary> /// <param name="owner">Owner MIME entity.</param> /// <param name="mediaType">MIME media type. For example: text/plain.</param> /// <param name="stream">Stream from where to read body.</param> /// <returns>Returns parsed body.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>stream</b>, <b>mediaType</b> or <b>stream</b> is null reference.</exception> /// <exception cref="ParseException">Is raised when any parsing errors.</exception> protected new static MIME_b Parse(MIME_Entity owner, string mediaType, SmartStream stream) { if (owner == null) { throw new ArgumentNullException("owner"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } if (stream == null) { throw new ArgumentNullException("stream"); } MIME_b_Text retVal = new MIME_b_Text(mediaType); Net_Utils.StreamCopy(stream, retVal.EncodedStream, Workaround.Definitions.MaxStreamLineLength); return retVal; } } }<file_sep>/web/studio/ASC.Web.Studio/Products/CRM/Warmup.aspx.cs  using System.Collections.Generic; using ASC.Web.Core; namespace ASC.Web.CRM { public partial class Warmup : WarmupPage { protected override List<string> Exclude { get { return new List<string>(1) { "Reports.aspx", "Cases.aspx", "Calls.aspx", "MailViewer.aspx" }; } } } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/POP3/Server/GetMessagesInfo_EventArgs.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.POP3.Server { /// <summary> /// Provides data for the GetMessgesList event. /// </summary> public class GetMessagesInfo_EventArgs { #region Members private readonly POP3_MessageCollection m_pPOP3_Messages; private readonly POP3_Session m_pSession; private readonly string m_UserName = ""; #endregion #region Properties /// <summary> /// Gets reference to pop3 session. /// </summary> public POP3_Session Session { get { return m_pSession; } } /// <summary> /// Gets referance to POP3 messages info. /// </summary> public POP3_MessageCollection Messages { get { return m_pPOP3_Messages; } } /// <summary> /// User Name. /// </summary> public string UserName { get { return m_UserName; } } /// <summary> /// Mailbox name. /// </summary> public string Mailbox { get { return m_UserName; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="session">Reference to pop3 session.</param> /// <param name="messages"></param> /// <param name="mailbox">Mailbox name.</param> public GetMessagesInfo_EventArgs(POP3_Session session, POP3_MessageCollection messages, string mailbox) { m_pSession = session; m_pPOP3_Messages = messages; m_UserName = mailbox; } #endregion } }<file_sep>/common/ASC.Core.Common/Billing/ITariffSyncService.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System.Collections.Generic; using System.ServiceModel; using ASC.Core.Tenants; namespace ASC.Core.Billing { [ServiceContract] public interface ITariffSyncService { [OperationContract] IEnumerable<TenantQuota> GetTariffs(int version, string key); } } <file_sep>/module/ASC.AuditTrail/LoginEventsRepository.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections.Generic; using ASC.AuditTrail.Mappers; using ASC.Common.Data; using ASC.Common.Data.Sql; using System.Linq; using ASC.Common.Data.Sql.Expressions; using ASC.Core.Tenants; using ASC.Core.Users; using Newtonsoft.Json; namespace ASC.AuditTrail.Data { public class LoginEventsRepository { private const string auditDbId = "core"; private static readonly List<string> auditColumns = new List<string> { "id", "ip", "login", "browser", "platform", "date", "tenant_id", "user_id", "page", "action", "description" }; public static IEnumerable<LoginEvent> GetLast(int tenant, int chunk) { var q = new SqlQuery("login_events au") .Select(auditColumns.Select(x => "au." + x).ToArray()) .LeftOuterJoin("core_user u", Exp.EqColumns("au.user_id", "u.id")) .Select("u.firstname", "u.lastname") .Where("au.tenant_id", tenant) .OrderBy("au.date", false) .SetMaxResults(chunk); using (var db = new DbManager(auditDbId)) { return db.ExecuteList(q).Select(ToLoginEvent).Where(x => x != null); } } public static IEnumerable<LoginEvent> Get(int tenant, DateTime from, DateTime to) { var q = new SqlQuery("login_events au") .Select(auditColumns.Select(x => "au." + x).ToArray()) .LeftOuterJoin("core_user u", Exp.EqColumns("au.user_id", "u.id")) .Select("u.firstname", "u.lastname") .Where("au.tenant_id", tenant) .Where(Exp.Between("au.date", from, to)) .OrderBy("au.date", false); using (var db = new DbManager(auditDbId)) { return db.ExecuteList(q).Select(ToLoginEvent).Where(x => x != null); } } public static int GetCount(int tenant, DateTime? from = null, DateTime? to = null) { var q = new SqlQuery("login_events") .SelectCount() .Where("tenant_id", tenant); if (from.HasValue && to.HasValue) { q.Where(Exp.Between("date", from.Value, to.Value)); } using (var db = new DbManager(auditDbId)) { return db.ExecuteScalar<int>(q); } } private static LoginEvent ToLoginEvent(object[] row) { try { var evt = new LoginEvent { Id = Convert.ToInt32(row[0]), IP = Convert.ToString(row[1]), Login = Convert.ToString(row[2]), Browser = Convert.ToString(row[3]), Platform = Convert.ToString(row[4]), Date = TenantUtil.DateTimeFromUtc(Convert.ToDateTime(row[5])), TenantId = Convert.ToInt32(row[6]), UserId = Guid.Parse(Convert.ToString(row[7])), Page = Convert.ToString(row[8]), Action = Convert.ToInt32(row[9]) }; if (row[10] != null) { evt.Description = JsonConvert.DeserializeObject<IList<string>>( Convert.ToString(row[10]), new JsonSerializerSettings { DateTimeZoneHandling = DateTimeZoneHandling.Utc }); } evt.UserName = (row[11] != null && row[12] != null) ? UserFormatter.GetUserName(Convert.ToString(row[11]), Convert.ToString(row[12])) : !string.IsNullOrWhiteSpace(evt.Login) ? evt.Login : evt.UserId == Core.Configuration.Constants.Guest.ID ? AuditReportResource.GuestAccount : AuditReportResource.UnknownAccount; evt.ActionText = AuditActionMapper.GetActionText(evt); return evt; } catch(Exception) { //log.Error("Error while forming event from db: " + ex); return null; } } } }<file_sep>/module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/SIP/Proxy/SIP_RegistrationBinding.cs /* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.SIP.Proxy { #region usings using System; using Message; using Stack; #endregion /// <summary> /// This class represents SIP registrar registration binding entry. Defined in RFC 3261 10.3. /// </summary> public class SIP_RegistrationBinding : IComparable { #region Members private readonly AbsoluteUri m_ContactURI; private readonly SIP_Registration m_pRegistration; private string m_CallID = ""; private int m_CSeqNo = 1; private int m_Expires = 3600; private DateTime m_LastUpdate; private SIP_Flow m_pFlow; private double m_QValue = 1.0; #endregion #region Properties /// <summary> /// Gets the last time when the binding was updated. /// </summary> public DateTime LastUpdate { get { return m_LastUpdate; } } /// <summary> /// Gets if binding has expired. /// </summary> public bool IsExpired { get { return TTL <= 0; } } /// <summary> /// Gets how many seconds binding has time to live. This is live calulated value, so it decreases every second. /// </summary> public int TTL { get { if (DateTime.Now > m_LastUpdate.AddSeconds(m_Expires)) { return 0; } else { return (int) ((m_LastUpdate.AddSeconds(m_Expires) - DateTime.Now)).TotalSeconds; } } } /// <summary> /// Gets data flow what added this binding. This value is null if binding was not added through network or /// flow has disposed. /// </summary> public SIP_Flow Flow { get { return m_pFlow; } } /// <summary> /// Gets contact URI what can be used to contact the registration. /// </summary> public AbsoluteUri ContactURI { get { return m_ContactURI; } } /// <summary> /// Gets binding priority. Higher value means greater priority. /// </summary> public double QValue { get { return m_QValue; } } /// <summary> /// Gets Call-ID header field value which added this binding. /// </summary> public string CallID { get { return m_CallID; } } /// <summary> /// Gets CSeq header field sequence number value which added this binding. /// </summary> public int CSeqNo { get { return m_CSeqNo; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="owner">Owner registration.</param> /// <param name="contactUri">Contact URI what can be used to contact the registration.</param> /// <exception cref="ArgumentNullException">Is raised when <b>owner</b> or <b>contactUri</b> is null reference.</exception> internal SIP_RegistrationBinding(SIP_Registration owner, AbsoluteUri contactUri) { if (owner == null) { throw new ArgumentNullException("owner"); } if (contactUri == null) { throw new ArgumentNullException("contactUri"); } m_pRegistration = owner; m_ContactURI = contactUri; } #endregion #region Methods /// <summary> /// Updates specified binding. /// </summary> /// <param name="flow">SIP data flow what updates this binding. This value is null if binding was not added through network or /// flow has disposed.</param> /// <param name="expires">Time in seconds when binding will expire.</param> /// <param name="qvalue">Binding priority. Higher value means greater priority.</param> /// <param name="callID">Call-ID header field value which added/updated this binding.</param> /// <param name="cseqNo">CSeq header field sequence number value which added/updated this binding.</param> public void Update(SIP_Flow flow, int expires, double qvalue, string callID, int cseqNo) { if (expires < 0) { throw new ArgumentException("Argument 'expires' value must be >= 0."); } if (qvalue < 0 || qvalue > 1) { throw new ArgumentException("Argument 'qvalue' value must be >= 0.000 and <= 1.000"); } if (callID == null) { throw new ArgumentNullException("callID"); } if (cseqNo < 0) { throw new ArgumentException("Argument 'cseqNo' value must be >= 0."); } m_pFlow = flow; m_Expires = expires; m_QValue = qvalue; m_CallID = callID; m_CSeqNo = cseqNo; m_LastUpdate = DateTime.Now; } /// <summary> /// Removes this binding from the registration. /// </summary> public void Remove() { m_pRegistration.RemoveBinding(this); } /// <summary> /// Converts <b>ContactUri</b> to valid Contact header value. /// </summary> /// <returns>Returns contact header value.</returns> public string ToContactValue() { SIP_t_ContactParam retVal = new SIP_t_ContactParam(); retVal.Parse(new StringReader(m_ContactURI.ToString())); retVal.Expires = m_Expires; return retVal.ToStringValue(); } /// <summary> /// Compares the current instance with another object of the same type. /// </summary> /// <param name="obj">An object to compare with this instance.</param> /// <returns>Returns 0 if two objects equal, -1 if this instance is less or 1 this instance is greater.</returns> public int CompareTo(object obj) { if (obj == null) { return -1; } if (!(obj is SIP_RegistrationBinding)) { return -1; } // We must reverse values, because greater value mean higer priority. SIP_RegistrationBinding compareValue = (SIP_RegistrationBinding) obj; if (compareValue.QValue == QValue) { return 0; } else if (compareValue.QValue > QValue) { return 1; } else if (compareValue.QValue < QValue) { return -1; } return -1; } #endregion } }
4873fc1fa0d23aab167e4894a03b776bed859032
[ "JavaScript", "C#", "Ruby", "Markdown" ]
500
C#
Ektai-Solution-Pty-Ltd/CommunityServer
88b4e0b6cbddb43cfda2fe9bcbfeca7fc1c681bc
ef3f9b75f71bb5daffea1a9b31c34e5a6b8098b8
refs/heads/main
<repo_name>MattisKarlsson/MasterVaccinator<file_sep>/src/Com/Massvaccination/Sleep.java package Com.Massvaccination; public class Sleep { public Sleep(int time) { try { Thread.sleep(time); } catch (Exception e) { } } } <file_sep>/src/Com/Massvaccination/Vaccine.java package Com.Massvaccination; import java.util.Random; class Vaccine { Issues issues = new Issues(); // Import Issues int afterLosses; public Vaccine() { Random random = new Random(); int randomAmount = random.nextInt(220000-60000)+60000; // Random amount between 220000 - 60000: +60000 sets the lowest amount. int lostAmount = (int) (Math.random() * 10000); // Random amount lost up to 10000 afterLosses = randomAmount - lostAmount; // Final number Display.vaccine(randomAmount, lostAmount, afterLosses, issues.displayIssue); // Call on Method vaccine in class Display with arguments. } }<file_sep>/src/Com/Massvaccination/Country.java package Com.Massvaccination; // Class to declare varibles and call on Display.countryInfo with args class Country { public int population; public String name; public void printInfo(){ Display.countryInfo(name, population); }} // Following classes to extend and store info per country. class Sweden extends Country{ public Sweden(){ super.population = 10_300_000; super.name = "Sweden"; } } class Denmark extends Country { public Denmark() { super.population = 5_806_000; super.name = "Denmark"; } } class Norway extends Country{ public Norway() { this.population = 5_385_000; this.name = "Norway"; } } class Finland extends Country { public Finland() { this.population = 5_545_000; this.name = "Finland"; } }
55e362a42205636c0c35f7ba4f58390cbeea99a7
[ "Java" ]
3
Java
MattisKarlsson/MasterVaccinator
9fe893a3970704143d61dd1386a78b4033df562b
e21518cca4901aace8aa93ebb9056f31f2a81808
refs/heads/master
<repo_name>mohnaufalp2000/Membuat-Aplikasi-Hitung-Umur<file_sep>/app/src/main/java/com/example/aplikasihitungumur/MainActivity.kt package com.example.aplikasihitungumur import android.app.DatePickerDialog import android.os.Build import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Toast import androidx.annotation.RequiresApi import kotlinx.android.synthetic.main.activity_main.* import org.joda.time.PeriodType import java.text.ParseException import java.text.SimpleDateFormat import java.util.* class MainActivity : AppCompatActivity() { @RequiresApi(Build.VERSION_CODES.O) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val c = Calendar.getInstance() val year = c.get(Calendar.YEAR) val month = c.get(Calendar.MONTH) val day = c.get(Calendar.DAY_OF_MONTH) date_birth.setOnClickListener { val date = DatePickerDialog(this, DatePickerDialog.OnDateSetListener { view, year, month, dayOfMonth -> date_birth.setText("" + dayOfMonth + "/" + month + "/" + year) }, year, month, day) date.show() } date_now.setOnClickListener { val date = DatePickerDialog(this, DatePickerDialog.OnDateSetListener { view, year, month, dayOfMonth -> date_now.setText("" + dayOfMonth + "/" + month + "/" + year) }, year, month, day) date.show() } calculate.setOnClickListener { val sDate = date_birth.text.toString() val eDate = date_now.text.toString() val format = SimpleDateFormat("dd/MM/yyyy") try { val date1 = format.parse(sDate) val date2 = format.parse(eDate) val startDate : Long = date1.time val endDate : Long = date2.time if (startDate<=endDate){ val period = org.joda.time.Period(startDate, endDate, PeriodType.yearMonthDay()) val years = period.years val months = period.months val days = period.days Hasil.setText("${years} Years ${months} Months ${days} Days ") } else{ Toast.makeText(applicationContext, "Salah Lurr", Toast.LENGTH_LONG).show() } } catch (e : ParseException){ e.printStackTrace() } } } }
ff0865805317a99ff90394518d36383ae8a27f07
[ "Kotlin" ]
1
Kotlin
mohnaufalp2000/Membuat-Aplikasi-Hitung-Umur
0bdbf29284f0fa33ca7dd100f9c255f4130b5e15
65007ffaec16255572ba0e89ee04305b67ad375b
refs/heads/master
<repo_name>jmg1478/GiphyWebsite<file_sep>/java/script.js const GIPHY_API_KEY = '<KEY>'; const searchCache = {}; const buildImageTags = (search) => { return searchCache[search].map(url => `<img src="${url}" /><br/>`) } // ================================================================================ function setGifs(searchVal) { document.getElementById('gifs').innerHTML = buildImageTags(searchVal); } function searchGifs() { const searchVal = document.getElementById('searchGifs').value; if (!searchVal) { return alert('you need to enter some searchy things'); } console.log(`going to start a search for: ${searchVal}`); fetch(`https://api.giphy.com/v1/gifs/search?q=${encodeURI(searchVal)}&api_key=${GIPHY_API_KEY}&limit=10`) .then(resp => resp.json()) .then(data => { const gifs = data.data; console.log('we got gifs', gifs); if (gifs.length > 0) { const firstGif = gifs.find(el => el.type === 'gif'); const imageUrl = firstGif.images.original.url; // pull out the image url and add it to the cache for future use! const urlsOnly = gifs.filter(gif => gif.type === 'gif').map(el => el.images.original.url); searchCache[searchVal] = urlsOnly; setGifs(searchVal); const searchHistory = document.getElementById('searchHistory'); const setImageButton = document.createElement("button"); setImageButton.innerText = `${searchVal}`; setImageButton.type = "button"; setImageButton.onclick = () => setGifs(`${searchVal}`); console.log('append button', setImageButton); searchHistory.appendChild(setImageButton); } }) .catch(err => console.log('oh no, an error happened', err)); };
7ac1f8081437830b5e112dfe493e8b604664322d
[ "JavaScript" ]
1
JavaScript
jmg1478/GiphyWebsite
5491bbae6999fb6d278d122e16228d307afa72d3
4555996897d0c8be57c4e2e7559c15ff6431d9e1
refs/heads/master
<file_sep>var weponApp = Vue.extend({}); var router = new VueRouter(); router.map({ "/list": { component: ListComponent }, "/detail/:id": { component: DetailComponent, name: "detail" } }); router.start(weponApp, "#wepon-app"); <file_sep>var ViewOptions = Vue.extend({ template: "#view-options", data: function() { return { option: new ViewOption(), view: true } }, methods: { reflectParent: function() { this.$emit("change-setting", this.option); }, toggle: function() { this.view = !this.view; } } }); Vue.component("view-options", ViewOptions); <file_sep>var Extractor = Vue.extend({ template: "#extractor", data: function() { return { condition: new FilterOption(), sort: { key: "name", order: 1 } }; }, computed: { items: function() { return this.condition.extractFrom(this.results); } }, props: { results: { type: Array, required: true }, viewOption: { type: ViewOption, required: true } }, methods: { changeOrder: function(key) { if (this.sort.key == key) { this.sort.order *= -1; } else { this.sort.key = key; this.sort.order = 1; } } }, filters: { convertGender: function(value) { if (value === 1) { return "男"; } if (value === 2) { return "女"; } return "両"; }, convertType: function(value) { if (value === 1) { return "剣士"; } if (value === 2) { return "ガンナー"; } return "両方"; }, convertTiming: function(value) { if (value == 99) { return "入手不可"; } return "★" + value; } } }); Vue.component("extractor", Extractor); <file_sep>var DetailComponent = Vue.extend({ template: "#wepon-detail", data: function() { return { wepon: {}, graph: null }; }, ready: function() { this.wepon = wepons.get(this.$route.params.id); var graphData = { labels: [ "射程", "火力", "連射" ], datasets: [ { data: [this.wepon.range, this.wepon.fire, this.wepon.rapid ] } ] }; var context = document.getElementById("wepon-graph").getContext("2d"); this.graph = new Chart(context).Radar(graphData); } }); <file_sep>var Equipment = function(csvArray) { this.index = 0; this.name = csvArray[this.index++]; this.gender = Number(csvArray[this.index++]); this.type = Number(csvArray[this.index++]); this.rare = Number(csvArray[this.index++]); this.slot = Number(csvArray[this.index++]), this.timing = { village: Number(csvArray[this.index++]), rally: Number(csvArray[this.index++]) }; this.difense = { min: Number(csvArray[this.index++]), max: Number(csvArray[this.index++]) }; this.registance = { fire: Number(csvArray[this.index++]), water: Number(csvArray[this.index++]), thunder: Number(csvArray[this.index++]), ice: Number(csvArray[this.index++]), dragon: Number(csvArray[this.index++]) }; this.skills = [ { name: csvArray[this.index++], value: Number(csvArray[this.index++]) || null }, { name: csvArray[this.index++], value: Number(csvArray[this.index++]) || null }, { name: csvArray[this.index++], value: Number(csvArray[this.index++]) || null }, { name: csvArray[this.index++], value: Number(csvArray[this.index++]) || null }, { name: csvArray[this.index++], value: Number(csvArray[this.index++]) || null } ]; this.materials = [ { name: csvArray[this.index++], count: Number(csvArray[this.index++]) || null }, { name: csvArray[this.index++], count: Number(csvArray[this.index++]) || null }, { name: csvArray[this.index++], count: Number(csvArray[this.index++]) || null }, { name: csvArray[this.index++], count: Number(csvArray[this.index++]) || null }, { name: csvArray[this.index++], count: Number(csvArray[this.index++]) || null } ] }; <file_sep>var ListComponent = Vue.extend({ template: "#wepon-list", data: function() { return { results: [] }; }, ready: function() { this.results = wepons.list(); } }); <file_sep>var MusicList = Vue.extend({ template: "#music-list-component", data: function() { return { model: { musicListData: [], playListId: null }, style: { view: false } }; }, methods: { create: function() { this.$emit("request-create", this.model.playListId); }, edit: function(paramId) { this.$emit("request-edit", { playListId: this.model.playListId, musicId: paramId }); }, remove: function(paramId) { this.$emit("request-delete", paramId); } }, events: { openMusicList: function(paramId) { this.$set("model.musicListData", musicData.getByPlayListId(paramId)); this.style.view = true; this.model.playListId = paramId; }, refleshMusicList: function() { this.$set("model.musicListData", musicData.getByPlayListId(this.model.playListId)); return; } } }); Vue.component("music-list", MusicList); <file_sep>var Wepon = function(param) { this.id = null; this.name = param.name; this.price = param.price; this.range = param.range; this.attack = param.attack; this.rapid = param.rapid; this.sub = param.sub; this.special = param.special; this.note = note; }; var WeponList = function() { this.seq = 1; this.data = []; }; WeponList.prototype = { add: function(wepon) { wepon.id = this.seq; this.seq++; this.data.push(wepon); }, list: function() { var results = []; var that = this; this.data.forEach(function(item) { results.push(that._createResult(item)); }); return results; }, get: function(id) { var results = this.data.filter(function(item) { return item.id == id; }); return results[0]; }, _createResult: function(item) { return { id: Number(item.id), name: String(item.name), price: Number(item.price), range: Number(item.range), fire: Number(item.fire), rapid: Number(item.rapid), sub: String(item.sub), special: String(item.special), note: String(item.note) }; } }; // データについてはhttp://ahbj.game-cmr.com/splatoon/data/wepon/index.htmlから // 参照させていただきました var wepons = new WeponList(); wepons.add({ name :"わかばシューター", price: null, range: 6, fire: 6, rapid:15, sub: "スプラッシュボム", special:"バリア", note:"初期" }); wepons.add({ name :"スプラシューター", price: 500, range: 10, fire: 9, rapid:11, sub: "クイックボム", special:"ボムラッシュ", note:"ランク2" }); wepons.add({ name :"プライムシューター", price: 8000, range: 14, fire: 11, rapid:8, sub: "スプラッシュボム", special:"トルネード", note:"ランク10" }); wepons.add({ name :".52ガロン", price: 3000, range: 10, fire: 14, rapid:6, sub: "スプラッシュシールド", special:"メガホンレーザー", note:"ランク5" }); wepons.add({ name :".96ガロン", price: 7600, range: 14, fire: 16, rapid:3, sub: "スプリンクラー", special:"スーパーセンサー", note:"ランク12" }); wepons.add({ name :"プロモデラーMG", price: 4500, range: 6, fire: 4, rapid:20, sub: "チェイスボム", special:"スーパーショット", note:"設計図:ランク7" }); <file_sep>var CsvLoader = Vue.extend({ template: "#csv-loader", data: function() { return { csvValues: "", view: true }; }, methods: { load: function() { var result = []; if (this.csvValues == null && this.csvValue == "") { return result; } var lines = this.csvValues.split(/\r\n|\r|\n/); lines.forEach(function(row) { result.push(new Equipment(row.split(","))); }); this.$emit("load-result", result); }, toggle:function() { this.view = !this.view; } } }); Vue.component("csv-loader", CsvLoader); <file_sep>var FilterCommand = function(exec) { this.exec = exec; }; var FilterOption = function() { this.name = null; this.gender = ""; this.type = ""; this.rare = null; this.slot = null; this.timing = { village: "", rally: "" }; this.difense = { min: null, max: null }; this.registance = { fire: null, water: null, thunder: null, ice: null, dragon: null }; this.skills = null; this.materials = null; }; FilterOption.prototype = { extractFrom: function(item) { var filterFunc = this._createFilters(); return item.filter(filterFunc); }, _createFilters: function() { var filters = []; for (var propKey in this) { var value = this[propKey]; if (typeof value == "function") { continue; } if (value == null || value == "") { continue; } switch(propKey) { case "rare": case "slot": filters.push(this._createNumericFunc(propKey, value)); break; case "timing": if (value.rally != null && value.rally != "") { var searchRally = value.rally; var searchFunc = this._createNumericSearch(searchRally); filters.push(new FilterCommand(function(item) { return searchFunc(item.timing.rally); })); } if (value.village != null && value.village != "") { var searchVillage = value.village; var searchFunc = this._createNumericSearch(searchVillage); filters.push(new FilterCommand(function(item) { return searchFunc(item.timing.village); })); } break; case "difense": if (value.min != null && value.min != "") { var searchMin = value.min; var searchFunc = this._createNumericSearch(searchMin); filters.push(new FilterCommand(function(item) { return searchFunc(item.difense.min); })); } if (value.max != null && value.max != "") { var searchMax = value.max; var searchFunc = this._createNumericSearch(searchMax); filters.push(new FilterCommand(function(item) { return searchFunc(item.difense.max); })); } break; case "registance": if (value.fire != null && value.fire != "") { var searchFire = value.fire; var searchFunc = this._createNumericSearch(searchFire); filters.push(new FilterCommand(function(item) { return searchFunc(item.registance.fire); })); } if (value.water != null && value.water != "") { var searchWater = value.water; var searchFunc = this._createNumericSearch(searchWater); filters.push(new FilterCommand(function(item) { return searchFunc(item.registance.water); })); } if (value.thunder != null && value.thunder != "") { var searchThunder = value.thunder; var searchFunc = this._createNumericSearch(searchThunder); filters.push(new FilterCommand(function(item) { return searchFunc(item.registance.thunder); })); } if (value.ice != null && value.ice != "") { var searchIce = value.ice; var searchFunc = this._createNumericSearch(searchIce); filters.push(new FilterCommand(function(item) { return searchFunc(item.registance.ice); })); } if (value.dragon != null && value.dragon != "") { var searchDragon = value.dragon; var searchFunc = this._createNumericSearch(searchDragon); filters.push(new FilterCommand(function(item) { return searchFunc(item.registance.dragono); })); } break; case "skills": var isMatchKey = (0 <= value.indexOf("name:")); var isMatchValue = (0 <= value.indexOf("value:")); var isNameValueSearch = false; var searchName = null; var searchValue = null; if (isMatchValue && isMatchKey) { var values = value.split(" "); for (var i = 0; i < values.length; i++) { var splitValue = values[i]; if (splitValue.indexOf("name:") == 0) { searchName = splitValue.split("name:")[1]; } if (splitValue.indexOf("value:") == 0) { searchValue = splitValue.split("value:")[1]; } } isNameValueSearch = ( (searchName != null) && (searchValue != null) ); } if (isNameValueSearch) { var searchFunc = this._createNumericSearch(searchValue); filters.push(new FilterCommand(function(item) { var skills = item.skills; for (var i = 0; i < skills.length; i++) { var skill = skills[i]; if (skill.name != searchName) { continue; } if (searchFunc(skill.value)) { return true; } } return false; })); } else { filters.push(this._createBasicFilter(propKey, value)); } break; default: filters.push(this._createBasicFilter(propKey, value)); break; } } return function(item) { for (var i = 0; i < filters.length; i++) { if (!filters[i].exec(item)) { return false; }; } return true; }; }, _createBasicFilter: function(key, value) { var data = new FilterCommand(function(item) { var itemValue = item[this.key] if (itemValue == null || itemValue === "") { return false } return (-1 < String(itemValue).indexOf(this.value)); }); data.key = key; data.value = value; return data; }, _createNumericFunc: function(key, value) { var that = this; var data = new FilterCommand(function(item) { var itemValue = item[this.key] if (itemValue == null || itemValue === "") { return false } var searchFunc = that._createNumericSearch(value); return searchFunc(itemValue); }); data.key = key; data.value = value; return data; }, _createNumericSearch: function(value) { var filterFunc = null; if (-1 < value.search("<=")) { return function(itemValue) { return itemValue <= Number(value.slice(2)); }; } if (-1 < value.search(">=")) { return function(itemValue) { return itemValue >= Number(value.slice(2)); }; } if (-1 < value.search("<")) { return function(itemValue) { return itemValue < Number(value.slice(1)); }; } if (-1 < value.search(">")) { return function(itemValue) { return itemValue > Number(value.slice(1)); }; } return function(itemValue) { return itemValue == value; } } } <file_sep>var PlayList = Vue.extend({ template: "#play-list-component", data:function() { return { playListData: [] }; }, ready: function() { this.playListData = playListData.getAll(); }, methods: { select: function(paramId) { this.$emit("request-select", paramId); }, create: function() { this.$emit("request-create"); }, edit: function(paramPlayListId) { this.$emit("request-edit", paramPlayListId); }, remove: function(paramPlayListId) { this.$emit("request-delete", paramPlayListId); } } }); Vue.component("play-list", PlayList); <file_sep>var musicData = { data: [], sequence: 1, addTestData: function(playListId) { this.data.push({ musicId: this.sequence, playListId: playListId, name: "音楽" + this.sequence }); var current = this.sequence; this.sequence++; return current; }, add: function(musicItem) { this.data.push({ musicId: this.sequence, playListId: musicItem.playListId, name: musicItem.name }); this.sequence++; }, update: function(updateItem) { for (var i = 0; i < this.data.length; i++) { var targetData = this.data[i]; if (targetData.musicId == updateItem.musicId) { targetData.name = updateItem.name; } } }, delete: function(paramId) { var targetIndex = null for (var i = 0; i < this.data.length; i++) { if (this.data[i].musicId == paramId ) { targetIndex = i; break; } } if (targetIndex != null) { this.data.splice(targetIndex, 1); } }, getById: function(paramId) { for (var i = 0; i < this.data.length; i++) { var targetData = this.data[i]; if (targetData.musicId == paramId ) { return targetData; } } return null; }, getByPlayListId: function(id) { return this.data.filter(function(v) { return v.playListId == id }); } }; <file_sep>var MusicModal = Vue.extend({ template: "#music-list-modal", data: function() { return { style: { view: false }, model: { musicId: null, playListId: null, name: null }, option: { editMode: false } }; }, methods: { save: function() { if (this.option.editMode == true) { musicData.update( { playListId: this.model.playListId, musicId: this.model.musicId, name : this.model.name } ); } else { musicData.add( { playListId: this.model.playListId, name : this.model.name } ); } this.close(); this.$emit("finish-save"); }, open: function(openParam) { this.style.view = true; this.model.musicId = openParam.musicId || 0; this.model.playListId = openParam.playListId || 0; var targetMusic = null; if (openParam.musicId != null) { targetMusic = musicData.getById(openParam.musicId); } if (targetMusic != null) { this.model.name = targetMusic.name; } else { this.model.name = null; } this.option.editMode = openParam.editMode || false; }, close: function() { this.model.musicId = null; this.model.playListId = null; this.model.name = null; this.style.view = false; } }, events: { openMusicModal: function(openParam) { this.open(openParam); return false; } } }); Vue.component("music-modal", MusicModal); <file_sep>var playListData = { data: [], sequence: 1, addTestData: function() { this.data.push({ id: this.sequence, name: "プレイリスト" + this.sequence, }); var current = this.sequence; this.sequence++; return current; }, add: function(playListItem) { this.data.push({ id: this.sequence, name: playListItem.name }); this.sequence++; }, update: function(updateItem) { for (var i = 0; i < this.data.length; i++) { var targetData = this.data[i]; if (targetData.id == updateItem.id) { targetData.name = updateItem.name; } } }, delete: function(paramId) { var targetIndex = null for (var i = 0; i < this.data.length; i++) { if (this.data[i].id == paramId ) { targetIndex = i; break; } } if (targetIndex != null) { this.data.splice(targetIndex, 1); } }, getAll: function() { return this.data; }, getById: function(paramId) { for (var i = 0; i < this.data.length; i++) { var targetData = this.data[i]; if (targetData.id == paramId ) { return targetData; } } return null; } };
76e983397c7931776fbbc82b66eb68ef444901cd
[ "JavaScript" ]
14
JavaScript
gloryof/VuePractice
096f9563e9af03d9a8473b41f40ac67e874ec737
8704924ef877211d49fc9830f7def78b1111c934
refs/heads/master
<file_sep># Node Food Order App Contributed to Gesto Hungry Hacker Challenge. A Node app built with MongoDB and Angular. Node provides the RESTful API. Angular provides the front end and accesses the API. MongoDB stores client orders. ## Required [node and npm] (http://nodejs.org) [mongodb] (https://www.mongodb.org/) ## Optional [git] (https://github.com/) [atom] (https://atom.io/) [json formatter] (http://jsonlint.com/) [curl] (https://curl.haxx.se/) [postman] (https://www.getpostman.com/) [mongobooster] (http://mongobooster.com/) ## Installation 1. Clone the repository: `git clone https://github.com/Tomoya32/Food-OrderApp.git` 2. Install the application: `npm install` 3. Start local MongoDB instance (e.g. For OSX use command: `mongod` in terminal to start it) 4. Start the server: `node server.js` 5. View in browser at `http://localhost:8080` ## API Documentation HTTP Verb URL Description GET /api/food Get all of the food items in the order POST /api/food Create a single food item DELETE /api/food/:food_id Delete a single food item ## Credits This app is inspired by Node Todo App "https://github.com/scotch-io/node-todo" <file_sep>angular.module('orderController', []) // inject the Order service factory into our controller .controller('mainController', ['$scope','$http','Orders', function($scope, $http, Orders) { $scope.formData = {}; $scope.loading = true; var menu = { 'foodList': [{ 'name': 'Buffalo Barb Championship Wing Sauce', 'price': '8.49' }, { 'name': 'Home-Grown Guacamole', 'price': '4.99' }, { 'name': 'Famous Barbecue Chicken', 'price': '6.99' }, { 'name': '<NAME>ger', 'price': '7.69' }, { 'name': 'Blushing Maine Lobster Cakes', 'price': '9.89' }, { 'name': 'Garlic Seafood Soup', 'price': '4.79' }, { 'name': 'Original Banana Split', 'price': '3.49' }, { 'name': 'Chocolate Crème Brulee with Blackberries', 'price': '5.49' }], 'valueSelected': { 'name': 'Famous Barbecue Chicken', 'price': '6.99' } } $scope.selectedValue = menu['valueSelected']; $scope.foodList = menu['foodList']; // GET ===================================================================== // when landing on the page, get all orders and show them // use the service to get all the orders Orders.get() .success(function(data) { $scope.orders = data; $scope.loading = false; }); // CREATE ================================================================== // when submitting the add form, send the text to the node API $scope.createOrder = function() { var order = {}; // validate the formData to make sure that something is there // if form is empty, nothing will happen if ($scope.formData.name != undefined) { $scope.loading = true; for(var i=0; i < menu.foodList.length; i++) { if(menu.foodList[i]['name'] == $scope.formData.name) { order = menu.foodList[i]; break; } } // call the create function from our service (returns a promise object) Orders.create(order) // if successful creation, call our get function to get all the new orders .success(function(data) { $scope.loading = false; $scope.formData = {}; // clear the form so our user is ready to enter another $scope.orders = data; // assign our new list of orders }); $scope.getTotal(); } }; // DELETE ================================================================== // delete a order after checking it $scope.deleteOrder = function(id) { $scope.loading = true; Orders.delete(id) // if successful creation, call our get function to get all the new orders .success(function(data) { $scope.loading = false; $scope.orders = data; // assign our new list of orders }); $scope.getTotal(); }; // calculate Total price using total API $scope.getTotal = function() { Orders.calculate() .success(function(data) { var total = 0; // sum up all prices of orders for(var i=0; i<data.length; i++) total += data[i].price; // 7.5% tax included total = total + total * 0.075; $scope.total = total.toFixed(2); }); }; }]);
c6c6fc8ab3e0c8b9e0b08e3bb8f841ae6493404f
[ "Markdown", "JavaScript" ]
2
Markdown
Tomoya32/Food-Order-App
a89d26a65285e290ae11dd85009c2806e50739a0
cf02f2f233f513685acf4eae21573f2dff9a6381
refs/heads/master
<repo_name>PeacEmbankment/Coputingcup2017<file_sep>/app/src/main/java/com/example/justinlam/coputingcup/MainActivity.java package com.example.justinlam.coputingcup; import android.Manifest; import android.app.Activity; import android.app.ProgressDialog; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.database.sqlite.SQLiteDatabase; import android.net.Uri; import android.os.Environment; import android.support.annotation.IntegerRes; import android.support.v4.app.ActivityCompat; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Toast; import android.os.Handler; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.ArrayList; //import java.util.logging.Handler; import static android.R.attr.data; import static java.lang.System.out; public class MainActivity extends AppCompatActivity { Context context; public ArrayList<String> listArrayList = new ArrayList<String>(); public int a=1; private ProgressDialog progressBar; private int progressBarStatus = 0; ProgressDialog progressDialog; private Handler progressBarHandler = new Handler(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } @Override protected void onPause() { super.onPause(); progressBar.dismiss(); } public void newthing(View view){ Log.d("new thing void",""); //Intent open_game1 = new Intent(context, addthingincalendar.class); // Hi Justine, // Don't exactly know the reason, "getBaseContext()" should be used instead of "context" // Father. Intent open_game1 = new Intent(getBaseContext(), addthingincalendar.class); Log.d("created intent",""); startActivity(open_game1); } // Storage Permissions private static final int REQUEST_EXTERNAL_STORAGE = 1; private static String[] PERMISSIONS_STORAGE = { Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE }; public static void verifyStoragePermissions(Activity activity) { // Check if we have write permission int permission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE); if (permission != PackageManager.PERMISSION_GRANTED) { // We don't have permission so prompt the user ActivityCompat.requestPermissions( activity, PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE ); } } public void importtxt(View view){ verifyStoragePermissions(MainActivity.this); String aDataRow = ""; try { String filepath = Environment.getExternalStorageDirectory().getPath(); File myFile = new File(filepath+"/testimport.txt"); FileInputStream fIn = new FileInputStream(myFile); BufferedReader myReader = new BufferedReader( new InputStreamReader(fIn)); boolean b=true; int c=0; int d=0; int value; boolean e=true; String temp_Activity_Number; String temp_Priority; String temp_Activity_title; String temp_Duration; String temp_prerequisite[] = new String[100]; ArrayList<String> listArrayList = new ArrayList<String>(); String parta[] = new String[5]; String partb[] = new String[5]; String partc[] = new String[5]; String partd[] = new String[100]; while ((aDataRow = myReader.readLine()) != null) { //Log.d("MainActivity","LogaDataRow: " + aDataRow); String[] parts = aDataRow.split(","); String[] parts1 = aDataRow.split(" "); if(b){b=false;Log.d("not b","");value=Integer.parseInt(aDataRow);e=false;} else { if (a == 1) { for (int i = 0; i < 4; i++) { if (!parts[i].isEmpty() && !parts[i].equals("")) { parta[i] = parts[i]; Log.d("a1", parta[i]); } else { Log.d("for break", ""); break; } } a++; } else if(a==2){ for (int i = 0; i < 2; i++) { if (!parts1[i].isEmpty() && !parts1[i].equals("")) { partb[i] = parts1[i]; Log.d("a2", partb[i]); if(i==0){c=Integer.parseInt(partb[i]);} if(i==1){d=Integer.parseInt(partb[i]);} } else { Log.d("for break", ""); break; } } a++; }else if(a==3){ for (int i = 0; i < c; i++) { if (!parts[i].isEmpty() && !parts[i].equals("") && !parts[i].equals(" ")) { partc[i] = parts[i]; Log.d("a3", partc[i]); } else { Log.d("for break", ""); break; } } if(d==0) { a = 1; }else{a=4;} }else if(d>0){ listArrayList.clear(); for (int i = 0; i < d; i++) { if (!parts[i].isEmpty() && !parts[i].equals("") && !parts[i].equals(" ")) { partd[i] = parts[i]; Log.d("d>0", partd[i]); listArrayList.add(parts[i]); } else { Log.d("for break", ""); break; } } a=1; }else{Log.d("d=0","");a=1;} } if(a==1){ if(e) { temp_Activity_Number = parta[0]; temp_Activity_title = parta[1]; temp_Priority = parta[2]; temp_Duration = parta[3]; String temp_Duration_split[] = temp_Duration.split(":"); String temp_Duration_split_second_half[] = temp_Duration_split[1].split("'"); temp_Duration = Integer.parseInt(temp_Duration_split[0]) * 60 + Integer.parseInt(temp_Duration_split_second_half[0]) + ""; Log.d("AN,AT,Pri,D,Pre", temp_Activity_Number + "," + temp_Activity_title+"," + temp_Priority +","+ temp_Duration +","+ listArrayList); DBhelper dBhelper = new DBhelper(this); SQLiteDatabase db = dBhelper.getReadableDatabase(); String insertSQL = "INSERT into activity ('activity_number', 'priority', 'activity_title', 'duration', 'prerequisite') values ('" + temp_Activity_Number + "', '" + temp_Priority + "','" + temp_Activity_title + "','" + temp_Duration + "','" + listArrayList + "')"; Log.d("SQL test",insertSQL); db.execSQL(insertSQL); Log.d("","successfully inserted into db"); for(int i = 0;i<c;i++) { int partc_int_start[]=new int[1000]; Log.d("partc",partc_int_start[i]+""); int partc_int_end[]=new int [1000]; String partc_split_space[]=partc[i].split(" "); String partc_split_space_hiven[]=partc_split_space[1].split("-"); String partc_split_space_hiven_colon1[]=partc_split_space_hiven[0].split(":"); String partc_split_space_hiven_colon2[]=partc_split_space_hiven[1].split(":"); if(partc_split_space[0].equals("Mon")){partc_int_start[i] = 1440;partc_int_end[i]=1440 ;} if(partc_split_space[0].equals("Tue")){partc_int_start[i] = 2880;partc_int_end[i]= 2880;} if(partc_split_space[0].equals("Wed")){partc_int_start[i] = 4320;partc_int_end[i]=4320 ;} if(partc_split_space[0].equals("Thr")){partc_int_start[i] = 5760;partc_int_end[i]= 5760;} if(partc_split_space[0].equals("Fri")){partc_int_start[i] = 7200;partc_int_end[i]= 7200;} if(partc_split_space[0].equals("Sat")){partc_int_start[i] = 8640;partc_int_end[i]= 8640;} if(partc_split_space[0].equals("Sun")){partc_int_start[i] = 10080;partc_int_end[i]= 10080;} Log.d("partc",partc_int_start[i]+""); partc_int_start[i]=partc_int_start[i]+Integer.parseInt(partc_split_space_hiven_colon1[0])*60+Integer.parseInt(partc_split_space_hiven_colon1[1]); Log.d("partc",partc_int_start[i]+""); partc_int_end[i]=partc_int_end[i]+Integer.parseInt(partc_split_space_hiven_colon2[0])*60+Integer.parseInt(partc_split_space_hiven_colon2[1]); Log.d("partc",partc_int_start[i]+""); Log.d("mainActivity inport",partc_split_space[0]+" "+ partc_split_space_hiven_colon1[0]+" "+partc_split_space_hiven_colon1[1]+" "+partc_split_space_hiven_colon2[0]+" "+partc_split_space_hiven_colon2[1]); String insertSQL2 = "INSERT into available_period ('activity_number', 'start_time', 'end_time') values ('" + temp_Activity_Number + "','" + partc_int_start[i] + "','" + partc_int_end[i] + "')"; Log.d("SQL2 test", insertSQL2); db.execSQL(insertSQL2); }db.close(); }else{e=true;} } }myReader.close(); /* DBhelper dBhelper = new DBhelper(ths); SQLiteDatabase db = dBhelper.getReadableDatabase(); String insertSQL = "INSERT into activity ('activity_number', 'priority', 'activity_title', 'duration', 'prerequisite') values ('" + value + "', '" + value3 + "','" + value2 + "','" + editextnum4 + "','" + prerequisite_available_arraylist + "')"; Log.d("SQL test",insertSQL); db.execSQL(insertSQL); Log.d("","successfully inserted into db"); myReader.close();*/ } catch (IOException e) { Log.e("mainActivity",""+e); } } public void exporttxt(View view){ Log.d("entered","exporttxt"); File patternDirectory = new File(Environment.getExternalStorageDirectory().getAbsolutePath().toString()+"/testexport.txt"); patternDirectory.mkdirs(); String filename = "testexport.txt"; String string = "Hello world!"; FileOutputStream outputStream; try { Log.d("entered","exporttxt try catch"); //outputStream = openFileOutput(filename, Context.MODE_PRIVATE); outputStream = new FileOutputStream (new File(patternDirectory.getAbsolutePath().toString()+"/testexport.txt"), true); OutputStreamWriter myOutWriter = new OutputStreamWriter(outputStream); myOutWriter.append("hello world!"); outputStream.write(string.getBytes()); outputStream.write(System.getProperty("line.separator").getBytes()); outputStream.write("hello world skip lined ".getBytes()); outputStream.close(); } catch (Exception e) { Log.d("MainActivity","e:"+e); } } public File getTempFile(Context context, String url) { File file; file = new File("hihihi"); try { String fileName = Uri.parse(url).getLastPathSegment(); file = File.createTempFile(fileName, null, context.getCacheDir()); } catch (IOException e) { // Error while creating file } return file; } public void viewcalendar(View view){ Intent open_game1 = new Intent(getBaseContext(), calendar.class); startActivity(open_game1); } public void clearAllData(View view) { DBhelper dBhelper = new DBhelper(this); SQLiteDatabase db = dBhelper.getReadableDatabase(); db.delete("activity", null, null); db.delete("available_period",null,null); db.delete("export",null,null); db.close (); } public void startAI(View view){ /*progressBar = new ProgressDialog(view.getContext()); progressBar.setCancelable(true); progressBar.setMessage("planning..."); progressBar.setProgressStyle(ProgressDialog.STYLE_SPINNER); progressBar.setProgress(0); progressBar.show(); progressBarStatus = 0; progressDialog = new ProgressDialog(this);*/ progressBar = new ProgressDialog(view.getContext()); progressBar.setCancelable(true); progressBar.setMessage("Planning ..."); progressBar.setProgressStyle(ProgressDialog.STYLE_SPINNER); progressBar.setProgress(0); progressBar.show(); progressBarStatus = 0; new Thread(new Runnable(){ public void run(){ /*progressBarStatus = 1;*/ //progressDialog = ProgressDialog.show(context,"","Hello",true); progressBarHandler.post(new Runnable() { @Override public void run() { //progressBar.setProgress(progressBarStatus); } }); //AI starts here //AI ends here progressBar.dismiss(); //progressDialog.dismiss(); } }).start(); } } <file_sep>/app/src/main/java/com/example/justinlam/coputingcup/addthingincalendar.java package com.example.justinlam.coputingcup; import android.content.Context; import android.content.Intent; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.Spinner; import android.widget.Toast; import java.util.ArrayList; public class addthingincalendar extends AppCompatActivity{ Context context; public static String value; public static String value2; public static String value3; public static String value4; public static String value5; public static String value6; public static int editextnum; public static int editextnum3; public static int editextnum4; public static int peroid[]; public Spinner spinnerDay, spinnerHour, spinnerMin,spinnerAll,spinnerPrerequisite,spinnerEndHour,spinnerEndMin; public ArrayList<String> period_available_arraylist = new ArrayList<String>(); public ArrayList<String> prerequisite_available_arraylist = new ArrayList<String>(); public ArrayList<String> period_available_end_arraylist = new ArrayList<String>(); private int period_number = 0; private int period_number2 = 0; private int peroid_end_number = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.addthingincalendarxml); String start_day[] = {"Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"}; spinnerDay = (Spinner) findViewById(R.id.day_spinner); ArrayAdapter<String> spinnerArrayAdapterDay = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, start_day); spinnerArrayAdapterDay.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // The drop down view spinnerDay.setAdapter(spinnerArrayAdapterDay); String start_hour[] = { "00","01", "02", "03", "04", "05", "06","07","08","09","10","11","12","13","14","15","16","17","18","19","20","21","22","23"}; spinnerHour = (Spinner) findViewById(R.id.hour_spinner); ArrayAdapter<String> spinnerArrayAdapterHour = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, start_hour); spinnerArrayAdapterHour.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // The drop down view spinnerHour.setAdapter(spinnerArrayAdapterHour); spinnerEndHour = (Spinner) findViewById(R.id.hour_end_spinner); ArrayAdapter<String> spinnerArrayAdapterEndHour = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, start_hour); spinnerArrayAdapterEndHour.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // The drop down view spinnerEndHour.setAdapter(spinnerArrayAdapterEndHour); String start_min[] = { "00","01", "02", "03", "04", "05", "06","07","08","09","10","11","12","13","14","15","16","17","18","19","20","21","22","23","24","25","26","27","28","29","30","31","32","33","34","35","36","37","38","39","40","41","42","43","44","45","46","47","48","49","50","51","52","53","54","55","56","57","58","59"}; spinnerMin = (Spinner) findViewById(R.id.minutes_spinner); ArrayAdapter<String> spinnerArrayAdapterMin = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, start_min); spinnerArrayAdapterMin.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // The drop down view spinnerMin.setAdapter(spinnerArrayAdapterMin); spinnerEndMin = (Spinner) findViewById(R.id.minutes_end_spinner); ArrayAdapter<String> spinnerArrayAdapterEndMin = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, start_min); spinnerArrayAdapterEndMin.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // The drop down view spinnerEndMin.setAdapter(spinnerArrayAdapterEndMin); } public void back(View view){ Intent open_game1 = new Intent(getBaseContext(), MainActivity.class); startActivity(open_game1); } public void addevent(View view){ EditText editText = (EditText) findViewById(R.id.editText); value = editText.getText().toString(); if(value.matches("")) {} else {editextnum = Integer.parseInt(value);} EditText editText2 = (EditText) findViewById(R.id.activity_name_edittext); value2 = editText2.getText().toString(); EditText editText3 = (EditText) findViewById(R.id.priority_edittext); value3 = editText3.getText().toString(); if(value3.matches("")) {} else{editextnum3 = Integer.parseInt(value3);} EditText editText4 = (EditText) findViewById(R.id.duration_edittext); value4 = editText4.getText().toString(); if(value4.matches("")){}else{editextnum4 = Integer.parseInt(value4);} if (value.matches("") || value2.matches("") || value3.matches("") || value4.matches("")) { Toast.makeText(getApplicationContext(), "You have not entered all the information", Toast.LENGTH_LONG).show(); } else{ DBhelper dBhelper = new DBhelper(this); SQLiteDatabase db = dBhelper.getReadableDatabase(); String insertSQL = "INSERT into activity ('activity_number', 'priority', 'activity_title', 'duration', 'prerequisite') values ('" + value + "', '" + value3 + "','" + value2 + "','" + editextnum4 + "','" + prerequisite_available_arraylist + "')"; Log.d("SQL test",insertSQL); db.execSQL(insertSQL); Log.d("","successfully inserted into db"); Log.d("value1234", editextnum + "," + value2 + "," + editextnum3 + "," + value4); for(int i = 0;i<period_available_arraylist.size();i++){ if(period_available_arraylist.get(i).substring(0,3).equals("Mon")){period_number=1440;} if(period_available_arraylist.get(i).substring(0,3).equals("Tue")){period_number=2880;} if(period_available_arraylist.get(i).substring(0,3).equals("Wed")){period_number=4320;} if(period_available_arraylist.get(i).substring(0,3).equals("Thr")){period_number=5760;} if(period_available_arraylist.get(i).substring(0,3).equals("Fri")){period_number=7200;} if(period_available_arraylist.get(i).substring(0,3).equals("Sat")){period_number=8640;} if(period_available_arraylist.get(i).substring(0,3).equals("Sun")){period_number=10080;} period_number2=period_number; Log.d("period ava arraylist03 ",period_available_arraylist.get(i).substring(0,3)); period_number=period_number+Integer.valueOf(period_available_arraylist.get(i).substring(4,6))*60; Log.d("period ava arraylist46 ",Integer.parseInt(period_available_arraylist.get(i).substring(4,6))*60+""); period_number=period_number+Integer.valueOf(period_available_arraylist.get(i).substring(7,9)); Log.d("period ava arraylist79 ",period_available_arraylist.get(i).substring(7,9)); Log.d("paa",period_available_arraylist+""); Log.d("period number",period_number+""); peroid_end_number=period_number2; peroid_end_number=peroid_end_number+Integer.valueOf(period_available_arraylist.get(i).substring(10,12))*60; Log.d("period ava arraylist911",Integer.parseInt(period_available_arraylist.get(i).substring(10,12))*60+""); peroid_end_number=peroid_end_number+Integer.valueOf(period_available_arraylist.get(i).substring(13,15)); Log.d("period ava arrayli.1315",period_available_arraylist.get(i).substring(13,15)); Log.d("paa",period_available_arraylist+""); Log.d("period number",peroid_end_number+""); String insertSQL2 = "INSERT into available_period ('activity_number', 'start_time', 'end_time') values ('" + editextnum + "','" + period_number + "','" + peroid_end_number + "')"; Log.d("SQL2 test",insertSQL2); db.execSQL(insertSQL2); } Intent open_game1 = new Intent(getBaseContext(), MainActivity.class); startActivity(open_game1); } } public void add_period(View view){ period_available_end_arraylist.add(spinnerEndHour.getSelectedItem()+":"+spinnerEndMin.getSelectedItem()); period_available_arraylist.add(spinnerDay.getSelectedItem()+" "+ spinnerHour.getSelectedItem()+":"+spinnerMin.getSelectedItem()+"-"+spinnerEndHour.getSelectedItem()+":"+spinnerEndMin.getSelectedItem()); spinnerAll = (Spinner) findViewById(R.id.all_period_spinner); ArrayAdapter<String> spinnerArrayAdapterAll = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, period_available_arraylist); spinnerArrayAdapterAll.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // The drop down view spinnerAll.setAdapter(spinnerArrayAdapterAll); Log.d("day,hour,min",spinnerDay.getSelectedItem()+""+ spinnerHour.getSelectedItem()+spinnerMin.getSelectedItem()+""); } public void add_prerequisite(View view){ EditText editText4 = (EditText) findViewById(R.id.prerequisite_edittext); value4 = editText4.getText().toString(); if(value4.matches("")) {} else{editextnum4 = Integer.parseInt(value4);} spinnerPrerequisite = (Spinner) findViewById(R.id.prerequisite_spinner); prerequisite_available_arraylist.add(value4); ArrayAdapter<String> spinnerArrayAdapterPrerequisite = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, prerequisite_available_arraylist); spinnerArrayAdapterPrerequisite.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // The drop down view spinnerPrerequisite.setAdapter(spinnerArrayAdapterPrerequisite); editText4.setText(""); } } <file_sep>/app/src/main/java/com/example/justinlam/coputingcup/DBhelper.java package com.example.justinlam.coputingcup; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import java.util.ArrayList; import java.util.List; public class DBhelper extends SQLiteOpenHelper { private static final int DATABASE_VERSION = 1; // Database Name private static final String DATABASE_NAME = "computingcupdb"; //this is rubbish. public DBhelper(Context context ) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { String CREATE_SQL = "CREATE TABLE IF NOT EXISTS activity ( 'activity_number' INTEGER PRIMARY KEY, 'priority' INTEGER NOT NULL, 'activity_title' TEXT NOT NULL,'duration' INTEGER NOT NULL, 'prerequisite' INTEGER)"; db.execSQL(CREATE_SQL); String CREATE_SQL2 = "CREATE TABLE IF NOT EXISTS available_period ( 'id' INTEGER PRIMARY KEY AUTOINCREMENT, 'activity_number' INTEGER NOT NULL, 'start_time' INTEGER NOT NULL, 'end_time' INTEGER NOT NULL)"; db.execSQL(CREATE_SQL2); String CREATE_SQL3 = "CREATE TABLE IF NOT EXISTS export ( 'activity_number' INTEGER PRIMARY KEY, 'startTime' INTEGER NOT NULL,'duration' INTEGER NOT NULL)"; db.execSQL(CREATE_SQL3); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // Drop older table if existed, all data will be gone!!! db.execSQL("DROP TABLE IF EXISTS activity"); // Create tables again onCreate(db); } public List<databaseModelList> getDataFromDB() { List<databaseModelList> modelList = new ArrayList<databaseModelList>(); String query; query = "select activity_number, priority, activity_title, duration, prerequisite from activity"; query = "select activity.activity_number, activity.priority, activity.activity_title, activity.duration, activity.prerequisite, (select group_concat(available_period.start_time||'-'||available_period.end_time) from available_period where available_period.activity_number=activity.activity_number) as available_period_concat from activity"; SQLiteDatabase db = this.getWritableDatabase(); Cursor cursor = db.rawQuery(query,null); if (cursor.moveToFirst()){ do { databaseModelList model = new databaseModelList(); model.setActivityNumber(cursor.getInt(0)); model.setPriority(cursor.getInt(1)); model.setActivityTitle(cursor.getString(2)); model.setDuration(cursor.getInt(3)); model.setPrerequisite(cursor.getString(4)); model.setAvailablePeriod(cursor.getString(5)); modelList.add(model); }while (cursor.moveToNext()); } return modelList; } public List<databaseModelList> getExportFromDB() { List<databaseModelList> modelList = new ArrayList<databaseModelList>(); String query; query = "select export.activity_number, activity.priority, activity.activity_title, activity.duration, activity.prerequisite, export.startTime FROM activity, export WHERE export.activity_number = activity.activity_number"; SQLiteDatabase db = this.getWritableDatabase(); Cursor cursor = db.rawQuery(query,null); if (cursor.moveToFirst()){ do { databaseModelList model = new databaseModelList(); model.setActivityNumber(cursor.getInt(0)); model.setPriority(cursor.getInt(1)); model.setActivityTitle(cursor.getString(2)); model.setDuration(cursor.getInt(3)); model.setPrerequisite(cursor.getString(4)); model.setStartTime(cursor.getInt(5)); modelList.add(model); }while (cursor.moveToNext()); } return modelList; } }
3dac52097edcbf14beaa081d54f993f295542600
[ "Java" ]
3
Java
PeacEmbankment/Coputingcup2017
c9f5ffeba2e4dbeb83fc208de39586179fb6e7b2
0cda133b49e8efa95c61f867efde86b6170ad42e
refs/heads/master
<file_sep> from pyramid import testing from webtest import TestApp import pytest from gitaconda_server import main @pytest.fixture(scope='session') def pyramid_settings(): return { 'sqlalchemy.url': 'sqlite://', } @pytest.fixture(scope='session') def pyramid_testing_setup(request): def fin(): testing.tearDown() request.addfinalizer(fin) return testing.setUp() @pytest.fixture(scope='module') def pyramid_server(pyramid_testing_setup, pyramid_settings): return TestApp(main({}, **pyramid_settings)) <file_sep> [app:main] use = egg:gitaconda#gitaconda-server pyramid.reload_templates = true session.type = file session.data_dir = /tmp/gitaconda_sessions/data session.lock_dir = /tmp/gitaconda_sessions/lock session.key = mykey session.secret = mysecret session.cookie_on_exception = true sqlalchemy.url = sqlite:// [server:main] use = egg:pyramid#wsgiref host = 0.0.0.0 port = 8080 <file_sep> def test_index(pyramid_server): res = pyramid_server.get('/', status=200) assert b'hello world' in res.body <file_sep> from os.path import join, dirname from setuptools import setup setup( name='gitaconda', version='0.1.0', author='<NAME>', author_email='<EMAIL>', url='gitconda.readthedocs.io', description='a simple and deployable github clone', long_description=open(join(dirname(__file__), 'README.rst')).read(), keywords='git management', packages=[ 'gitaconda_server', 'gitaconda_shell', ], entry_points={ 'paste.app_factory': { 'gitaconda-server = gitaconda_server:main' }, }, install_requires=[ # gitaconda-server 'pyramid', 'pyramid_chameleon', 'pyramid_beaker', 'pyramid_tm', 'pyramid_sqlalchemy', ], license='GPLv3+', classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Environment :: Web Environment', 'Framework :: Pyramid', 'Intended Audience :: Developers', 'License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Topic :: Software Development :: Version Control', ], test_suite='tests', tests_require=[ 'pytest', 'webtest', ], setup_requires=[ 'pytest_runner', ], ) <file_sep> from pyramid.view import view_config, view_defaults from pyramid.renderers import get_renderer from pyramid.interfaces import IBeforeRender from pyramid.events import subscriber @subscriber(IBeforeRender) def globals_factory(event): event['master'] = get_renderer('gitaconda_server:templates/master.pt').implementation() event['base_anon'] = get_renderer('gitaconda_server:templates/base_anon.pt').implementation() event['base_auth'] = get_renderer('gitaconda_server:templates/base_auth.pt').implementation() @view_config(route_name='index', renderer='gitaconda_server:templates/index.pt') def index(request): return {} <file_sep> from pyramid_beaker import session_factory_from_settings from pyramid.config import Configurator def main(global_config, **settings): session_factory = session_factory_from_settings(settings) config = Configurator(settings=settings) config.set_session_factory(session_factory) config.include('pyramid_chameleon') config.include('pyramid_beaker') config.include('pyramid_tm') config.include('pyramid_sqlalchemy') # anon routes config.add_route('index', '/') config.add_route('signin', '/signin') config.add_route('signup', '/signup') config.add_route('search', '/search') # auth'd routes config.add_route('pullrequests', '/pullrequests') config.add_route('issues', '/issues') config.add_static_view(name='static', path='gitaconda_server:static') config.scan('.views') return config.make_wsgi_app()
b91ef4330ce4434ad9f4842031b1439d570e9e43
[ "Python", "INI" ]
6
Python
oaken-source/gitaconda
070a2d2f24ba12a10dbfac32cd7ccc8b144a2062
7dab2c593160093ff6347a17101a8f01a79873b0
refs/heads/master
<repo_name>RealityVirtually2019/IronMan<file_sep>/Assets/LeapMotion/Modules/GraphicRenderer/Scripts/SupportInfo.cs /****************************************************************************** * Copyright (C) Leap Motion, Inc. 2011-2018. * * Leap Motion proprietary and confidential. * * * * Use subject to the terms of the Leap Motion SDK Agreement available at * * https://developer.leapmotion.com/sdk_agreement, or another agreement * * between Leap Motion and you, your company or other organization. * ******************************************************************************/ using System; using System.Collections.Generic; namespace Leap.Unity.GraphicalRenderer { /// <summary> /// The support info class provides a very basic way to notify that something /// is fully supported, partially supported, or not supported. The struct contains /// a support type, which can be either Full, Warning, or Error. The struct /// also contains a message to give information about the support. /// </summary> [Serializable] public struct SupportInfo { public SupportType support; public string message; /// <summary> /// Helper getter to return a struct that signifies full support. /// </summary> public static SupportInfo FullSupport() { return new SupportInfo() { support = SupportType.Full, message = null }; } /// <summary> /// Helper getter to return a struct that signifies partial support with a warning message. /// </summary> public static SupportInfo Warning(string message) { return new SupportInfo() { support = SupportType.Warning, message = message }; } /// <summary> /// Helper getter to return a struct that signifies no support with an error message. /// </summary> public static SupportInfo Error(string message) { return new SupportInfo() { support = SupportType.Error, message = message }; } /// <summary> /// Helper method that returns either the current support info struct, or the argument /// support info struct. The argument is only chosen as the return value if it has /// less support than the current support. /// </summary> public SupportInfo OrWorse(SupportInfo other) { if (other.support > support) { return other; } else { return this; } } } public enum SupportType { Full, Warning, Error } public static class SupportUtil { /// <summary> /// Helper method to only support the first element in a list. /// </summary> public static void OnlySupportFirstFeature<T>(List<SupportInfo> info) { for (int i = 1; i < info.Count; i++) { info[i] = SupportInfo.Error("Only the first " + LeapGraphicTagAttribute.GetTagName(typeof(T)) + " is supported."); } } } } <file_sep>/Assets/LeapMotion/Modules/GraphicRenderer/Scripts/Features/CustomChannel/CustomChannelFeatureBase.cs /****************************************************************************** * Copyright (C) Leap Motion, Inc. 2011-2018. * * Leap Motion proprietary and confidential. * * * * Use subject to the terms of the Leap Motion SDK Agreement available at * * https://developer.leapmotion.com/sdk_agreement, or another agreement * * between Leap Motion and you, your company or other organization. * ******************************************************************************/ using System; using UnityEngine; using Leap.Unity.Attributes; namespace Leap.Unity.GraphicalRenderer { public interface ICustomChannelFeature { string channelName { get; } } [Serializable] public abstract class CustomChannelFeatureBase<T> : LeapGraphicFeature<T>, ICustomChannelFeature where T : LeapFeatureData, new() { [Tooltip("The name of the channel. This is the name used to access the channel from within the shader.")] [Delayed] [EditTimeOnly] [SerializeField] private string _channelName = "_CustomChannel"; public string channelName { get { return _channelName; } } public override SupportInfo GetSupportInfo(LeapGraphicGroup group) { foreach (var feature in group.features) { if (feature == this) continue; var channelFeature = feature as ICustomChannelFeature; if (channelFeature != null && channelFeature.channelName == channelName) { return SupportInfo.Error("Cannot have two custom channels with the same name."); } } return SupportInfo.FullSupport(); } } } <file_sep>/Assets/Hover/Core/Scripts/Items/Helpers/HoverIndicatorOverrider.cs using Hover.Core.Renderers; using Hover.Core.Utils; using UnityEngine; namespace Hover.Core.Items.Helpers { /*================================================================================================*/ [ExecuteInEditMode] [RequireComponent(typeof(TreeUpdater))] [RequireComponent(typeof(HoverItemRendererUpdater))] public class HoverIndicatorOverrider : MonoBehaviour, ITreeUpdateable, ISettingsController { public const string MinHightlightProgressName = "MinHightlightProgress"; public const string MinSelectionProgressName = "MinSelectionProgress"; public ISettingsControllerMap Controllers { get; private set; } [DisableWhenControlled(DisplaySpecials=true, RangeMin=0, RangeMax=1)] public float MinHightlightProgress = 0; [DisableWhenControlled(RangeMin=0, RangeMax=1)] public float MinSelectionProgress = 0; //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ protected HoverIndicatorOverrider() { Controllers = new SettingsControllerMap(); } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public virtual void Start() { //do nothing... } /*--------------------------------------------------------------------------------------------*/ public virtual void TreeUpdate() { HoverItemRendererUpdater rendUp = GetComponent<HoverItemRendererUpdater>(); HoverIndicator rendInd = rendUp.ActiveRenderer.GetIndicator(); rendInd.Controllers.Set(HoverIndicator.HighlightProgressName, this); rendInd.Controllers.Set(HoverIndicator.SelectionProgressName, this); rendInd.HighlightProgress = Mathf.Max(rendInd.HighlightProgress, MinHightlightProgress); rendInd.SelectionProgress = Mathf.Max(rendInd.SelectionProgress, MinSelectionProgress); Controllers.TryExpireControllers(); } } } <file_sep>/Assets/Hover/Core/Scripts/Items/Managers/HoverItemHighlightState.cs using System; using System.Collections.Generic; using Hover.Core.Cursors; using Hover.Core.Items.Types; using UnityEngine; namespace Hover.Core.Items.Managers { /*================================================================================================*/ [ExecuteInEditMode] public class HoverItemHighlightState : MonoBehaviour { [Serializable] public struct Highlight { public bool IsNearestAcrossAllItems; public ICursorData Cursor; public Vector3 NearestWorldPos; public float Distance; public float Progress; } public bool IsHighlightPrevented { get; private set; } public Highlight? NearestHighlight { get; private set; } public List<Highlight> Highlights { get; private set; } public bool IsNearestAcrossAllItemsForAnyCursor { get; private set; } public HoverCursorDataProvider CursorDataProvider; public HoverItemRendererUpdater ProximityProvider; public HoverInteractionSettings InteractionSettings; private readonly HashSet<string> vPreventHighlightMap; private readonly HashSet<CursorType> vIsNearestForCursorTypeMap; //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public HoverItemHighlightState() { Highlights = new List<Highlight>(); vPreventHighlightMap = new HashSet<string>(); vIsNearestForCursorTypeMap = new HashSet<CursorType>(); } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public void Awake() { if ( CursorDataProvider == null ) { CursorDataProvider = FindObjectOfType<HoverCursorDataProvider>(); } if ( ProximityProvider == null ) { ProximityProvider = GetComponent<HoverItemRendererUpdater>(); } if ( InteractionSettings == null ) { InteractionSettings = (GetComponent<HoverInteractionSettings>() ?? FindObjectOfType<HoverItemsManager>().GetComponent<HoverInteractionSettings>()); } if ( CursorDataProvider == null ) { Debug.LogWarning("Could not find 'CursorDataProvider'."); } if ( ProximityProvider == null ) { //TODO: show warning elsewhere? the renderer is typically added *after* this //Debug.LogWarning("Could not find 'ProximityProvider'."); } if ( InteractionSettings == null ) { Debug.LogWarning("Could not find 'InteractionSettings'."); } } /*--------------------------------------------------------------------------------------------*/ public void Update() { Highlights.Clear(); NearestHighlight = null; UpdateIsHighlightPrevented(); if ( IsHighlightPrevented || ProximityProvider == null || CursorDataProvider == null || InteractionSettings == null ) { return; } AddLatestHighlightsAndFindNearest(); } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public Highlight? GetHighlight(CursorType pType) { for ( int i = 0 ; i < Highlights.Count ; i++ ) { Highlight high = Highlights[i]; if ( high.Cursor.Type == pType ) { return high; } } return null; } /*--------------------------------------------------------------------------------------------*/ public float MaxHighlightProgress { get { IItemDataSelectable selData = (GetComponent<HoverItemData>() as IItemDataSelectable); if ( selData != null && selData.IsStickySelected ) { return 1; } return (NearestHighlight == null ? 0 : NearestHighlight.Value.Progress); } } /*--------------------------------------------------------------------------------------------*/ public void ResetAllNearestStates() { vIsNearestForCursorTypeMap.Clear(); } /*--------------------------------------------------------------------------------------------*/ public void SetNearestAcrossAllItemsForCursor(CursorType pType) { vIsNearestForCursorTypeMap.Add(pType); } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public void PreventHighlightViaDisplay(string pName, bool pPrevent) { if ( pPrevent ) { vPreventHighlightMap.Add(pName); } else { vPreventHighlightMap.Remove(pName); } } /*--------------------------------------------------------------------------------------------*/ public bool IsHighlightPreventedViaAnyDisplay() { return (vPreventHighlightMap.Count > 0); } /*--------------------------------------------------------------------------------------------*/ public bool IsHighlightPreventedViaDisplay(string pName) { return vPreventHighlightMap.Contains(pName); } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ private void UpdateIsHighlightPrevented() { HoverItem hoverItem = GetComponent<HoverItem>(); HoverItemData itemData = GetComponent<HoverItem>().Data; IItemDataSelectable selData = (itemData as IItemDataSelectable); IsHighlightPrevented = ( selData == null || !itemData.IsEnabled || //!itemData.IsVisible || !itemData.IsAncestryEnabled || //!itemData.IsAncestryVisible || !hoverItem.gameObject.activeInHierarchy || IsHighlightPreventedViaAnyDisplay() ); } /*--------------------------------------------------------------------------------------------*/ private void AddLatestHighlightsAndFindNearest() { float minDist = float.MaxValue; List<ICursorData> cursors = CursorDataProvider.Cursors; int cursorCount = cursors.Count; for ( int i = 0 ; i < cursorCount ; i++ ) { ICursorData cursor = cursors[i]; if ( !cursor.CanCauseSelections ) { continue; } Highlight high = CalculateHighlight(cursor); high.IsNearestAcrossAllItems = vIsNearestForCursorTypeMap.Contains(cursor.Type); Highlights.Add(high); if ( high.Distance >= minDist ) { continue; } minDist = high.Distance; NearestHighlight = high; } IsNearestAcrossAllItemsForAnyCursor = (vIsNearestForCursorTypeMap.Count > 0); } /*--------------------------------------------------------------------------------------------*/ private Highlight CalculateHighlight(ICursorData pCursor) { var high = new Highlight(); high.Cursor = pCursor; if ( !Application.isPlaying ) { return high; } Vector3 cursorWorldPos = (pCursor.BestRaycastResult == null ? pCursor.WorldPosition : pCursor.BestRaycastResult.Value.WorldPosition); high.NearestWorldPos = ProximityProvider.GetNearestWorldPosition(cursorWorldPos); high.Distance = (cursorWorldPos-high.NearestWorldPos).magnitude; high.Progress = Mathf.InverseLerp(InteractionSettings.HighlightDistanceMax, InteractionSettings.HighlightDistanceMin, high.Distance); return high; } } } <file_sep>/Assets/IronManUI/Scripts/Editor/TextBoxEditor.cs using UnityEngine; using UnityEditor; // namespace IronManUI { // [CustomEditor(typeof(TextBox))] // public class TextBoxEditor : Editor { // Vector2 scroll; // public override void OnInspectorGUI() { // DrawDefaultInspector(); // TextBox target = this.target as TextBox; // GUILayout.Label("Text"); // scroll = GUILayout.BeginScrollView(scroll); // target.text = GUILayout.TextArea(target.text); // GUILayout.EndScrollView(); // } // } // }<file_sep>/Assets/Hover/Editor/Items/HoverItemDataEditor.cs using Hover.Core.Items; using Hover.Core.Items.Types; using UnityEditor; using UnityEngine; namespace Hover.Editor.Items { /*================================================================================================*/ [CustomEditor(typeof(HoverItemData), true)] [CanEditMultipleObjects] public class HoverItemDataEditor : UnityEditor.Editor { private GUIStyle vVertStyle; private string vIsHiddenOpenKey; private string vIsEventOpenKey; private HoverItemData vData; //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public void OnEnable() { vVertStyle = EditorUtil.GetVerticalSectionStyle(); int targetId = target.GetInstanceID(); vIsHiddenOpenKey = "IsHiddenOpen"+targetId; vIsEventOpenKey = "IsEventOpen"+targetId; } /*--------------------------------------------------------------------------------------------*/ public override void OnInspectorGUI() { vData = (HoverItemData)target; serializedObject.Update(); DrawItems(); serializedObject.ApplyModifiedProperties(); } /*--------------------------------------------------------------------------------------------*/ public override bool RequiresConstantRepaint() { return EditorPrefs.GetBool(vIsHiddenOpenKey); } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ private void DrawItems() { DrawMainItems(); DrawEventItemGroup(); DrawHiddenItemGroup(); } /*--------------------------------------------------------------------------------------------*/ private void DrawMainItems() { EditorGUILayout.PropertyField(serializedObject.FindProperty("_Id"), new GUIContent("ID")); EditorGUILayout.PropertyField(serializedObject.FindProperty("_Label")); EditorGUILayout.PropertyField(serializedObject.FindProperty("_IsEnabled")); //// HoverItemDataSelector selectorData = (vData as HoverItemDataSelector); HoverItemDataCheckbox checkboxData = (vData as HoverItemDataCheckbox); HoverItemDataRadio radioData = (vData as HoverItemDataRadio); HoverItemDataSlider sliderData = (vData as HoverItemDataSlider); HoverItemDataSticky stickyData = (vData as HoverItemDataSticky); if ( selectorData != null ) { EditorGUILayout.PropertyField(serializedObject.FindProperty("_Action")); } else if ( checkboxData != null ) { EditorGUILayout.PropertyField(serializedObject.FindProperty("_Value"), new GUIContent("Checkbox Value")); } else if ( radioData != null ) { EditorGUILayout.PropertyField(serializedObject.FindProperty("_GroupId"), new GUIContent("Radio Group ID")); EditorGUILayout.PropertyField(serializedObject.FindProperty("_Value"), new GUIContent("Radio Value")); } else if ( sliderData != null ) { EditorGUILayout.PropertyField(serializedObject.FindProperty("_LabelFormat"), new GUIContent("Slider Label Format")); EditorGUILayout.PropertyField(serializedObject.FindProperty("_RangeMin"), new GUIContent("Slider Range Min")); EditorGUILayout.PropertyField(serializedObject.FindProperty("_RangeMax"), new GUIContent("Slider Range Max")); float rangeValue = Mathf.Lerp( sliderData.RangeMin, sliderData.RangeMax, sliderData.Value); rangeValue = EditorGUILayout.Slider( "Slider Range Value", rangeValue, sliderData.RangeMin, sliderData.RangeMax); if ( sliderData.RangeValue != rangeValue ) { serializedObject.FindProperty("_Value").floatValue = Mathf.InverseLerp(sliderData.RangeMin, sliderData.RangeMax, rangeValue); } EditorGUILayout.PropertyField(serializedObject.FindProperty("_Ticks"), new GUIContent("Slider Ticks")); EditorGUILayout.PropertyField(serializedObject.FindProperty("_Snaps"), new GUIContent("Slider Snaps")); EditorGUILayout.PropertyField(serializedObject.FindProperty("_AllowJump"), new GUIContent("Slider Allow Jump")); EditorGUILayout.PropertyField(serializedObject.FindProperty("_FillStartingPoint"), new GUIContent("Slider Fill Starting-Point")); EditorGUILayout.PropertyField(serializedObject.FindProperty("_AllowIdleDeselection"), new GUIContent("Allow Idle Deselection")); } else if ( stickyData != null ) { EditorGUILayout.PropertyField(serializedObject.FindProperty("_AllowIdleDeselection"), new GUIContent("Allow Idle Deselection")); } } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ private void DrawEventItemGroup() { HoverItemDataSelectable selectableData = (vData as HoverItemDataSelectable); if ( selectableData == null ) { return; } bool isEventOpen = EditorGUILayout.Foldout(EditorPrefs.GetBool(vIsEventOpenKey), "Events"); EditorPrefs.SetBool(vIsEventOpenKey, isEventOpen); if ( isEventOpen ) { EditorGUILayout.BeginVertical(vVertStyle); DrawEventItems(); EditorGUILayout.EndVertical(); } } /*--------------------------------------------------------------------------------------------*/ private void DrawEventItems() { HoverItemDataSelectableBool selBoolData = (vData as HoverItemDataSelectableBool); HoverItemDataSelectableFloat selFloatData = (vData as HoverItemDataSelectableFloat); EditorGUILayout.PropertyField(serializedObject.FindProperty("OnEnabledChangedEvent")); EditorGUILayout.PropertyField(serializedObject.FindProperty("OnSelectedEvent")); EditorGUILayout.PropertyField(serializedObject.FindProperty("OnDeselectedEvent")); if ( selBoolData != null ) { EditorGUILayout.PropertyField(serializedObject.FindProperty("OnValueChangedEvent")); } if ( selFloatData != null ) { EditorGUILayout.PropertyField(serializedObject.FindProperty("OnValueChangedEvent")); } } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ private void DrawHiddenItemGroup() { bool isHiddenOpen = EditorGUILayout.Foldout(EditorPrefs.GetBool(vIsHiddenOpenKey), "Info"); EditorPrefs.SetBool(vIsHiddenOpenKey, isHiddenOpen); if ( isHiddenOpen ) { EditorGUILayout.BeginVertical(vVertStyle); GUI.enabled = false; DrawHiddenItems(); GUI.enabled = true; EditorGUILayout.EndVertical(); } } /*--------------------------------------------------------------------------------------------*/ private void DrawHiddenItems() { HoverItemDataSelectable selectableData = (vData as HoverItemDataSelectable); EditorGUILayout.IntField("Auto ID", vData.AutoId); EditorGUILayout.Toggle("Is Ancestry Enabled", vData.IsAncestryEnabled); EditorGUILayout.Toggle("Is Ancestry Visible", vData.IsAncestryVisible); if ( selectableData == null ) { return; } EditorGUILayout.Toggle("Is Sticky-Selected", selectableData.IsStickySelected); EditorGUILayout.Toggle("Ignore Selection", selectableData.IgnoreSelection); IItemDataRadio radioData = (vData as IItemDataRadio); IItemDataSlider sliderData = (vData as IItemDataSlider); if ( radioData != null ) { EditorGUILayout.TextField("Radio Default Group ID", radioData.DefaultGroupId); } if ( sliderData != null ) { EditorGUILayout.TextField("Slider Formatted Label", sliderData.GetFormattedLabel(sliderData)); EditorGUILayout.Slider("Slider Value", sliderData.Value, 0, 1); EditorGUILayout.Slider("Slider Snapped Value", sliderData.SnappedValue, 0, 1); EditorGUILayout.Slider("Slider Snapped Range Value", sliderData.SnappedRangeValue, sliderData.RangeMin, sliderData.RangeMax); EditorGUILayout.TextField("Slider Hover Value", sliderData.HoverValue+""); EditorGUILayout.TextField("Slider Snapped Hover Value",sliderData.SnappedHoverValue+""); } } } } <file_sep>/Assets/LeapMotion/Modules/GraphicRenderer/Scripts/Graphics/ProceduralMeshGraphics/LeapSpriteGraphic.cs /****************************************************************************** * Copyright (C) Leap Motion, Inc. 2011-2018. * * Leap Motion proprietary and confidential. * * * * Use subject to the terms of the Leap Motion SDK Agreement available at * * https://developer.leapmotion.com/sdk_agreement, or another agreement * * between Leap Motion and you, your company or other organization. * ******************************************************************************/ using UnityEngine; using Leap.Unity.Query; namespace Leap.Unity.GraphicalRenderer { /// <summary> /// The Sprite Graphic is a type of procedural mesh graphic that allows you to directly /// use sprite objects as meshes. This component grabs mesh data directly from the sprite /// itself, and so supports non-rectangular meshes. /// </summary> [DisallowMultipleComponent] public class LeapSpriteGraphic : LeapMeshGraphicBase { public override void RefreshMeshData() { var spriteData = this.Sprite(); if (spriteData == null || spriteData.sprite == null) { mesh = null; remappableChannels = 0; return; } var sprite = spriteData.sprite; if (mesh == null) { mesh = new Mesh(); } mesh.name = "Sprite Mesh"; mesh.hideFlags = HideFlags.HideAndDontSave; mesh.Clear(keepVertexLayout: false); mesh.vertices = sprite.vertices.Query().Select(v => (Vector3)v).ToArray(); mesh.triangles = sprite.triangles.Query().Select(i => (int)i).ToArray(); Vector2[] uvs; if (SpriteAtlasUtil.TryGetAtlasedUvs(sprite, out uvs)) { mesh.uv = uvs; } mesh.RecalculateBounds(); //We are using atlas uvs, so no remapping allowed! remappableChannels = 0; } } } <file_sep>/Assets/LeapMotion/Modules/GraphicRenderer/Scripts/Graphics/ProceduralMeshGraphics/LeapBoxGraphic.cs /****************************************************************************** * Copyright (C) Leap Motion, Inc. 2011-2018. * * Leap Motion proprietary and confidential. * * * * Use subject to the terms of the Leap Motion SDK Agreement available at * * https://developer.leapmotion.com/sdk_agreement, or another agreement * * between Leap Motion and you, your company or other organization. * ******************************************************************************/ using System.Collections.Generic; using UnityEngine; using UnityEngine.Rendering; using Leap.Unity.Query; using Leap.Unity.Attributes; using System; namespace Leap.Unity.GraphicalRenderer { /// <summary> /// The Box Graphic is a type of procedural mesh graphic that can generate thick panels /// with a number of useful features: /// - It allows nine slicing when using a sprite as the source for the texture data. /// - It allows automatic tessellation such that it can be correctly warped by a space. /// - It allows automatic resizing based on an attached RectTransform. /// </summary> [DisallowMultipleComponent] public class LeapBoxGraphic : LeapSlicedGraphic { [MinValue(0.0001f)] [EditTimeOnly] [SerializeField] private float _thickness = 0.01f; /// <summary> /// Gets the dimensions of the box graphic in local space. /// </summary> public Vector3 size { get { return new Vector3(_size.x, _size.y, _thickness); } private set { _size = new Vector2(value.x, value.y); _thickness = value.z; } } public override void RefreshSlicedMeshData(Vector2i resolution, RectMargins meshMargins, RectMargins uvMargins) { List<Vector3> verts = new List<Vector3>(); List<Vector2> uvs = new List<Vector2>(); List<Vector3> normals = new List<Vector3>(); List<int> tris = new List<int>(); // Back for (int vy = 0; vy < resolution.y; vy++) { for (int vx = 0; vx < resolution.x; vx++) { Vector2 vert; vert.x = calculateVertAxis(vx, resolution.x, rect.width, meshMargins.left, meshMargins.right); vert.y = calculateVertAxis(vy, resolution.y, rect.height, meshMargins.top, meshMargins.bottom); verts.Add(vert + new Vector2(rect.x, rect.y)); normals.Add(Vector3.forward); Vector2 uv; uv.x = calculateVertAxis(vx, resolution.x, 1, uvMargins.left, uvMargins.right); uv.y = calculateVertAxis(vy, resolution.y, 1, uvMargins.top, uvMargins.bottom); uvs.Add(uv); } } int backVertsCount = verts.Count; // Front float depth = -size.z; for (int vy = 0; vy < resolution.y; vy++) { for (int vx = 0; vx < resolution.x; vx++) { Vector3 vert = Vector3.zero; vert.x = calculateVertAxis(vx, resolution.x, rect.width, meshMargins.left, meshMargins.right); vert.y = calculateVertAxis(vy, resolution.y, rect.height, meshMargins.top, meshMargins.bottom); verts.Add(vert + new Vector3(rect.x, rect.y, depth)); normals.Add(Vector3.back); Vector2 uv; uv.x = calculateVertAxis(vx, resolution.x, 1, uvMargins.left, uvMargins.right); uv.y = calculateVertAxis(vy, resolution.y, 1, uvMargins.top, uvMargins.bottom); uvs.Add(uv); } } // Back for (int vy = 0; vy < resolution.y - 1; vy++) { for (int vx = 0; vx < resolution.x - 1; vx++) { int vertIndex = vy * resolution.x + vx; tris.Add(vertIndex); tris.Add(vertIndex + 1); tris.Add(vertIndex + 1 + resolution.x); tris.Add(vertIndex); tris.Add(vertIndex + 1 + resolution.x); tris.Add(vertIndex + resolution.x); } } // Front for (int vy = 0; vy < resolution.y - 1; vy++) { for (int vx = 0; vx < resolution.x - 1; vx++) { int vertIndex = backVertsCount + (vy * resolution.x + vx); tris.Add(vertIndex); tris.Add(vertIndex + 1 + resolution.x); tris.Add(vertIndex + 1); tris.Add(vertIndex); tris.Add(vertIndex + resolution.x); tris.Add(vertIndex + 1 + resolution.x); } } // Edges int ex = 0, ey = 0; int backVertIdx = verts.Count, frontVertIdx = verts.Count; // Left for (int vy = 0; vy < resolution.y; vy++) { // Repeat back edge, left side Vector2 vert; vert.x = calculateVertAxis(ex, resolution.x, rect.width, meshMargins.left, meshMargins.right); vert.y = calculateVertAxis(vy, resolution.y, rect.height, meshMargins.top, meshMargins.bottom); verts.Add(vert + new Vector2(rect.x, rect.y)); normals.Add(Vector3.left); frontVertIdx += 1; Vector2 uv; uv.x = calculateVertAxis(ex, resolution.x, 1, uvMargins.left, uvMargins.right) + 0.01F /* cheat UVs in, prevents edge tearing */; uv.y = calculateVertAxis(vy, resolution.y, 1, uvMargins.top, uvMargins.bottom); uvs.Add(uv); } for (int vy = 0; vy < resolution.y; vy++) { // Repeat front edge, left side Vector3 vert = Vector3.zero; vert.x = calculateVertAxis(ex, resolution.x, rect.width, meshMargins.left, meshMargins.right); vert.y = calculateVertAxis(vy, resolution.y, rect.height, meshMargins.top, meshMargins.bottom); verts.Add(vert + new Vector3(rect.x, rect.y, depth)); normals.Add(Vector3.left); Vector2 uv; uv.x = calculateVertAxis(ex, resolution.x, 1, uvMargins.left, uvMargins.right); uv.y = calculateVertAxis(vy, resolution.y, 1, uvMargins.top, uvMargins.bottom); uvs.Add(uv); } for (int vy = 0; vy < resolution.y - 1; vy++) { // Add quads addQuad(tris, frontVertIdx + vy, backVertIdx + vy, backVertIdx + vy + 1, frontVertIdx + vy + 1); } // Right ex = resolution.x - 1; backVertIdx = verts.Count; frontVertIdx = verts.Count; for (int vy = 0; vy < resolution.y; vy++) { // Repeat back edge, right side Vector2 vert; vert.x = calculateVertAxis(ex, resolution.x, rect.width, meshMargins.left, meshMargins.right); vert.y = calculateVertAxis(vy, resolution.y, rect.height, meshMargins.top, meshMargins.bottom); verts.Add(vert + new Vector2(rect.x, rect.y)); normals.Add(Vector3.right); frontVertIdx += 1; Vector2 uv; uv.x = calculateVertAxis(ex, resolution.x, 1, uvMargins.left, uvMargins.right) - 0.01F /* cheat UVs in, prevents edge tearing */; uv.y = calculateVertAxis(vy, resolution.y, 1, uvMargins.top, uvMargins.bottom); uvs.Add(uv); } for (int vy = 0; vy < resolution.y; vy++) { // Repeat front edge, right side Vector3 vert = Vector3.zero; vert.x = calculateVertAxis(ex, resolution.x, rect.width, meshMargins.left, meshMargins.right); vert.y = calculateVertAxis(vy, resolution.y, rect.height, meshMargins.top, meshMargins.bottom); verts.Add(vert + new Vector3(rect.x, rect.y, depth)); normals.Add(Vector3.right); Vector2 uv; uv.x = calculateVertAxis(ex, resolution.x, 1, uvMargins.left, uvMargins.right); uv.y = calculateVertAxis(vy, resolution.y, 1, uvMargins.top, uvMargins.bottom); uvs.Add(uv); } for (int vy = 0; vy < resolution.y - 1; vy++) { // Add quads addQuad(tris, frontVertIdx + vy + 1, backVertIdx + vy + 1, backVertIdx + vy, frontVertIdx + vy); } // Top ey = resolution.y - 1; backVertIdx = verts.Count; frontVertIdx = verts.Count; for (int vx = 0; vx < resolution.x; vx++) { // Repeat back edge, upper side Vector2 vert; vert.x = calculateVertAxis(vx, resolution.x, rect.width, meshMargins.left, meshMargins.right); vert.y = calculateVertAxis(ey, resolution.y, rect.height, meshMargins.top, meshMargins.bottom); verts.Add(vert + new Vector2(rect.x, rect.y)); normals.Add(Vector3.up); frontVertIdx += 1; Vector2 uv; uv.x = calculateVertAxis(vx, resolution.x, 1, uvMargins.left, uvMargins.right); uv.y = calculateVertAxis(ey, resolution.y, 1, uvMargins.top, uvMargins.bottom) - 0.01F /* cheat UVs in, prevents edge tearing */; uvs.Add(uv); } for (int vx = 0; vx < resolution.x; vx++) { // Repeat front edge, upper side Vector3 vert = Vector3.zero; vert.x = calculateVertAxis(vx, resolution.x, rect.width, meshMargins.left, meshMargins.right); vert.y = calculateVertAxis(ey, resolution.y, rect.height, meshMargins.top, meshMargins.bottom); verts.Add(vert + new Vector3(rect.x, rect.y, depth)); normals.Add(Vector3.up); Vector2 uv; uv.x = calculateVertAxis(vx, resolution.x, 1, uvMargins.left, uvMargins.right); uv.y = calculateVertAxis(ey, resolution.y, 1, uvMargins.top, uvMargins.bottom); uvs.Add(uv); } for (int vx = 0; vx < resolution.x - 1; vx++) { // Add quads addQuad(tris, frontVertIdx + vx, backVertIdx + vx, backVertIdx + vx + 1, frontVertIdx + vx + 1); } // Bottom ey = 0; backVertIdx = verts.Count; frontVertIdx = verts.Count; for (int vx = 0; vx < resolution.x; vx++) { // Repeat back edge, upper side Vector2 vert; vert.x = calculateVertAxis(vx, resolution.x, rect.width, meshMargins.left, meshMargins.right); vert.y = calculateVertAxis(ey, resolution.y, rect.height, meshMargins.top, meshMargins.bottom); verts.Add(vert + new Vector2(rect.x, rect.y)); normals.Add(Vector3.down); frontVertIdx += 1; Vector2 uv; uv.x = calculateVertAxis(vx, resolution.x, 1, uvMargins.left, uvMargins.right); uv.y = calculateVertAxis(ey, resolution.y, 1, uvMargins.top, uvMargins.bottom) + 0.01F /* cheat UVs in, prevents edge tearing */; uvs.Add(uv); } for (int vx = 0; vx < resolution.x; vx++) { // Repeat front edge, upper side Vector3 vert = Vector3.zero; vert.x = calculateVertAxis(vx, resolution.x, rect.width, meshMargins.left, meshMargins.right); vert.y = calculateVertAxis(ey, resolution.y, rect.height, meshMargins.top, meshMargins.bottom); verts.Add(vert + new Vector3(rect.x, rect.y, depth)); normals.Add(Vector3.down); Vector2 uv; uv.x = calculateVertAxis(vx, resolution.x, 1, uvMargins.left, uvMargins.right); uv.y = calculateVertAxis(ey, resolution.y, 1, uvMargins.top, uvMargins.bottom); uvs.Add(uv); } for (int vx = 0; vx < resolution.x - 1; vx++) { // Add quads addQuad(tris, frontVertIdx + vx + 1, backVertIdx + vx + 1, backVertIdx + vx, frontVertIdx + vx); } if (mesh == null) { mesh = new Mesh(); } mesh.name = "Box Mesh"; mesh.hideFlags = HideFlags.HideAndDontSave; mesh.Clear(keepVertexLayout: false); mesh.SetVertices(verts); mesh.SetNormals(normals); mesh.SetTriangles(tris, 0); mesh.SetUVs(uvChannel.Index(), uvs); mesh.RecalculateBounds(); remappableChannels = UVChannelFlags.UV0; } private void addQuad(List<int> tris, int idx0, int idx1, int idx2, int idx3) { tris.Add(idx0); tris.Add(idx1); tris.Add(idx2); tris.Add(idx0); tris.Add(idx2); tris.Add(idx3); } } } <file_sep>/Assets/LeapMotion/Modules/GraphicRenderer/Scripts/Editor/MeshRendererConversion.cs /****************************************************************************** * Copyright (C) Leap Motion, Inc. 2011-2018. * * Leap Motion proprietary and confidential. * * * * Use subject to the terms of the Leap Motion SDK Agreement available at * * https://developer.leapmotion.com/sdk_agreement, or another agreement * * between Leap Motion and you, your company or other organization. * ******************************************************************************/ using System.Collections.Generic; using UnityEngine; using UnityEditor; using Leap.Unity.Query; namespace Leap.Unity.GraphicalRenderer { public static class MeshRendererConversion { private const string CONTEXT_PATH = "CONTEXT/MeshRenderer/Convert To Leap Graphic Mesh"; [MenuItem(CONTEXT_PATH)] public static void convert(MenuCommand command) { var graphicRenderer = (command.context as MeshRenderer).GetComponentInParent<LeapGraphicRenderer>(); if (graphicRenderer.groups.Count == 0) { graphicRenderer.editor.CreateGroup(typeof(LeapBakedRenderer)); } var group = graphicRenderer.groups[0]; var graphics = new List<LeapMeshGraphic>(); var meshRenderers = (command.context as MeshRenderer).GetComponentsInChildren<MeshRenderer>(); foreach (var meshRenderer in meshRenderers) { var material = meshRenderer.sharedMaterial; if (material == null) continue; var shader = material.shader; if (shader == null) continue; var filter = meshRenderer.GetComponent<MeshFilter>(); if (filter == null) continue; var mesh = filter.sharedMesh; if (mesh == null) continue; int propCount = ShaderUtil.GetPropertyCount(shader); for (int i = 0; i < propCount; i++) { if (ShaderUtil.GetPropertyType(shader, i) == ShaderUtil.ShaderPropertyType.TexEnv) { string propName = ShaderUtil.GetPropertyName(shader, i); if (material.GetTexture(propName) == null) continue; var feature = group.features.Query(). OfType<LeapTextureFeature>(). FirstOrDefault(f => f.propertyName == propName); if (feature == null) { feature = group.editor.AddFeature(typeof(LeapTextureFeature)) as LeapTextureFeature; feature.channel = UnityEngine.Rendering.UVChannelFlags.UV0; feature.propertyName = propName; } } } var graphic = meshRenderer.gameObject.AddComponent<LeapMeshGraphic>(); Undo.RegisterCreatedObjectUndo(graphic, "Create Leap Mesh Graphic"); group.TryAddGraphic(graphic); graphics.Add(graphic); } foreach (var graphic in graphics) { var meshRenderer = graphic.GetComponent<MeshRenderer>(); var meshFilter = graphic.GetComponent<MeshFilter>(); var material = meshRenderer.sharedMaterial; graphic.SetMesh(meshFilter.sharedMesh); foreach (var dataObj in graphic.featureData) { var textureData = dataObj as LeapTextureData; if (textureData == null) { continue; } var feature = textureData.feature as LeapTextureFeature; if (!material.HasProperty(feature.propertyName)) { continue; } Texture2D tex2d = material.GetTexture(feature.propertyName) as Texture2D; if (tex2d == null) { continue; } textureData.texture = tex2d; } Undo.DestroyObjectImmediate(meshRenderer); Undo.DestroyObjectImmediate(meshFilter); } group.renderer.editor.ScheduleRebuild(); } [MenuItem(CONTEXT_PATH, validate = true)] public static bool convertValidate(MenuCommand command) { var graphicRenderer = (command.context as MeshRenderer).GetComponentInParent<LeapGraphicRenderer>(); return graphicRenderer != null; } } } <file_sep>/Assets/LeapMotion/Modules/GraphicRenderer/Scripts/Utility/TextWrapper.cs /****************************************************************************** * Copyright (C) Leap Motion, Inc. 2011-2018. * * Leap Motion proprietary and confidential. * * * * Use subject to the terms of the Leap Motion SDK Agreement available at * * https://developer.leapmotion.com/sdk_agreement, or another agreement * * between Leap Motion and you, your company or other organization. * ******************************************************************************/ using System; using System.Collections.Generic; namespace Leap.Unity.GraphicalRenderer { public static class TextWrapper { /// <summary> /// References a contiguous sequence of characters in a string. /// </summary> public struct Token { public int start; public int end; public int length { get { return end - start; } set { end = start + value; } } public bool IsNewline(string source) { return source[start] == '\n'; } public bool IsWhitespace(string source) { return char.IsWhiteSpace(source[start]); } public float GetWidth(string source, Func<char, float> charWidth) { float width = 0; for (int i = 0; i < length; i++) { width += charWidth(source[i + start]); } return width; } } /// <summary> /// References a contiguous sequence of characters in a string /// </summary> public struct Line { public int start; public int end; public float width; public int length { get { return end - start; } set { end = start + value; } } public void TrimEnd(string source, Func<char, float> charWidth) { while (length > 0) { char end = source[start + length - 1]; if (char.IsWhiteSpace(end)) { width -= charWidth(end); length--; } else { return; } } } } /// <summary> /// Given a string, turn it into a list of tokens. A token is either: /// - A single whitespace character /// - A collection of non-whitespace characters /// This algorithm will never create more than one token from a contiguous /// section of non-whitespace tokens. /// </summary> public static void Tokenize(string text, List<Token> tokens) { int index = 0; int textLength = text.Length; while (true) { while (true) { if (index >= textLength) { return; } if (!char.IsWhiteSpace(text[index])) { break; } tokens.Add(new Token() { start = index, length = 1 }); index++; } Token token = new Token() { start = index }; index++; while (index < textLength && !char.IsWhiteSpace(text[index])) { index++; } token.length = index - token.start; tokens.Add(token); } } /// <summary> /// Given a list of tokens, turn it into a list of lines. /// The lines will satisfy the following properties: /// - No line will be longer than the maxLineWidth /// - No token will be split unless it is both /// - the first token on a line /// - too long to fit on the line /// - No line will contain any newline characters /// /// Note that width is not measured in character count, but in /// character width provided by the given delegate /// </summary> public static void Wrap(string source, List<Token> tokens, List<Line> lines, Func<char, float> widthFunc, float maxLineWidth) { if (tokens.Count == 0) { return; } int tokenIndex = 0; Token token = tokens[0]; while (true) { if (token.IsNewline(source)) { lines.Add(new Line() { start = token.start, length = 0, width = 0 }); goto LOOP_END; } NEW_LINE_CONTINUE_TOKEN: float firstTokenWidth = widthFunc(source[token.start]); //Line starts out equal to the first character of the first token Line line = new Line() { start = token.start, end = token.end, width = firstTokenWidth }; //Add as many of the rest of the characters of the token as we can for (int i = token.start + 1; i < token.end; i++) { float charWidth = widthFunc(source[i]); //If the line gets too big, we are forced to truncate! if (firstTokenWidth + charWidth > maxLineWidth) { line.end = i; line.width = firstTokenWidth; lines.Add(line); token.start = i; //Start a new line with the remainder of the current token goto NEW_LINE_CONTINUE_TOKEN; } firstTokenWidth += charWidth; } //Set line equal to the first token line.width = firstTokenWidth; line.length = token.length; //Move to the next token to begin adding them to the line tokenIndex++; if (tokenIndex >= tokens.Count) { //Line only contains first token, which cannot be whitespace, so we don't trim lines.Add(line); return; } token = tokens[tokenIndex]; //Fit the rest of the tokens on this line while (true) { //If the token is a newline, simply add the line and finish the main loop if (token.IsNewline(source)) { line.TrimEnd(source, widthFunc); lines.Add(line); break; } //If a non-whitespace token is too big, finish the line float tokenWidth = token.GetWidth(source, widthFunc); if (line.width + tokenWidth > maxLineWidth && !token.IsWhitespace(source)) { line.TrimEnd(source, widthFunc); lines.Add(line); //Go start a new line with the current token goto NEW_LINE_CONTINUE_TOKEN; } //Otherwise append to the line and keep trying tokens line.length += token.length; line.width += tokenWidth; tokenIndex++; if (tokenIndex >= tokens.Count) { lines.Add(line); return; } token = tokens[tokenIndex]; } LOOP_END: tokenIndex++; if (tokenIndex >= tokens.Count) { return; } token = tokens[tokenIndex]; } } } } <file_sep>/Assets/LeapMotion/Modules/GraphicRenderer/Scripts/Graphics/ProceduralMeshGraphics/Abstract/LeapSlicedGraphic.cs /****************************************************************************** * Copyright (C) Leap Motion, Inc. 2011-2018. * * Leap Motion proprietary and confidential. * * * * Use subject to the terms of the Leap Motion SDK Agreement available at * * https://developer.leapmotion.com/sdk_agreement, or another agreement * * between Leap Motion and you, your company or other organization. * ******************************************************************************/ using Leap.Unity.Attributes; using Leap.Unity.Query; using UnityEngine; using UnityEngine.Rendering; namespace Leap.Unity.GraphicalRenderer { /// <summary> /// The base class for LeapPanelGraphic, LeapBoxGraphic, and similar generators. /// </summary> /// <details> /// This base class represents shared code when constructing graphics that: /// - Are generally rectangular, supporting dynamic tesselation along the X and Y axes /// - Can be intuitively controlled by an associated RectTransform /// - Support nine-slicing when using a Sprite as a source for Texture data /// </details> [DisallowMultipleComponent] public abstract class LeapSlicedGraphic : LeapMeshGraphicBase { #region Constants public const int MAX_RESOLUTION = 128; #endregion #region Inspector [EditTimeOnly] [SerializeField] protected int _sourceDataIndex = -1; //************// // Resolution // [Tooltip("Specifies whether or not this panel has a specific resolution, or whether this " + "panel automatically changes its resolution based on its size")] [EditTimeOnly] [SerializeField] protected ResolutionType _resolutionType = ResolutionType.VerticesPerRectilinearMeter; [HideInInspector] [SerializeField] protected int _resolution_vert_x = 4, _resolution_vert_y = 4; [EditTimeOnly] [SerializeField] protected Vector2 _resolution_verts_per_meter = new Vector2(20, 20); [MinValue(0)] [EditTimeOnly] [SerializeField] protected Vector2 _size = new Vector2(0.1f, 0.1f); //**************// // Nine Slicing // [Tooltip("Uses sprite data to generate a nine sliced panel.")] [EditTimeOnly] [SerializeField] protected bool _nineSliced = false; #endregion #region Properties /// <summary> /// Returns the current resolution type being used for this panel. /// </summary> public ResolutionType resolutionType { get { return _resolutionType; } } /// <summary> /// Returns the current local-space rect of this panel. If there is a /// RectTransform attached to this panel, this value is the same as calling /// rectTransform.rect. /// </summary> public Rect rect { get { RectTransform rectTransform = GetComponent<RectTransform>(); if (rectTransform != null) { _size = rectTransform.rect.size; return rectTransform.rect; } else { return new Rect(-_size / 2, _size); } } } /// <summary> /// Gets or sets whether or not this panel is currently using nine slicing. /// </summary> public bool nineSliced { get { return _nineSliced && canNineSlice; } set { _nineSliced = value; setSourceFeatureDirty(); } } /// <summary> /// Returns whether or not the current source supports nine slicing. /// </summary> public bool canNineSlice { get { var spriteData = sourceData as LeapSpriteData; return spriteData != null && spriteData.sprite != null; } } /// <summary> /// Returns which uv channel is being used for this panel. It will /// always match the uv channel being used by the source. /// </summary> public UVChannelFlags uvChannel { get { if (sourceData == null) { return UVChannelFlags.UV0; } var feature = sourceData.feature; if (feature is LeapTextureFeature) { return (feature as LeapTextureFeature).channel; } else if (feature is LeapSpriteFeature) { return (feature as LeapSpriteFeature).channel; } else { return UVChannelFlags.UV0; } } } #endregion #region Unity Events protected override void Reset() { base.Reset(); assignDefaultSourceValue(); setSourceFeatureDirty(); } protected override void OnValidate() { base.OnValidate(); if (sourceData == null) { assignDefaultSourceValue(); } _resolution_vert_x = Mathf.Max(0, _resolution_vert_x); _resolution_vert_y = Mathf.Max(0, _resolution_vert_y); _resolution_verts_per_meter = Vector2.Max(_resolution_verts_per_meter, Vector2.zero); if (_resolutionType == ResolutionType.Vertices) { _resolution_verts_per_meter.x = _resolution_vert_x / rect.width; _resolution_verts_per_meter.y = _resolution_vert_y / rect.height; } else { _resolution_vert_x = Mathf.RoundToInt(_resolution_verts_per_meter.x * rect.width); _resolution_vert_y = Mathf.RoundToInt(_resolution_verts_per_meter.y * rect.height); } setSourceFeatureDirty(); } #endregion #region Leap Graphic /// <summary> /// Returns the current feature data object being used as source. /// </summary> public LeapFeatureData sourceData { get { if (_sourceDataIndex == -1) { assignDefaultSourceValue(); } if (_sourceDataIndex < 0 || _sourceDataIndex >= featureData.Count) { return null; } return featureData[_sourceDataIndex]; } #if UNITY_EDITOR set { _sourceDataIndex = _featureData.IndexOf(value); setSourceFeatureDirty(); } #endif } /// <summary> /// Returns whether or not a feature data object is a valid object /// that can be used to drive texture data for this panel. Only /// a TextureData object or a SpriteData object are currently valid. /// </summary> public static bool IsValidDataSource(LeapFeatureData dataSource) { return dataSource is LeapTextureData || dataSource is LeapSpriteData; } protected void assignDefaultSourceValue() { _sourceDataIndex = featureData.Query().IndexOf(IsValidDataSource); } protected void setSourceFeatureDirty() { if (sourceData != null) { sourceData.MarkFeatureDirty(); } } #endregion #region Leap Mesh Graphic public override void RefreshMeshData() { if (sourceData == null) { assignDefaultSourceValue(); } Vector4 borderSize = Vector4.zero; Vector4 borderUvs = Vector4.zero; Rect rect; RectTransform rectTransform = GetComponent<RectTransform>(); if (rectTransform != null) { rect = rectTransform.rect; _size = rect.size; } else { rect = new Rect(-_size / 2, _size); } if (_nineSliced && sourceData is LeapSpriteData) { var spriteData = sourceData as LeapSpriteData; if (spriteData.sprite == null) { mesh = null; remappableChannels = 0; return; } var sprite = spriteData.sprite; Vector4 border = sprite.border; borderSize = border / sprite.pixelsPerUnit; borderUvs = border; borderUvs.x /= sprite.textureRect.width; borderUvs.z /= sprite.textureRect.width; borderUvs.y /= sprite.textureRect.height; borderUvs.w /= sprite.textureRect.height; } int vertsX, vertsY; if (_resolutionType == ResolutionType.Vertices) { vertsX = Mathf.RoundToInt(_resolution_vert_x); vertsY = Mathf.RoundToInt(_resolution_vert_y); } else { vertsX = Mathf.RoundToInt(rect.width * _resolution_verts_per_meter.x); vertsY = Mathf.RoundToInt(rect.height * _resolution_verts_per_meter.y); } vertsX += _nineSliced ? 4 : 2; vertsY += _nineSliced ? 4 : 2; vertsX = Mathf.Min(vertsX, MAX_RESOLUTION); vertsY = Mathf.Min(vertsY, MAX_RESOLUTION); RefreshSlicedMeshData(new Vector2i() { x = vertsX, y = vertsY }, borderSize, borderUvs); } #endregion /// <summary> /// Set the mesh property equal to the correct mesh given the Sliced Graphic's /// current settings. /// /// Resolution along the X and Y axes are provided, as well as mesh-space and /// UV-space margins to pass into calculateVertAxis as border0 and border1 to support /// nine slicing (see Mesh Data Support). /// </summary> public abstract void RefreshSlicedMeshData(Vector2i resolution, RectMargins meshMargins, RectMargins uvMargins); #region Mesh Data Support /// <summary> /// Given a vertex index from an edge, the total vertCount and size /// along the current dimension, and the distance to the beginning and end borders /// along the current dimension (if nine-slicing is enabled ONLY), this method will /// return the distance along the current dimension that the vertIdx should be from /// the origin of the dimension. /// /// If the sliced graphic has nine-slicing enabled, or if alwaysRespectBorder is /// set to true, the second and second-to-last vertices along an edge will reflect /// the border margin arguments instead of a uniform tesselation along the whole /// width of the dimension. Inner vertices will then respect this non-uniformity, /// slicing the rest of the inner width evenly. /// /// e.g. Determine the distance along the X axis for: /// - vertIdx = 4, the fifth vertex along the X axis /// - vertCount = 16, given sixteen total grid columns (16 verts per X-axis row) /// - size = 2, given a box width of 2 units /// - border0 = 0.2f, given the left border starts at 0.2 units from the left edge /// - border1 = 0.2f, given the right border starts at 0.2 units from the right edge /// This method will return the X axis coordinate of the fifth vertex accordingly. /// To calculate the corresponding Y axis coordinate, simply provide the vertCount, /// size, and border information for the Y dimension instead. /// </summary> protected float calculateVertAxis(int vertIdx, int vertCount, float size, float border0, float border1, bool alwaysRespectBorder = false) { if (_nineSliced || alwaysRespectBorder) { if (vertIdx == 0) { return 0; } else if (vertIdx == (vertCount - 1)) { return size; } else if (vertIdx == 1) { return border0; } else if (vertIdx == (vertCount - 2)) { return size - border1; } else { return ((vertIdx - 1.0f) / (vertCount - 3.0f)) * (size - border0 - border1) + border0; } } else { return (vertIdx / (vertCount - 1.0f)) * size; } } #endregion #region Supporting Types public enum ResolutionType { Vertices, VerticesPerRectilinearMeter } public struct Vector2i { public int x; public int y; } public struct RectMargins { /// <summary> Margin width from the left edge. </summary> public float left; /// <summary> Margin width from the top edge. </summary> public float top; /// <summary> Margin width from the right edge. </summary> public float right; /// <summary> Margin width from the bottom edge. </summary> public float bottom; public RectMargins(float left, float top, float right, float bottom) { this.left = left; this.top = top; this.right = right; this.bottom = bottom; } public static implicit operator Vector4(RectMargins m) { return new Vector4(m.left, m.top, m.right, m.bottom); } public static implicit operator RectMargins(Vector4 v) { return new RectMargins(v.x, v.y, v.z, v.w); } } #endregion } } <file_sep>/Assets/Hover/Core/Scripts/Cursors/HoverCursorRenderersBuilder.cs using Hover.Core.Utils; using UnityEngine; namespace Hover.Core.Cursors { /*================================================================================================*/ [ExecuteInEditMode] public class HoverCursorRenderersBuilder : MonoBehaviour { public CursorCapabilityType MinimumCapabilityType = CursorCapabilityType.None; public GameObject CursorRendererPrefab; public GameObject IdleRendererPrefab; [TriggerButton("Build Cursor Renderers")] public bool ClickToBuild; //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public void Awake() { if ( CursorRendererPrefab == null ) { CursorRendererPrefab = Resources.Load<GameObject>( "Prefabs/HoverOpaqueCursorArcRenderer-Default"); } if ( IdleRendererPrefab == null ) { IdleRendererPrefab = Resources.Load<GameObject>( "Prefabs/HoverOpaqueIdleArcRenderer-Default"); } } /*--------------------------------------------------------------------------------------------*/ public void OnEditorTriggerButtonSelected() { UnityUtil.FindOrAddHoverKitPrefab(); PerformBuild(); } /*--------------------------------------------------------------------------------------------*/ public void Update() { if ( ClickToBuild ) { DestroyImmediate(this, false); } } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public void PerformBuild() { HoverCursorDataProvider cursorProv = FindObjectOfType<HoverCursorDataProvider>(); foreach ( ICursorData cursorData in cursorProv.Cursors ) { if ( cursorData.Capability < MinimumCapabilityType ) { continue; } BuildCursor(cursorProv, cursorData); } } /*--------------------------------------------------------------------------------------------*/ private void BuildCursor(HoverCursorDataProvider pProv, ICursorData pData) { var curGo = new GameObject(pData.Type+""); curGo.transform.SetParent(gameObject.transform, false); TreeUpdater treeUp = curGo.AddComponent<TreeUpdater>(); HoverCursorFollower follow = curGo.AddComponent<HoverCursorFollower>(); follow.CursorDataProvider = pProv; follow.CursorType = pData.Type; follow.FollowCursorActive = false; follow.ScaleUsingCursorSize = true; HoverCursorRendererUpdater cursRendUp = curGo.AddComponent<HoverCursorRendererUpdater>(); cursRendUp.CursorRendererPrefab = CursorRendererPrefab; if ( pData.Idle != null ) { HoverIdleRendererUpdater idleRendUp = curGo.AddComponent<HoverIdleRendererUpdater>(); idleRendUp.IdleRendererPrefab = IdleRendererPrefab; } follow.Update(); //moves interface to the correct cursor transform treeUp.Update(); //force renderer creation } } } <file_sep>/Assets/LeapMotion/Modules/InteractionEngine/Scripts/UI/Anchors/Editor/AnchorEditor.cs /****************************************************************************** * Copyright (C) Leap Motion, Inc. 2011-2018. * * Leap Motion proprietary and confidential. * * * * Use subject to the terms of the Leap Motion SDK Agreement available at * * https://developer.leapmotion.com/sdk_agreement, or another agreement * * between Leap Motion and you, your company or other organization. * ******************************************************************************/ using Leap.Unity; using System.Collections; using System.Collections.Generic; using UnityEditor; using UnityEngine; namespace Leap.Unity.Interaction { [CanEditMultipleObjects] [CustomEditor(typeof(Anchor))] public class AnchorEditor : CustomEditorBase<Anchor> { protected override void OnEnable() { base.OnEnable(); deferProperty("_eventTable"); specifyCustomDrawer("_eventTable", drawEventTable); } private EnumEventTableEditor _tableEditor; private void drawEventTable(SerializedProperty property) { if (_tableEditor == null) { _tableEditor = new EnumEventTableEditor(property, typeof(Anchor.EventType)); } _tableEditor.DoGuiLayout(); } } } <file_sep>/Assets/Hover/Core/Scripts/Layouts/Rect/HoverLayoutRectGroup.cs using System.Collections.Generic; using Hover.Core.Utils; using UnityEngine; namespace Hover.Core.Layouts.Rect { /*================================================================================================*/ [ExecuteInEditMode] [RequireComponent(typeof(TreeUpdater))] public abstract class HoverLayoutRectGroup : MonoBehaviour, ISettingsController, ITreeUpdateable { public ISettingsControllerMap Controllers { get; private set; } protected readonly List<HoverLayoutRectGroupChild> vChildItems; //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ protected HoverLayoutRectGroup() { Controllers = new SettingsControllerMap(); vChildItems = new List<HoverLayoutRectGroupChild>(); } /*--------------------------------------------------------------------------------------------*/ public int ChildCount { get { return vChildItems.Count; } } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public void Start() { //do nothing... } /*--------------------------------------------------------------------------------------------*/ public virtual void TreeUpdate() { FillChildItemsList(); Controllers.TryExpireControllers(); } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ protected virtual void FillChildItemsList() { vChildItems.Clear(); int childCount = transform.childCount; for ( int i = 0 ; i < childCount ; i++ ) { Transform childTx = transform.GetChild(i); ILayoutableRect elem = childTx.GetComponent<ILayoutableRect>(); if ( elem == null ) { //Debug.LogWarning("Item '"+childTx.name+"' does not have a renderer "+ // "that implements '"+typeof(IRectangleLayoutElement).Name+"'."); continue; } if ( !elem.isActiveAndEnabled ) { continue; } var item = new HoverLayoutRectGroupChild(elem, childTx.GetComponent<HoverLayoutRectRelativeSizer>()); vChildItems.Add(item); } } } } <file_sep>/Assets/Hover/Core/Scripts/Items/Managers/HoverItemsRaycastManager.cs using System; using System.Collections.Generic; using Hover.Core.Cursors; using Hover.Core.Utils; using UnityEngine; namespace Hover.Core.Items.Managers { /*================================================================================================*/ [RequireComponent(typeof(HoverItemsManager))] public class HoverItemsRaycastManager : MonoBehaviour { public HoverCursorDataProvider CursorDataProvider; private List<HoverItemHighlightState> vHighStates; //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public void Awake() { if ( CursorDataProvider == null ) { CursorDataProvider = FindObjectOfType<HoverCursorDataProvider>(); } if ( CursorDataProvider == null ) { throw new ArgumentNullException("CursorDataProvider"); } vHighStates = new List<HoverItemHighlightState>(); } /*--------------------------------------------------------------------------------------------*/ public void Update() { HoverItemsManager itemsMan = GetComponent<HoverItemsManager>(); itemsMan.FillListWithExistingItemComponents(vHighStates); CalcNearestRaycastResults(); } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ private void CalcNearestRaycastResults() { List<ICursorData> cursors = CursorDataProvider.Cursors; int cursorCount = cursors.Count; for ( int i = 0 ; i < cursorCount ; i++ ) { ICursorData cursor = cursors[i]; cursor.BestRaycastResult = CalcNearestRaycastResult(cursor); /*if ( cursor.BestRaycastResult != null ) { Color col = (cursor.BestRaycastResult.Value.IsHit ? Color.green : Color.red); Debug.DrawLine(cursor.BestRaycastResult.Value.WorldPosition, cursor.WorldPosition, col); }*/ } } /*--------------------------------------------------------------------------------------------*/ private RaycastResult? CalcNearestRaycastResult(ICursorData pCursor) { if ( !pCursor.IsRaycast || !pCursor.CanCauseSelections ) { return null; } float minHighSqrDist = float.MaxValue; float minCastSqrDist = float.MaxValue; var worldRay = new Ray(pCursor.WorldPosition, pCursor.WorldRotation*pCursor.RaycastLocalDirection); RaycastResult result = new RaycastResult(); result.WorldPosition = worldRay.GetPoint(10000); result.WorldRotation = pCursor.WorldRotation; for ( int i = 0 ; i < vHighStates.Count ; i++ ) { HoverItemHighlightState item = vHighStates[i]; if ( !item.isActiveAndEnabled || item.IsHighlightPreventedViaAnyDisplay() ) { continue; } RaycastResult raycast; Vector3 nearHighWorldPos = item.ProximityProvider .GetNearestWorldPosition(worldRay, out raycast); if ( !raycast.IsHit ) { continue; } float highSqrDist = (raycast.WorldPosition-nearHighWorldPos).sqrMagnitude; float castSqrDist = (raycast.WorldPosition-pCursor.WorldPosition).sqrMagnitude; //float hitSqrDist = Mathf.Pow(item.InteractionSettings.HighlightDistanceMin, 2); float hitSqrDist = 0.0000001f; highSqrDist = Mathf.Max(highSqrDist, hitSqrDist); bool isHighlightWorse = (highSqrDist > minHighSqrDist); bool isComparingHits = (highSqrDist <= hitSqrDist && minHighSqrDist <= hitSqrDist); bool isRaycastNearer = (castSqrDist < minCastSqrDist); if ( isHighlightWorse || (isComparingHits && !isRaycastNearer) ) { continue; } minHighSqrDist = highSqrDist; minCastSqrDist = castSqrDist; result = raycast; } return result; } } } <file_sep>/Assets/LeapMotion/Modules/InteractionEngine/Examples/6. Dynamic UI/Tests/Scripts/RenderWireSphere.cs /****************************************************************************** * Copyright (C) Leap Motion, Inc. 2011-2018. * * Leap Motion proprietary and confidential. * * * * Use subject to the terms of the Leap Motion SDK Agreement available at * * https://developer.leapmotion.com/sdk_agreement, or another agreement * * between Leap Motion and you, your company or other organization. * ******************************************************************************/ using Leap.Unity.RuntimeGizmos; using System.Collections; using System.Collections.Generic; using UnityEngine; namespace Leap.Unity.Examples { [AddComponentMenu("")] public class RenderWireSphere : MonoBehaviour, IRuntimeGizmoComponent { public float radius = 0.30F; public Color color = Color.red; public void OnDrawRuntimeGizmos(RuntimeGizmoDrawer drawer) { if (!gameObject.activeInHierarchy) return; drawer.color = color; drawer.DrawWireSphere(this.transform.position, radius); } } } <file_sep>/Assets/LeapMotion/Modules/InteractionEngine/Examples/2. Basic UI/MovePoseExample.cs /****************************************************************************** * Copyright (C) Leap Motion, Inc. 2011-2018. * * Leap Motion proprietary and confidential. * * * * Use subject to the terms of the Leap Motion SDK Agreement available at * * https://developer.leapmotion.com/sdk_agreement, or another agreement * * between Leap Motion and you, your company or other organization. * ******************************************************************************/ using UnityEngine; namespace Leap.Unity.Interaction.Examples { public class MovePoseExample : MonoBehaviour { public Transform target; private Pose _selfToTargetPose = Pose.identity; private void OnEnable() { _selfToTargetPose = this.transform.ToPose().inverse * target.transform.ToPose(); } private void Start() { #if UNITY_2017_2_OR_NEWER if (Physics.autoSyncTransforms) { Debug.LogWarning( "Physics.autoSyncTransforms is enabled. This will cause Interaction " + "Buttons and similar elements to 'wobble' when this script is used to " + "move a parent transform. You can modify this setting in " + "Edit->Project Settings->Physics."); } #endif } private void Update() { target.transform.SetPose(this.transform.ToPose() * _selfToTargetPose); } } } <file_sep>/Assets/LeapMotion/Modules/GraphicRenderer/Scripts/Graphics/ProceduralMeshGraphics/Editor/LeapPanelOutlineGraphicEditor.cs /****************************************************************************** * Copyright (C) Leap Motion, Inc. 2011-2018. * * Leap Motion proprietary and confidential. * * * * Use subject to the terms of the Leap Motion SDK Agreement available at * * https://developer.leapmotion.com/sdk_agreement, or another agreement * * between Leap Motion and you, your company or other organization. * ******************************************************************************/ using System; using System.Collections.Generic; using UnityEngine; using UnityEditor; using Leap.Unity.Query; namespace Leap.Unity.GraphicalRenderer { [CanEditMultipleObjects] [CustomEditor(typeof(LeapPanelOutlineGraphic), editorForChildClasses: true)] public class LeapPanelOutlineGraphicEditor : LeapSlicedGraphicEditor { protected override void OnEnable() { base.OnEnable(); specifyConditionalDrawing(() => targets.Query() .Cast<LeapPanelOutlineGraphic>() .Any(t => !t.nineSliced || t.overrideSpriteBorders), "_thickness"); } } } <file_sep>/Assets/LeapMotion/Core/Scripts/Attachments/AttachmentHandEnableDisable.cs /****************************************************************************** * Copyright (C) Leap Motion, Inc. 2011-2018. * * Leap Motion proprietary and confidential. * * * * Use subject to the terms of the Leap Motion SDK Agreement available at * * https://developer.leapmotion.com/sdk_agreement, or another agreement * * between Leap Motion and you, your company or other organization. * ******************************************************************************/ using Leap.Unity; using Leap.Unity.Attachments; using System.Collections; using System.Collections.Generic; using UnityEngine; namespace Leap.Unity.Attachments { public class AttachmentHandEnableDisable : MonoBehaviour { public AttachmentHand attachmentHand; void Update() { // Deactivation trigger if (!attachmentHand.isTracked && attachmentHand.gameObject.activeSelf) { attachmentHand.gameObject.SetActive(false); } // Reactivation trigger if (attachmentHand.isTracked && !attachmentHand.gameObject.activeSelf) { attachmentHand.gameObject.SetActive(true); } } } } <file_sep>/Assets/LeapMotion/Core/Scripts/Utils/RuntimeColliderGizmos.cs /****************************************************************************** * Copyright (C) Leap Motion, Inc. 2011-2018. * * Leap Motion proprietary and confidential. * * * * Use subject to the terms of the Leap Motion SDK Agreement available at * * https://developer.leapmotion.com/sdk_agreement, or another agreement * * between Leap Motion and you, your company or other organization. * ******************************************************************************/ using UnityEngine; namespace Leap.Unity.RuntimeGizmos { public class RuntimeColliderGizmos : MonoBehaviour, IRuntimeGizmoComponent { public Color color = Color.white; public bool useWireframe = true; public bool traverseHierarchy = true; public bool drawTriggers = false; /// <summary> /// An empty Start() method; gives the MonoBehaviour an enable/disable checkbox. /// </summary> void Start() { } public void OnDrawRuntimeGizmos(RuntimeGizmoDrawer drawer) { if (!this.gameObject.activeInHierarchy || !this.enabled) return; drawer.color = color; drawer.DrawColliders(gameObject, useWireframe, traverseHierarchy, drawTriggers); } } } <file_sep>/Assets/Hover/Core/Scripts/Items/Managers/HoverItemSelectionState.cs using System; using Hover.Core.Cursors; using Hover.Core.Items.Types; using UnityEngine; namespace Hover.Core.Items.Managers { /*================================================================================================*/ [RequireComponent(typeof(HoverItem))] [RequireComponent(typeof(HoverItemHighlightState))] public class HoverItemSelectionState : MonoBehaviour { public float SelectionProgress { get; private set; } public bool IsSelectionPrevented { get; private set; } public bool WasSelectedThisFrame { get; private set; } private DateTime? vSelectionStart; private float vDistanceUponSelection; //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public void Update() { TryResetSelection(); UpdateSelectionProgress(); UpdateState(); UpdateNearestCursor(); } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ private void TryResetSelection() { if ( !GetComponent<HoverItemHighlightState>().IsHighlightPrevented ) { return; } HoverItemData itemData = GetComponent<HoverItem>().Data; IItemDataSelectable selData = (itemData as IItemDataSelectable); vSelectionStart = null; if ( selData != null ) { selData.DeselectStickySelections(); } } /*--------------------------------------------------------------------------------------------*/ private void UpdateSelectionProgress() { HoverItemHighlightState highState = GetComponent<HoverItemHighlightState>(); if ( vSelectionStart == null ) { HoverItemData itemData = GetComponent<HoverItem>().Data; IItemDataSelectable selData = (itemData as IItemDataSelectable); if ( selData == null || !selData.IsStickySelected ) { SelectionProgress = 0; return; } HoverItemHighlightState.Highlight? nearestHigh = highState.NearestHighlight; float nearDist = highState.InteractionSettings.StickyReleaseDistance; float minHighDist = (nearestHigh == null ? float.MaxValue : nearestHigh.Value.Distance); SelectionProgress = Mathf.InverseLerp(nearDist, vDistanceUponSelection, minHighDist); return; } float ms = (float)(DateTime.UtcNow-(DateTime)vSelectionStart).TotalMilliseconds; SelectionProgress = Math.Min(1, ms/highState.InteractionSettings.SelectionMilliseconds); } /*--------------------------------------------------------------------------------------------*/ private bool UpdateState() { HoverItemData itemData = GetComponent<HoverItem>().Data; IItemDataSelectable selData = (itemData as IItemDataSelectable); WasSelectedThisFrame = false; if ( selData == null || selData.IgnoreSelection ) { return false; } //// HoverItemHighlightState highState = GetComponent<HoverItemHighlightState>(); bool hasNearestCursorWithFullHigh = false; bool canDeselect = ( highState.IsHighlightPrevented || !highState.IsNearestAcrossAllItemsForAnyCursor || !selData.IsEnabled ); for ( int i = 0 ; i < highState.Highlights.Count ; i++ ) { HoverItemHighlightState.Highlight high = highState.Highlights[i]; if ( high.IsNearestAcrossAllItems && high.Progress >= 1 ) { hasNearestCursorWithFullHigh = true; break; } } if ( SelectionProgress <= 0 || canDeselect ) { selData.DeselectStickySelections(); } if ( canDeselect || !hasNearestCursorWithFullHigh ) { IsSelectionPrevented = false; vSelectionStart = null; return false; } //// if ( IsSelectionPrevented ) { vSelectionStart = null; return false; } if ( vSelectionStart == null ) { vSelectionStart = DateTime.UtcNow; return false; } if ( SelectionProgress < 1 ) { return false; } vSelectionStart = null; IsSelectionPrevented = true; WasSelectedThisFrame = true; vDistanceUponSelection = highState.NearestHighlight.Value.Distance; selData.Select(); return true; } /*--------------------------------------------------------------------------------------------*/ private void UpdateNearestCursor() { HoverItemHighlightState highState = GetComponent<HoverItemHighlightState>(); HoverItemHighlightState.Highlight? nearestHigh = highState.NearestHighlight; if ( nearestHigh == null ) { return; } ICursorData cursor = nearestHigh.Value.Cursor; cursor.MaxItemSelectionProgress = Mathf.Max( cursor.MaxItemSelectionProgress, SelectionProgress); } } } <file_sep>/Assets/IronManUI/Scripts/UI/Fingertip.cs /** * Author: <NAME> * Created: 01.18.2019 * * MIT Reality Virtually Hackathon **/ using UnityEngine; using System.Collections.Generic; namespace IronManUI { [RequireComponent(typeof(Rigidbody))] public class Fingertip : MonoBehaviour { public Rigidbody rbody; private bool previouslyGrabbing; public bool grabbing; // public bool grabbing { // get { // return _grabbing; // } // set { // if (_grabbing == value) // return; // _grabbing = value; // if (_grabbing) // BeginGrab(); // else // EndGrab(); // } // } protected float passiveTouchForce = 1.5f; /** For velocity */ private Vector3? previousPosition; protected Vector3 velocity; private HashSet<AbstractIMComponent> touchingCompList = new HashSet<AbstractIMComponent>(); // private GrabInfo currentGrab; protected void OnEnable() { // collider. rbody = GetComponent<Rigidbody>(); previousPosition = transform.position; } protected void Update() { UpdateVelocity(); UpdateGrab(); } protected void UpdateVelocity() { /** Calculate velocity (kinematic rigidbodies don't track this...)*/ if (previousPosition.HasValue) { velocity = (transform.position - previousPosition.Value) / Time.deltaTime; } else { velocity = Vector3.zero; } previousPosition = transform.position; } protected void UpdateGrab() { if (grabbing != previouslyGrabbing) { if (grabbing) BeginGrab(); // else // EndGrab(); previouslyGrabbing = grabbing; } // if (currentGrab == null) // return; // var moveDelta = transform.position - currentGrab.fingerAnchor; // // currentGrab.component.translationMotion.origin = currentGrab.componentAnchor + moveDelta; // currentGrab.component.model.targetPosition = currentGrab.componentAnchor + moveDelta; } void OnCollisionEnter(Collision collision) { // Debug.Log("Fingertip Collision enter"); var component = collision.GetIronManComponent(); if (component != null) { touchingCompList.Add(component); } } /** Applies force to component motion integrator so it subtly reacts to user's fingers */ void OnCollisionStay(Collision collision) { var component = collision.GetIronManComponent(); if (component != null) { // Debug.Log("Component: " + component + " , motion: " + component.translationMotion); // var deltaVelocity = collision.relativeVelocity - component.velocity; //AM relative velocity does not incorporate velocity of the non-rigidbody collider var deltaVelocity = velocity - component.translationMotion.velocity; // Debug.Log("Touched UI Moved: " + component); if (velocity.magnitude < 10) component.translationMotion.AddAcceleration(deltaVelocity * passiveTouchForce); // Debug.Log("delta v: " + deltaVelocity); } } void OnCollisionExit(Collision collision) { // Debug.Log("Fingertip Collision exit"); var component = collision.GetIronManComponent(); if (component != null) { touchingCompList.Remove(component); } // if (currentGrab != null && component == currentGrab.component) { // EndGrab(); // } } public void BeginGrab() { foreach (var comp in touchingCompList) { Debug.Log("Beginning Grab: " + comp); comp.grab.Begin(this, transform.position); } } // public void EndGrab() { // if (currentGrab != null) { // currentGrab.component.translationMotion.origin = null; //remove spring force // currentGrab = null; // Debug.Log("Ending Grab"); // } // } } }<file_sep>/Assets/IronManUI/Scripts/PresentationManager.cs /** * Author: <NAME> * Created: 01.19.2019 * * MIT Reality Virtually Hackathon **/ using UnityEngine; using System.Collections.Generic; using System.IO; namespace IronManUI { [System.Serializable] public class SlideModel { public string name; public Vector3 position; public List<IMComponentModel> components = new List<IMComponentModel>(); } [System.Serializable] public class PresentationModel { public string name = "Untitled"; public List<SlideModel> slides = new List<SlideModel>(); public string SaveToJson() { return JsonUtility.ToJson(this, true); } public void LoadFromJson(string json) { JsonUtility.FromJsonOverwrite(json, this); } } public class PresentationManager : MonoBehaviour { public static PresentationManager instance { get; private set; } public string presentationFile = "Assets/Resources/Presentations/Main Presentation.pxr"; public string presentationName = "Untitled"; public Slide slidePrefab; public TextBox textPrefab; public ThreeDItem threeDPrefab; private Slide _currentSlide; public Slide currentSlide { get { return _currentSlide; } set { if (_currentSlide == value) return; if (_currentSlide != null) { _currentSlide.Deactivate(); } _currentSlide = value; _currentSlide.Activate(); } } // private PresentationModel model; void OnEnable() { if (instance != null && instance != this) Debug.LogWarning("Having multiple presentations in a scene is not supported"); instance = this; Load(); } public void Load() { string json = File.ReadAllText(presentationFile); PresentationModel model; if (json != null && json.Length > 0) { model = new PresentationModel(); model.LoadFromJson(json); } else { model = MakeDefault(); } SetModel(model); } public void Save() { var model = ExtractModel(); string json = model.SaveToJson(); File.WriteAllText(presentationFile, json); } protected void SetModel(PresentationModel model) { presentationName = model.name; GetComponentsInChildren<Slide>().DestroyAllGameObjects(); foreach (var slideModel in model.slides) { var slideObject = Instantiate(slidePrefab); slideObject.SetModel(this, slideModel); slideObject.transform.parent = transform; } } protected PresentationModel ExtractModel() { var model = new PresentationModel(); model.name = presentationName; foreach (var slide in GetComponentsInChildren<Slide>()) { model.slides.Add(slide.ExtractModel()); } return model; } public PresentationModel MakeDefault() { var model = new PresentationModel(); var slide1 = new SlideModel(); slide1.name = "Test slide 1"; model.slides.Add(slide1); var slide2 = new SlideModel(); slide2.name = "Test slide 2"; model.slides.Add(slide2); return model; } public AbstractIMComponent InstantiateComponent(IMComponentModel model) { if (model == null) { Debug.LogWarning("Cannot create component for null model"); return null; } if (model is TextBoxModel) { var textbox = Instantiate(textPrefab) as TextBox; textbox.model.Copy(model); } else if (model is ThreeDItemModel) { var item = Instantiate(threeDPrefab); item.model.Copy(model); } Debug.LogWarning("Cannot create component for model: " + model.GetType()); return null; } public void SlideWaypointTouched(Slide slide) { if (slide == null) return; currentSlide = slide; } } }<file_sep>/Assets/Hover/Core/Scripts/Renderers/Items/Sliders/HoverFillSlider.cs using System.Collections.Generic; using Hover.Core.Renderers.Shapes; using Hover.Core.Renderers.Utils; using Hover.Core.Utils; using UnityEngine; namespace Hover.Core.Renderers.Items.Sliders { /*================================================================================================*/ [RequireComponent(typeof(HoverIndicator))] [RequireComponent(typeof(HoverShape))] public class HoverFillSlider : HoverFill { public const string SegmentInfoName = "SegmentInfo"; public const int SegmentCount = 4; [DisableWhenControlled(DisplaySpecials=true)] public HoverRendererSliderSegments SegmentInfo; [DisableWhenControlled] public GameObject TickPrefab; [DisableWhenControlled] public HoverMesh SegmentA; [DisableWhenControlled] public HoverMesh SegmentB; [DisableWhenControlled] public HoverMesh SegmentC; [DisableWhenControlled] public HoverMesh SegmentD; [DisableWhenControlled] public List<HoverMesh> Ticks; //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public override int GetChildMeshCount() { return SegmentCount+Ticks.Count; } /*--------------------------------------------------------------------------------------------*/ public override HoverMesh GetChildMesh(int pIndex) { switch ( pIndex ) { case 0: return SegmentA; case 1: return SegmentB; case 2: return SegmentC; case 3: return SegmentD; } return Ticks[pIndex-4]; } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public override void TreeUpdate() { base.TreeUpdate(); UpdateTickList(); } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ private void UpdateTickList() { if ( SegmentInfo == null || SegmentInfo.TickInfoList == null ) { return; } int newTickCount = SegmentInfo.TickInfoList.Count; if ( Ticks.Count == newTickCount ) { return; } #if UNITY_EDITOR //ticks are often added within a prefab; this forces serialization of the "Ticks" list UnityEditor.EditorUtility.SetDirty(this); #endif if ( TickPrefab == null ) { Debug.LogWarning("Cannot build ticks without a prefab reference.", this); return; } while ( Ticks.Count < newTickCount ) { HoverMesh tickMesh = RendererUtil.TryBuildPrefabRenderer<HoverMesh>(TickPrefab); tickMesh.name = "Tick"+Ticks.Count; tickMesh.transform.SetParent(gameObject.transform, false); Ticks.Add(tickMesh); } while ( Ticks.Count > newTickCount ) { int lastTickIndex = Ticks.Count-1; HoverMesh tick = Ticks[lastTickIndex]; Ticks.RemoveAt(lastTickIndex); if ( Application.isPlaying ) { Destroy(tick.gameObject); } else { tick.gameObject.SetActive(false); tick.GetComponent<TreeUpdater>().enabled = false; DestroyImmediate(tick.gameObject); } } GetComponent<TreeUpdater>().ImmediateReloadTreeChildren(); } } } <file_sep>/Assets/Hover/Core/Scripts/Renderers/Shapes/Arc/HoverShapeArc.cs using Hover.Core.Layouts.Arc; using Hover.Core.Layouts.Rect; using Hover.Core.Renderers.Utils; using Hover.Core.Utils; using UnityEngine; namespace Hover.Core.Renderers.Shapes.Arc { /*================================================================================================*/ public class HoverShapeArc : HoverShape, ILayoutableArc, ILayoutableRect { public const string OuterRadiusName = "OuterRadius"; public const string InnerRadiusName = "InnerRadius"; public const string ArcDegreesName = "ArcDegrees"; public const string OuterOffsetName = "OuterOffset"; public const string InnerOffsetName = "InnerOffset"; [DisableWhenControlled(RangeMin=0)] public float OuterRadius = 0.1f; [DisableWhenControlled(RangeMin=0)] public float InnerRadius = 0.04f; [DisableWhenControlled(RangeMin=0, RangeMax=360)] public float ArcDegrees = 60; [DisableWhenControlled] public Vector3 OuterOffset = Vector3.zero; [DisableWhenControlled] public Vector3 InnerOffset = Vector3.zero; private Plane vWorldPlane; private float vPrevOuterRad; private float vPrevInnerRad; private float vPrevDegrees; private Vector3 vPrevOuterOff; private Vector3 vPrevInnerOff; //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public override Vector3 GetCenterWorldPosition() { if ( ArcDegrees >= 360 ) { return gameObject.transform.position; } var midLocalPos = new Vector3((OuterRadius+InnerRadius)/2, 0, 0); return gameObject.transform.TransformPoint(midLocalPos); } /*--------------------------------------------------------------------------------------------*/ public override Vector3 GetNearestWorldPosition(Vector3 pFromWorldPosition) { return RendererUtil.GetNearestWorldPositionOnArc(pFromWorldPosition, gameObject.transform, OuterRadius, InnerRadius, ArcDegrees); } /*--------------------------------------------------------------------------------------------*/ public override Vector3 GetNearestWorldPosition(Ray pFromWorldRay, out RaycastResult pRaycast) { pRaycast = new RaycastResult(); Vector3? nearWorldPos = RendererUtil.GetNearestWorldPositionOnPlane(pFromWorldRay, vWorldPlane); if ( nearWorldPos == null ) { return pFromWorldRay.origin; } pRaycast.IsHit = true; pRaycast.WorldPosition = nearWorldPos.Value; pRaycast.WorldRotation = transform.rotation; pRaycast.WorldPlane = vWorldPlane; return GetNearestWorldPosition(pRaycast.WorldPosition); } /*--------------------------------------------------------------------------------------------*/ public override float GetSliderValueViaNearestWorldPosition(Vector3 pNearestWorldPosition, Transform pSliderContainerTx, HoverShape pHandleButtonShape) { HoverShapeArc buttonShapeArc = (pHandleButtonShape as HoverShapeArc); if ( buttonShapeArc == null ) { Debug.LogError("Expected slider handle to have a '"+typeof(HoverShapeArc).Name+ "' component attached to it.", this); return 0; } Vector3 nearLocalPos = pSliderContainerTx.InverseTransformPoint(pNearestWorldPosition); float fromDeg; Vector3 fromAxis; Quaternion fromLocalRot = Quaternion.FromToRotation(Vector3.right, nearLocalPos.normalized); fromLocalRot.ToAngleAxis(out fromDeg, out fromAxis); fromDeg *= Mathf.Sign(nearLocalPos.y); float halfTrackDeg = (ArcDegrees-buttonShapeArc.ArcDegrees)/2; return Mathf.InverseLerp(-halfTrackDeg, halfTrackDeg, fromDeg); } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public void SetArcLayout(float pOuterRadius, float pInnerRadius, float pArcDegrees, ISettingsController pController) { Controllers.Set(OuterRadiusName, pController); Controllers.Set(InnerRadiusName, pController); Controllers.Set(ArcDegreesName, pController); OuterRadius = pOuterRadius; InnerRadius = pInnerRadius; ArcDegrees = pArcDegrees; } /*--------------------------------------------------------------------------------------------*/ public void SetRectLayout(float pSizeX, float pSizeY, ISettingsController pController) { Controllers.Set(OuterRadiusName, pController); OuterRadius = Mathf.Min(pSizeX, pSizeY)/2; } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public override void TreeUpdate() { base.TreeUpdate(); vWorldPlane = RendererUtil.GetWorldPlane(gameObject.transform); DidSettingsChange = ( DidSettingsChange || OuterRadius != vPrevOuterRad || InnerRadius != vPrevInnerRad || ArcDegrees != vPrevDegrees || OuterOffset != vPrevOuterOff || InnerOffset != vPrevInnerOff ); UpdateShapeArcChildren(); vPrevOuterRad = OuterRadius; vPrevInnerRad = InnerRadius; vPrevDegrees = ArcDegrees; vPrevOuterOff = OuterOffset; vPrevInnerOff = InnerOffset; } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ private void UpdateShapeArcChildren() { if ( !ControlChildShapes ) { return; } TreeUpdater tree = GetComponent<TreeUpdater>(); for ( int i = 0 ; i < tree.TreeChildrenThisFrame.Count ; i++ ) { TreeUpdater child = tree.TreeChildrenThisFrame[i]; HoverShapeArc childArc = child.GetComponent<HoverShapeArc>(); if ( childArc == null ) { continue; } Quaternion offsetRot = Quaternion.Inverse(childArc.transform.localRotation); childArc.Controllers.Set(OuterRadiusName, this); childArc.Controllers.Set(InnerRadiusName, this); childArc.Controllers.Set(ArcDegreesName, this); childArc.Controllers.Set(OuterOffsetName, this); childArc.Controllers.Set(InnerOffsetName, this); childArc.OuterRadius = OuterRadius; childArc.InnerRadius = InnerRadius; childArc.ArcDegrees = ArcDegrees; childArc.OuterOffset = offsetRot*OuterOffset; childArc.InnerOffset = offsetRot*InnerOffset; } } } } <file_sep>/Assets/LeapMotion/Modules/GraphicRenderer/Scripts/Editor/LeapGraphicRendererEditor.cs /****************************************************************************** * Copyright (C) Leap Motion, Inc. 2011-2018. * * Leap Motion proprietary and confidential. * * * * Use subject to the terms of the Leap Motion SDK Agreement available at * * https://developer.leapmotion.com/sdk_agreement, or another agreement * * between Leap Motion and you, your company or other organization. * ******************************************************************************/ using System.Reflection; using UnityEngine; using UnityEditor; using Leap.Unity.Query; namespace Leap.Unity.GraphicalRenderer { [CustomEditor(typeof(LeapGraphicRenderer))] public class LeapGraphicRendererEditor : CustomEditorBase<LeapGraphicRenderer> { private const int BUTTON_WIDTH = 60; private static Color BUTTON_COLOR = Color.white * 0.95f; private static Color BUTTON_HIGHLIGHTED_COLOR = Color.white * 0.6f; private LeapGraphicRenderer _renderer; private SerializedProperty _selectedGroup; private GenericMenu _addGroupMenu; private SerializedProperty _groupProperty; private LeapGuiGroupEditor _groupEditor; protected override void OnEnable() { base.OnEnable(); if (target == null) { return; } _renderer = target as LeapGraphicRenderer; _selectedGroup = serializedObject.FindProperty("_selectedGroup"); var allTypes = Assembly.GetAssembly(typeof(LeapGraphicRenderer)).GetTypes(); var allRenderingMethods = allTypes.Query(). Where(t => !t.IsAbstract && !t.IsGenericType && t.IsSubclassOf(typeof(LeapRenderingMethod))); _addGroupMenu = new GenericMenu(); foreach (var renderingMethod in allRenderingMethods) { _addGroupMenu.AddItem(new GUIContent(LeapGraphicTagAttribute.GetTagName(renderingMethod)), false, () => { serializedObject.ApplyModifiedProperties(); Undo.RecordObject(_renderer, "Created group"); EditorUtility.SetDirty(_renderer); _renderer.editor.CreateGroup(renderingMethod); serializedObject.Update(); updateGroupProperty(); }); } _groupEditor = new LeapGuiGroupEditor(target, serializedObject); } public override void OnInspectorGUI() { using (new ProfilerSample("Draw Graphic Renderer Editor")) { updateGroupProperty(); drawScriptField(); bool anyVertexLit = false; foreach (var camera in FindObjectsOfType<Camera>()) { if (camera.actualRenderingPath == RenderingPath.VertexLit) { anyVertexLit = true; break; } } if (anyVertexLit) { EditorGUILayout.HelpBox("The vertex lit rendering path is not supported.", MessageType.Error); } drawToolbar(); if (_groupProperty != null) { drawGroupHeader(); GUILayout.BeginVertical(EditorStyles.helpBox); _groupEditor.DoGuiLayout(_groupProperty); GUILayout.EndVertical(); } else { EditorGUILayout.HelpBox("To get started, create a new rendering group!", MessageType.Info); } serializedObject.ApplyModifiedProperties(); } } private void drawToolbar() { EditorGUILayout.BeginHorizontal(); using (new EditorGUI.DisabledGroupScope(EditorApplication.isPlaying)) { var prevColor = GUI.color; if (GUILayout.Button("New Group", EditorStyles.toolbarDropDown)) { _addGroupMenu.ShowAsContext(); } if (_groupProperty != null) { if (GUILayout.Button("Delete Group", EditorStyles.toolbarButton)) { serializedObject.ApplyModifiedProperties(); Undo.RecordObject(_renderer, "Deleted group"); EditorUtility.SetDirty(_renderer); _renderer.editor.DestroySelectedGroup(); serializedObject.Update(); _groupEditor.Invalidate(); updateGroupProperty(); } } GUI.color = prevColor; } GUILayout.FlexibleSpace(); Rect r = GUILayoutUtility.GetLastRect(); GUI.Label(r, "", EditorStyles.toolbarButton); EditorGUILayout.EndHorizontal(); } private void drawGroupHeader() { EditorGUILayout.BeginHorizontal(); var prevColor = GUI.color; for (int i = 0; i < _renderer.groups.Count; i++) { if (i == _selectedGroup.intValue) { GUI.color = BUTTON_HIGHLIGHTED_COLOR; } else { GUI.color = BUTTON_COLOR; } var group = _renderer.groups[i]; if (GUILayout.Button(group.name, EditorStyles.toolbarButton)) { _selectedGroup.intValue = i; _groupEditor.Invalidate(); updateGroupProperty(); } } GUI.color = prevColor; GUILayout.FlexibleSpace(); Rect rect = GUILayoutUtility.GetLastRect(); GUI.Label(rect, "", EditorStyles.toolbarButton); EditorGUILayout.EndHorizontal(); } private void updateGroupProperty() { var groupArray = serializedObject.FindProperty("_groups"); if (groupArray.arraySize == 0) { _groupProperty = null; return; } int selectedGroupIndex = _selectedGroup.intValue; if (selectedGroupIndex < 0 || selectedGroupIndex >= groupArray.arraySize) { _selectedGroup.intValue = 0; selectedGroupIndex = 0; } _groupProperty = groupArray.GetArrayElementAtIndex(selectedGroupIndex); } private bool HasFrameBounds() { _renderer.editor.RebuildEditorPickingMeshes(); return _renderer.groups.Query(). SelectMany(g => g.graphics.Query()). Select(e => e.editor.pickingMesh). Any(m => m != null); } private Bounds OnGetFrameBounds() { _renderer.editor.RebuildEditorPickingMeshes(); return _renderer.groups.Query(). SelectMany(g => g.graphics.Query()). Select(e => e.editor.pickingMesh). ValidUnityObjs(). Select(m => m.bounds). Fold((a, b) => { a.Encapsulate(b); return a; }); } } } <file_sep>/Assets/Hover/Core/Scripts/Renderers/Shapes/Arc/HoverFillButtonArcUpdater.cs using Hover.Core.Renderers.Items.Buttons; using Hover.Core.Renderers.Utils; using Hover.Core.Utils; using UnityEngine; namespace Hover.Core.Renderers.Shapes.Arc { /*================================================================================================*/ [RequireComponent(typeof(TreeUpdater))] [RequireComponent(typeof(HoverFillButton))] [RequireComponent(typeof(HoverShapeArc))] public class HoverFillButtonArcUpdater : MonoBehaviour, ITreeUpdateable, ISettingsController { public enum EdgePositionType { Inner, Outer } public float EdgeThickness = 0.001f; public EdgePositionType EdgePosition = EdgePositionType.Inner; //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public void Start() { //do nothing... } /*--------------------------------------------------------------------------------------------*/ public void TreeUpdate() { EdgeThickness = Mathf.Max(0, EdgeThickness); UpdateMeshes(); } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ private void UpdateMeshes() { HoverFillButton fillButton = gameObject.GetComponent<HoverFillButton>(); HoverShapeArc shapeArc = gameObject.GetComponent<HoverShapeArc>(); bool isOuterEdge = (EdgePosition == EdgePositionType.Outer); float inset = EdgeThickness*Mathf.Sign(shapeArc.OuterRadius-shapeArc.InnerRadius); float insetOuterRadius = shapeArc.OuterRadius - (isOuterEdge ? inset : 0); float insetInnerRadius = shapeArc.InnerRadius + (isOuterEdge ? 0 : inset); float edgeOuterRadius = (isOuterEdge ? shapeArc.OuterRadius : insetInnerRadius); float edgeInnerRadius = (isOuterEdge ? insetOuterRadius : shapeArc.InnerRadius); if ( fillButton.Background != null ) { UpdateMeshShape(fillButton.Background, insetOuterRadius, insetInnerRadius); } if ( fillButton.Highlight != null ) { UpdateMeshShape(fillButton.Highlight, insetOuterRadius, insetInnerRadius); } if ( fillButton.Selection != null ) { UpdateMeshShape(fillButton.Selection, insetOuterRadius, insetInnerRadius); } if ( fillButton.Edge != null ) { UpdateMeshShape(fillButton.Edge, edgeOuterRadius, edgeInnerRadius, fillButton.ShowEdge); } } /*--------------------------------------------------------------------------------------------*/ protected virtual void UpdateMeshShape(HoverMesh pMesh, float pOuterRad, float pInnerRad, bool pShowMesh=true) { HoverShapeArc meshShape = pMesh.GetComponent<HoverShapeArc>(); pMesh.Controllers.Set(SettingsControllerMap.GameObjectActiveSelf, this); meshShape.Controllers.Set(HoverShapeArc.OuterRadiusName, this); meshShape.Controllers.Set(HoverShapeArc.InnerRadiusName, this); RendererUtil.SetActiveWithUpdate(pMesh, (pShowMesh && pMesh.IsMeshVisible)); meshShape.OuterRadius = pOuterRad; meshShape.InnerRadius = pInnerRad; } } } <file_sep>/Assets/LeapMotion/Modules/GraphicRenderer/Scripts/Utility/SpriteUtil.cs /****************************************************************************** * Copyright (C) Leap Motion, Inc. 2011-2018. * * Leap Motion proprietary and confidential. * * * * Use subject to the terms of the Leap Motion SDK Agreement available at * * https://developer.leapmotion.com/sdk_agreement, or another agreement * * between Leap Motion and you, your company or other organization. * ******************************************************************************/ using UnityEngine; #if UNITY_EDITOR using UnityEditor; using UnityEditor.Sprites; #endif using System; using System.Collections.Generic; namespace Leap.Unity.GraphicalRenderer { public static class SpriteAtlasUtil { #if UNITY_EDITOR public static void ShowInvalidSpriteWarning(IList<LeapGraphicFeatureBase> features) { bool anyRectsInvalid = false; foreach (var feature in features) { var spriteFeature = feature as LeapSpriteFeature; if (spriteFeature == null) continue; foreach (var spriteData in spriteFeature.featureData) { var sprite = spriteData.sprite; if (sprite == null) continue; Rect rect; if (TryGetAtlasedRect(sprite, out rect)) { if (rect.Area() == 0) { anyRectsInvalid = true; } } } } if (anyRectsInvalid) { EditorGUILayout.HelpBox("Due to a Unity bug, packed sprites may be invalid until " + "PlayMode has been entered at least once.", MessageType.Warning); } } #endif public static bool TryGetAtlasedRect(Sprite sprite, out Rect rect) { Vector2[] uvs; if (!TryGetAtlasedUvs(sprite, out uvs)) { rect = default(Rect); return false; } float minX, minY, maxX, maxY; minX = maxX = uvs[0].x; minY = maxY = uvs[0].y; for (int j = 1; j < uvs.Length; j++) { minX = Mathf.Min(minX, uvs[j].x); minY = Mathf.Min(minY, uvs[j].y); maxX = Mathf.Max(maxX, uvs[j].x); maxY = Mathf.Max(maxY, uvs[j].y); } rect = Rect.MinMaxRect(minX, minY, maxX, maxY); return true; } public static bool TryGetAtlasedUvs(Sprite sprite, out Vector2[] uvs) { #if UNITY_EDITOR if (!Application.isPlaying) return tryGetAtlasedUvsEditor(sprite, out uvs); else #endif return tryGetAtlasedUvs(sprite, out uvs); } private static bool tryGetAtlasedUvs(Sprite sprite, out Vector2[] uvs) { if (sprite.packed) { uvs = sprite.uv; return true; } else { uvs = null; return false; } } #if UNITY_EDITOR private static bool tryGetAtlasedUvsEditor(Sprite sprite, out Vector2[] uvs) { try { uvs = SpriteUtility.GetSpriteUVs(sprite, getAtlasData: true); return true; } catch (Exception) { uvs = null; return false; } } #endif } } <file_sep>/Assets/PolyToolkit/Editor/PtUtils.cs // Copyright 2017 Google Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using UnityEngine; using System.IO; using System.Text; using PolyToolkit; using PolyToolkitInternal; using UnityEditor; namespace PolyToolkitEditor { public static class PtUtils { /// <summary> /// Name of the Poly Toolkit manifest file. /// </summary> private const string MANIFEST_FILE_NAME = "poly_toolkit_manifest.dat"; /// <summary> /// Poly Toolkit base path (normally Assets/PolyToolkit, unless the user moved it). /// This is computed lazily. /// </summary> private static string basePath = null; /// <summary> /// Normalizes a Unity local asset path: trims, converts back slashes into forward slashes, /// removes trailing slash. /// </summary> /// <param name="path">The path to normalize (e.g., " Assets\Foo/Bar\Qux ").</param> /// <returns>The normalized path (e.g., "Assets/Foo/Bar/Qux")</returns> public static string NormalizeLocalPath(string path) { path = path.Trim().Replace('\\', '/'); // Strip the trailing slash, if there is one. if (path.EndsWith("/")) path = path.Substring(0, path.Length - 1); return path; } /// <summary> /// Converts a local path (like "Assets/Foo/Bar") into an absolute system-dependent path /// (like "C:\Users\foo\MyUnityProject\Assets\Foo\Bar"). /// </summary> /// <param name="localPath">The local path to convert.</param> /// <returns>The absolute path.</returns> public static string ToAbsolutePath(string localPath) { return Path.Combine( Path.GetDirectoryName(Application.dataPath).Replace('/', Path.DirectorySeparatorChar), localPath.Replace('/', Path.DirectorySeparatorChar)); } /// <summary> /// Sanitizes the given string to use as a file name. /// </summary> /// <param name="str">The string to sanitize</param> /// <returns>The sanitized version, with invalid characters converted to _.</returns> public static string SanitizeToUseAsFileName(string str) { if (str == null) { throw new System.Exception("Can't sanitize a null string"); } StringBuilder sb = new StringBuilder(); bool lastCharElided = false; for (int i = 0; i < Mathf.Min(str.Length, 40); i++) { char c = str[i]; if ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z')) { lastCharElided = false; } else { if (lastCharElided) continue; c = '_'; lastCharElided = true; } sb.Append(c); } return sb.ToString(); } /// <summary> /// Returns the default asset path for the given asset. /// </summary> public static string GetDefaultPtAssetPath(PolyAsset asset) { return string.Format("{0}/{1}.asset", NormalizeLocalPath(PtSettings.Instance.assetObjectsPath), GetPtAssetBaseName(asset)); } public static string GetPtAssetBaseName(PolyAsset asset) { return string.Format("{0}_{1}_{2}", SanitizeToUseAsFileName(asset.displayName), SanitizeToUseAsFileName(asset.authorName), SanitizeToUseAsFileName(asset.name).Replace("assets_", "")); } public static string GetPtBaseLocalPath() { if (basePath != null) return basePath; // Get the root path of the project. Something like C:\Foo\Bar\MyUnityProject string rootPath = Path.GetDirectoryName(Application.dataPath); // Find the poly_toolkit_manifest.data file. That marks the installation path of Poly Toolkit. string[] matches = Directory.GetFiles(Application.dataPath, MANIFEST_FILE_NAME, SearchOption.AllDirectories); if (matches == null || matches.Length == 0) { throw new System.Exception("Could not find base directory for Poly Toolkit (poly_toolkit_manifest.data missing)."); } else if (matches.Length > 1) { Debug.LogError("Found more than one Poly Toolkit installation in your project. Make sure there is only one."); // Continue anyway (by "best effort" -- arbitrarily use the first one). } // Found it. Now we have calculate the path relative to rootPath. For that, we have to normalize the // separators because on Windows we normally get an inconsistent mix of '/' and '\'. rootPath = rootPath.Replace('\\', '/'); if (!rootPath.EndsWith("/")) rootPath += "/"; string manifestPath = matches[0].Replace('\\', '/').Replace(MANIFEST_FILE_NAME, ""); // Now rootPath is something like "C:/Foo/Bar/MyUnityProject/" // and manifestPath is something like "C:/Foo/Bar/MyUnityProject/Some/Path/PolyToolkit". // We want to extract the "Some/Path/PolyToolkit" part. if (!manifestPath.StartsWith(rootPath)) { throw new System.Exception(string.Format("Could not find local path from '{0}' (data path is '{1}')", matches[0], Application.dataPath)); } // Cache it. basePath = NormalizeLocalPath(manifestPath.Substring(rootPath.Length)); return basePath; } /// <summary> /// Loads a texture file from the Poly Toolkit installation folder given a relative path /// from the installation folder to the texture. /// </summary> /// <param name="relativePath">The relative path were the texture is located. For example, /// this could be Editor/Textures/PolyToolkitTitle.png.</param> /// <returns>The texture.</returns> public static Texture2D LoadTexture2DFromRelativePath(string relativePath) { string basePath = PtUtils.GetPtBaseLocalPath(); return AssetDatabase.LoadAssetAtPath<Texture2D>(Path.Combine(basePath, relativePath)); } } }<file_sep>/Assets/LeapMotion/Modules/GraphicRenderer/Scripts/Features/BlendShape/LeapBlendShapeData.cs /****************************************************************************** * Copyright (C) Leap Motion, Inc. 2011-2018. * * Leap Motion proprietary and confidential. * * * * Use subject to the terms of the Leap Motion SDK Agreement available at * * https://developer.leapmotion.com/sdk_agreement, or another agreement * * between Leap Motion and you, your company or other organization. * ******************************************************************************/ using System; using System.Collections.Generic; using UnityEngine; using Leap.Unity.Query; using Leap.Unity.Attributes; namespace Leap.Unity.GraphicalRenderer { public partial class LeapGraphic { /// <summary> /// Helper method to set the blend shape amount for a blend shape /// data object attached to this graphic. This method will throw /// an exception if there is no blend shape data obj attached to /// this graphic. /// </summary> public void SetBlendShapeAmount(float amount) { getFeatureDataOrThrow<LeapBlendShapeData>().amount = amount; } /// <summary> /// Helper method to get the blend shape amount for a blend shape /// data object attached to this graphic. This method will throw /// an exception if there is no blend shape data obj attached to /// this graphic. /// </summary> public float GetBlendShapeAmount() { return getFeatureDataOrThrow<LeapBlendShapeData>().amount; } } [LeapGraphicTag("Blend Shape")] [Serializable] public class LeapBlendShapeData : LeapFeatureData { [Range(0, 1)] [SerializeField] private float _amount = 0; [EditTimeOnly] [SerializeField] private BlendShapeType _type = BlendShapeType.Scale; [EditTimeOnly] [MinValue(0)] [SerializeField] private float _scale = 1.1f; [EditTimeOnly] [SerializeField] private Vector3 _translation = new Vector3(0, 0, 0.1f); [EditTimeOnly] [SerializeField] private Vector3 _rotation = new Vector3(0, 0, 5); [EditTimeOnly] [SerializeField] private Transform _transform; /// <summary> /// Gets or sets the amount of strength for this blend shape. /// The value should be in the 0-1 range, where 0 is no strength, /// and 1 is complete strength. /// </summary> public float amount { get { return _amount; } set { if (value != _amount) { MarkFeatureDirty(); _amount = value; } } } /// <summary> /// Returns the blended vertices based on the current mesh /// this blend shape is attached to. If you want to ensure /// this blend shape data is up-to-date, make sure to call /// RefreshMeshData on the graphic itself first. /// </summary> public bool TryGetBlendShape(List<Vector3> blendVerts) { if (!(graphic is LeapMeshGraphicBase)) { return false; } var meshGraphic = graphic as LeapMeshGraphicBase; var mesh = meshGraphic.mesh; if (mesh == null) { return false; } if (_type == BlendShapeType.Mesh) { if (mesh.blendShapeCount <= 0) { return false; } Vector3[] deltaVerts = new Vector3[mesh.vertexCount]; Vector3[] deltaNormals = new Vector3[mesh.vertexCount]; Vector3[] deltaTangents = new Vector3[mesh.vertexCount]; mesh.GetBlendShapeFrameVertices(0, 0, deltaVerts, deltaNormals, deltaTangents); mesh.vertices.Query().Zip(deltaVerts.Query(), (a, b) => a + b).FillList(blendVerts); return true; } else { Matrix4x4 transformation; switch (_type) { case BlendShapeType.Translation: transformation = Matrix4x4.TRS(_translation, Quaternion.identity, Vector3.one); break; case BlendShapeType.Rotation: transformation = Matrix4x4.TRS(Vector3.zero, Quaternion.Euler(_rotation), Vector3.one); break; case BlendShapeType.Scale: transformation = Matrix4x4.TRS(Vector3.zero, Quaternion.identity, Vector3.one * _scale); break; case BlendShapeType.Transform: if (_transform == null) { return false; } transformation = graphic.transform.worldToLocalMatrix * _transform.localToWorldMatrix; break; default: throw new InvalidOperationException(); } mesh.vertices.Query().Select(transformation.MultiplyPoint).FillList(blendVerts); return true; } } public enum BlendShapeType { Translation, Rotation, Scale, Transform, Mesh } } } <file_sep>/Assets/LeapMotion/Modules/GraphicRenderer/Scripts/RenderingMethods/LeapMesherBase.cs /****************************************************************************** * Copyright (C) Leap Motion, Inc. 2011-2018. * * Leap Motion proprietary and confidential. * * * * Use subject to the terms of the Leap Motion SDK Agreement available at * * https://developer.leapmotion.com/sdk_agreement, or another agreement * * between Leap Motion and you, your company or other organization. * ******************************************************************************/ using System; using System.Collections.Generic; using UnityEngine; using UnityEngine.Rendering; using UnityEngine.Assertions; #if UNITY_EDITOR using UnityEditor; using UnityEditor.Sprites; #endif using Leap.Unity.Query; using Leap.Unity.Attributes; namespace Leap.Unity.GraphicalRenderer { public abstract class LeapMesherBase : LeapRenderingMethod<LeapMeshGraphicBase>, ISupportsFeature<LeapTextureFeature>, ISupportsFeature<LeapSpriteFeature>, ISupportsFeature<LeapRuntimeTintFeature>, ISupportsFeature<LeapBlendShapeFeature>, ISupportsFeature<CustomFloatChannelFeature>, ISupportsFeature<CustomVectorChannelFeature>, ISupportsFeature<CustomColorChannelFeature>, ISupportsFeature<CustomMatrixChannelFeature> { [Serializable] private class JaggedRects : JaggedArray<Rect> { public JaggedRects(int length) : base(length) { } } public const string MESH_ASSET_NAME = "Mesh Data"; public const string TEXTURE_ASSET_NAME = "Texture Data"; public const string UV_0_FEATURE = LeapGraphicRenderer.FEATURE_PREFIX + "VERTEX_UV_0"; public const string UV_1_FEATURE = LeapGraphicRenderer.FEATURE_PREFIX + "VERTEX_UV_1"; public const string UV_2_FEATURE = LeapGraphicRenderer.FEATURE_PREFIX + "VERTEX_UV_2"; public const string UV_3_FEATURE = LeapGraphicRenderer.FEATURE_PREFIX + "VERTEX_UV_3"; public const string COLORS_FEATURE = LeapGraphicRenderer.FEATURE_PREFIX + "VERTEX_COLORS"; public const string NORMALS_FEATURE = LeapGraphicRenderer.FEATURE_PREFIX + "VERTEX_NORMALS"; public static string GetUvFeature(UVChannelFlags flags) { switch (flags) { case UVChannelFlags.UV0: return UV_0_FEATURE; case UVChannelFlags.UV1: return UV_1_FEATURE; case UVChannelFlags.UV2: return UV_2_FEATURE; case UVChannelFlags.UV3: return UV_3_FEATURE; default: throw new InvalidOperationException(); } } public Action<Texture2D, AtlasUvs> OnPostProcessAtlas; #region INSPECTOR FIELDS //BEGIN MESH SETTINGS [Tooltip("Should this renderer include uv0 coordinates in the generated meshes.")] [EditTimeOnly, SerializeField, HideInInspector] private bool _useUv0 = true; [Tooltip("Should this renderer include uv1 coordinates in the generated meshes.")] [EditTimeOnly, SerializeField, HideInInspector] private bool _useUv1 = false; [Tooltip("Should this renderer include uv2 coordinates in the generated meshes.")] [EditTimeOnly, SerializeField, HideInInspector] private bool _useUv2 = false; [Tooltip("Should this renderer include uv3 coordinates in the generated meshes.")] [EditTimeOnly, SerializeField, HideInInspector] private bool _useUv3 = false; [Tooltip("Should this renderer include vertex colors in the generated meshes.")] [EditTimeOnly, SerializeField, HideInInspector] private bool _useColors = true; [Tooltip("Multiply all vertex colors for all graphics by this color.")] [EditTimeOnly, SerializeField, HideInInspector] private Color _bakedTint = Color.white; [Tooltip("Should this renderer include normals in the generated meshes.")] [EditTimeOnly, SerializeField, HideInInspector] private bool _useNormals = false; //BEGIN RENDERING SETTINGS [Tooltip("Shader to use to display the graphics.")] [EditTimeOnly, SerializeField] protected Shader _shader; [Tooltip("The layer that the visual representation of the graphics. It is independent from the layer the graphics occupy.")] [SerializeField] private SingleLayer _visualLayer = 0; [Tooltip("The atlas combines multiple textures into a single texture automatically, allowing each graphic to have a different " + "texture but still allow the graphics as a whole to render efficiently.")] [SerializeField] private AtlasBuilder _atlas = new AtlasBuilder(); #endregion protected GenerationState _generation = GenerationState.GetGenerationState(); //Internal cache of requirements protected bool _doesRequireColors; protected bool _doesRequireNormals; protected bool _doesRequireVertInfo; protected List<UVChannelFlags> _requiredUvChannels = new List<UVChannelFlags>(); //Feature lists protected List<LeapTextureFeature> _textureFeatures = new List<LeapTextureFeature>(); protected List<LeapSpriteFeature> _spriteFeatures = new List<LeapSpriteFeature>(); protected List<LeapRuntimeTintFeature> _tintFeatures = new List<LeapRuntimeTintFeature>(); protected List<LeapBlendShapeFeature> _blendShapeFeatures = new List<LeapBlendShapeFeature>(); protected List<CustomFloatChannelFeature> _floatChannelFeatures = new List<CustomFloatChannelFeature>(); protected List<CustomVectorChannelFeature> _vectorChannelFeatures = new List<CustomVectorChannelFeature>(); protected List<CustomColorChannelFeature> _colorChannelFeatures = new List<CustomColorChannelFeature>(); protected List<CustomMatrixChannelFeature> _matrixChannelFeatures = new List<CustomMatrixChannelFeature>(); //### Generated Data ### [SerializeField] protected Material _material; [SerializeField] protected RendererMeshData _meshes; [SerializeField] protected RendererTextureData _packedTextures; //#### Sprite/Texture Remapping #### [SerializeField] private AtlasUvs _atlasUvs; [NonSerialized] protected MaterialPropertyBlock _spriteTextureBlock; //#### Tinting #### protected const string TINTS_PROPERTY = LeapGraphicRenderer.PROPERTY_PREFIX + "Tints"; protected List<Vector4> _tintColors = new List<Vector4>(); //#### Blend Shapes #### protected const string BLEND_SHAPE_AMOUNTS_PROPERTY = LeapGraphicRenderer.PROPERTY_PREFIX + "BlendShapeAmounts"; protected List<float> _blendShapeAmounts = new List<float>(); //#### Custom Channels #### public const string CUSTOM_CHANNEL_KEYWORD = LeapGraphicRenderer.FEATURE_PREFIX + "ENABLE_CUSTOM_CHANNELS"; protected List<float> _customFloatChannelData = new List<float>(); protected List<Vector4> _customVectorChannelData = new List<Vector4>(); protected List<Color> _customColorChannelData = new List<Color>(); protected List<Matrix4x4> _customMatrixChannelData = new List<Matrix4x4>(); public Material material { get { return _material; } } #if UNITY_EDITOR public virtual bool IsAtlasDirty { get { return _atlas.isDirty; } } public virtual void RebuildAtlas(ProgressBar progress) { Undo.RecordObject(renderer, "Rebuilt atlas"); progress.Begin(2, "Rebuilding Atlas", "", () => { Texture2D[] packedTextures; group.GetSupportedFeatures(_textureFeatures); _atlas.UpdateTextureList(_textureFeatures); _atlas.RebuildAtlas(progress, out packedTextures, out _atlasUvs); progress.Begin(3, "", "", () => { progress.Step("Post-Process Atlas"); if (OnPostProcessAtlas != null) { for (int i = 0; i < packedTextures.Length; i++) { try { OnPostProcessAtlas(packedTextures[i], _atlasUvs); } catch (Exception e) { Debug.LogException(e); } } } progress.Step("Saving To Asset"); //Now that all post-process has finished, finally mark no longer readable //Don't change the mipmaps because a post process might have uploaded custom data for (int i = 0; i < packedTextures.Length; i++) { packedTextures[i].Apply(updateMipmaps: false, makeNoLongerReadable: true); } _packedTextures.AssignTextures(packedTextures, _textureFeatures.Query().Select(f => f.propertyName).ToArray()); progress.Begin(_textureFeatures.Count, "", "Loading Into Scene", () => { foreach (var feature in _textureFeatures) { _material.SetTexture(feature.propertyName, _packedTextures.GetTexture(feature.propertyName)); } }); }); }); } #endif public virtual void GetSupportInfo(List<LeapTextureFeature> features, List<SupportInfo> info) { for (int i = 0; i < features.Count; i++) { var feature = features[i]; if (group.features.Query().OfType<LeapSpriteFeature>().Any(s => s.channel == feature.channel)) { info[i] = info[i].OrWorse(SupportInfo.Error("Texture features cannot currently share uvs with sprite features.")); } } } public virtual void GetSupportInfo(List<LeapSpriteFeature> features, List<SupportInfo> info) { SupportUtil.OnlySupportFirstFeature<LeapSpriteFeature>(info); #if UNITY_EDITOR if (!Application.isPlaying) { Packer.RebuildAtlasCacheIfNeeded(EditorUserBuildSettings.activeBuildTarget); } for (int i = 0; i < features.Count; i++) { var feature = features[i]; if (!feature.AreAllSpritesPacked()) { info[i] = SupportInfo.Error("Not all sprites are packed."); } if (!feature.AreAllSpritesOnSameTexture()) { info[i] = SupportInfo.Error("Not all sprites are packed into same atlas."); } } #endif for (int i = 0; i < features.Count; i++) { var feature = features[i]; if (group.features.Query().OfType<LeapTextureFeature>().Any(s => s.channel == feature.channel)) { info[i] = info[i].OrWorse(SupportInfo.Error("Sprite features cannot currently share uvs with texture features.")); } } } public virtual void GetSupportInfo(List<LeapRuntimeTintFeature> features, List<SupportInfo> info) { SupportUtil.OnlySupportFirstFeature<LeapRuntimeTintFeature>(info); } public virtual void GetSupportInfo(List<LeapBlendShapeFeature> features, List<SupportInfo> info) { SupportUtil.OnlySupportFirstFeature<LeapBlendShapeFeature>(info); } //Full unconditional support for all custom channels public virtual void GetSupportInfo(List<CustomFloatChannelFeature> features, List<SupportInfo> info) { } public virtual void GetSupportInfo(List<CustomVectorChannelFeature> features, List<SupportInfo> info) { } public virtual void GetSupportInfo(List<CustomColorChannelFeature> features, List<SupportInfo> info) { } public virtual void GetSupportInfo(List<CustomMatrixChannelFeature> features, List<SupportInfo> info) { } public override void OnEnableRenderer() { loadAllSupportedFeatures(); prepareMaterial(); //Sprite textures cannot be accessed at edit time, so we need to make sure //to upload them to the material right as the renderer is enabled if (_spriteFeatures != null) { uploadSpriteTextures(); } } public override void OnDisableRenderer() { } public override void OnUpdateRenderer() { if (_material == null) { prepareMaterial(); } updateTinting(); updateBlendShapes(); updateCustomChannels(); } #if UNITY_EDITOR public override void OnDisableRendererEditor() { base.OnDisableRendererEditor(); } public override void OnUpdateRendererEditor() { base.OnUpdateRendererEditor(); _meshes.Validate(this); _packedTextures.Validate(this); setupForBuilding(); PreventDuplication(ref _material); buildMesh(); } #endif #region UPDATE protected virtual void updateTinting() { foreach (var tintFeature in _tintFeatures) { if (!tintFeature.isDirtyOrEditTime) continue; using (new ProfilerSample("Update Tinting")) { if (QualitySettings.activeColorSpace == ColorSpace.Linear) { tintFeature.featureData.Query().Select(d => (Vector4)d.color.linear).FillList(_tintColors); } else { tintFeature.featureData.Query().Select(d => (Vector4)d.color).FillList(_tintColors); } _material.SetVectorArraySafe(TINTS_PROPERTY, _tintColors); } } } protected virtual void updateBlendShapes() { foreach (var blendShapeFeature in _blendShapeFeatures) { if (!blendShapeFeature.isDirtyOrEditTime) continue; using (new ProfilerSample("Update Blend Shapes")) { blendShapeFeature.featureData.Query().Select(d => d.amount).FillList(_blendShapeAmounts); _material.SetFloatArraySafe(BLEND_SHAPE_AMOUNTS_PROPERTY, _blendShapeAmounts); } } } protected virtual void updateCustomChannels() { using (new ProfilerSample("Update Custom Channels")) { foreach (var floatChannelFeature in _floatChannelFeatures) { if (!floatChannelFeature.isDirtyOrEditTime) continue; floatChannelFeature.featureData.Query().Select(d => d.value).FillList(_customFloatChannelData); _material.SetFloatArraySafe(floatChannelFeature.channelName, _customFloatChannelData); } foreach (var vectorChannelFeature in _vectorChannelFeatures) { if (!vectorChannelFeature.isDirtyOrEditTime) continue; vectorChannelFeature.featureData.Query().Select(d => d.value).FillList(_customVectorChannelData); _material.SetVectorArraySafe(vectorChannelFeature.channelName, _customVectorChannelData); } foreach (var colorChannelFeature in _colorChannelFeatures) { if (!colorChannelFeature.isDirtyOrEditTime) continue; colorChannelFeature.featureData.Query().Select(d => d.value).FillList(_customColorChannelData); _material.SetColorArraySafe(colorChannelFeature.channelName, _customColorChannelData); } foreach (var matrixChannelFeature in _matrixChannelFeatures) { if (!matrixChannelFeature.isDirty) continue; matrixChannelFeature.featureData.Query().Select(d => d.value).FillList(_customMatrixChannelData); _material.SetMatrixArraySafe(matrixChannelFeature.channelName, _customMatrixChannelData); } } } #endregion #region GENERATION SETUP protected virtual void setupForBuilding() { using (new ProfilerSample("Mesh Setup")) { MeshCache.Clear(); loadAllSupportedFeatures(); prepareMeshes(); prepareMaterial(); if (_textureFeatures.Count != 0) { _atlas.UpdateTextureList(_textureFeatures); } if (_spriteFeatures.Count != 0) { #if UNITY_EDITOR Packer.RebuildAtlasCacheIfNeeded(EditorUserBuildSettings.activeBuildTarget); #endif extractSpriteRects(); uploadSpriteTextures(); } } } protected virtual void loadAllSupportedFeatures() { using (new ProfilerSample("Load All Supported Features")) { group.GetSupportedFeatures(_textureFeatures); group.GetSupportedFeatures(_spriteFeatures); group.GetSupportedFeatures(_tintFeatures); group.GetSupportedFeatures(_blendShapeFeatures); group.GetSupportedFeatures(_floatChannelFeatures); group.GetSupportedFeatures(_vectorChannelFeatures); group.GetSupportedFeatures(_colorChannelFeatures); group.GetSupportedFeatures(_matrixChannelFeatures); _doesRequireColors = doesRequireMeshColors(); _doesRequireNormals = doesRequireMeshNormals(); _doesRequireVertInfo = doesRequireVertInfo(); _requiredUvChannels.Clear(); foreach (var channel in MeshUtil.allUvChannels) { if (channel == UVChannelFlags.UV3 && _doesRequireVertInfo) continue; if (doesRequireUvChannel(channel)) { _requiredUvChannels.Add(channel); } } } } protected virtual void prepareMeshes() { _meshes.Clear(); _generation.Reset(); } protected virtual void prepareMaterial() { if (_material == null) { _material = new Material(_shader); } #if UNITY_EDITOR Undo.RecordObject(_material, "Touched material"); #endif _material.shader = _shader; _material.name = "Procedural Graphic Material"; foreach (var keyword in _material.shaderKeywords) { _material.DisableKeyword(keyword); } if (_spriteTextureBlock == null) { _spriteTextureBlock = new MaterialPropertyBlock(); } _spriteTextureBlock.Clear(); if (_doesRequireColors) { _material.EnableKeyword(COLORS_FEATURE); } if (_doesRequireNormals) { _material.EnableKeyword(NORMALS_FEATURE); } foreach (var channel in _requiredUvChannels) { _material.EnableKeyword(GetUvFeature(channel)); } if (_customColorChannelData.Count > 0 || _customFloatChannelData.Count > 0 || _customVectorChannelData.Count > 0 || _customMatrixChannelData.Count > 0) { _material.EnableKeyword(CUSTOM_CHANNEL_KEYWORD); } if (_textureFeatures.Count != 0) { foreach (var feature in _textureFeatures) { _material.SetTexture(feature.propertyName, _packedTextures.GetTexture(feature.propertyName)); } } if (_tintFeatures.Count != 0) { _material.EnableKeyword(LeapRuntimeTintFeature.FEATURE_NAME); } if (_blendShapeFeatures.Count != 0) { _material.EnableKeyword(LeapBlendShapeFeature.FEATURE_NAME); } } protected virtual void extractSpriteRects() { using (new ProfilerSample("Extract Sprite Rects")) { foreach (var spriteFeature in _spriteFeatures) { for (int i = 0; i < spriteFeature.featureData.Count; i++) { var dataObj = spriteFeature.featureData[i]; var sprite = dataObj.sprite; if (sprite == null) continue; Rect rect; if (SpriteAtlasUtil.TryGetAtlasedRect(sprite, out rect)) { _atlasUvs.SetRect(spriteFeature.channel.Index(), sprite, rect); } else { _atlasUvs.SetRect(spriteFeature.channel.Index(), sprite, default(Rect)); } } } } } protected virtual void uploadSpriteTextures() { using (new ProfilerSample("Upload Sprite Textures")) { foreach (var spriteFeature in _spriteFeatures) { var tex = spriteFeature.featureData.Query(). Select(d => d.sprite). Where(s => s != null). #if UNITY_EDITOR Select(s => SpriteUtility.GetSpriteTexture(s, getAtlasData: true)). #else Select(s => s.texture). #endif FirstOrDefault(); if (tex != null) { #if UNITY_EDITOR if (!Application.isPlaying) { _spriteTextureBlock.SetTexture(spriteFeature.propertyName, tex); } else #endif { _material.SetTexture(spriteFeature.propertyName, tex); } } } } } #endregion #region MESH GENERATION protected virtual void buildMesh() { using (new ProfilerSample("Build Mesh")) { beginMesh(); for (_generation.graphicIndex = 0; _generation.graphicIndex < group.graphics.Count; _generation.graphicIndex++) { //For re-generation of everything, graphicIndex == graphicId _generation.graphicId = _generation.graphicIndex; _generation.graphic = group.graphics[_generation.graphicIndex] as LeapMeshGraphicBase; buildGraphic(); } if (_generation.isGenerating) { finishAndAddMesh(); } } _meshes.ClearPool(); } protected virtual void buildGraphic() { using (new ProfilerSample("Build Graphic")) { refreshMeshData(); if (_generation.graphic.mesh == null) return; buildTopology(); if (_doesRequireColors) { buildColors(); } foreach (var channel in _requiredUvChannels) { buildUvs(channel); } if (_doesRequireVertInfo) { buildVertInfo(); } foreach (var blendShapeFeature in _blendShapeFeatures) { buildBlendShapes(blendShapeFeature.featureData[_generation.graphicIndex]); } _generation.graphic.isRepresentationDirty = false; } } protected virtual void refreshMeshData() { using (new ProfilerSample("Refresh Mesh Data")) { _generation.graphic.RefreshMeshData(); } } protected virtual void buildTopology() { using (new ProfilerSample("Build Topology")) { var topology = MeshCache.GetTopology(_generation.graphic.mesh); int vertOffset = _generation.verts.Count; for (int i = 0; i < topology.tris.Length; i++) { _generation.tris.Add(topology.tris[i] + vertOffset); } if (_doesRequireNormals) { var normals = MeshCache.GetNormals(_generation.graphic.mesh); for (int i = 0; i < topology.verts.Length; i++) { Vector3 meshVert; Vector3 meshNormal; graphicVertNormalToMeshVertNormal(topology.verts[i], normals[i], out meshVert, out meshNormal); _generation.verts.Add(meshVert); _generation.normals.Add(meshNormal); } } else { for (int i = 0; i < topology.verts.Length; i++) { _generation.verts.Add(graphicVertToMeshVert(topology.verts[i])); } } } } protected virtual void buildColors() { using (new ProfilerSample("Build Colors")) { Color totalTint; if (QualitySettings.activeColorSpace == ColorSpace.Linear) { totalTint = _bakedTint.linear * _generation.graphic.vertexColor.linear; } else { totalTint = _bakedTint * _generation.graphic.vertexColor; } var colors = MeshCache.GetColors(_generation.graphic.mesh); if (QualitySettings.activeColorSpace == ColorSpace.Linear) { for (int i = 0; i < colors.Length; i++) { _generation.colors.Add(colors[i].linear * totalTint); } } else { for (int i = 0; i < colors.Length; i++) { _generation.colors.Add(colors[i] * totalTint); } } } } protected virtual void buildUvs(UVChannelFlags channel) { using (new ProfilerSample("Build Uvs")) { var uvs = MeshCache.GetUvs(_generation.graphic.mesh, channel); var targetList = _generation.uvs[channel.Index()]; targetList.AddRange(uvs); //If we cannot remap this channel, just return if ((_generation.graphic.remappableChannels & channel) == 0) { return; } UnityEngine.Object key; if (_textureFeatures.Count > 0) { key = _textureFeatures[0].featureData[_generation.graphicIndex].texture; } else if (_spriteFeatures.Count > 0) { key = _spriteFeatures[0].featureData[_generation.graphicIndex].sprite; } else { return; } Rect rect = _atlasUvs.GetRect(channel.Index(), key); MeshUtil.RemapUvs(targetList, rect, uvs.Count); } } protected virtual void buildVertInfo() { using (new ProfilerSample("Build Special Uv3")) { _generation.vertInfo.Append(_generation.graphic.mesh.vertexCount, new Vector4(0, 0, 0, _generation.graphicId)); } } protected virtual void buildBlendShapes(LeapBlendShapeData blendShapeData) { using (new ProfilerSample("Build Blend Shapes")) { List<Vector3> blendVerts = Pool<List<Vector3>>.Spawn(); try { if (!blendShapeData.TryGetBlendShape(blendVerts)) { return; } int offset = _generation.verts.Count - blendVerts.Count; for (int i = 0; i < blendVerts.Count; i++) { Vector3 shapeVert = blendVerts[i]; Vector3 delta = blendShapeDelta(shapeVert, _generation.verts[i + offset]); Vector4 currVertInfo = _generation.vertInfo[i + offset]; currVertInfo.x = delta.x; currVertInfo.y = delta.y; currVertInfo.z = delta.z; _generation.vertInfo[i + offset] = currVertInfo; } } finally { blendVerts.Clear(); Pool<List<Vector3>>.Recycle(blendVerts); } } } protected virtual Vector3 blendShapeDelta(Vector3 shapeVert, Vector3 originalVert) { return graphicVertToMeshVert(shapeVert) - originalVert; } protected virtual void beginMesh(Mesh mesh = null) { Assert.IsNull(_generation.mesh, "Cannot begin a new mesh without finishing the current mesh."); _generation.Reset(); if (mesh == null) { mesh = _meshes.GetMeshFromPoolOrNew(); } else { mesh.Clear(keepVertexLayout: false); } mesh.name = "Procedural Graphic Mesh"; mesh.hideFlags = HideFlags.None; _generation.mesh = mesh; } protected virtual void finishMesh(bool deleteEmptyMeshes = true) { using (new ProfilerSample("Finish Mesh")) { if (_generation.verts.Count == 0 && deleteEmptyMeshes) { if (!Application.isPlaying) { UnityEngine.Object.DestroyImmediate(_generation.mesh, allowDestroyingAssets: true); } _generation.mesh = null; return; } _generation.mesh.SetVertices(_generation.verts); _generation.mesh.SetTriangles(_generation.tris, 0); if (_generation.normals.Count == _generation.verts.Count) { _generation.mesh.SetNormals(_generation.normals); } if (_generation.vertInfo.Count == _generation.verts.Count) { _generation.mesh.SetTangents(_generation.vertInfo); } if (_generation.colors.Count == _generation.verts.Count) { _generation.mesh.SetColors(_generation.colors); } foreach (var channel in _requiredUvChannels) { _generation.mesh.SetUVs(channel.Index(), _generation.uvs[channel.Index()]); } postProcessMesh(); } } protected virtual void finishAndAddMesh(bool deleteEmptyMeshes = true) { finishMesh(deleteEmptyMeshes); if (_generation.mesh != null) { _meshes.AddMesh(_generation.mesh); _generation.mesh = null; } } protected virtual void postProcessMesh() { } protected struct GenerationState { public LeapMeshGraphicBase graphic; public int graphicIndex; public int graphicId; public Mesh mesh; public List<Vector3> verts; public List<Vector3> normals; public List<Vector4> vertInfo; public List<int> tris; public List<Color> colors; public List<Vector4>[] uvs; public bool isGenerating { get { return mesh != null; } } public static GenerationState GetGenerationState() { GenerationState state = new GenerationState(); state.verts = new List<Vector3>(); state.normals = new List<Vector3>(); state.vertInfo = new List<Vector4>(); state.tris = new List<int>(); state.colors = new List<Color>(); state.uvs = new List<Vector4>[4] { new List<Vector4>(), new List<Vector4>(), new List<Vector4>(), new List<Vector4>() }; return state; } public void Reset() { verts.Clear(); normals.Clear(); vertInfo.Clear(); tris.Clear(); colors.Clear(); for (int i = 0; i < 4; i++) { uvs[i].Clear(); } } } #endregion #region UTILITY protected IEnumerable<UVChannelFlags> enabledUvChannels { get { if (_useUv0) yield return UVChannelFlags.UV0; if (_useUv1) yield return UVChannelFlags.UV1; if (_useUv2) yield return UVChannelFlags.UV2; if (_useUv3) yield return UVChannelFlags.UV3; } } protected virtual bool doesRequireMeshColors() { return _useColors; } protected virtual bool doesRequireMeshNormals() { return _useNormals; } protected virtual bool doesRequireUvChannel(UVChannelFlags channel) { switch (channel) { case UVChannelFlags.UV0: return _useUv0; case UVChannelFlags.UV1: return _useUv1; case UVChannelFlags.UV2: return _useUv2; case UVChannelFlags.UV3: return _useUv3; default: throw new ArgumentException("Invalid channel argument."); } } protected void drawMesh(Mesh mesh, Matrix4x4 transform) { #if UNITY_EDITOR if (!Application.isPlaying) { Graphics.DrawMesh(mesh, transform, _material, _visualLayer, null, 0, _spriteTextureBlock); } else #endif { Graphics.DrawMesh(mesh, transform, _material, _visualLayer); } } protected virtual bool doesRequireVertInfo() { return _tintFeatures.Count != 0 || _blendShapeFeatures.Count != 0 || _customFloatChannelData.Count != 0 || _customVectorChannelData.Count != 0 || _customMatrixChannelData.Count != 0 || _customColorChannelData.Count != 0; } protected abstract Vector3 graphicVertToMeshVert(Vector3 vertex); protected abstract void graphicVertNormalToMeshVertNormal(Vector3 vertex, Vector3 normal, out Vector3 meshVert, out Vector3 meshNormal); #endregion } } <file_sep>/Assets/Hover/Core/Scripts/Items/HoverItemBuilder.cs using Hover.Core.Items.Managers; using Hover.Core.Utils; using UnityEngine; namespace Hover.Core.Items { /*================================================================================================*/ [ExecuteInEditMode] public class HoverItemBuilder : MonoBehaviour { public HoverItem.HoverItemType ItemType = HoverItem.HoverItemType.Selector; public GameObject ButtonRendererPrefab; public GameObject SliderRendererPrefab; [TriggerButton("Build Item")] public bool ClickToBuild; //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public void Awake() { if ( ButtonRendererPrefab == null ) { ButtonRendererPrefab = Resources.Load<GameObject>( "Prefabs/HoverAlphaButtonRectRenderer-Default"); } if ( SliderRendererPrefab == null ) { SliderRendererPrefab = Resources.Load<GameObject>( "Prefabs/HoverAlphaSliderRectRenderer-Default"); } } /*--------------------------------------------------------------------------------------------*/ public void OnEditorTriggerButtonSelected() { UnityUtil.FindOrAddHoverKitPrefab(); PerformBuild(); } /*--------------------------------------------------------------------------------------------*/ public void Update() { if ( ClickToBuild ) { DestroyImmediate(this, false); } } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public void PerformBuild() { TreeUpdater treeUp = gameObject.AddComponent<TreeUpdater>(); HoverItem item = gameObject.AddComponent<HoverItem>(); item.ItemType = ItemType; HoverItemHighlightState highState = gameObject.AddComponent<HoverItemHighlightState>(); gameObject.AddComponent<HoverItemSelectionState>(); HoverItemRendererUpdater rendUp = gameObject.AddComponent<HoverItemRendererUpdater>(); rendUp.ButtonRendererPrefab = ButtonRendererPrefab; rendUp.SliderRendererPrefab = SliderRendererPrefab; highState.ProximityProvider = rendUp; treeUp.Update(); //forces the entire item to update } } } <file_sep>/Assets/Hover/Core/Scripts/Renderers/CanvasElements/HoverCanvas.cs using System; using Hover.Core.Renderers.Utils; using Hover.Core.Utils; using UnityEngine; namespace Hover.Core.Renderers.CanvasElements { /*================================================================================================*/ [ExecuteInEditMode] [RequireComponent(typeof(TreeUpdater))] [RequireComponent(typeof(Canvas))] [RequireComponent(typeof(CanvasGroup))] public class HoverCanvas : MonoBehaviour, ISettingsController, ITreeUpdateable { public const string SizeXName = "SizeX"; public const string SizeYName = "SizeY"; public enum CanvasAlignmentType { Left, Center, Right, TextLeftAndIconRight, TextRightAndIconLeft, Custom } public enum IconSizeType { FontSize, ThreeQuartersFontSize, OneAndHalfFontSize, DoubleFontSize, Custom } public ISettingsControllerMap Controllers { get; private set; } [DisableWhenControlled(DisplaySpecials=true)] public HoverLabel Label; public HoverIcon IconOuter; public HoverIcon IconInner; [DisableWhenControlled(RangeMin=0.0001f)] public float Scale = 0.0002f; [DisableWhenControlled(RangeMin=0)] public float SizeX = 0.1f; [DisableWhenControlled(RangeMin=0)] public float SizeY = 0.1f; [DisableWhenControlled(RangeMin=0)] public float PaddingX = 0.005f; [DisableWhenControlled(RangeMin=0)] public float PaddingY = 0.005f; [DisableWhenControlled] public CanvasAlignmentType Alignment = CanvasAlignmentType.Left; [DisableWhenControlled] public IconSizeType IconSize = IconSizeType.FontSize; [DisableWhenControlled] public bool UseMirrorLayout = false; [HideInInspector] [SerializeField] private bool _IsBuilt; //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public HoverCanvas() { Controllers = new SettingsControllerMap(); } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public Canvas CanvasComponent { get { return GetComponent<Canvas>(); } } /*--------------------------------------------------------------------------------------------*/ public CanvasGroup CanvasGroupComponent { get { return GetComponent<CanvasGroup>(); } } /*--------------------------------------------------------------------------------------------*/ public float UnscaledPaddedSizeX { get { return SizeX-PaddingX*2; } } /*--------------------------------------------------------------------------------------------*/ public float UnscaledPaddedSizeY { get { return SizeY-PaddingY*2; } } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public void Awake() { if ( !_IsBuilt ) { BuildElements(); _IsBuilt = true; } } /*--------------------------------------------------------------------------------------------*/ public virtual void Start() { //do nothing... } /*--------------------------------------------------------------------------------------------*/ public void TreeUpdate() { UpdateCanvasComponent(); UpdateScale(); UpdateActiveStates(); UpdateIconSizeSettings(); UpdateCanvasAlignmentSettings(); Controllers.TryExpireControllers(); } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ private void BuildElements() { CanvasComponent.renderMode = RenderMode.WorldSpace; CanvasComponent.sortingOrder = 1; Label = BuildLabel(); IconOuter = BuildIcon("IconOuter"); IconInner = BuildIcon("IconInner"); IconOuter.IconType = HoverIcon.IconOffset.RadioOuter; IconInner.IconType = HoverIcon.IconOffset.RadioInner; IconInner.ImageComponent.color = new Color(1, 1, 1, 0.7f); } /*--------------------------------------------------------------------------------------------*/ private HoverLabel BuildLabel() { var labelGo = new GameObject("Label"); labelGo.transform.SetParent(gameObject.transform, false); return labelGo.AddComponent<HoverLabel>(); } /*--------------------------------------------------------------------------------------------*/ private HoverIcon BuildIcon(string pName) { var iconGo = new GameObject(pName); iconGo.transform.SetParent(gameObject.transform, false); return iconGo.AddComponent<HoverIcon>(); } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ private void UpdateCanvasComponent() { Canvas canvas = CanvasComponent; RectTransform rectTx = canvas.GetComponent<RectTransform>(); gameObject.transform.localScale = Vector3.one*Scale; rectTx.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, UnscaledPaddedSizeX/Scale); rectTx.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, UnscaledPaddedSizeY/Scale); } /*--------------------------------------------------------------------------------------------*/ private void UpdateScale() { Label.Controllers.Set(HoverLabel.CanvasScaleName, this); IconOuter.Controllers.Set(HoverIcon.CanvasScaleName, this); IconInner.Controllers.Set(HoverIcon.CanvasScaleName, this); Label.CanvasScale = Scale; IconOuter.CanvasScale = Scale; IconInner.CanvasScale = Scale; } /*--------------------------------------------------------------------------------------------*/ private void UpdateActiveStates() { bool isLabelActive = (!string.IsNullOrEmpty(Label.TextComponent.text)); bool isIconOuterActive = (IconOuter.IconType != HoverIcon.IconOffset.None); bool isIconInnerActive = (IconInner.IconType != HoverIcon.IconOffset.None); Label.Controllers.Set(SettingsControllerMap.GameObjectActiveSelf, this); IconOuter.Controllers.Set(SettingsControllerMap.GameObjectActiveSelf, this); IconInner.Controllers.Set(SettingsControllerMap.GameObjectActiveSelf, this); RendererUtil.SetActiveWithUpdate(Label, isLabelActive); RendererUtil.SetActiveWithUpdate(IconOuter, isIconOuterActive); RendererUtil.SetActiveWithUpdate(IconInner, isIconInnerActive); } /*--------------------------------------------------------------------------------------------*/ private void UpdateIconSizeSettings() { if ( IconSize == IconSizeType.Custom ) { return; } IconOuter.Controllers.Set(HoverIcon.SizeXName, this); IconOuter.Controllers.Set(HoverIcon.SizeYName, this); IconInner.Controllers.Set(HoverIcon.SizeXName, this); IconInner.Controllers.Set(HoverIcon.SizeYName, this); float fontSize = Label.TextComponent.fontSize*Label.CanvasScale; switch ( IconSize ) { case IconSizeType.FontSize: IconOuter.SizeX = fontSize; break; case IconSizeType.ThreeQuartersFontSize: IconOuter.SizeX = fontSize*0.75f; break; case IconSizeType.OneAndHalfFontSize: IconOuter.SizeX = fontSize*1.5f; break; case IconSizeType.DoubleFontSize: IconOuter.SizeX = fontSize*2; break; } IconOuter.SizeY = IconOuter.SizeX; IconInner.SizeX = IconOuter.SizeX; IconInner.SizeY = IconOuter.SizeY; } /*--------------------------------------------------------------------------------------------*/ private void UpdateCanvasAlignmentSettings() { if ( Alignment == CanvasAlignmentType.Custom ) { return; } const float iconVertShiftMult = -0.35f; Vector3 labelLocalScale = Label.transform.localScale; float fontSize = Label.TextComponent.fontSize*Label.CanvasScale/2; float iconAvailW = UnscaledPaddedSizeX-IconOuter.SizeX; float iconPad = IconOuter.SizeX*0.2f; float iconShiftX = 0; float iconShiftY = 0; float labelInsetL = 0; float labelInsetR = 0; float labelInsetT = 0; TextAnchor labelAlign; switch ( Alignment ) { //icon case CanvasAlignmentType.Left: case CanvasAlignmentType.TextRightAndIconLeft: iconShiftX = -0.5f*iconAvailW; iconShiftY = iconVertShiftMult*fontSize; labelInsetL = IconOuter.SizeX+iconPad; break; case CanvasAlignmentType.Center: iconShiftY = (fontSize+iconPad)/2; labelInsetT = (IconOuter.SizeY+iconPad)/2; break; case CanvasAlignmentType.Right: case CanvasAlignmentType.TextLeftAndIconRight: iconShiftX = 0.5f*iconAvailW; iconShiftY = iconVertShiftMult*fontSize; labelInsetR = IconOuter.SizeX+iconPad; break; default: throw new Exception("Unhandled alignment: "+Alignment); } switch ( Alignment ) { //label case CanvasAlignmentType.Left: case CanvasAlignmentType.TextLeftAndIconRight: labelAlign = (UseMirrorLayout ? TextAnchor.MiddleRight : TextAnchor.MiddleLeft); break; case CanvasAlignmentType.Center: labelAlign = TextAnchor.MiddleCenter; break; case CanvasAlignmentType.Right: case CanvasAlignmentType.TextRightAndIconLeft: labelAlign = (UseMirrorLayout ? TextAnchor.MiddleLeft : TextAnchor.MiddleRight); break; default: throw new Exception("Unhandled alignment: "+Alignment); } Label.Controllers.Set(SettingsControllerMap.TransformLocalPosition, this); Label.Controllers.Set(SettingsControllerMap.TransformLocalScale+".x", this); Label.Controllers.Set(HoverLabel.SizeXName, this); Label.Controllers.Set(HoverLabel.SizeYName, this); Label.Controllers.Set(SettingsControllerMap.TextAlignment, this); IconOuter.Controllers.Set(SettingsControllerMap.TransformLocalPosition, this); IconInner.Controllers.Set(SettingsControllerMap.TransformLocalPosition, this); labelLocalScale.x = (UseMirrorLayout ? -1 : 1); Label.transform.localScale = labelLocalScale; if ( !IconOuter.gameObject.activeSelf && !IconInner.gameObject.activeSelf ) { iconShiftX = 0; iconShiftY = 0; labelInsetL = 0; labelInsetR = 0; labelInsetT = 0; } var labelLocalPos = new Vector3((labelInsetL-labelInsetR)/2, -labelInsetT, 0); var iconLocalPos = new Vector3(iconShiftX, iconShiftY, 0); Label.SizeX = UnscaledPaddedSizeX-labelInsetL-labelInsetR; Label.SizeY = UnscaledPaddedSizeY-labelInsetT; Label.TextComponent.alignment = labelAlign; Label.transform.localPosition = labelLocalPos/Scale; IconOuter.transform.localPosition = iconLocalPos/Scale; IconInner.transform.localPosition = IconOuter.transform.localPosition; } } } <file_sep>/Assets/Hover/Core/Scripts/Renderers/Shapes/Arc/HoverFillSliderArcUpdater.cs using Hover.Core.Renderers.Items.Sliders; using Hover.Core.Renderers.Utils; using Hover.Core.Utils; using UnityEngine; namespace Hover.Core.Renderers.Shapes.Arc { /*================================================================================================*/ [RequireComponent(typeof(HoverShapeArc))] public class HoverFillSliderArcUpdater : HoverFillSliderUpdater { [DisableWhenControlled(RangeMin=0, DisplaySpecials=true)] public float InsetOuter = 0.01f; [DisableWhenControlled(RangeMin=0)] public float InsetInner = 0.01f; [DisableWhenControlled(RangeMin=0, RangeMax=1)] public float TickRelativeSizeX = 0.5f; [DisableWhenControlled] public bool UseTrackUv = false; private float vMeshOuterRadius; private float vMeshInnerRadius; private float vTickOuterRadius; private float vTickInnerRadius; //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ protected override void UpdateFillMeshes() { HoverShapeArc shapeArc = gameObject.GetComponent<HoverShapeArc>(); vMeshOuterRadius = shapeArc.OuterRadius-InsetOuter; vMeshInnerRadius = shapeArc.InnerRadius+InsetInner; base.UpdateFillMeshes(); } /*--------------------------------------------------------------------------------------------*/ protected override void ResetFillMesh(HoverMesh pSegmentMesh) { HoverShapeArc meshShapeArc = pSegmentMesh.GetComponent<HoverShapeArc>(); meshShapeArc.Controllers.Set(HoverShapeArc.OuterRadiusName, this); meshShapeArc.Controllers.Set(HoverShapeArc.InnerRadiusName, this); meshShapeArc.Controllers.Set(HoverShapeArc.ArcDegreesName, this); meshShapeArc.OuterRadius = vMeshOuterRadius; meshShapeArc.InnerRadius = vMeshInnerRadius; meshShapeArc.ArcDegrees = 0; } /*--------------------------------------------------------------------------------------------*/ protected override void UpdateFillMesh(HoverMesh pSegmentMesh, SliderUtil.SegmentInfo pSegmentInfo, float pStartPos, float pEndPos) { HoverShapeArc meshShapeArc = pSegmentMesh.GetComponent<HoverShapeArc>(); HoverMeshArc meshArc = (HoverMeshArc)pSegmentMesh; pSegmentMesh.Controllers.Set(SettingsControllerMap.TransformLocalRotation, this); pSegmentMesh.Controllers.Set(HoverMesh.DisplayModeName, this); meshArc.Controllers.Set(HoverMeshArc.UvMinArcDegreeName, this); meshArc.Controllers.Set(HoverMeshArc.UvMaxArcDegreeName, this); meshShapeArc.ArcDegrees = pSegmentInfo.EndPosition-pSegmentInfo.StartPosition; pSegmentMesh.DisplayMode = (pSegmentInfo.IsFill ? HoverMesh.DisplayModeType.SliderFill : HoverMesh.DisplayModeType.Standard); meshArc.UvMinArcDegree = (UseTrackUv ? Mathf.InverseLerp(pStartPos, pEndPos, pSegmentInfo.StartPosition) : 0); meshArc.UvMaxArcDegree = (UseTrackUv ? Mathf.InverseLerp(pStartPos, pEndPos, pSegmentInfo.EndPosition) : 1); pSegmentMesh.transform.localRotation = Quaternion.AngleAxis( (pSegmentInfo.StartPosition+pSegmentInfo.EndPosition)/2, Vector3.forward); } /*--------------------------------------------------------------------------------------------*/ protected override void ActivateFillMesh(HoverMesh pSegmentMesh) { HoverShapeArc meshShapeArc = pSegmentMesh.GetComponent<HoverShapeArc>(); pSegmentMesh.Controllers.Set(SettingsControllerMap.GameObjectActiveSelf, this); RendererUtil.SetActiveWithUpdate(pSegmentMesh, (meshShapeArc.ArcDegrees > 0)); } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ protected override void UpdateTickMeshes() { HoverShapeArc shapeArc = gameObject.GetComponent<HoverShapeArc>(); float inset = (shapeArc.OuterRadius-shapeArc.InnerRadius-InsetOuter-InsetInner)* (1-TickRelativeSizeX)/2; vTickOuterRadius = shapeArc.OuterRadius-InsetOuter-inset; vTickInnerRadius = shapeArc.InnerRadius+InsetInner+inset; base.UpdateTickMeshes(); } /*--------------------------------------------------------------------------------------------*/ protected override void UpdateTickMesh(HoverMesh pTickMesh, SliderUtil.SegmentInfo pTickInfo) { HoverShapeArc meshShapeArc = pTickMesh.GetComponent<HoverShapeArc>(); pTickMesh.Controllers.Set(SettingsControllerMap.GameObjectActiveSelf, this); pTickMesh.Controllers.Set(SettingsControllerMap.TransformLocalRotation, this); meshShapeArc.Controllers.Set(HoverShapeArc.OuterRadiusName, this); meshShapeArc.Controllers.Set(HoverShapeArc.InnerRadiusName, this); meshShapeArc.Controllers.Set(HoverShapeArc.ArcDegreesName, this); meshShapeArc.OuterRadius = vTickOuterRadius; meshShapeArc.InnerRadius = vTickInnerRadius; meshShapeArc.ArcDegrees = pTickInfo.EndPosition-pTickInfo.StartPosition; pTickMesh.transform.localRotation = Quaternion.AngleAxis( (pTickInfo.StartPosition+pTickInfo.EndPosition)/2, Vector3.forward); RendererUtil.SetActiveWithUpdate(pTickMesh, !pTickInfo.IsHidden); } } } <file_sep>/Assets/Hover/Core/Scripts/Renderers/CanvasElements/HoverCanvasSizeUpdater.cs using System; using Hover.Core.Renderers.Shapes; using Hover.Core.Renderers.Shapes.Arc; using Hover.Core.Renderers.Shapes.Rect; using Hover.Core.Utils; using UnityEngine; namespace Hover.Core.Renderers.CanvasElements { /*================================================================================================*/ [RequireComponent(typeof(HoverCanvas))] public class HoverCanvasSizeUpdater : MonoBehaviour, ITreeUpdateable, ISettingsController { public HoverShape Shape; //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public void Start() { //do nothing... } /*--------------------------------------------------------------------------------------------*/ public void TreeUpdate() { if ( Shape == null ) { Debug.LogWarning("No '"+typeof(HoverShape).Name+"' reference provided."); return; } HoverCanvas canvas = GetComponent<HoverCanvas>(); HoverShapeRect shapeRect = (Shape as HoverShapeRect); HoverShapeArc shapeArc = (Shape as HoverShapeArc); if ( shapeRect ) { UpdateWithRect(canvas, shapeRect); } else if ( shapeArc != null ) { UpdateWithArc(canvas, shapeArc); } else { throw new Exception("Shape not supported: "+Shape); } } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ private void UpdateWithRect(HoverCanvas pHoverCanvas, HoverShapeRect pShapeRect) { pHoverCanvas.Controllers.Set(HoverCanvas.SizeXName, this); pHoverCanvas.Controllers.Set(HoverCanvas.SizeYName, this); pHoverCanvas.SizeX = pShapeRect.SizeX; pHoverCanvas.SizeY = pShapeRect.SizeY; } /*--------------------------------------------------------------------------------------------*/ private void UpdateWithArc(HoverCanvas pHoverCanvas, HoverShapeArc pShapeArc) { pHoverCanvas.Controllers.Set(SettingsControllerMap.TransformLocalPosition+".x", this); pHoverCanvas.Controllers.Set(HoverCanvas.SizeXName, this); pHoverCanvas.SizeX = pShapeArc.OuterRadius-pShapeArc.InnerRadius; Vector3 canvasLocalPos = pHoverCanvas.transform.localPosition; canvasLocalPos.x = pShapeArc.InnerRadius+pHoverCanvas.SizeX/2; pHoverCanvas.transform.localPosition = canvasLocalPos; } } } <file_sep>/Assets/Hover/Core/Scripts/Renderers/Shapes/Rect/HoverMeshRectHollowTab.cs using Hover.Core.Utils; using UnityEngine; namespace Hover.Core.Renderers.Shapes.Rect { /*================================================================================================*/ [RequireComponent(typeof(HoverIndicator))] [RequireComponent(typeof(HoverShapeRect))] public class HoverMeshRectHollowTab : HoverMeshRect { public const string TabOutwardName = "TabOutward"; public const string TabThicknessName = "TabThickness"; public const string ShowTabNName = "ShowTabN"; public const string ShowTabEName = "ShowTabE"; public const string ShowTabSName = "ShowTabS"; public const string ShowTabWName = "ShowTabW"; public SizeType InnerSizeType = SizeType.Min; [DisableWhenControlled] public float TabOutward = 0.01f; [DisableWhenControlled] public float TabThickness = 0.025f; [DisableWhenControlled] public bool ShowTabN = true; [DisableWhenControlled] public bool ShowTabE = false; [DisableWhenControlled] public bool ShowTabS = false; [DisableWhenControlled] public bool ShowTabW = false; private SizeType vPrevInnerType; private float vPrevTabOut; private float vPrevTabThick; private bool vPrevTabN; private bool vPrevTabE; private bool vPrevTabS; private bool vPrevTabW; //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public override bool IsMeshVisible { get { HoverShapeRect shape = GetComponent<HoverShapeRect>(); float innerProg = GetDimensionProgress(InnerSizeType); float outerProg = GetDimensionProgress(OuterSizeType); return (shape.SizeX != 0 && shape.SizeY != 0 && outerProg != innerProg); } } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ protected override bool ShouldUpdateMesh() { bool shouldUpdate = ( base.ShouldUpdateMesh() || InnerSizeType != vPrevInnerType || TabOutward != vPrevTabOut || TabThickness != vPrevTabThick || vPrevTabN != ShowTabN || vPrevTabE != ShowTabE || vPrevTabS != ShowTabS || vPrevTabW != ShowTabW ); vPrevInnerType = InnerSizeType; vPrevTabOut = TabOutward; vPrevTabThick = TabThickness; vPrevTabN = ShowTabN; vPrevTabE = ShowTabE; vPrevTabS = ShowTabS; vPrevTabW = ShowTabW; return shouldUpdate; } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ protected override void UpdateMesh() { HoverShapeRect shape = GetComponent<HoverShapeRect>(); float innerProg = GetDimensionProgress(InnerSizeType); float outerProg = GetDimensionProgress(OuterSizeType); float outerW; float outerH; float innerW; float innerH; if ( shape.SizeX >= shape.SizeY ) { outerH = shape.SizeY*outerProg; innerH = shape.SizeY*innerProg; outerW = shape.SizeX-(shape.SizeY-outerH); innerW = shape.SizeX-(shape.SizeY-innerH); } else { outerW = shape.SizeX*outerProg; innerW = shape.SizeX*innerProg; outerH = shape.SizeY-(shape.SizeX-outerW); innerH = shape.SizeY-(shape.SizeX-innerW); } MeshUtil.BuildHollowRectangleTabMesh(vMeshBuild, outerW, outerH, innerW, innerH, TabOutward*outerProg, TabThickness*outerProg, innerProg/outerProg, ShowTabN, ShowTabE, ShowTabS, ShowTabW); UpdateAutoUv(shape, outerW, outerH); UpdateMeshUvAndColors(); vMeshBuild.Commit(); vMeshBuild.CommitColors(); } } } <file_sep>/Assets/LeapMotion/Modules/GraphicRenderer/Scripts/Features/Sprite/LeapSpriteFeature.cs /****************************************************************************** * Copyright (C) Leap Motion, Inc. 2011-2018. * * Leap Motion proprietary and confidential. * * * * Use subject to the terms of the Leap Motion SDK Agreement available at * * https://developer.leapmotion.com/sdk_agreement, or another agreement * * between Leap Motion and you, your company or other organization. * ******************************************************************************/ using System; using UnityEngine; using UnityEngine.Rendering; #if UNITY_EDITOR using UnityEditor; using UnityEditor.Sprites; #endif using Leap.Unity.Attributes; namespace Leap.Unity.GraphicalRenderer { [LeapGraphicTag("Sprite", 20)] [Serializable] public class LeapSpriteFeature : LeapGraphicFeature<LeapSpriteData> { [Delayed] [EditTimeOnly] public string propertyName = "_MainTex"; [EditTimeOnly] public UVChannelFlags channel = UVChannelFlags.UV0; #if UNITY_EDITOR public bool AreAllSpritesPacked() { foreach (var dataObj in featureData) { if (dataObj.sprite == null) continue; if (!dataObj.sprite.packed) { return false; } } return true; } public bool AreAllSpritesOnSameTexture() { Texture2D mainTex = null; foreach (var dataObj in featureData) { if (dataObj.sprite == null) continue; string atlasName; Texture2D atlasTex; Packer.GetAtlasDataForSprite(dataObj.sprite, out atlasName, out atlasTex); if (mainTex == null) { mainTex = atlasTex; } else { if (mainTex != atlasTex) { return false; } } } return true; } #endif } } <file_sep>/Assets/LeapMotion/Modules/GraphicRenderer/Scripts/Utility/AtlasBuilder.cs /****************************************************************************** * Copyright (C) Leap Motion, Inc. 2011-2018. * * Leap Motion proprietary and confidential. * * * * Use subject to the terms of the Leap Motion SDK Agreement available at * * https://developer.leapmotion.com/sdk_agreement, or another agreement * * between Leap Motion and you, your company or other organization. * ******************************************************************************/ using System; using System.Collections.Generic; using UnityEngine; using UnityEngine.Rendering; using Leap.Unity.Query; using Leap.Unity.Attributes; namespace Leap.Unity.GraphicalRenderer { /// <summary> /// A class that contains mapping information that specifies how a texture /// is packed into an atlas. /// </summary> [Serializable] public class AtlasUvs { [Serializable] public class TextureToRect : SerializableDictionary<UnityEngine.Object, Rect> { } [SerializeField] private TextureToRect _channel0 = new TextureToRect(); [SerializeField] private TextureToRect _channel1 = new TextureToRect(); [SerializeField] private TextureToRect _channel2 = new TextureToRect(); [SerializeField] private TextureToRect _channel3 = new TextureToRect(); [SerializeField] private Rect[] _nullRects = new Rect[4]; /// <summary> /// Given a texture object and a uv channel, return the rect that /// this texture occupies within the atlas. If the key is not /// present in the atlas, the default rect is returned. If a null /// texture is passed in, the rect for the empty texture (which is valid!) /// is returned. /// </summary> public Rect GetRect(int channel, UnityEngine.Object key) { if (key == null) { return _nullRects[channel]; } else { Rect r; getChannel(channel).TryGetValue(key, out r); return r; } } /// <summary> /// Given a texture object and a uv channel, store into this data /// structure the rect that the texture takes up inside of the atlas. /// A null texture object is valid, and represents the empty texture. /// </summary> public void SetRect(int channel, UnityEngine.Object key, Rect rect) { if (key == null) { _nullRects[channel] = rect; } else { getChannel(channel)[key] = rect; } } private TextureToRect getChannel(int channel) { switch (channel) { case 0: return _channel0; case 1: return _channel1; case 2: return _channel2; case 3: return _channel3; default: throw new Exception(); } } } [Serializable] public class AtlasBuilder { [Tooltip("When non-zero, extends each texture by a certain number of pixels, filling in the space with texture data based on the texture wrap mode.")] [MinValue(0)] [EditTimeOnly, SerializeField] private int _border = 0; [Tooltip("When non-zero, adds an amount of empty space between each texture.")] [MinValue(0)] [EditTimeOnly, SerializeField] private int _padding = 0; [Tooltip("Should the atlas have mip maps?")] [EditTimeOnly, SerializeField] private bool _mipMap = true; [Tooltip("The filter mode that should be used for the atlas.")] [EditTimeOnly, SerializeField] private FilterMode _filterMode = FilterMode.Bilinear; [Tooltip("The texture format that should be used for the atlas.")] [EditTimeOnly, SerializeField] private TextureFormat _format = TextureFormat.ARGB32; [Tooltip("The maximum atlas size in pixels.")] [MinValue(16)] [MaxValue(8192)] [EditTimeOnly, SerializeField] private int _maxAtlasSize = 4096; [Tooltip("Add textures to this array to ensure that they are always present in the atlas.")] [SerializeField] private TextureReference[] _extraTextures; /// <summary> /// Returns whether or not the results built by this atlas have become invalid. /// </summary> public bool isDirty { get { return _currHash != _atlasHash; } } private static Material _cachedBlitMaterial = null; private static void enableBlitPass(Texture tex) { if (_cachedBlitMaterial == null) { _cachedBlitMaterial = new Material(Shader.Find("Hidden/Leap Motion/Graphic Renderer/InternalPack")); _cachedBlitMaterial.hideFlags = HideFlags.HideAndDontSave; } _cachedBlitMaterial.mainTexture = tex; _cachedBlitMaterial.SetPass(0); } private List<LeapTextureFeature> _features = new List<LeapTextureFeature>(); private Hash _atlasHash = 1; private Hash _currHash = 0; /// <summary> /// Updates the internal list of textures given some texture features to build an atlas for. /// This method does not do any atlas work, but must be called before RebuildAtlas is called. /// Once this method is called, you can check the isDirty flag to see if a rebuild is needed. /// </summary> public void UpdateTextureList(List<LeapTextureFeature> textureFeatures) { _features.Clear(); _features.AddRange(textureFeatures); _currHash = new Hash() { _border, _padding, _mipMap, _filterMode, _format, _maxAtlasSize }; if (_extraTextures == null) { _extraTextures = new TextureReference[0]; } for (int i = 0; i < _extraTextures.Length; i++) { switch (_extraTextures[i].channel) { case UVChannelFlags.UV0: case UVChannelFlags.UV1: case UVChannelFlags.UV2: case UVChannelFlags.UV3: break; default: _extraTextures[i].channel = UVChannelFlags.UV0; break; } } foreach (var extra in _extraTextures) { _currHash.Add(extra.texture); _currHash.Add(extra.channel); } foreach (var feature in _features) { _currHash.Add(feature.channel); foreach (var dataObj in feature.featureData) { _currHash.Add(dataObj.texture); } } } /// <summary> /// Actually perform the build for the atlas. This method outputs the atlas textures, and the atlas /// uvs that map textures into the atlas. This method takes in a progress bar so that the atlas /// process can be tracked visually, since it can take quite a bit of time when there are a lot of /// textures to pack. /// </summary> public void RebuildAtlas(ProgressBar progress, out Texture2D[] packedTextures, out AtlasUvs channelMapping) { if (!Utils.IsCompressible(_format)) { Debug.LogWarning("Format " + _format + " is not compressible! Using ARGB32 instead."); _format = TextureFormat.ARGB32; } _atlasHash = _currHash; packedTextures = new Texture2D[_features.Count]; channelMapping = new AtlasUvs(); mainProgressLoop(progress, packedTextures, channelMapping); //Clear cache foreach (var texture in _cachedProcessedTextures.Values) { UnityEngine.Object.DestroyImmediate(texture); } _cachedProcessedTextures.Clear(); foreach (var texture in _cachedDefaultTextures.Values) { UnityEngine.Object.DestroyImmediate(texture); } _cachedDefaultTextures.Clear(); } private void mainProgressLoop(ProgressBar progress, Texture2D[] packedTextures, AtlasUvs channelMapping) { progress.Begin(5, "", "", () => { foreach (var channel in MeshUtil.allUvChannels) { progress.Begin(1, "", channel + ": ", () => { doPerChannelPack(progress, channel, packedTextures, channelMapping); }); } finalizeTextures(progress, packedTextures); }); } private void doPerChannelPack(ProgressBar progress, UVChannelFlags channel, Texture2D[] packedTextures, AtlasUvs channelMapping) { var mainTextureFeature = _features.Query().FirstOrDefault(f => f.channel == channel); if (mainTextureFeature == null) return; Texture2D defaultTexture, packedTexture; Texture2D[] rawTextureArray, processedTextureArray; progress.Step("Prepare " + channel); prepareForPacking(mainTextureFeature, out defaultTexture, out packedTexture, out rawTextureArray, out processedTextureArray); progress.Step("Pack " + channel); var packedRects = packedTexture.PackTextures(processedTextureArray, _padding, _maxAtlasSize, makeNoLongerReadable: false); packedTexture.Apply(updateMipmaps: true, makeNoLongerReadable: true); packedTextures[_features.IndexOf(mainTextureFeature)] = packedTexture; packSecondaryTextures(progress, channel, mainTextureFeature, packedTexture, packedRects, packedTextures); //Correct uvs to account for the added border for (int i = 0; i < packedRects.Length; i++) { float dx = 1.0f / packedTexture.width; float dy = 1.0f / packedTexture.height; Rect r = packedRects[i]; if (processedTextureArray[i] != defaultTexture) { dx *= _border; dy *= _border; } r.x += dx; r.y += dy; r.width -= dx * 2; r.height -= dy * 2; packedRects[i] = r; } for (int i = 0; i < rawTextureArray.Length; i++) { channelMapping.SetRect(channel.Index(), rawTextureArray[i], packedRects[i]); } } private void packSecondaryTextures(ProgressBar progress, UVChannelFlags channel, LeapTextureFeature mainFeature, Texture2D packedTexture, Rect[] packedRects, Texture2D[] packedTextures) { //All texture features that are NOT the main texture do not get their own atlas step //They are simply copied into a new texture var nonMainFeatures = _features.Query().Where(f => f.channel == channel).Skip(1).ToList(); progress.Begin(nonMainFeatures.Count, "", "Copying secondary textures: ", () => { foreach (var secondaryFeature in nonMainFeatures) { RenderTexture secondaryRT = new RenderTexture(packedTexture.width, packedTexture.height, 0, RenderTextureFormat.ARGB32, RenderTextureReadWrite.Linear); RenderTexture.active = secondaryRT; GL.Clear(clearDepth: false, clearColor: true, backgroundColor: Color.black); GL.LoadPixelMatrix(0, 1, 0, 1); progress.Begin(secondaryFeature.featureData.Count, "", secondaryFeature.propertyName, () => { for (int i = 0; i < secondaryFeature.featureData.Count; i++) { var mainTexture = mainFeature.featureData[i].texture; if (mainTexture == null) { progress.Step(); continue; } var secondaryTexture = secondaryFeature.featureData[i].texture; if (secondaryTexture == null) { progress.Step(); continue; } progress.Step(secondaryTexture.name); Rect rect = packedRects[i]; //Use mainTexture instead of secondaryTexture here to calculate correct border to line up with main texture float borderDX = _border / (float)mainTexture.width; float borderDY = _border / (float)mainTexture.height; drawTexture(secondaryTexture, secondaryRT, rect, borderDX, borderDY); } }); packedTextures[_features.IndexOf(secondaryFeature)] = convertToTexture2D(secondaryRT, mipmap: false); } }); } private void finalizeTextures(ProgressBar progress, Texture2D[] packedTextures) { progress.Begin(packedTextures.Length, "", "Finalizing ", () => { for (int i = 0; i < packedTextures.Length; i++) { progress.Begin(2, "", _features[i].propertyName + ": ", () => { Texture2D tex = packedTextures[i]; RenderTexture rt = new RenderTexture(tex.width, tex.height, 0, RenderTextureFormat.ARGB32, RenderTextureReadWrite.Linear); GL.LoadPixelMatrix(0, 1, 0, 1); drawTexture(tex, rt, new Rect(0, 0, 1, 1), 0, 0); progress.Step("Copying Texture"); tex = convertToTexture2D(rt, _mipMap); progress.Step("Compressing Texture"); #if UNITY_EDITOR UnityEditor.EditorUtility.CompressTexture(tex, _format, TextureCompressionQuality.Best); #endif tex.filterMode = _filterMode; progress.Step("Updating Texture"); //keep the texture as readable because the user might want to do things with the texture! tex.Apply(updateMipmaps: true, makeNoLongerReadable: false); packedTextures[i] = tex; }); } }); } private void prepareForPacking(LeapTextureFeature feature, out Texture2D defaultTexture, out Texture2D packedTexture, out Texture2D[] rawTextureArray, out Texture2D[] processedTextureArray) { if (_extraTextures == null) { _extraTextures = new TextureReference[0]; } rawTextureArray = feature.featureData.Query(). Select(dataObj => dataObj.texture). Concat(_extraTextures.Query(). Where(p => p.channel == feature.channel). Select(p => p.texture)). ToArray(); processedTextureArray = rawTextureArray.Query(). Select(t => processTexture(t)). ToArray(); defaultTexture = getDefaultTexture(Color.white); //TODO, pull color from feature data for (int i = 0; i < processedTextureArray.Length; i++) { if (processedTextureArray[i] == null) { processedTextureArray[i] = defaultTexture; } } packedTexture = new Texture2D(1, 1, TextureFormat.ARGB32, mipmap: false, linear: true); packedTexture.filterMode = _filterMode; } private Dictionary<Texture2D, Texture2D> _cachedProcessedTextures = new Dictionary<Texture2D, Texture2D>(); private Texture2D processTexture(Texture2D source) { using (new ProfilerSample("Process Texture")) { if (source == null) { return null; } Texture2D processed; if (_cachedProcessedTextures.TryGetValue(source, out processed)) { return processed; } RenderTexture destRT = new RenderTexture(source.width + _border * 2, source.height + _border * 2, 0, RenderTextureFormat.ARGB32, RenderTextureReadWrite.Linear); GL.LoadPixelMatrix(0, 1, 0, 1); drawTexture(source, destRT, new Rect(0, 0, 1, 1), _border / (float)source.width, _border / (float)source.height); processed = convertToTexture2D(destRT, mipmap: false); _cachedProcessedTextures[source] = processed; return processed; } } private void drawTexture(Texture2D source, RenderTexture dst, Rect rect, float borderDX, float borderDY) { enableBlitPass(source); RenderTexture.active = dst; GL.Begin(GL.QUADS); GL.TexCoord(new Vector2(0 - borderDX, 0 - borderDY)); GL.Vertex(rect.Corner00()); GL.TexCoord(new Vector2(1 + borderDX, 0 - borderDY)); GL.Vertex(rect.Corner10()); GL.TexCoord(new Vector2(1 + borderDX, 1 + borderDY)); GL.Vertex(rect.Corner11()); GL.TexCoord(new Vector2(0 - borderDX, 1 + borderDY)); GL.Vertex(rect.Corner01()); GL.End(); } private Texture2D convertToTexture2D(RenderTexture source, bool mipmap) { Texture2D tex = new Texture2D(source.width, source.height, TextureFormat.ARGB32, mipmap, linear: true); RenderTexture.active = source; tex.ReadPixels(new Rect(0, 0, tex.width, tex.height), 0, 0); tex.Apply(updateMipmaps: false, makeNoLongerReadable: false); RenderTexture.active = null; source.Release(); UnityEngine.Object.DestroyImmediate(source); return tex; } private Dictionary<Color, Texture2D> _cachedDefaultTextures = new Dictionary<Color, Texture2D>(); private Texture2D getDefaultTexture(Color color) { Texture2D texture; if (!_cachedDefaultTextures.TryGetValue(color, out texture)) { texture = new Texture2D(3, 3, TextureFormat.ARGB32, mipmap: false); texture.SetPixels(new Color[3 * 3].Fill(color)); _cachedDefaultTextures[color] = texture; } return texture; } [Serializable] public class TextureReference { public Texture2D texture; public UVChannelFlags channel = UVChannelFlags.UV0; } } } <file_sep>/Assets/LeapMotion/Core/Scripts/Animation/Tween/Enums.cs /****************************************************************************** * Copyright (C) Leap Motion, Inc. 2011-2018. * * Leap Motion proprietary and confidential. * * * * Use subject to the terms of the Leap Motion SDK Agreement available at * * https://developer.leapmotion.com/sdk_agreement, or another agreement * * between Leap Motion and you, your company or other organization. * ******************************************************************************/ namespace Leap.Unity.Animation { public enum Direction { Forward = 1, Backward = -1 } public enum SmoothType { Linear = 1, Smooth = 2, SmoothEnd = 3, SmoothStart = 4 } } <file_sep>/Assets/LeapMotion/Modules/GraphicRenderer/Examples/Scripts/ExampleArrayController.cs /****************************************************************************** * Copyright (C) Leap Motion, Inc. 2011-2018. * * Leap Motion proprietary and confidential. * * * * Use subject to the terms of the Leap Motion SDK Agreement available at * * https://developer.leapmotion.com/sdk_agreement, or another agreement * * between Leap Motion and you, your company or other organization. * ******************************************************************************/ using System.Collections.Generic; using UnityEngine; using Leap.Unity.Query; using Leap.Unity.GraphicalRenderer; public class ExampleArrayController : MonoBehaviour { [SerializeField] private AnimationCurve _motionCurve; [SerializeField] private Gradient _gradient; private List<LeapGraphic> _graphics = new List<LeapGraphic>(); private List<Vector3> _originalPositions = new List<Vector3>(); private List<LeapBlendShapeData> _blendShapeData = new List<LeapBlendShapeData>(); private List<LeapRuntimeTintData> _tintData = new List<LeapRuntimeTintData>(); private void Start() { _graphics.AddRange(GetComponentsInChildren<LeapGraphic>()); _graphics.Query().Select(g => g.transform.localPosition).FillList(_originalPositions); _graphics.Query().Select(g => g.GetFeatureData<LeapBlendShapeData>()).FillList(_blendShapeData); _graphics.Query().Select(g => g.GetFeatureData<LeapRuntimeTintData>()).FillList(_tintData); } private void Update() { float fade = Mathf.Clamp01(Time.time * 0.5f - 0.5f); for (int i = 0; i < _graphics.Count; i++) { _graphics[i].transform.localPosition = _originalPositions[i]; float a = fade * 10 * noise(_graphics[i].transform.position, 42.0f, 0.8f); float b = noise(_graphics[i].transform.position * 1.7f, 23, 0.35f); float c = fade * _motionCurve.Evaluate(b); float d = fade * (c * 0.1f + a * (c * 0.03f + 0.01f) + _graphics[i].transform.position.z * 0.14f); _blendShapeData[i].amount = c; _graphics[i].transform.localPosition += Vector3.up * d; _tintData[i].color = fade * _gradient.Evaluate(b); } } private float noise(Vector3 offset, float seed, float speed) { float x1 = seed * 23.1239879f; float y1 = seed * 82.1239812f; x1 -= (int)x1; y1 -= (int)y1; x1 *= 10; y1 *= 10; float x2 = seed * 23.1239879f; float y2 = seed * 82.1239812f; x2 -= (int)x2; y2 -= (int)y2; x2 *= 10; y2 *= 10; return Mathf.PerlinNoise(offset.x + x1 + Time.time * speed, offset.z + y1 + Time.time * speed) * 0.5f + Mathf.PerlinNoise(offset.x + x2 - Time.time * speed, offset.z + y2 - Time.time * speed) * 0.5f; } } <file_sep>/Assets/LeapMotion/Modules/GraphicRenderer/Scripts/EditTimeApis/LeapMeshGraphicEditorApi.cs /****************************************************************************** * Copyright (C) Leap Motion, Inc. 2011-2018. * * Leap Motion proprietary and confidential. * * * * Use subject to the terms of the Leap Motion SDK Agreement available at * * https://developer.leapmotion.com/sdk_agreement, or another agreement * * between Leap Motion and you, your company or other organization. * ******************************************************************************/ using System.Collections.Generic; using UnityEngine; using UnityEngine.Assertions; using Leap.Unity.Space; namespace Leap.Unity.GraphicalRenderer { public abstract partial class LeapMeshGraphicBase : LeapGraphic { #if UNITY_EDITOR public class MeshEditorApi : EditorApi { protected readonly LeapMeshGraphicBase _meshGraphic; public MeshEditorApi(LeapMeshGraphicBase meshGraphic) : base(meshGraphic) { _meshGraphic = meshGraphic; } public override void RebuildEditorPickingMesh() { base.RebuildEditorPickingMesh(); Assert.IsNotNull(_meshGraphic); _meshGraphic.RefreshMeshData(); List<Vector3> pickingVerts = new List<Vector3>(); List<int> pickingTris = new List<int>(); pickingVerts.Clear(); pickingTris.Clear(); if (pickingMesh == null) { pickingMesh = new Mesh(); pickingMesh.MarkDynamic(); pickingMesh.hideFlags = HideFlags.HideAndDontSave; pickingMesh.name = "Graphic Picking Mesh"; } pickingMesh.Clear(keepVertexLayout: false); if (_meshGraphic.mesh == null) return; var topology = MeshCache.GetTopology(_meshGraphic.mesh); for (int i = 0; i < topology.tris.Length; i++) { pickingTris.Add(topology.tris[i] + pickingVerts.Count); } ITransformer transformer = null; if (_meshGraphic.anchor != null) { transformer = _meshGraphic.anchor.transformer; } for (int i = 0; i < topology.verts.Length; i++) { Vector3 localRectVert = _meshGraphic.attachedGroup.renderer.transform.InverseTransformPoint(_meshGraphic.transform.TransformPoint(topology.verts[i])); if (transformer != null) { localRectVert = transformer.TransformPoint(localRectVert); } localRectVert = _meshGraphic.attachedGroup.renderer.transform.TransformPoint(localRectVert); pickingVerts.Add(localRectVert); } pickingMesh.SetVertices(pickingVerts); pickingMesh.SetTriangles(pickingTris, 0, calculateBounds: true); pickingMesh.RecalculateNormals(); } } #endif } } <file_sep>/Assets/LeapMotion/Modules/GraphicRenderer/Scripts/Graphics/LeapMeshGraphic.cs /****************************************************************************** * Copyright (C) Leap Motion, Inc. 2011-2018. * * Leap Motion proprietary and confidential. * * * * Use subject to the terms of the Leap Motion SDK Agreement available at * * https://developer.leapmotion.com/sdk_agreement, or another agreement * * between Leap Motion and you, your company or other organization. * ******************************************************************************/ using UnityEngine; using UnityEngine.Rendering; using Leap.Unity.Attributes; namespace Leap.Unity.GraphicalRenderer { /// <summary> /// This class is a base class for all graphics that can be represented by a mesh object. /// </summary> [DisallowMultipleComponent] public abstract partial class LeapMeshGraphicBase : LeapGraphic { [Tooltip("The tint to apply to the vertex colors of this mesh. This value cannot be changed " + "at edit time. You can use a RuntimeTintFeature if you want to change the color of " + "an object at runtime.")] [EditTimeOnly] public Color vertexColor = Color.white; /// <summary> /// Returns the mesh that represents this graphic. It can have any topology, any number of /// uv channels, vertex colors, or normals. Note that the specific rendering method you might /// use might not support all of these features! /// </summary> public Mesh mesh { get; protected set; } /// <summary> /// Returns an enum mask that represents the union of all channels that are allowed to be remapped /// for this mesh. If a uv channel is included in this mask, the matching uv coordinates are allowed /// to be remapped by any rendering method to implement texture atlasing. /// /// You would exclude a uv channel from this mask if you dont want the uv coordinates to change in /// any way. This can happen if your coordinates are already referencing a pre-built atlas, or if /// the values do not actually reference texture coordinates at all. /// </summary> public UVChannelFlags remappableChannels { get; protected set; } /// <summary> /// When this method is called, the mesh property and the remappableChannels property must be assigned /// to valid states correctly matching the current state of the object. This is the method where you /// would do procedural mesh generation, or dynamic creations of mesh objects. /// </summary> public abstract void RefreshMeshData(); public LeapMeshGraphicBase() { #if UNITY_EDITOR editor = new MeshEditorApi(this); #endif } } /// <summary> /// This class is the trivial implementation of LeapMeshGraphicBase. It references a mesh asset /// directly to represent this graphic, and allows the user to directly specify which channels /// are allowed to be remapped. /// </summary> public class LeapMeshGraphic : LeapMeshGraphicBase { [Tooltip("The mesh that will represent this graphic")] [EditTimeOnly] [SerializeField] private Mesh _mesh; [Tooltip("All channels that are allowed to be remapped into atlas coordinates.")] [EditTimeOnly] [EnumFlags] [SerializeField] private UVChannelFlags _remappableChannels = UVChannelFlags.UV0 | UVChannelFlags.UV1 | UVChannelFlags.UV2 | UVChannelFlags.UV3; /// <summary> /// Call this method at edit time or at runtime to set the specific mesh to be used to /// represent this graphic. This method cannot fail at edit time, but might fail at runtime /// if the attached group does not support changing the representation of a graphic dynamically. /// </summary> public void SetMesh(Mesh mesh) { if (isAttachedToGroup && !attachedGroup.addRemoveSupported) { Debug.LogWarning("Changing the representation of the graphic is not supported by this rendering type"); } isRepresentationDirty = true; _mesh = mesh; } public override void RefreshMeshData() { //For the trivial MeshGraphic, simply copy data into the properties. mesh = _mesh; remappableChannels = _remappableChannels; } } } <file_sep>/Assets/Hover/Core/Scripts/Layouts/Arc/HoverLayoutArcGroupChild.cs namespace Hover.Core.Layouts.Arc { /*================================================================================================*/ public struct HoverLayoutArcGroupChild { public ILayoutableArc Elem { get; private set; } public HoverLayoutArcRelativeSizer RelSizer { get; private set; } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public HoverLayoutArcGroupChild(ILayoutableArc pElem, HoverLayoutArcRelativeSizer pSizer) { Elem = pElem; RelSizer = pSizer; } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public float RelativeThickness { get { return (RelSizer == null ? 1 : RelSizer.RelativeThickness); } } /*--------------------------------------------------------------------------------------------*/ public float RelativeArcDegrees { get { return (RelSizer == null ? 1 : RelSizer.RelativeArcDegrees); } } /*--------------------------------------------------------------------------------------------*/ public float RelativeRadiusOffset { get { return (RelSizer == null ? 0 : RelSizer.RelativeRadiusOffset); } } /*--------------------------------------------------------------------------------------------*/ public float RelativeStartDegreeOffset { get { return (RelSizer == null ? 0 : RelSizer.RelativeStartDegreeOffset); } } } } <file_sep>/Assets/LeapMotion/Modules/GraphicRenderer/Scripts/LeapRenderingMethod.cs /****************************************************************************** * Copyright (C) Leap Motion, Inc. 2011-2018. * * Leap Motion proprietary and confidential. * * * * Use subject to the terms of the Leap Motion SDK Agreement available at * * https://developer.leapmotion.com/sdk_agreement, or another agreement * * between Leap Motion and you, your company or other organization. * ******************************************************************************/ using System; using System.Collections.Generic; using UnityEngine; using UnityEngine.Assertions; using UnityObject = UnityEngine.Object; #if UNITY_EDITOR using UnityEditor; #endif using Leap.Unity.Space; namespace Leap.Unity.GraphicalRenderer { public interface ILeapInternalRenderingMethod { LeapGraphicRenderer renderer { set; } LeapGraphicGroup group { set; } } [Serializable] public abstract class LeapRenderingMethod : ILeapInternalRenderingMethod { public const string DATA_FOLDER_NAME = "_ElementData"; [NonSerialized] private LeapGraphicRenderer _renderer; [NonSerialized] private LeapGraphicGroup _group; /// <summary> /// Gets the renderer this rendering method is attached to. /// </summary> public LeapGraphicRenderer renderer { get { return _renderer; } } /// <summary> /// Gets the group this rendering method is attached to. /// </summary> public LeapGraphicGroup group { get { return _group; } } /// <summary> /// Sets the renderer this rendering method is attached to. /// </summary> LeapGraphicRenderer ILeapInternalRenderingMethod.renderer { set { _renderer = value; } } /// <summary> /// Sets the group this rendering methid is attached to. /// </summary> LeapGraphicGroup ILeapInternalRenderingMethod.group { set { _group = value; } } public abstract SupportInfo GetSpaceSupportInfo(LeapSpace space); /// <summary> /// Called when the renderer is enabled at runtime. /// </summary> public abstract void OnEnableRenderer(); /// <summary> /// Called when the renderer is disabled at runtime. /// </summary> public abstract void OnDisableRenderer(); /// <summary> /// Called from LateUpdate during runtime. Use this to update the /// renderer using any changes made to during this frame. /// </summary> public abstract void OnUpdateRenderer(); #if UNITY_EDITOR /// <summary> /// Called curing edit time when this renderering method is created. /// Use this for any edit-time construction you need. /// </summary> public virtual void OnEnableRendererEditor() { } /// <summary> /// Called during edit time when this rendering method is destroyed. /// Use this for edit-time clean up. /// </summary> public virtual void OnDisableRendererEditor() { } /// <summary> /// Called during edit time to update the renderer status. This is /// called every time a change is performed, but it is /// not called all the time! /// </summary> public virtual void OnUpdateRendererEditor() { } #endif public abstract bool IsValidGraphic<T>(); public abstract bool IsValidGraphic(LeapGraphic graphic); public abstract LeapGraphic GetValidGraphicOnObject(GameObject obj); private static Dictionary<UnityObject, object> _assetToOwner = new Dictionary<UnityObject, object>(); public void PreventDuplication<T>(ref T t) where T : UnityObject { Assert.IsNotNull(t); object owner; if (_assetToOwner.TryGetValue(t, out owner)) { if (owner.Equals(this)) { return; } if (t is Texture2D) { Texture2D tex = t as Texture2D; RenderTexture rt = new RenderTexture(tex.width, tex.height, 0, RenderTextureFormat.ARGB32, RenderTextureReadWrite.Linear); Graphics.Blit(tex, rt); Texture2D newTex = new Texture2D(tex.width, tex.height, TextureFormat.ARGB32, tex.mipmapCount > 1, true); RenderTexture.active = rt; newTex.ReadPixels(new Rect(0, 0, tex.width, tex.height), 0, 0); newTex.Apply(); RenderTexture.active = null; rt.Release(); UnityObject.DestroyImmediate(rt); t = newTex as T; } else { t = UnityObject.Instantiate(t); } } _assetToOwner[t] = this; } } public abstract class LeapRenderingMethod<GraphicType> : LeapRenderingMethod where GraphicType : LeapGraphic { public const string ASSET_PATH = "Assets/Generated/RendererData/"; public override bool IsValidGraphic<T>() { Type t = typeof(T); Type graphicType = typeof(GraphicType); return t == graphicType || (t.IsSubclassOf(graphicType)); } public override bool IsValidGraphic(LeapGraphic graphic) { return graphic is GraphicType; } public override LeapGraphic GetValidGraphicOnObject(GameObject obj) { return obj.GetComponent<GraphicType>(); } } } <file_sep>/Assets/LeapMotion/Modules/GraphicRenderer/Scripts/RenderingMethods/Editor/LeapDynamicRendererDrawer.cs /****************************************************************************** * Copyright (C) Leap Motion, Inc. 2011-2018. * * Leap Motion proprietary and confidential. * * * * Use subject to the terms of the Leap Motion SDK Agreement available at * * https://developer.leapmotion.com/sdk_agreement, or another agreement * * between Leap Motion and you, your company or other organization. * ******************************************************************************/ using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEditor; namespace Leap.Unity.GraphicalRenderer { [CustomPropertyDrawer(typeof(LeapDynamicRenderer))] public class LeapDynamicRendererDrawer : LeapMesherBaseDrawer { public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) { base.OnGUI(position, property, label); //Nothing to do yet! } } } <file_sep>/Assets/LeapMotion/Modules/GraphicRenderer/Scripts/Graphics/LeapTextGraphic.cs /****************************************************************************** * Copyright (C) Leap Motion, Inc. 2011-2018. * * Leap Motion proprietary and confidential. * * * * Use subject to the terms of the Leap Motion SDK Agreement available at * * https://developer.leapmotion.com/sdk_agreement, or another agreement * * between Leap Motion and you, your company or other organization. * ******************************************************************************/ using UnityEngine; using System.Collections.Generic; using Leap.Unity.Attributes; namespace Leap.Unity.GraphicalRenderer { public class LeapTextGraphic : LeapGraphic { [TextArea] [SerializeField] private string _text; [Header("Character")] [EditTimeOnly, SerializeField] private FontStyle _fontStyle; [EditTimeOnly, SerializeField] private int _fontSize = 14; [EditTimeOnly, SerializeField] private float _lineSpacing = 1; [Header("Paragraph")] [EditTimeOnly, SerializeField] private HorizontalAlignment _horizontalAlignment; [EditTimeOnly, SerializeField] private VerticalAlignment _verticalAlignment; [EditTimeOnly, SerializeField] private Color _color = Color.black; private bool _tokensDirty = true; private List<TextWrapper.Token> _cachedTokens = new List<TextWrapper.Token>(); public List<TextWrapper.Token> tokens { get { if (_tokensDirty) { _cachedTokens.Clear(); TextWrapper.Tokenize(text, _cachedTokens); _tokensDirty = false; } return _cachedTokens; } } public string text { get { if (_text == null) { return ""; } else { return _text; } } set { if (value != _text) { _tokensDirty = true; _text = value; isRepresentationDirty = true; } } } public FontStyle fontStyle { get { return _fontStyle; } set { if (value != _fontStyle) { _fontStyle = value; isRepresentationDirty = true; } } } public int fontSize { get { return _fontSize; } set { if (value != _fontSize) { _fontSize = value; isRepresentationDirty = true; } } } public float lineSpacing { get { return _lineSpacing; } set { if (value != _lineSpacing) { _lineSpacing = value; isRepresentationDirty = true; } } } public HorizontalAlignment horizontalAlignment { get { return _horizontalAlignment; } set { if (value != _horizontalAlignment) { _horizontalAlignment = value; isRepresentationDirty = true; } } } public VerticalAlignment verticalAlignment { get { return _verticalAlignment; } set { if (value != _verticalAlignment) { _verticalAlignment = value; isRepresentationDirty = true; } } } public Color color { get { return _color; } set { if (value != _color) { _color = value; isRepresentationDirty = true; } } } protected override void OnValidate() { base.OnValidate(); _tokensDirty = true; } private Rect _prevRect; public bool HasRectChanged() { RectTransform rectTransform = transform as RectTransform; if (rectTransform == null) { return false; } Rect newRect = rectTransform.rect; if (newRect != _prevRect) { _prevRect = newRect; return true; } return false; } public enum HorizontalAlignment { Left, Center, Right } public enum VerticalAlignment { Top, Center, Bottom } } } <file_sep>/Assets/LeapMotion/Modules/GraphicRenderer/Scripts/Features/Sprite/LeapSpriteData.cs /****************************************************************************** * Copyright (C) Leap Motion, Inc. 2011-2018. * * Leap Motion proprietary and confidential. * * * * Use subject to the terms of the Leap Motion SDK Agreement available at * * https://developer.leapmotion.com/sdk_agreement, or another agreement * * between Leap Motion and you, your company or other organization. * ******************************************************************************/ using System; using UnityEngine; using UnityEngine.Serialization; using Leap.Unity.Attributes; namespace Leap.Unity.GraphicalRenderer { public static class LeapSpriteFeatureExtension { public static LeapSpriteData Sprite(this LeapGraphic graphic) { return graphic.GetFeatureData<LeapSpriteData>(); } } [LeapGraphicTag("Sprite")] [Serializable] public class LeapSpriteData : LeapFeatureData { [FormerlySerializedAs("sprite")] [EditTimeOnly, SerializeField] private Sprite _sprite; public Sprite sprite { get { return _sprite; } set { _sprite = value; graphic.isRepresentationDirty = true; MarkFeatureDirty(); } } } } <file_sep>/Assets/IronManUI/Scripts/UI/SlideWaypoint.cs using UnityEngine; namespace IronManUI { public class SlideWaypoint : MonoBehaviour { public Slide slide; public PresentationManager manager { get { if (slide == null) return null; return slide.manager; } } private Spring3Motion scalingMotion = new Spring3Motion(); private BoxCollider boxCollider; public bool IsCurrentSlide() { if (slide == null) return false; return slide.IsCurrentSlide(); } void OnEnable() { boxCollider = gameObject.AddComponent<BoxCollider>(); UpdateColliderBounds(); } void Update() { scalingMotion.origin = IsCurrentSlide() ? Vector3.zero : Vector3.one; scalingMotion.Update(); transform.localScale = scalingMotion.position.MinValue(0); } void UpdateColliderBounds() { var bounds = gameObject.GetBounds(); boxCollider.size = bounds.size; // boxCollider.center = bounds.center; //bounds calculation needs to be fixed before using this } void SetSlide(Slide slide) { this.slide = slide; } void OnCollisionEnter(Collision collision) { if (collision.gameObject.GetComponent<Fingertip>() != null) HandleClick(); } void OnMouseDown() { HandleClick(); } public void HandleClick() { Debug.Log("Waypoint Clicked: " + slide); if (manager != null) { manager.SlideWaypointTouched(slide); } } } }<file_sep>/Assets/Hover/Editor/AutomatedBuilds.cs using System; using UnityEditor; namespace Hover.Editor { /*================================================================================================*/ public class AutomatedBuilds { public const string DemoPath = "Assets/Hover/Demo/"; public const string BoardKeysPath = DemoPath+"BoardKeys/Scenes/"; public const string CastCubesPath = DemoPath+"CastCubes/Scenes/"; //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public static void BuildBoardKeysVr() { Build(BuildTarget.StandaloneWindows, BoardKeysPath, "HoverboardDemo-LeapVR"); } /*--------------------------------------------------------------------------------------------*/ public static void BuildBoardKeysNonVr() { const string leapHeadScene = "HoverboardDemo-LeapOnly-HeadMount"; const string leapTableScene = "HoverboardDemo-LeapOnly-TableMount"; Build(BuildTarget.StandaloneWindows, BoardKeysPath, leapHeadScene); Build(BuildTarget.StandaloneWindows, BoardKeysPath, leapTableScene); //Build(BuildTarget.StandaloneOSXIntel, BoardKeysPath, leapHeadScene); //Build(BuildTarget.StandaloneOSXIntel, BoardKeysPath, leapTableScene); } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public static void BuildCastCubesVr() { Build(BuildTarget.StandaloneWindows, CastCubesPath, "HovercastDemo-LeapVR"); Build(BuildTarget.StandaloneWindows, CastCubesPath, "HovercastDemo-LeapLookVR"); } /*--------------------------------------------------------------------------------------------*/ public static void BuildCastCubesNonVr() { const string leapHeadScene = "HovercastDemo-LeapOnly-HeadMount"; const string leapTableScene = "HovercastDemo-LeapOnly-TableMount"; Build(BuildTarget.StandaloneWindows, CastCubesPath, leapHeadScene); Build(BuildTarget.StandaloneWindows, CastCubesPath, leapTableScene); //Build(BuildTarget.StandaloneOSXIntel, CastCubesPath, leapHeadScene); //Build(BuildTarget.StandaloneOSXIntel, CastCubesPath, leapTableScene); } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ private static void Build(BuildTarget pPlatform, string pPath, string pScene) { BuildPipeline.BuildPlayer( new[] { pPath+pScene+".unity" }, GetPath(pPlatform, pScene), pPlatform, BuildOptions.None ); } /*--------------------------------------------------------------------------------------------*/ private static string GetPath(BuildTarget pPlatform, string pScene) { string platformLabel; string outputFilename = pScene; switch ( pPlatform ) { case BuildTarget.StandaloneWindows: platformLabel = "PC"; outputFilename += ".exe"; break; case BuildTarget.StandaloneOSXIntel: platformLabel = "Mac"; break; default: throw new Exception("Unsupported build target: "+pPlatform); } string demoGroup = pScene.Substring(0, pScene.IndexOf('-')); //string date = DateTime.UtcNow.ToString("yyyy-MM-dd"); return "../Builds/Auto/"+demoGroup+"-"+/*date+"-"+*/platformLabel+"/"+outputFilename; } } } <file_sep>/Assets/Hover/Core/Scripts/Renderers/IProximityProvider.cs using Hover.Core.Utils; using UnityEngine; namespace Hover.Core.Renderers { /*================================================================================================*/ public interface IProximityProvider { //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ Vector3 GetNearestWorldPosition(Vector3 pFromWorldPosition); /*--------------------------------------------------------------------------------------------*/ Vector3 GetNearestWorldPosition(Ray pFromWorldRay, out RaycastResult pRaycast); } } <file_sep>/Assets/Hover/Core/Scripts/Cursors/HoverCursorData.cs using System.Collections.Generic; using Hover.Core.Utils; using UnityEngine; namespace Hover.Core.Cursors { /*================================================================================================*/ public class HoverCursorData : MonoBehaviour, ICursorDataForInput { public RaycastResult? BestRaycastResult { get; set; } public float MaxItemHighlightProgress { get; set; } public float MaxItemSelectionProgress { get; set; } public List<StickySelectionInfo> ActiveStickySelections { get; private set; } [SerializeField] private CursorType _Type; [SerializeField] private CursorCapabilityType _Capability = CursorCapabilityType.Full; [SerializeField] private bool _IsRaycast = false; [SerializeField] private Vector3 _RaycastLocalDirection = Vector3.up; [SerializeField] private float _Size = 1; [SerializeField] [Range(0, 1)] private float _TriggerStrength = 0; private ICursorIdle vIdle; //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public HoverCursorData() { ActiveStickySelections = new List<StickySelectionInfo>(); } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public CursorType Type { get { return _Type; } } /*--------------------------------------------------------------------------------------------*/ public bool IsActive { get { return isActiveAndEnabled; } } /*--------------------------------------------------------------------------------------------*/ public bool CanCauseSelections { get { return (IsActive && Capability == CursorCapabilityType.Full); } } /*--------------------------------------------------------------------------------------------*/ public CursorCapabilityType Capability { get { return _Capability; } } /*--------------------------------------------------------------------------------------------*/ public bool IsRaycast { get { return _IsRaycast; } } /*--------------------------------------------------------------------------------------------*/ public Vector3 RaycastLocalDirection { get { return _RaycastLocalDirection; } } /*--------------------------------------------------------------------------------------------*/ public float Size { get { return _Size; } } /*--------------------------------------------------------------------------------------------*/ public float TriggerStrength { get { return _TriggerStrength; } } /*--------------------------------------------------------------------------------------------*/ public Vector3 WorldPosition { get { return transform.position; } } /*--------------------------------------------------------------------------------------------*/ public Quaternion WorldRotation { get { return transform.rotation; } } /*--------------------------------------------------------------------------------------------*/ public ICursorIdle Idle { get { if ( vIdle == null ) { vIdle = GetComponent<ICursorIdle>(); } return vIdle; } } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public void SetIsRaycast(bool pIsRaycast) { _IsRaycast = pIsRaycast; } /*--------------------------------------------------------------------------------------------*/ public void SetRaycastLocalDirection(Vector3 pRaycastLocalDirection) { _RaycastLocalDirection = pRaycastLocalDirection; } /*--------------------------------------------------------------------------------------------*/ public void SetCapability(CursorCapabilityType pCapability) { _Capability = pCapability; } /*--------------------------------------------------------------------------------------------*/ public void SetSize(float pSize) { _Size = pSize; } /*--------------------------------------------------------------------------------------------*/ public void SetTriggerStrength(float pTriggerStrength) { _TriggerStrength = pTriggerStrength; } /*--------------------------------------------------------------------------------------------*/ public void SetWorldPosition(Vector3 pWorldPosition) { transform.position = pWorldPosition; } /*--------------------------------------------------------------------------------------------*/ public void SetWorldRotation(Quaternion pWorldRotation) { transform.rotation = pWorldRotation; } /*--------------------------------------------------------------------------------------------*/ public void SetIdle(ICursorIdle pIdle) { vIdle = pIdle; } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public void SetUsedByInput(bool pIsUsed) { enabled = pIsUsed; } /*--------------------------------------------------------------------------------------------*/ public void ActivateIfUsedByInput() { gameObject.SetActive(enabled && Capability != CursorCapabilityType.None); } } } <file_sep>/Assets/IronManUI/Scripts/Util/Vector3Integrator.cs /** * Author: <NAME> * Created: 01.18.2019 * * MIT Reality Virtually Hackathon **/ using UnityEngine; namespace IronManUI { /** AM: Provides basic physical motion influenced by acceleration inputs */ public class Vector3Motion { public float energyLoss = 6f; public Vector3 position; private Vector3 accel; public Vector3 velocity { get; private set; } public void AddAcceleration(Vector3 accel) { this.accel += accel; } virtual public void Update(float deltaTime) { velocity += accel * deltaTime; velocity *= Mathf.Max(0, (1 - energyLoss * deltaTime)); position += velocity * deltaTime + accel * (.5f * deltaTime * deltaTime); accel = Vector3.zero; } } public class Spring3Motion : Vector3Motion { public Vector3? origin; /** AM: Controls strength of spring acceleration toward the origin */ public float springK = 50; public void Update() { Update(Time.deltaTime); } override public void Update(float deltaTime) { if (springK > 0 && origin.HasValue) AddAcceleration(CalculateDelta() * springK); base.Update(deltaTime); } virtual protected Vector3 CalculateDelta() { return (origin.Value - position); } } /* Angle in degrees */ public class Spring3AngularMotion : Spring3Motion { override public void Update(float deltaTime) { base.Update(deltaTime); position = Modulus(position, 360); } //TODO AM cleanup/optimize override protected Vector3 CalculateDelta() { Vector3 delta = Modulus(origin.Value - position, 360); //AM this modulus might not be necessary if (delta.x > 180) delta.x -= 360; if (delta.y > 180) delta.y -= 360; if (delta.z > 180) delta.z -= 360; return delta; } public static float Modulus(float x, float m) { return ((x % m) + m) % m; } public static Vector3 Modulus(Vector3 angle, float m) { angle.x = Modulus(angle.x, m); angle.y = Modulus(angle.y, m); angle.z = Modulus(angle.z, m); return angle; } } }<file_sep>/Assets/LeapMotion/Modules/GraphicRenderer/Scripts/EditTimeApis/LeapGraphicEditorApi.cs /****************************************************************************** * Copyright (C) Leap Motion, Inc. 2011-2018. * * Leap Motion proprietary and confidential. * * * * Use subject to the terms of the Leap Motion SDK Agreement available at * * https://developer.leapmotion.com/sdk_agreement, or another agreement * * between Leap Motion and you, your company or other organization. * ******************************************************************************/ using UnityEngine; using Leap.Unity.Space; namespace Leap.Unity.GraphicalRenderer { public abstract partial class LeapGraphic : MonoBehaviour { #if UNITY_EDITOR public EditorApi editor { get; protected set; } public class EditorApi { private readonly LeapGraphic _graphic; public Mesh pickingMesh; public EditorApi(LeapGraphic graphic) { _graphic = graphic; } public virtual void OnValidate() { _graphic.isRepresentationDirty = true; foreach (var data in _graphic._featureData) { data.MarkFeatureDirty(); } if (!Application.isPlaying) { if (_graphic.isAttachedToGroup && !_graphic.transform.IsChildOf(_graphic._attachedRenderer.transform)) { _graphic.OnDetachedFromGroup(); } if (_graphic.isAttachedToGroup) { _graphic._attachedRenderer.editor.ScheduleRebuild(); _graphic._preferredRendererType = _graphic.attachedGroup.renderingMethod.GetType(); } } else { var group = _graphic.attachedGroup; if (group != null) { if (!group.graphics.Contains(_graphic)) { _graphic.OnDetachedFromGroup(); group.TryAddGraphic(_graphic); } } } } public virtual void OnDrawGizmos() { if (pickingMesh != null && pickingMesh.vertexCount != 0) { Gizmos.color = new Color(1, 0, 0, 0); Gizmos.DrawMesh(pickingMesh); } } /// <summary> /// Called whenever this graphic needs to rebuild its editor picking mesh. /// This mesh is a fully warped representation of the graphic, which allows /// it to be accurately picked when the user clicks in the scene view. /// </summary> public virtual void RebuildEditorPickingMesh() { } /// <summary> /// Called whenever this graphic is attached to a specific group. This method /// is only called at edit time! /// </summary> public virtual void OnAttachedToGroup(LeapGraphicGroup group, LeapSpaceAnchor anchor) { if (!Application.isPlaying) { _graphic._preferredRendererType = group.renderingMethod.GetType(); } } } #endif } } <file_sep>/Assets/Hover/Core/Scripts/Utils/TreeUpdater.cs using System.Collections.Generic; using UnityEngine; namespace Hover.Core.Utils { /*================================================================================================*/ [ExecuteInEditMode] public class TreeUpdater : MonoBehaviour { //NOTE: use this with renamed ITreeUpdateable "TreeUpdate()" => "Update()" //private const bool IsProfilingMode = false; public bool DidTreeUpdateThisFrame { get; private set; } public TreeUpdater TreeParentThisFrame { get; private set; } public int TreeDepthLevelThisFrame { get; private set; } public List<ITreeUpdateable> TreeUpdatablesThisFrame { get; private set; } public List<TreeUpdater> TreeChildrenThisFrame { get; private set; } private bool vIsDestroyed; //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public TreeUpdater() { TreeUpdatablesThisFrame = new List<ITreeUpdateable>(); TreeChildrenThisFrame = new List<TreeUpdater>(); } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public void Update() { /*if ( IsProfilingMode && Application.isPlaying ) { return; }*/ if ( DidTreeUpdateThisFrame ) { return; } AscendTreeOrBegin(true); } /*--------------------------------------------------------------------------------------------*/ public void UpdateAtAndBelowThisLevel() { BeginAtThisTreeLevel(); } /*--------------------------------------------------------------------------------------------*/ public void LateUpdate() { DidTreeUpdateThisFrame = false; } /*--------------------------------------------------------------------------------------------*/ public void OnDestroy() { vIsDestroyed = true; } /*--------------------------------------------------------------------------------------------*/ public void ImmediateReloadTreeChildren() { //int before = TreeChildrenThisFrame.Count; FindTreeChildren(); //int after = TreeChildrenThisFrame.Count; //Debug.Log("ImmediateReloadTreeChildren: "+name+" / "+before+" => "+after, gameObject); } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ private void AscendTreeOrBegin(bool pFromUpdate) { //if ( pFromUpdate ) { Debug.Log("AscendTreeOrBegin: "+gameObject.name, gameObject); } Transform parTx = transform.parent; TreeUpdater parTreeUp = (parTx == null ? null : parTx.GetComponent<TreeUpdater>()); if ( parTreeUp == null || !parTreeUp.isActiveAndEnabled ) { BeginAtThisTreeLevel(); return; } parTreeUp.AscendTreeOrBegin(false); } /*--------------------------------------------------------------------------------------------*/ private void BeginAtThisTreeLevel() { //Debug.Log("BeginAtThisTreeLevel: "+gameObject.name, gameObject); if ( vIsDestroyed ) { return; } SendTreeUpdates(0); DescendTree(0); } /*--------------------------------------------------------------------------------------------*/ private void SendTreeUpdates(int pDepth) { //Debug.Log(new string('-', pDepth)+"SendTreeUpdates: "+gameObject.name, gameObject); if ( vIsDestroyed ) { return; } gameObject.GetComponents(TreeUpdatablesThisFrame); FindTreeChildren(); for ( int i = 0 ; i < TreeUpdatablesThisFrame.Count ; i++ ) { ITreeUpdateable treeUp = TreeUpdatablesThisFrame[i]; if ( !treeUp.isActiveAndEnabled ) { continue; } treeUp.TreeUpdate(); } DidTreeUpdateThisFrame = true; TreeDepthLevelThisFrame = pDepth; } /*--------------------------------------------------------------------------------------------*/ private void FindTreeChildren() { TreeChildrenThisFrame.Clear(); int childCount = transform.childCount; for ( int i = 0 ; i < childCount ; i++ ) { Transform childTx = transform.GetChild(i); TreeUpdater childTreeUp = childTx.GetComponent<TreeUpdater>(); if ( childTreeUp == null ) { continue; } childTreeUp.TreeParentThisFrame = this; TreeChildrenThisFrame.Add(childTreeUp); } } /*--------------------------------------------------------------------------------------------*/ private void DescendTree(int pDepth) { //Debug.Log(new string('-', pDepth)+"DescendTree: "+gameObject.name, gameObject); if ( vIsDestroyed ) { return; } int childDepth = pDepth+1; for ( int i = 0 ; i < TreeChildrenThisFrame.Count ; i++ ) { TreeUpdater childTreeUp = TreeChildrenThisFrame[i]; childTreeUp.SendTreeUpdates(childDepth); childTreeUp.DescendTree(childDepth); } } } } <file_sep>/Assets/IronManUI/Scripts/UI/AbstractIMComponent.cs /** * Author: <NAME> * Created: 01.18.2019 * * MIT Reality Virtually Hackathon **/ using System; using System.Collections.Generic; using UnityEngine; namespace IronManUI { [System.Serializable] public class IMComponentModel { public Vector3 targetPosition; public Vector3 hiddenPosition; public Vector3 targetRotation; public Vector3 hiddenRotation; public Vector3 targetScale = Vector3.one; public Vector3 hiddenScale; virtual public void Copy(IMComponentModel o) { targetPosition = o.targetPosition; hiddenPosition = o.hiddenPosition; targetRotation = o.targetRotation; hiddenRotation = o.hiddenRotation; targetScale = o.targetScale; hiddenScale = o.hiddenScale; } } public abstract class AbstractIMComponent : MonoBehaviour { protected float touchThickness = .02f; public readonly Spring3Motion translationMotion = new Spring3Motion(); public readonly Spring3AngularMotion rotationMotion = new Spring3AngularMotion(); public readonly Spring3Motion scalingMotion = new Spring3Motion(); // public Vector3 targetPosition { // get { // return _internalModel.targetPosition; // } // set { // _internalModel.targetPosition = value; // } // } // public Vector3 targetRotation { // get { // return _internalModel.targetRotation; // } // set { // _internalModel.targetRotation = value; // } // } // public Vector3 targetScale { // get { // return _internalModel.targetScale; // } // set { // _internalModel.targetScale = value; // } // } abstract public IMComponentModel model { get; } public bool visible = true; public GrabHandler grab { get; private set; } private IMComponentMenuHandler menuHandler; // private IMComponentModel _internalModel; // get { // if (_model == null) // _model = CreateDefaultModel(); // return _model; // } // set { //setting a null value resets the model to default // if (value != null && value.GetType() != GetModelType()) { // Debug.LogWarningFormat("Error setting model of type {0} to {1}", value.GetType(), GetType()); // return; // } // _model = value; // } // } // virtual public void SetModel(IMComponentModel value) { // if (value != null && value.GetType() != GetModelType()) { // Debug.LogWarningFormat("Error setting model of type {0} to {1}", value.GetType(), GetType()); // return; // } // if (value == null) // _internalModel = CreateDefaultModel(); // else // _internalModel = value; // } // virtual public IMComponentModel ExtractModel() { // return _internalModel; // } virtual protected void OnEnable() { grab = new GrabHandler(this); menuHandler = new IMComponentMenuHandler(this); // model = CreateDefaultModel(); // targetvisible ? transform.position; // rotationMotion.position = transform.rotation.eulerAngles; // scalingMotion.position = transform.localScale; } virtual protected void OnDisable() { grab = null; menuHandler = null; } virtual protected void Update() { grab.Update(); menuHandler.Update(); var parentT = transform.parent; var parentM = parentT == null ? Matrix4x4.identity : parentT.localToWorldMatrix; translationMotion.origin = parentM.MultiplyPoint(visible ? model.targetPosition : model.hiddenPosition); rotationMotion.origin = parentM.MultiplyVector(visible ? model.targetRotation : model.hiddenRotation); scalingMotion.origin = visible ? model.targetScale : model.hiddenScale; //don't transform, because scalingMotion is calculated for local if (Application.isPlaying) { translationMotion.Update(Time.deltaTime); transform.position = translationMotion.position; rotationMotion.Update(Time.deltaTime); transform.rotation = Quaternion.Euler(rotationMotion.position); scalingMotion.Update(Time.deltaTime); transform.localScale = scalingMotion.position.MinValue(0); } else { transform.position = translationMotion.origin.Value; transform.rotation = Quaternion.Euler(scalingMotion.origin.Value); transform.localScale = scalingMotion.origin.Value; } } abstract protected Type GetModelType(); abstract protected IMComponentModel CreateDefaultModel(); // void OnTriggerEnter(Collider collider) { // Debug.Log("Component Collision enter"); // var fingertip = collider.gameObject.GetComponent<Fingertip>(); // if (fingertip != null) { // Debug.Log("Touched by finger: " + fingertip); // } // } // void OnTriggerExit(Collider collider) { // Debug.Log("Component Collision exit"); // } } public class GrabHandler { // private Dictionary<Fingertip, GrabInfo> grabs = new Dictionary<Fingertip, GrabInfo>(); private List<Fingertip> grabs = new List<Fingertip>(2); private AbstractIMComponent parent; private Vector3 componentPositionAnchor; private Vector3 componentRotationAnchor; private Vector3 componentScaleAnchor; private Vector3? grabAvgAnchor; private float grabRadiusAnchor; private Vector3 grabRotationAnchor; // private Vector3? grabCenter; public GrabHandler(AbstractIMComponent parent) { this.parent = parent; } public void Begin(Fingertip finger, Vector3 grabPoint) { if (grabs.Count > 1) //Max two grab points for now return; if (grabs.Contains(finger)) return; grabs.Add(finger);//, new GrabInfo(grabPoint, parent.transform.position); grabAvgAnchor = null; } // public void End(Fingertip finger) { // if (grabs.Remove(finger)) { // grabAvgAnchor = null; // } // } public void Update() { //check that all grabing fingers are still grabbing. Remove them if not List<Fingertip> removeKeys = new List<Fingertip>(); foreach (var finger in grabs) { if (!finger.grabbing) removeKeys.Add(finger); } if (removeKeys.Count > 0) { grabAvgAnchor = null; } foreach (var key in removeKeys) { grabs.Remove(key); } if (grabs.Count > 0) { if (grabAvgAnchor.HasValue) { Vector3 grabAvg, grabRotation; float grabRadius; CalculateGrabStats(out grabAvg, out grabRadius, out grabRotation); parent.model.targetPosition = componentPositionAnchor + (grabAvg - grabAvgAnchor.Value); parent.model.targetRotation = componentRotationAnchor + (grabRotation - grabRotationAnchor); if (grabRadiusAnchor > .01 && grabRadius > .01) //safety checking parent.model.targetScale = componentScaleAnchor * (grabRadius/ grabRadiusAnchor); } else { Vector3 p; CalculateGrabStats(out p, out grabRadiusAnchor, out grabRotationAnchor); grabAvgAnchor = p; var t = parent.transform; componentPositionAnchor = t.position; componentRotationAnchor = t.rotation.eulerAngles; componentScaleAnchor = t.localScale; } } } void CalculateGrabStats(out Vector3 position, out float radius, out Vector3 rotation) { if (grabs.Count == 1) { var transform = grabs[0].transform; position = transform.position; rotation = Vector3.up; //transform.rotation.eulerAngles; //AM disable single hand rotation radius = 1; } else if (grabs.Count == 2) { var p0 = grabs[0].transform.position; var p1 = grabs[1].transform.position; position = (p1 + p0) * .5f; Vector3 delta = (p1 - p0); radius = delta.magnitude; rotation = Quaternion.LookRotation(delta, Vector3.up).eulerAngles; //AM any way to optimize this? rotation.x = 0; //AM: Don't support tilting the text. At least not until I can work out better math for this } else { position = Vector3.zero; radius = 0; rotation = Vector3.zero; } } // public class GrabInfo { // public readonly Vector3 grabAnchor; // public readonly Vector3 componentAnchor; // public GrabInfo(Vector3 grabAnchor, Vector3 componentAnchor) { // this.grabAnchor = grabAnchor; // this.componentAnchor = componentAnchor; // } // } } }<file_sep>/Assets/Hover/Editor/Input/HovercursorDataProviderEditor.cs using System.Collections.Generic; using Hover.Core.Cursors; using UnityEditor; using UnityEngine; namespace Hover.Editor.Input { /*================================================================================================*/ [CanEditMultipleObjects] [CustomEditor(typeof(HoverCursorDataProvider))] public class HovercursorDataProviderEditor : UnityEditor.Editor { private HoverCursorDataProvider vTarget; //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public override void OnInspectorGUI() { vTarget = (HoverCursorDataProvider)target; DrawDefaultInspector(); EditorGUILayout.Separator(); DrawCursorList("Cursors", vTarget.Cursors); if ( vTarget.ExcludedCursors.Count == 0 ) { return; } EditorGUILayout.Separator(); EditorGUILayout.HelpBox("One or more duplicate cursor types were found. The following "+ "cursors have been excluded from the cursor list.", MessageType.Error); DrawCursorList("Excluded Cursors", vTarget.ExcludedCursors); } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ private void DrawCursorList(string pLabel, List<ICursorData> pCursors) { EditorGUILayout.LabelField(pLabel, EditorStyles.boldLabel); GUI.enabled = false; for ( int i = 0 ; i < pCursors.Count ; i++ ) { ICursorData cursor = pCursors[i]; EditorGUILayout.ObjectField(cursor.Type+"", (Object)cursor, cursor.GetType(), true); } GUI.enabled = true; } } } <file_sep>/Assets/LeapMotion/Modules/GraphicRenderer/Scripts/RenderingMethods/AssetData/RendererMeshData.cs /****************************************************************************** * Copyright (C) Leap Motion, Inc. 2011-2018. * * Leap Motion proprietary and confidential. * * * * Use subject to the terms of the Leap Motion SDK Agreement available at * * https://developer.leapmotion.com/sdk_agreement, or another agreement * * between Leap Motion and you, your company or other organization. * ******************************************************************************/ using System; using System.Collections.Generic; using UnityEngine; #if UNITY_EDITOR using UnityEditor; #endif namespace Leap.Unity.GraphicalRenderer { [Serializable] public class RendererMeshData { [SerializeField] private List<Mesh> meshes = new List<Mesh>(); [System.NonSerialized] private Queue<Mesh> _tempMeshPool = new Queue<Mesh>(); private void OnDestroy() { foreach (var mesh in meshes) { UnityEngine.Object.DestroyImmediate(mesh); } } public void Clear() { foreach (var mesh in meshes) { if (mesh != null) { mesh.Clear(keepVertexLayout: false); _tempMeshPool.Enqueue(mesh); } } meshes.Clear(); } public Mesh GetMeshFromPoolOrNew() { if (_tempMeshPool.Count > 0) { return _tempMeshPool.Dequeue(); } else { return new Mesh(); } } public void ClearPool() { while (_tempMeshPool.Count > 0) { UnityEngine.Object.DestroyImmediate(_tempMeshPool.Dequeue()); } } public void AddMesh(Mesh mesh) { mesh.hideFlags = HideFlags.HideInHierarchy | HideFlags.HideInInspector; meshes.Add(mesh); } public void RemoveMesh(int index) { Mesh mesh = meshes[index]; meshes.RemoveAt(index); UnityEngine.Object.DestroyImmediate(mesh); } public void Validate(LeapRenderingMethod renderingMethod) { for (int i = meshes.Count; i-- != 0;) { Mesh mesh = meshes[i]; if (mesh == null) { meshes.RemoveAt(i); continue; } renderingMethod.PreventDuplication(ref mesh); meshes[i] = mesh; } } public int Count { get { return meshes.Count; } } public Mesh this[int index] { get { return meshes[index]; } set { meshes[index] = value; } } } } <file_sep>/Assets/LeapMotion/Modules/GraphicRenderer/Scripts/Features/CustomChannel/CustomChannelDataBase.cs /****************************************************************************** * Copyright (C) Leap Motion, Inc. 2011-2018. * * Leap Motion proprietary and confidential. * * * * Use subject to the terms of the Leap Motion SDK Agreement available at * * https://developer.leapmotion.com/sdk_agreement, or another agreement * * between Leap Motion and you, your company or other organization. * ******************************************************************************/ using System; using UnityEngine; namespace Leap.Unity.GraphicalRenderer { public partial class LeapGraphic { /// <summary> /// Helper method to get a custom channel data object given the name of the /// feature it is attached to. This method can only be used if the graphic /// is currently attached to a group. /// </summary> public T GetCustomChannel<T>(string channelName) where T : CustomChannelDataBase { if (!isAttachedToGroup) { throw new Exception("Cannot get a custom channel by name if the graphic is not attached to a group."); } int index = -1; for (int i = 0; i < _featureData.Count; i++) { var feature = _featureData[i].feature as ICustomChannelFeature; if (feature == null) { continue; } if (feature.channelName == channelName) { index = i; break; } } if (index == -1) { throw new Exception("No custom channel of the name " + channelName + " could be found."); } T featureDataObj = _featureData[index] as T; if (featureDataObj == null) { throw new Exception("The channel name " + channelName + " did not match to a custom channel of type " + typeof(T).Name + "."); } return featureDataObj; } } public abstract class CustomChannelDataBase : LeapFeatureData { } public abstract class CustomChannelDataBase<T> : CustomChannelDataBase { [SerializeField] private T _value; public T value { get { return _value; } set { if (!value.Equals(_value)) { MarkFeatureDirty(); _value = value; } } } } } <file_sep>/Assets/Hover/Core/Scripts/Items/Helpers/HoverChildItemsEnabler.cs using System.Collections.Generic; using Hover.Core.Utils; using UnityEngine; namespace Hover.Core.Items.Helpers { /*================================================================================================*/ [ExecuteInEditMode] [RequireComponent(typeof(TreeUpdater))] [RequireComponent(typeof(HoverChildItemsFinder))] public class HoverChildItemsEnabler : MonoBehaviour, ITreeUpdateable { public bool AreItemsEnabled = true; //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public void Start() { //do nothing... } /*--------------------------------------------------------------------------------------------*/ public void TreeUpdate() { List<HoverItemData> items = GetComponent<HoverChildItemsFinder>().ChildItems; for ( int i = 0 ; i < items.Count ; i++ ) { HoverItemData item = items[i]; //TODO: item.Controllers.Set(HoverItemData.IsEnabledName, this); item.IsEnabled = AreItemsEnabled; } } } } <file_sep>/Assets/Hover/Core/Scripts/Items/Types/IItemDataCheckbox.cs namespace Hover.Core.Items.Types { /*================================================================================================*/ public interface IItemDataCheckbox : IItemDataSelectable<bool> { } } <file_sep>/Assets/Hover/Core/Scripts/Cursors/CursorCapabilityType.cs namespace Hover.Core.Cursors { /*================================================================================================*/ public enum CursorCapabilityType { None, TransformOnly, Full } } <file_sep>/Assets/IronManUI/Scripts/UI/ImageItem.cs /** * Author: <NAME>, <NAME> * Created: 01.19.2019 * * MIT Reality Virtually Hackathon **/ using UnityEngine; using UnityEngine.UI; // using System.Collections; using System.IO; using System; namespace IronManUI { [System.Serializable] public class ImageModel : IMComponentModel { public float resourceScale = 1f; public string resource = ""; override public void Copy(IMComponentModel o) { var o1 = o as ImageModel; if (o1 != null) { resource = o1.resource; resourceScale = o1.resourceScale; } } } [ExecuteInEditMode] [RequireComponent(typeof(BoxCollider))] public class ImageItem : AbstractIMComponent { public ImageModel imageModel; override public IMComponentModel model { get { if (imageModel == null) imageModel = new ImageModel(); return imageModel; } } protected BoxCollider boxCollider; private string loadedResName; override protected void OnEnable() { base.OnEnable(); boxCollider = GetComponent<BoxCollider>(); if (boxCollider == null) boxCollider = gameObject.AddComponent<BoxCollider>(); } override protected void OnDisable() { base.OnDisable(); gameObject.DestroyChildren(); loadedResName = null; } override protected void Update() { ImageModel model = this.model as ImageModel; if (model.resource != loadedResName) { gameObject.DestroyChildren(); var resource = Resources.Load(model.resource); if (resource != null) { var obj = Instantiate(resource) as GameObject; if (obj != null) { obj.transform.parent = transform; obj.transform.localScale = new Vector3(model.resourceScale, model.resourceScale, model.resourceScale); } } loadedResName = model.resource; } // var bounds = gameObject.GetBounds(); //TODO needs help // boxCollider.size = bounds.size; // boxCollider.center = bounds.center; if (transform.childCount > 0) { transform.GetChild(0).transform.localScale = new Vector3(model.resourceScale, model.resourceScale, model.resourceScale); } base.Update(); } override protected IMComponentModel CreateDefaultModel() { return new ImageModel(); } protected override Type GetModelType() { return typeof(ImageModel); } } } // // research on loading 2D images into scene // // ref: http://gyanendushekhar.com/2017/07/08/load-image-runtime-unity/ // public class LoadTexture : MonoBehaviour { // Texture2D myTexture; // // Use this for initialization // void Start () { // // load texture from resource folder // myTexture = Resources.Load ("Images/Factories.jpg") as Texture2D; // GameObject rawImage = GameObject.Find ("RawImage"); // rawImage.GetComponent<RawImage> ().texture = myTexture; // } // } // ref: https://forum.unity.com/threads/generating-sprites-dynamically-from-png-or-jpeg-files-in-c.343735/ // public class IMG2Sprite : MonoBehaviour { // // // This script loads a PNG or JPEG image from disk and returns it as a Sprite // // Drop it on any GameObject/Camera in your scene (singleton implementation) // // // // Usage from any other script: // // MySprite = IMG2Sprite.instance.LoadNewSprite(FilePath, [PixelsPerUnit (optional)]) // private static IMG2Sprite _instance; // public static IMG2Sprite instance // { // get // { // //If _instance hasn't been set yet, we grab it from the scene! // //This will only happen the first time this reference is used. // if(_instance == null) // _instance = GameObject.FindObjectOfType<IMG2Sprite>(); // return _instance; // } // } // public Sprite LoadNewSprite(string FilePath, float PixelsPerUnit = 100.0f) { // // Load a PNG or JPG image from disk to a Texture2D, assign this texture to a new sprite and return its reference // Sprite NewSprite = new Sprite(); // Texture2D SpriteTexture = LoadTexture(FilePath); // NewSprite = Sprite.Create(SpriteTexture, new Rect(0, 0, SpriteTexture.width, SpriteTexture.height),new Vector2(0,0), PixelsPerUnit); // return NewSprite; // } // public Texture2D LoadTexture(string FilePath) { // // Load a PNG or JPG file from disk to a Texture2D // Texture2D Tex2D; // byte[] FileData; // if (File.Exists(FilePath)){ // FileData = File.ReadAllBytes(FilePath); // Tex2D = new Texture2D(2, 2); // Create new "empty" texture // if (Tex2D.LoadImage(FileData)) // Load the imagedata into the texture (size is set automatically) // return Tex2D; // If data = readable -> return texture // } // return null; // Return null if load failed // } // public class ImageBoxModel : IMComponentModel { // public string text = "La_Fortuna_Waterfall_Pool.jpg"; // } // [RequireComponent(typeof(BoxCollider))] // public class ImageBox : AbstractIMComponent { // protected BoxCollider boxCollider; // public Image image; // public string text { // get { // return image.source // } // set { // textMesh.text = value; // } // } // override protected void OnEnable() { // base.OnEnable(); // boxCollider = GetComponent<BoxCollider>(); // } // override protected void Update() { // textMesh.text = (model as TextBoxModel).text; // var bounds = textMesh.bounds; // boxCollider.size = new Vector3(bounds.size.x, bounds.size.y, touchThickness); // boxCollider.center = bounds.center; // base.Update(); // } // override protected IMComponentModel CreateDefaultModel() // { // return new ImageBoxModel(); // } // protected override Type GetModelType() // { // return typeof(ImageBoxModel); // } // public static Texture2D LoadPNG(string filePath) { // Texture2D tex = null; // byte[] fileData; // if (File.Exists(filePath)) { // fileData = File.ReadAllBytes(filePath); // tex = new Texture2D(2, 2); // tex.LoadImage(fileData); //..this will auto-resize the texture dimensions. // } // return tex; // } <file_sep>/Assets/IronManUI/Scripts/Editor/PresentationManagerEditor.cs using UnityEngine; using UnityEditor; namespace IronManUI { [CustomEditor(typeof(PresentationManager))] public class PresentationManagerEditor : Editor { public override void OnInspectorGUI() { DrawDefaultInspector(); PresentationManager target = this.target as PresentationManager; if (GUILayout.Button("Save Presentation")) { target.Save(); } } } }<file_sep>/Assets/IronManUI/Scripts/Slide.cs /** * Author: <NAME> * Created: 01.19.2019 * * MIT Reality Virtually Hackathon **/ using UnityEngine; using TMPro; namespace IronManUI { [System.Serializable] public class Slide : MonoBehaviour { public TextMeshPro labelText; public PresentationManager manager; public bool IsCurrentSlide() { if (manager == null) return false; return manager.currentSlide == this; } public void SetModel(PresentationManager manager, SlideModel slideModel) { this.manager = manager; name = slideModel.name; transform.position = slideModel.position; if (labelText != null) labelText.text = name; foreach (var compModel in slideModel.components) { var comp = manager.InstantiateComponent(compModel); if (comp != null) comp.transform.parent = transform; } } public SlideModel ExtractModel() { var model = new SlideModel(); model.name = name; model.position = transform.position; foreach (var comp in GetComponentsInChildren<AbstractIMComponent>()) { model.components.Add(comp.model); } return model; } public void Activate() { Debug.Log("Activating slide " + this); foreach (var comp in GetComponentsInChildren<AbstractIMComponent>()) { comp.visible = true; } } public void Deactivate() { Debug.Log("Closing slide " + this); foreach (var comp in GetComponentsInChildren<AbstractIMComponent>()) { comp.visible = false; } } } }<file_sep>/Assets/LeapMotion/Modules/GraphicRenderer/Scripts/RenderingMethods/LeapBakedRenderer.cs /****************************************************************************** * Copyright (C) Leap Motion, Inc. 2011-2018. * * Leap Motion proprietary and confidential. * * * * Use subject to the terms of the Leap Motion SDK Agreement available at * * https://developer.leapmotion.com/sdk_agreement, or another agreement * * between Leap Motion and you, your company or other organization. * ******************************************************************************/ using System; using System.Collections.Generic; using UnityEngine; #if UNITY_EDITOR using UnityEditor; #endif using Leap.Unity.Space; using Leap.Unity.Query; using Leap.Unity.Attributes; namespace Leap.Unity.GraphicalRenderer { [LeapGraphicTag("Baked")] [Serializable] public class LeapBakedRenderer : LeapMesherBase { public const string DEFAULT_SHADER = "LeapMotion/GraphicRenderer/Unlit/Baked"; #region INSPECTOR FIELDS [Tooltip("What type of graphic motion should be supported by this renderer? Currently there are only two modes, None, and Translation.")] [EditTimeOnly] [SerializeField] private MotionType _motionType = MotionType.Translation; [Tooltip("Should the baked renderer create an actual game object and attach a mesh renderer to it in order to display the graphics?")] [EditTimeOnly] [SerializeField] private bool _createMeshRenderers; #endregion #region PRIVATE VARIABLES [SerializeField, HideInInspector] private List<MeshRendererContainer> _renderers = new List<MeshRendererContainer>(); //## Rect space private const string RECT_POSITIONS = LeapGraphicRenderer.PROPERTY_PREFIX + "Rect_GraphicPositions"; private List<Vector4> _rect_graphicPositions = new List<Vector4>(); //## Cylindrical/Spherical spaces private const string CURVED_PARAMETERS = LeapGraphicRenderer.PROPERTY_PREFIX + "Curved_GraphicParameters"; private List<Vector4> _curved_graphicParameters = new List<Vector4>(); //## Cache data to be used inside of graphicVertToMeshVert private Matrix4x4 _translation_graphicVertToMeshVert; private Matrix4x4 _noMotion_graphicVertToLocalVert; private ITransformer _noMotion_transformer; #endregion public enum MotionType { None, Translation } public override SupportInfo GetSpaceSupportInfo(LeapSpace space) { if (space == null || space is LeapCylindricalSpace || space is LeapSphericalSpace) { return SupportInfo.FullSupport(); } else { return SupportInfo.Error("Baked Renderer does not support " + space.GetType().Name); } } public override void OnEnableRenderer() { base.OnEnableRenderer(); foreach (var renderer in _renderers) { renderer.ClearPropertyBlock(); } } public override void OnUpdateRenderer() { using (new ProfilerSample("Update Baked Renderer")) { base.OnUpdateRenderer(); if (_motionType != MotionType.None) { if (renderer.space == null) { using (new ProfilerSample("Build Material Data")) { _rect_graphicPositions.Clear(); foreach (var graphic in group.graphics) { Vector3 localSpace; if (graphic.isActiveAndEnabled) { localSpace = renderer.transform.InverseTransformPoint(graphic.transform.position); } else { localSpace = Vector3.one * float.NaN; } _rect_graphicPositions.Add(localSpace); } } using (new ProfilerSample("Upload Material Data")) { _material.SetVectorArraySafe(RECT_POSITIONS, _rect_graphicPositions); } } else if (renderer.space is LeapRadialSpace) { var radialSpace = renderer.space as LeapRadialSpace; using (new ProfilerSample("Build Material Data")) { _curved_graphicParameters.Clear(); foreach (var graphic in group.graphics) { var t = graphic.anchor.transformer as IRadialTransformer; Vector4 vectorRepresentation; if (graphic.isActiveAndEnabled) { vectorRepresentation = t.GetVectorRepresentation(graphic.transform); } else { vectorRepresentation = Vector4.one * float.NaN; } _curved_graphicParameters.Add(vectorRepresentation); } } using (new ProfilerSample("Upload Material Data")) { _material.SetFloat(SpaceProperties.RADIAL_SPACE_RADIUS, radialSpace.radius); _material.SetVectorArraySafe(CURVED_PARAMETERS, _curved_graphicParameters); } } } if (!_createMeshRenderers) { using (new ProfilerSample("Draw Meshes")) { for (int i = 0; i < _meshes.Count; i++) { drawMesh(_meshes[i], renderer.transform.localToWorldMatrix); } } } } } #if UNITY_EDITOR public override void OnEnableRendererEditor() { base.OnEnableRendererEditor(); _shader = Shader.Find(DEFAULT_SHADER); } public override void OnDisableRendererEditor() { base.OnDisableRendererEditor(); foreach (var renderer in _renderers) { renderer.Destroy(); } _renderers.Clear(); } public override void OnUpdateRendererEditor() { base.OnUpdateRendererEditor(); if (_renderers == null) { _renderers = new List<MeshRendererContainer>(); } if (_createMeshRenderers) { for (int i = _renderers.Count; i-- != 0;) { if (_renderers[i].obj == null) { _renderers.RemoveAt(i); } } while (_renderers.Count > _meshes.Count) { _renderers.RemoveLast().Destroy(); } while (_renderers.Count < _meshes.Count) { _renderers.Add(new MeshRendererContainer(renderer.transform)); } for (int i = 0; i < _meshes.Count; i++) { _renderers[i].MakeValid(renderer.transform, i, _meshes[i], _material, _spriteTextureBlock); } } else { while (_renderers.Count > 0) { _renderers.RemoveLast().Destroy(); } } } #endif protected override void prepareMaterial() { if (_shader == null) { _shader = Shader.Find(DEFAULT_SHADER); } base.prepareMaterial(); switch (_motionType) { case MotionType.Translation: _material.EnableKeyword(LeapGraphicRenderer.FEATURE_MOVEMENT_TRANSLATION); break; } if (_motionType != MotionType.None) { if (renderer.space is LeapCylindricalSpace) { _material.EnableKeyword(SpaceProperties.CYLINDRICAL_FEATURE); } else if (renderer.space is LeapSphericalSpace) { _material.EnableKeyword(SpaceProperties.SPHERICAL_FEATURE); } } } protected override void buildTopology() { //If the next graphic is going to put us over the limit, finish the current mesh //and start a new one. if (_generation.verts.Count + _generation.graphic.mesh.vertexCount > MeshUtil.MAX_VERT_COUNT) { finishAndAddMesh(); beginMesh(); } switch (_motionType) { case MotionType.None: _noMotion_transformer = _generation.graphic.transformer; _noMotion_graphicVertToLocalVert = renderer.transform.worldToLocalMatrix * _generation.graphic.transform.localToWorldMatrix; break; case MotionType.Translation: _translation_graphicVertToMeshVert = Matrix4x4.TRS(-renderer.transform.InverseTransformPoint(_generation.graphic.transform.position), Quaternion.identity, Vector3.one) * renderer.transform.worldToLocalMatrix * _generation.graphic.transform.localToWorldMatrix; break; default: throw new NotImplementedException(); } base.buildTopology(); } protected override void postProcessMesh() { base.postProcessMesh(); //For the baked renderer, the mesh really never accurately represents it's visual position //or size, so just disable culling entirely by making the bound gigantic. _generation.mesh.bounds = new Bounds(Vector3.zero, Vector3.one * 100000); } protected override bool doesRequireVertInfo() { if (_motionType != MotionType.None) { return true; } return base.doesRequireVertInfo(); } protected override Vector3 graphicVertToMeshVert(Vector3 vertex) { switch (_motionType) { case MotionType.None: var localVert = _noMotion_graphicVertToLocalVert.MultiplyPoint3x4(vertex); return _noMotion_transformer.TransformPoint(localVert); case MotionType.Translation: return _translation_graphicVertToMeshVert.MultiplyPoint3x4(vertex); } throw new NotImplementedException(); } protected override void graphicVertNormalToMeshVertNormal(Vector3 vertex, Vector3 normal, out Vector3 meshVert, out Vector3 meshNormal) { switch (_motionType) { case MotionType.None: var localVert = _noMotion_graphicVertToLocalVert.MultiplyPoint3x4(vertex); var localNormal = _noMotion_graphicVertToLocalVert.MultiplyVector(normal); var matrix = _noMotion_transformer.GetTransformationMatrix(localVert); meshVert = matrix.MultiplyPoint3x4(Vector3.zero); meshNormal = matrix.MultiplyVector(localNormal); return; case MotionType.Translation: meshVert = _translation_graphicVertToMeshVert.MultiplyPoint3x4(vertex); meshNormal = _translation_graphicVertToMeshVert.MultiplyVector(normal); return; } throw new NotImplementedException(); } [Serializable] protected class MeshRendererContainer { public GameObject obj; public MeshFilter filter; public MeshRenderer renderer; public MeshRendererContainer(Transform root) { obj = new GameObject("Graphic Renderer"); obj.transform.SetParent(root); #if UNITY_EDITOR Undo.RegisterCreatedObjectUndo(obj, "Created graphic renderer"); #endif filter = null; renderer = null; } public void Destroy() { #if UNITY_EDITOR if (!Application.isPlaying) { Undo.DestroyObjectImmediate(obj); } else #endif { UnityEngine.Object.Destroy(obj); } } public void MakeValid(Transform root, int index, Mesh mesh, Material material, MaterialPropertyBlock block) { obj.transform.SetParent(root); obj.transform.SetSiblingIndex(index); obj.SetActive(true); obj.transform.localPosition = Vector3.zero; obj.transform.localRotation = Quaternion.identity; obj.transform.localScale = Vector3.one; if (filter == null) { filter = InternalUtility.AddComponent<MeshFilter>(obj); } filter.sharedMesh = mesh; if (renderer == null) { renderer = InternalUtility.AddComponent<MeshRenderer>(obj); } renderer.enabled = true; renderer.sharedMaterial = material; renderer.SetPropertyBlock(block); } public void ClearPropertyBlock() { renderer.SetPropertyBlock(new MaterialPropertyBlock()); } } } } <file_sep>/Assets/Hover/Core/Scripts/Items/Types/HoverItemDataSelectableBool.cs using System; using UnityEngine; using UnityEngine.Events; namespace Hover.Core.Items.Types { /*================================================================================================*/ [Serializable] public abstract class HoverItemDataSelectableBool : HoverItemDataSelectable, IItemDataSelectable<bool> { [Serializable] public class BoolValueChangedEventHandler : UnityEvent<IItemDataSelectable<bool>> {} public BoolValueChangedEventHandler OnValueChangedEvent = new BoolValueChangedEventHandler(); public event ItemEvents.ValueChangedHandler<bool> OnValueChanged; [SerializeField] protected bool _Value = false; //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ protected HoverItemDataSelectableBool() { OnValueChanged += (x => { OnValueChangedEvent.Invoke(x); }); } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public virtual bool Value { get { return _Value; } set { if ( value == _Value ) { return; } _Value = value; OnValueChanged(this); } } } } <file_sep>/Assets/Hover/Core/Scripts/Cursors/CursorType.cs using System.Collections.Generic; namespace Hover.Core.Cursors { /*================================================================================================*/ public enum CursorType { LeftPalm, LeftThumb, LeftIndex, LeftMiddle, LeftRing, LeftPinky, RightPalm, RightThumb, RightIndex, RightMiddle, RightRing, RightPinky, Look } /*================================================================================================*/ public struct CursorTypeComparer : IEqualityComparer<CursorType> { //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public bool Equals(CursorType pTypeA, CursorType pTypeB) { return pTypeA == pTypeB; } /*--------------------------------------------------------------------------------------------*/ public int GetHashCode(CursorType pType) { return (int)pType; } } } <file_sep>/Assets/Hover/Core/Scripts/Renderers/Items/Sliders/HoverRendererSliderUpdater.cs using Hover.Core.Utils; using UnityEngine; namespace Hover.Core.Renderers.Items.Sliders { /*================================================================================================*/ [RequireComponent(typeof(TreeUpdater))] [RequireComponent(typeof(HoverRendererSlider))] public abstract class HoverRendererSliderUpdater : MonoBehaviour, ITreeUpdateable, ISettingsController { //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public virtual void Start() { //do nothing... } /*--------------------------------------------------------------------------------------------*/ public abstract void TreeUpdate(); } } <file_sep>/Assets/LeapMotion/Modules/GraphicRenderer/Scripts/Graphics/ProceduralMeshGraphics/LeapPanelGraphic.cs /****************************************************************************** * Copyright (C) Leap Motion, Inc. 2011-2018. * * Leap Motion proprietary and confidential. * * * * Use subject to the terms of the Leap Motion SDK Agreement available at * * https://developer.leapmotion.com/sdk_agreement, or another agreement * * between Leap Motion and you, your company or other organization. * ******************************************************************************/ using System.Collections.Generic; using UnityEngine; using UnityEngine.Rendering; namespace Leap.Unity.GraphicalRenderer { /// <summary> /// The Panel Graphic is a type of procedural mesh graphic that can generate flat /// panels with a number of useful features: /// - It allows nine slicing when using a sprite as the source for the texture data. /// - It allows automatic tessellation such that it can be correctly warped by a space. /// - It allows automatic resizing based on an attached RectTransform. /// </summary> [DisallowMultipleComponent] public class LeapPanelGraphic : LeapSlicedGraphic { public override void RefreshSlicedMeshData(Vector2i resolution, RectMargins meshMargins, RectMargins uvMargins) { List<Vector3> verts = new List<Vector3>(); List<Vector2> uvs = new List<Vector2>(); List<int> tris = new List<int>(); for (int vy = 0; vy < resolution.y; vy++) { for (int vx = 0; vx < resolution.x; vx++) { Vector2 vert; vert.x = calculateVertAxis(vx, resolution.x, rect.width, meshMargins.left, meshMargins.right); vert.y = calculateVertAxis(vy, resolution.y, rect.height, meshMargins.top, meshMargins.bottom); verts.Add(vert + new Vector2(rect.x, rect.y)); Vector2 uv; uv.x = calculateVertAxis(vx, resolution.x, 1, uvMargins.left, uvMargins.right); uv.y = calculateVertAxis(vy, resolution.y, 1, uvMargins.top, uvMargins.bottom); uvs.Add(uv); } } for (int vy = 0; vy < resolution.y - 1; vy++) { for (int vx = 0; vx < resolution.x - 1; vx++) { int vertIndex = vy * resolution.x + vx; tris.Add(vertIndex); tris.Add(vertIndex + 1 + resolution.x); tris.Add(vertIndex + 1); tris.Add(vertIndex); tris.Add(vertIndex + resolution.x); tris.Add(vertIndex + 1 + resolution.x); } } if (mesh == null) { mesh = new Mesh(); } mesh.name = "Panel Mesh"; mesh.hideFlags = HideFlags.HideAndDontSave; mesh.Clear(keepVertexLayout: false); mesh.SetVertices(verts); mesh.SetTriangles(tris, 0); mesh.SetUVs(uvChannel.Index(), uvs); mesh.RecalculateBounds(); remappableChannels = UVChannelFlags.UV0; } } } <file_sep>/Assets/LeapMotion/Core/Scripts/Attributes/InspectorName.cs /****************************************************************************** * Copyright (C) Leap Motion, Inc. 2011-2018. * * Leap Motion proprietary and confidential. * * * * Use subject to the terms of the Leap Motion SDK Agreement available at * * https://developer.leapmotion.com/sdk_agreement, or another agreement * * between Leap Motion and you, your company or other organization. * ******************************************************************************/ using UnityEngine; namespace Leap.Unity.Attributes { public class InspectorNameAttribute : CombinablePropertyAttribute, IFullPropertyDrawer { public readonly string name; public InspectorNameAttribute(string name) { this.name = name; } #if UNITY_EDITOR public void DrawProperty(Rect rect, UnityEditor.SerializedProperty property, GUIContent label) { label.text = name; UnityEditor.EditorGUI.PropertyField(rect, property, label, includeChildren: true); } #endif } } <file_sep>/Assets/Hover/Core/Scripts/Items/Types/IItemDataSelectable.cs namespace Hover.Core.Items.Types { /*================================================================================================*/ public interface IItemDataSelectable : IItemData { event ItemEvents.SelectedHandler OnSelected; event ItemEvents.DeselectedHandler OnDeselected; bool IsStickySelected { get; } bool IgnoreSelection { get; } bool AllowIdleDeselection { get; set; } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ void Select(); /*--------------------------------------------------------------------------------------------*/ void DeselectStickySelections(); } } <file_sep>/Assets/Hover/Core/Scripts/Renderers/Shapes/Rect/HoverMeshRectHollow.cs using Hover.Core.Utils; using UnityEngine; namespace Hover.Core.Renderers.Shapes.Rect { /*================================================================================================*/ [RequireComponent(typeof(HoverIndicator))] [RequireComponent(typeof(HoverShapeRect))] public class HoverMeshRectHollow : HoverMeshRect { [DisableWhenControlled] public SizeType InnerSizeType = SizeType.Min; private SizeType vPrevInnerType; //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public override bool IsMeshVisible { get { HoverShapeRect shape = GetComponent<HoverShapeRect>(); float innerProg = GetDimensionProgress(InnerSizeType); float outerProg = GetDimensionProgress(OuterSizeType); return (shape.SizeX != 0 && shape.SizeY != 0 && outerProg != innerProg); } } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ protected override bool ShouldUpdateMesh() { bool shouldUpdate = ( base.ShouldUpdateMesh() || InnerSizeType != vPrevInnerType ); vPrevInnerType = InnerSizeType; return shouldUpdate; } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ protected override void UpdateMesh() { HoverShapeRect shape = GetComponent<HoverShapeRect>(); float innerProg = GetDimensionProgress(InnerSizeType); float outerProg = GetDimensionProgress(OuterSizeType); float outerW; float outerH; float innerW; float innerH; if ( shape.SizeX >= shape.SizeY ) { outerH = shape.SizeY*outerProg; innerH = shape.SizeY*innerProg; outerW = shape.SizeX-(shape.SizeY-outerH); innerW = shape.SizeX-(shape.SizeY-innerH); } else { outerW = shape.SizeX*outerProg; innerW = shape.SizeX*innerProg; outerH = shape.SizeY-(shape.SizeX-outerW); innerH = shape.SizeY-(shape.SizeX-innerW); } MeshUtil.BuildHollowRectangleMesh(vMeshBuild, outerW, outerH, innerW, innerH); UpdateAutoUv(shape, outerW, outerH); UpdateMeshUvAndColors(); vMeshBuild.Commit(); vMeshBuild.CommitColors(); } } } <file_sep>/Assets/Hover/Core/Scripts/Cursors/HoverCursorRendererUpdater.cs using Hover.Core.Renderers; using Hover.Core.Renderers.Cursors; using Hover.Core.Renderers.Utils; using Hover.Core.Utils; using UnityEngine; namespace Hover.Core.Cursors { /*================================================================================================*/ [ExecuteInEditMode] [RequireComponent(typeof(TreeUpdater))] [RequireComponent(typeof(HoverCursorFollower))] public class HoverCursorRendererUpdater : MonoBehaviour, ITreeUpdateable, ISettingsController { public GameObject CursorRendererPrefab; protected HoverRendererCursor CursorRenderer; [TriggerButton("Rebuild Cursor Renderer")] public bool ClickToRebuildRenderer; private GameObject vPrevCursorPrefab; //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public void Awake() { vPrevCursorPrefab = CursorRendererPrefab; } /*--------------------------------------------------------------------------------------------*/ public virtual void Start() { //do nothing... } /*--------------------------------------------------------------------------------------------*/ public virtual void TreeUpdate() { DestroyRendererIfNecessary(); CursorRenderer = (CursorRenderer ?? FindOrBuildCursor()); UpdateRenderer(gameObject.GetComponent<HoverCursorFollower>()); } /*--------------------------------------------------------------------------------------------*/ public void OnEditorTriggerButtonSelected() { //do nothing here, check for (ClickToRebuildRenderer == true) elsewhere... } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ private void DestroyRendererIfNecessary() { if ( ClickToRebuildRenderer || CursorRendererPrefab != vPrevCursorPrefab ) { vPrevCursorPrefab = CursorRendererPrefab; RendererUtil.DestroyRenderer(CursorRenderer); CursorRenderer = null; } ClickToRebuildRenderer = false; } /*--------------------------------------------------------------------------------------------*/ private HoverRendererCursor FindOrBuildCursor() { return RendererUtil.FindOrBuildRenderer<HoverRendererCursor>(gameObject.transform, CursorRendererPrefab, "Cursor", typeof(HoverRendererCursor)); } /*--------------------------------------------------------------------------------------------*/ private void UpdateRenderer(HoverCursorFollower pFollower) { ICursorData cursorData = pFollower.GetCursorData(); HoverIndicator cursorInd = CursorRenderer.GetIndicator(); CursorRenderer.Controllers.Set(SettingsControllerMap.GameObjectActiveSelf, this); CursorRenderer.Controllers.Set(HoverRendererCursor.IsRaycastName, this); CursorRenderer.Controllers.Set(HoverRendererCursor.ShowRaycastLineName, this); CursorRenderer.Controllers.Set(HoverRendererCursor.RaycastWorldOriginName, this); cursorInd.Controllers.Set(HoverIndicator.HighlightProgressName, this); cursorInd.Controllers.Set(HoverIndicator.SelectionProgressName, this); RendererUtil.SetActiveWithUpdate(CursorRenderer, (cursorData.IsActive && cursorData.Capability != CursorCapabilityType.None)); CursorRenderer.IsRaycast = cursorData.IsRaycast; CursorRenderer.ShowRaycastLine = (cursorData.CanCauseSelections && cursorData.Type != CursorType.Look); CursorRenderer.RaycastWorldOrigin = cursorData.WorldPosition; cursorInd.HighlightProgress = cursorData.MaxItemHighlightProgress; cursorInd.SelectionProgress = cursorData.MaxItemSelectionProgress; } } } <file_sep>/Assets/LeapMotion/Modules/GraphicRenderer/Scripts/EditTimeApis/LeapGraphicRendererEditorApi.cs /****************************************************************************** * Copyright (C) Leap Motion, Inc. 2011-2018. * * Leap Motion proprietary and confidential. * * * * Use subject to the terms of the Leap Motion SDK Agreement available at * * https://developer.leapmotion.com/sdk_agreement, or another agreement * * between Leap Motion and you, your company or other organization. * ******************************************************************************/ using System; using System.Collections.Generic; using UnityEngine; using UnityEngine.Assertions; #if UNITY_EDITOR using UnityEditor; #endif using Leap.Unity.Space; namespace Leap.Unity.GraphicalRenderer { public partial class LeapGraphicRenderer : MonoBehaviour { //Need to keep this outside of the #if guards or else Unity will throw a fit //about the serialized format changing between editor and build [SerializeField] #pragma warning disable 0414 private int _selectedGroup = 0; #pragma warning restore 0414 #if UNITY_EDITOR public readonly EditorApi editor; [ContextMenu("Show all hidden objects (INTERNAL)")] private void showAllHiddenObjects() { foreach (var obj in FindObjectsOfType<UnityEngine.Object>()) { obj.hideFlags = HideFlags.None; } } public class EditorApi { private LeapGraphicRenderer _renderer; [NonSerialized] private Hash _previousHierarchyHash; public EditorApi(LeapGraphicRenderer renderer) { _renderer = renderer; InternalUtility.OnAnySave += onAnySave; } public void OnValidate() { Assert.IsFalse(InternalUtility.IsPrefab(_renderer), "Should never run editor validation on a prefab"); for (int i = _renderer._groups.Count; i-- > 0;) { if (_renderer._groups[i] == null) { _renderer._groups.RemoveAt(i); } } _renderer.validateSpaceComponent(); foreach (var group in _renderer._groups) { group.editor.OnValidate(); } } public void OnDestroy() { InternalUtility.OnAnySave -= onAnySave; foreach (var group in _renderer._groups) { group.editor.OnDestroy(); } } /// <summary> /// Creates a new group for this graphic renderer, and assigns it the /// given rendering method. This is an editor only api, as creating new /// groups cannot be done at runtime. /// </summary> public void CreateGroup(Type rendererType) { AssertHelper.AssertEditorOnly(); Assert.IsNotNull(rendererType); var group = new LeapGraphicGroup(_renderer, rendererType); _renderer._selectedGroup = _renderer._groups.Count; _renderer._groups.Add(group); } /// <summary> /// Destroys the currently selected group. This is an editor-only api, /// as destroying groups cannot be done at runtime. /// </summary> public void DestroySelectedGroup() { AssertHelper.AssertEditorOnly(); var toDestroy = _renderer._groups[_renderer._selectedGroup]; _renderer._groups.RemoveAt(_renderer._selectedGroup); toDestroy.editor.OnDestroy(); if (_renderer._selectedGroup >= _renderer._groups.Count && _renderer._selectedGroup != 0) { _renderer._selectedGroup--; } } /// <summary> /// Returns the rendering method of the currently selected group. This /// is an editor-only api, as the notion of selection does not exist at /// runtime. /// </summary> public LeapRenderingMethod GetSelectedRenderingMethod() { return _renderer._groups[_renderer._selectedGroup].renderingMethod; } /// <summary> /// Schedules a full editor rebuild of all graphic groups and their representations. /// This method only schedules the rebuild, it does not actually execute it. The /// rebuild will happen on during the next editor tick. /// /// This is an editor-only api. During runtime rebuilding is handled automatically, /// and full rebuilds do not occur. /// </summary> public void ScheduleRebuild() { AssertHelper.AssertEditorOnly(); //Dirty the hash by changing it to something else _previousHierarchyHash++; } /// <summary> /// Force a rebuild of all editor picking meshes for all graphics attached to all /// groups. Editor picking meshes are what allow graphics to be accurately picked /// in the scene view even if they are in a curved space. /// </summary> public void RebuildEditorPickingMeshes() { //No picking meshes for prefabs if (InternalUtility.IsPrefab(_renderer)) { return; } if (!Application.isPlaying) { if (_renderer._space != null) { _renderer._space.RebuildHierarchy(); _renderer._space.RecalculateTransformers(); } validateGraphics(); foreach (var group in _renderer._groups) { group.editor.ValidateGraphicList(); group.RebuildFeatureData(); group.RebuildFeatureSupportInfo(); group.editor.RebuildEditorPickingMeshes(); } } foreach (var group in _renderer._groups) { group.editor.RebuildEditorPickingMeshes(); } } /// <summary> /// Changes the rendering method of the selected group. This method is just /// a helpful wrapper around the ChangeRenderingMethod of the LeapGraphicGroup class. /// </summary> public void ChangeRenderingMethodOfSelectedGroup(Type renderingMethod, bool addFeatures) { _renderer._groups[_renderer._selectedGroup].editor.ChangeRenderingMethod(renderingMethod, addFeatures); } /// <summary> /// Adds a feature to the currently selected group. This method is just /// a helpful wrapper around the AddFeature method of the LeapGraphicGroup class. /// </summary> public void AddFeatureToSelectedGroup(Type featureType) { _renderer._groups[_renderer._selectedGroup].editor.AddFeature(featureType); } /// <summary> /// Removes a feature from the currently selected group. This method is just /// a helpful wrapper around the RemoveFeature method of the LeapGraphicGroup class. /// </summary> public void RemoveFeatureFromSelectedGroup(int featureIndex) { _renderer._groups[_renderer._selectedGroup].editor.RemoveFeature(featureIndex); } public void DoLateUpdateEditor() { Undo.RecordObject(_renderer, "Update graphic renderer."); Assert.IsFalse(InternalUtility.IsPrefab(_renderer), "Should never do editor updates for prefabs"); _renderer.validateSpaceComponent(); bool needsRebuild = false; using (new ProfilerSample("Calculate Should Rebuild")) { foreach (var group in _renderer._groups) { #if UNITY_EDITOR if (!Application.isPlaying) { group.editor.ValidateGraphicList(); } #endif foreach (var graphic in group.graphics) { if (graphic.isRepresentationDirty) { needsRebuild = true; break; } } foreach (var feature in group.features) { if (feature.isDirty) { needsRebuild = true; break; } } } Hash hierarchyHash = Hash.GetHierarchyHash(_renderer.transform); if (_renderer._space != null) { hierarchyHash.Add(_renderer._space.GetSettingHash()); } if (_previousHierarchyHash != hierarchyHash) { _previousHierarchyHash = hierarchyHash; needsRebuild = true; } } DoEditorUpdateLogic(needsRebuild); } public void DoEditorUpdateLogic(bool fullRebuild) { Undo.RecordObject(_renderer, "Do Editor Update Logic"); Assert.IsFalse(InternalUtility.IsPrefab(_renderer), "Should never do editor updates for prefabs"); using (new ProfilerSample("Validate Space Component")) { _renderer.validateSpaceComponent(); } if (fullRebuild) { if (_renderer._space != null) { using (new ProfilerSample("Rebuild Space")) { _renderer._space.RebuildHierarchy(); _renderer._space.RecalculateTransformers(); } } using (new ProfilerSample("Validate graphics")) { validateGraphics(); } foreach (var group in _renderer._groups) { using (new ProfilerSample("Validate Graphic List")) { group.editor.ValidateGraphicList(); } using (new ProfilerSample("Rebuild Feature Data")) { group.RebuildFeatureData(); } using (new ProfilerSample("Rebuild Feature Support Info")) { group.RebuildFeatureSupportInfo(); } using (new ProfilerSample("Update Renderer Editor")) { group.editor.UpdateRendererEditor(); } } } using (new ProfilerSample("Update Renderer")) { foreach (var group in _renderer._groups) { group.UpdateRenderer(); } } Undo.CollapseUndoOperations(Undo.GetCurrentGroup()); } private void onAnySave() { if (_renderer == null || InternalUtility.IsPrefab(_renderer)) { InternalUtility.OnAnySave -= onAnySave; return; } DoEditorUpdateLogic(fullRebuild: true); } [NonSerialized] private List<LeapGraphic> _tempGraphicList = new List<LeapGraphic>(); private void validateGraphics() { Assert.IsFalse(InternalUtility.IsPrefab(_renderer), "Should never validate graphics for prefabs"); _renderer.GetComponentsInChildren(includeInactive: true, result: _tempGraphicList); HashSet<LeapGraphic> graphicsInGroup = Pool<HashSet<LeapGraphic>>.Spawn(); try { foreach (var group in _renderer._groups) { for (int i = group.graphics.Count; i-- != 0;) { if (group.graphics[i] == null) { group.graphics.RemoveAt(i); } else { graphicsInGroup.Add(group.graphics[i]); } } foreach (var graphic in _tempGraphicList) { if (graphic.isAttachedToGroup) { //If the graphic claims it is attached to this group, but it really isn't, remove //it and re-add it. bool graphicThinksItsInGroup = graphic.attachedGroup == group; bool isActuallyInGroup = graphicsInGroup.Contains(graphic); //Also re add it if it is attached to a completely different renderer! if (graphicThinksItsInGroup != isActuallyInGroup || graphic.attachedGroup.renderer != _renderer) { if (!group.TryRemoveGraphic(graphic)) { //If we fail, detach using force!! graphic.OnDetachedFromGroup(); } group.TryAddGraphic(graphic); } } } graphicsInGroup.Clear(); } } finally { graphicsInGroup.Clear(); Pool<HashSet<LeapGraphic>>.Recycle(graphicsInGroup); } foreach (var graphic in _tempGraphicList) { if (graphic.isAttachedToGroup) { //procede to validate //If the graphic is anchored to the wrong anchor, detach and reattach var anchor = _renderer._space == null ? null : LeapSpaceAnchor.GetAnchor(graphic.transform); if (graphic.anchor != anchor) { var group = graphic.attachedGroup; if (group.TryRemoveGraphic(graphic)) { group.TryAddGraphic(graphic); } } } } } } #endif } } <file_sep>/Assets/LeapMotion/Modules/GraphicRenderer/Scripts/Editor/LeapGraphicEditor.cs /****************************************************************************** * Copyright (C) Leap Motion, Inc. 2011-2018. * * Leap Motion proprietary and confidential. * * * * Use subject to the terms of the Leap Motion SDK Agreement available at * * https://developer.leapmotion.com/sdk_agreement, or another agreement * * between Leap Motion and you, your company or other organization. * ******************************************************************************/ using UnityEngine; using UnityEditor; using Leap.Unity; using Leap.Unity.Query; namespace Leap.Unity.GraphicalRenderer { [CanEditMultipleObjects] [CustomEditor(typeof(LeapGraphic), editorForChildClasses: true, isFallback = true)] public class LeapGraphicEditor : LeapGraphicEditorBase<LeapGraphic> { } public abstract class LeapGraphicEditorBase<T> : CustomEditorBase<T> where T : LeapGraphic { //Used ONLY for feature data drawers public static LeapGraphicFeatureBase currentFeature { get; private set; } private SerializedProperty _featureList; private SerializedProperty _featureTable; protected override void OnEnable() { base.OnEnable(); hideField("_anchor"); hideField("_featureData"); hideField("_attachedRenderer"); hideField("_attachedGroupIndex"); hideField("_preferredRendererType"); hideField("_favoriteGroupName"); _featureList = serializedObject.FindProperty("_featureData"); _featureTable = MultiTypedListUtil.GetTableProperty(_featureList); dontShowScriptField(); } public override void OnInspectorGUI() { LeapGraphicGroup mainGroup = null; LeapGraphicGroup sharedGroup = null; if (targets.Query().All(g => g.isAttachedToGroup)) { var mainRenderer = targets[0].attachedGroup.renderer; if (targets.Query().All(g => g.attachedGroup.renderer == mainRenderer)) { mainGroup = targets[0].attachedGroup; if (targets.Query().All(g => g.attachedGroup == mainGroup)) { sharedGroup = mainGroup; } } } drawScriptAndGroupGui(mainGroup); base.OnInspectorGUI(); drawFeatureData(sharedGroup); } protected void drawScriptAndGroupGui(LeapGraphicGroup mainGroup) { using (new GUILayout.HorizontalScope()) { drawScriptField(); Color originalColor = GUI.color; try { string buttonText; if (!targets.Query().All(g => g.attachedGroup == mainGroup)) { buttonText = "-"; } else if (mainGroup == null) { buttonText = "None"; GUI.color = Color.yellow; } else { buttonText = mainGroup.name; } var renderer = targets.Query(). Select(t => t.GetComponentInParent<LeapGraphicRenderer>()). UniformOrDefault(); if (GUILayout.Button(buttonText, EditorStyles.miniButton, GUILayout.Width(60))) { GenericMenu groupMenu = new GenericMenu(); groupMenu.AddItem(new GUIContent("None"), false, () => { foreach (var graphic in targets) { serializedObject.ApplyModifiedProperties(); graphic.TryDetach(); EditorUtility.SetDirty(graphic); serializedObject.SetIsDifferentCacheDirty(); serializedObject.Update(); } }); if (renderer != null) { int index = 0; foreach (var group in renderer.groups.Query().Where(g => g.renderingMethod.IsValidGraphic(targets[0]))) { groupMenu.AddItem(new GUIContent(index.ToString() + ": " + group.name), false, () => { bool areFeaturesUnequal = false; var typesA = group.features.Query().Select(f => f.GetType()).ToList(); foreach (var graphic in targets) { if (!graphic.isAttachedToGroup) { continue; } var typesB = graphic.attachedGroup.features.Query().Select(f => f.GetType()).ToList(); if (!Utils.AreEqualUnordered(typesA, typesB)) { areFeaturesUnequal = true; break; } } if (areFeaturesUnequal && LeapGraphicPreferences.promptWhenGroupChange) { if (!EditorUtility.DisplayDialog("Features Are Different!", "The group you are moving to has a different feature set than the current group, " + "this can result in data loss! Are you sure you want to change group?", "Continue", "Cancel")) { return; } } foreach (var graphic in targets) { serializedObject.ApplyModifiedProperties(); if (graphic.isAttachedToGroup) { if (graphic.TryDetach()) { group.TryAddGraphic(graphic); } } else { group.TryAddGraphic(graphic); } EditorUtility.SetDirty(graphic); EditorUtility.SetDirty(renderer); serializedObject.SetIsDifferentCacheDirty(); serializedObject.Update(); } renderer.editor.ScheduleRebuild(); }); index++; } } groupMenu.ShowAsContext(); } } finally { GUI.color = originalColor; } } } protected void drawFeatureData(LeapGraphicGroup sharedGroup) { using (new ProfilerSample("Draw Leap Gui Graphic Editor")) { if (targets.Length == 0) return; var mainGraphic = targets[0]; if (mainGraphic.featureData.Count == 0) { return; } if (mainGraphic.attachedGroup != null) { SpriteAtlasUtil.ShowInvalidSpriteWarning(mainGraphic.attachedGroup.features); } int maxGraphics = LeapGraphicPreferences.graphicMax; if (targets.Query().Any(e => e.attachedGroup != null && e.attachedGroup.graphics.IndexOf(e) >= maxGraphics)) { string noun = targets.Length == 1 ? "This graphic" : "Some of these graphics"; string rendererName = targets.Length == 1 ? "its renderer" : "their renderers"; EditorGUILayout.HelpBox(noun + " may not be properly displayed because there are too many graphics on " + rendererName + ". " + "Either lower the number of graphics or increase the maximum graphic count by visiting " + "Edit->Preferences.", MessageType.Warning); } //If we are not all attached to the same group we cannot show features if (!targets.Query().Select(g => g.attachedGroup).AllEqual()) { return; } EditorGUILayout.Space(); using (new GUILayout.HorizontalScope()) { EditorGUILayout.LabelField("Feature Data: ", EditorStyles.boldLabel); if (sharedGroup != null) { var meshRendering = sharedGroup.renderingMethod as LeapMesherBase; if (meshRendering != null && meshRendering.IsAtlasDirty && !EditorApplication.isPlaying) { if (GUILayout.Button("Refresh Atlas", GUILayout.MaxHeight(EditorGUIUtility.singleLineHeight))) { meshRendering.RebuildAtlas(new ProgressBar()); sharedGroup.renderer.editor.ScheduleRebuild(); } } } } for (int i = 0; i < _featureTable.arraySize; i++) { var idIndex = _featureTable.GetArrayElementAtIndex(i); var dataProp = MultiTypedListUtil.GetReferenceProperty(_featureList, idIndex); EditorGUILayout.LabelField(LeapGraphicTagAttribute.GetTagName(dataProp.type)); if (mainGraphic.attachedGroup != null) { currentFeature = mainGraphic.attachedGroup.features[i]; } EditorGUI.indentLevel++; EditorGUILayout.PropertyField(dataProp, includeChildren: true); EditorGUI.indentLevel--; currentFeature = null; } serializedObject.ApplyModifiedProperties(); } } protected bool HasFrameBounds() { return targets.Query(). Any(t => t.editor.pickingMesh != null); } protected Bounds OnGetFrameBounds() { return targets.Query(). Select(e => e.editor.pickingMesh). ValidUnityObjs(). Select(m => m.bounds). Fold((a, b) => { a.Encapsulate(b); return a; }); } } } <file_sep>/Assets/Hover/Core/Scripts/Cursors/ICursorData.cs using System.Collections.Generic; using Hover.Core.Utils; using UnityEngine; namespace Hover.Core.Cursors { /*================================================================================================*/ public interface ICursorData { CursorType Type { get; } bool IsActive { get; } bool CanCauseSelections { get; } CursorCapabilityType Capability { get; } bool IsRaycast { get; } Vector3 RaycastLocalDirection { get; } float Size { get; } float TriggerStrength { get; } Vector3 WorldPosition { get; } Quaternion WorldRotation { get; } ICursorIdle Idle { get; } RaycastResult? BestRaycastResult { get; set; } float MaxItemHighlightProgress { get; set; } float MaxItemSelectionProgress { get; set; } List<StickySelectionInfo> ActiveStickySelections { get; } } } <file_sep>/Assets/LeapMotion/Core/Scripts/Attributes/Disable.cs /****************************************************************************** * Copyright (C) Leap Motion, Inc. 2011-2018. * * Leap Motion proprietary and confidential. * * * * Use subject to the terms of the Leap Motion SDK Agreement available at * * https://developer.leapmotion.com/sdk_agreement, or another agreement * * between Leap Motion and you, your company or other organization. * ******************************************************************************/ #if UNITY_EDITOR using UnityEditor; #endif namespace Leap.Unity.Attributes { public class DisableAttribute : CombinablePropertyAttribute, IPropertyDisabler { #if UNITY_EDITOR public bool ShouldDisable(SerializedProperty property) { return true; } #endif } } <file_sep>/Assets/Hover/Core/Scripts/Renderers/Cursors/HoverRendererCursor.cs using System; using Hover.Core.Renderers.CanvasElements; using Hover.Core.Renderers.Utils; using Hover.Core.Utils; using UnityEngine; namespace Hover.Core.Renderers.Cursors { /*================================================================================================*/ public class HoverRendererCursor : HoverRenderer { public const string IsRaycastName = "IsRaycast"; public const string ShowRaycastLineName = "ShowRaycastLine"; public const string RaycastWorldOriginName = "RaycastWorldOrigin"; [DisableWhenControlled] public HoverFillCursor Fill; [DisableWhenControlled] public HoverRaycastLine RaycastLine; [DisableWhenControlled] public bool IsRaycast; [DisableWhenControlled] public bool ShowRaycastLine; [DisableWhenControlled] public Vector3 RaycastWorldOrigin; [DisableWhenControlled] public float RaycastOffsetZ = -0.001f; //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public override int GetChildFillCount() { return 1; } /*--------------------------------------------------------------------------------------------*/ public override HoverFill GetChildFill(int pIndex) { switch ( pIndex ) { case 0: return Fill; } throw new ArgumentOutOfRangeException(); } /*--------------------------------------------------------------------------------------------*/ public override int GetChildRendererCount() { return 0; } /*--------------------------------------------------------------------------------------------*/ public override HoverRenderer GetChildRenderer(int pIndex) { throw new ArgumentOutOfRangeException(); } /*--------------------------------------------------------------------------------------------*/ public override HoverCanvas GetCanvas() { return null; } /*--------------------------------------------------------------------------------------------*/ public override HoverCanvasDataUpdater GetCanvasDataUpdater() { return null; } /*--------------------------------------------------------------------------------------------*/ public override Vector3 GetCenterWorldPosition() { return transform.position; } /*--------------------------------------------------------------------------------------------*/ public override Vector3 GetNearestWorldPosition(Vector3 pFromWorldPosition) { return Vector3.zero; } /*--------------------------------------------------------------------------------------------*/ public override Vector3 GetNearestWorldPosition(Ray pFromWorldRay, out RaycastResult pRaycast) { pRaycast = new RaycastResult(); return Vector3.zero; } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public override void TreeUpdate() { base.TreeUpdate(); UpdatePosition(); } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ private void UpdatePosition() { if ( RaycastLine != null ) { RaycastLine.Controllers.Set(SettingsControllerMap.GameObjectActiveSelf, this); RaycastLine.Controllers.Set(HoverRaycastLine.RaycastWorldOriginName, this); RaycastLine.RaycastWorldOrigin = RaycastWorldOrigin; RendererUtil.SetActiveWithUpdate(RaycastLine, (IsRaycast && ShowRaycastLine)); } if ( !Application.isPlaying || !IsRaycast ) { return; } Controllers.Set(SettingsControllerMap.TransformLocalPosition+".z", this); Vector3 localPos = transform.localPosition; localPos.z = RaycastOffsetZ/transform.lossyScale.z; transform.localPosition = localPos; } } } <file_sep>/Assets/Hover/Core/Scripts/Items/Types/HoverItemDataText.cs using System; namespace Hover.Core.Items.Types { /*================================================================================================*/ [Serializable] public class HoverItemDataText : HoverItemData, IItemDataText { } } <file_sep>/Assets/Hover/Core/Scripts/Layouts/Rect/ILayoutableRect.cs using Hover.Core.Utils; using UnityEngine; namespace Hover.Core.Layouts.Rect { /*================================================================================================*/ public interface ILayoutableRect { bool isActiveAndEnabled { get; } Transform transform { get; } ISettingsControllerMap Controllers { get; } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ void SetRectLayout(float pSizeX, float pSizeY, ISettingsController pController); } } <file_sep>/Assets/Hover/Editor/Items/Managers/HoverItemSelectionStateEditor.cs using Hover.Core.Items.Managers; using UnityEditor; using UnityEngine; namespace Hover.Editor.Items.Managers { /*================================================================================================*/ [CanEditMultipleObjects] [CustomEditor(typeof(HoverItemSelectionState))] public class HoverItemSelectionStateEditor : UnityEditor.Editor { private string vIsSelectionOpenKey; private GUIStyle vVertStyle; private HoverItemSelectionState vTarget; //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public void OnEnable() { vIsSelectionOpenKey = "IsSelectionOpen"+target.GetInstanceID(); vVertStyle = EditorUtil.GetVerticalSectionStyle(); } /*--------------------------------------------------------------------------------------------*/ public override bool RequiresConstantRepaint() { return EditorPrefs.GetBool(vIsSelectionOpenKey); } /*--------------------------------------------------------------------------------------------*/ public override void OnInspectorGUI() { vTarget = (HoverItemSelectionState)target; DrawDefaultInspector(); DrawSelectionInfo(); } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ private void DrawSelectionInfo() { bool isHighOpen = EditorGUILayout.Foldout(EditorPrefs.GetBool(vIsSelectionOpenKey), "Item Selection Information"); EditorPrefs.SetBool(vIsSelectionOpenKey, isHighOpen); if ( !isHighOpen ) { return; } EditorGUILayout.BeginVertical(vVertStyle); if ( !Application.isPlaying ) { EditorGUILayout.HelpBox("At runtime, this section displays live information about "+ "the item's selection state. You can access this "+ "information via code.", MessageType.Info); EditorGUILayout.EndVertical(); return; } GUI.enabled = false; EditorGUILayout.Toggle("Is Selection Prevented", vTarget.IsSelectionPrevented); EditorGUILayout.Slider("Selection Progress", vTarget.SelectionProgress, 0, 1); GUI.enabled = true; EditorGUILayout.EndVertical(); } } } <file_sep>/Assets/LeapMotion/Modules/GraphicRenderer/Scripts/Features/Texture/LeapTextureData.cs /****************************************************************************** * Copyright (C) Leap Motion, Inc. 2011-2018. * * Leap Motion proprietary and confidential. * * * * Use subject to the terms of the Leap Motion SDK Agreement available at * * https://developer.leapmotion.com/sdk_agreement, or another agreement * * between Leap Motion and you, your company or other organization. * ******************************************************************************/ using System; using UnityEngine; using UnityEngine.Serialization; using Leap.Unity.Attributes; namespace Leap.Unity.GraphicalRenderer { public static class LeapTextureFeatureExtension { public static LeapTextureData Texture(this LeapGraphic graphic) { return graphic.GetFeatureData<LeapTextureData>(); } } [LeapGraphicTag("Texture")] [Serializable] public class LeapTextureData : LeapFeatureData { [FormerlySerializedAs("texture")] [EditTimeOnly, SerializeField] private Texture2D _texture; public Texture2D texture { get { return _texture; } set { _texture = value; graphic.isRepresentationDirty = true; MarkFeatureDirty(); } } } } <file_sep>/Assets/Hover/Core/Scripts/Layouts/Rect/HoverLayoutRectPaddingSettings.cs using System; using UnityEngine; namespace Hover.Core.Layouts.Rect { /*================================================================================================*/ [Serializable] public class HoverLayoutRectPaddingSettings { public float Top = 0; public float Bottom = 0; public float Left = 0; public float Right = 0; public float Between = 0; //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public void ClampValues(HoverLayoutRectRow pRectRow) { if ( pRectRow.ChildCount <= 0 ) { return; } Top = Mathf.Clamp(Top, 0, pRectRow.SizeY); Bottom = Mathf.Clamp(Bottom, 0, pRectRow.SizeY-Top); Left = Mathf.Clamp(Left, 0, pRectRow.SizeX); Right = Mathf.Clamp(Right, 0, pRectRow.SizeX-Left); float maxTotalBetweenSize = (pRectRow.IsHorizontal ? pRectRow.SizeX-Left-Right : pRectRow.SizeY-Top-Bottom); Between = Mathf.Clamp(Between, 0, maxTotalBetweenSize/(pRectRow.ChildCount-1)); } } } <file_sep>/Assets/LeapMotion/Modules/GraphicRenderer/Scripts/RenderingMethods/Editor/LeapTextRendererDrawer.cs /****************************************************************************** * Copyright (C) Leap Motion, Inc. 2011-2018. * * Leap Motion proprietary and confidential. * * * * Use subject to the terms of the Leap Motion SDK Agreement available at * * https://developer.leapmotion.com/sdk_agreement, or another agreement * * between Leap Motion and you, your company or other organization. * ******************************************************************************/ using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEditor; namespace Leap.Unity.GraphicalRenderer { [CustomPropertyDrawer(typeof(LeapTextRenderer))] public class LeapTextRendererDrawer : CustomPropertyDrawerBase { private static float HELP_BOX_HEIGHT = EditorGUIUtility.singleLineHeight * 2; protected override void init(SerializedProperty property) { base.init(property); drawCustom(rect => { }, EditorGUIUtility.singleLineHeight * 0.5f); drawCustom(rect => EditorGUI.LabelField(rect, "Text Settings", EditorStyles.boldLabel), EditorGUIUtility.singleLineHeight); var fontProp = property.FindPropertyRelative("_font"); drawCustom(rect => { Font font = fontProp.objectReferenceValue as Font; if (font != null && !font.dynamic) { rect.height = HELP_BOX_HEIGHT; EditorGUI.HelpBox(rect, "Only dynamic fonts are currently supported.", MessageType.Error); rect.y += HELP_BOX_HEIGHT; } rect.height = EditorGUIUtility.singleLineHeight; EditorGUI.PropertyField(rect, fontProp); }, () => { Font font = fontProp.objectReferenceValue as Font; if (font != null && !font.dynamic) { return HELP_BOX_HEIGHT + EditorGUIUtility.singleLineHeight; } else { return EditorGUIUtility.singleLineHeight; } }); drawProperty("_dynamicPixelsPerUnit"); drawProperty("_useColor"); drawPropertyConditionally("_globalTint", "_useColor"); drawProperty("_shader"); drawProperty("_scale"); } } } <file_sep>/Assets/Hover/Core/Scripts/Cursors/HoverCursorDataProvider.cs using System; using System.Collections.Generic; using UnityEngine; namespace Hover.Core.Cursors { /*================================================================================================*/ [ExecuteInEditMode] public class HoverCursorDataProvider : MonoBehaviour { public List<ICursorData> Cursors { get; private set; } public List<ICursorData> ExcludedCursors { get; private set; } private readonly List<ICursorDataForInput> vCursorsForInput; private readonly Dictionary<CursorType, ICursorDataForInput> vCursorMap; //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public HoverCursorDataProvider() { Cursors = new List<ICursorData>(); ExcludedCursors = new List<ICursorData>(); vCursorsForInput = new List<ICursorDataForInput>(); vCursorMap = new Dictionary<CursorType, ICursorDataForInput>(new CursorTypeComparer()); } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public void Awake() { Update(); } /*--------------------------------------------------------------------------------------------*/ public void Update() { gameObject.GetComponentsInChildren(true, vCursorsForInput); Cursors.Clear(); ExcludedCursors.Clear(); vCursorMap.Clear(); for ( int i = 0 ; i < vCursorsForInput.Count ; i++ ) { ICursorDataForInput cursor = vCursorsForInput[i]; if ( vCursorMap.ContainsKey(cursor.Type) ) { ExcludedCursors.Add(cursor); continue; } Cursors.Add(cursor); vCursorMap.Add(cursor.Type, cursor); } } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public bool HasCursorData(CursorType pType) { if ( vCursorMap.Count == 0 ) { Update(); //Debug.Log("Early cursor request. Found "+vCursorMap.Count+" cursor(s)."); } return vCursorMap.ContainsKey(pType); } /*--------------------------------------------------------------------------------------------*/ public ICursorData GetCursorData(CursorType pType) { return GetCursorDataForInput(pType); } /*--------------------------------------------------------------------------------------------*/ public ICursorDataForInput GetCursorDataForInput(CursorType pType) { if ( !HasCursorData(pType) ) { throw new Exception("No '"+pType+"' cursor was found."); } return vCursorMap[pType]; } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public void MarkAllCursorsUnused() { for ( int i = 0 ; i < vCursorsForInput.Count ; i++ ) { vCursorsForInput[i].SetUsedByInput(false); } } /*--------------------------------------------------------------------------------------------*/ public void ActivateAllCursorsBasedOnUsage() { for ( int i = 0 ; i < Cursors.Count ; i++ ) { vCursorsForInput[i].ActivateIfUsedByInput(); } } } } <file_sep>/Assets/Hover/Core/Scripts/Items/Types/HoverItemDataSelector.cs using System; using UnityEngine; namespace Hover.Core.Items.Types { /*================================================================================================*/ [Serializable] public class HoverItemDataSelector : HoverItemDataSelectable, IItemDataSelector { [SerializeField] private SelectorActionType _Action = SelectorActionType.Default; //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public SelectorActionType Action { get { return _Action; } set { _Action = value; } } } } <file_sep>/Assets/Hover/Core/Scripts/Renderers/Cursors/HoverFillIdle.cs using System; using Hover.Core.Renderers.Shapes; using Hover.Core.Renderers.Utils; using Hover.Core.Utils; using UnityEngine; namespace Hover.Core.Renderers.Cursors { /*================================================================================================*/ [RequireComponent(typeof(HoverIndicator))] [RequireComponent(typeof(HoverShape))] public class HoverFillIdle : HoverFill { [DisableWhenControlled(DisplaySpecials=true)] public HoverMesh Timer; [DisableWhenControlled] public HoverMesh ItemPointer; //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public override int GetChildMeshCount() { return 1; } /*--------------------------------------------------------------------------------------------*/ public override HoverMesh GetChildMesh(int pIndex) { switch ( pIndex ) { case 0: return Timer; //case 1: return ItemPointer; } throw new ArgumentOutOfRangeException(); } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public override void TreeUpdate() { base.TreeUpdate(); UpdateMeshes(); } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ private void UpdateMeshes() { if ( Timer != null ) { UpdateMesh(Timer); } } /*--------------------------------------------------------------------------------------------*/ private void UpdateMesh(HoverMesh pMesh, bool pShowMesh=true) { pMesh.Controllers.Set(SettingsControllerMap.GameObjectActiveSelf, this); RendererUtil.SetActiveWithUpdate(pMesh, (pShowMesh && pMesh.IsMeshVisible)); } } } <file_sep>/Assets/LeapMotion/Modules/GraphicRenderer/Scripts/RenderingMethods/Editor/LeapMesherBaseDrawer.cs /****************************************************************************** * Copyright (C) Leap Motion, Inc. 2011-2018. * * Leap Motion proprietary and confidential. * * * * Use subject to the terms of the Leap Motion SDK Agreement available at * * https://developer.leapmotion.com/sdk_agreement, or another agreement * * between Leap Motion and you, your company or other organization. * ******************************************************************************/ using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEditor; using Leap.Unity.Query; namespace Leap.Unity.GraphicalRenderer { [CustomPropertyDrawer(typeof(LeapMesherBase), useForChildren: true)] public class LeapMesherBaseDrawer : CustomPropertyDrawerBase { private const float HEADER_HEADROOM = 8; private const float MESH_LABEL_WIDTH = 100.0f; private const float REFRESH_BUTTON_WIDTH = 100; private static float SHADER_WARNING_HEIGHT = 40; private static float SHADER_WARNING_FIX_WIDTH = 50; private SerializedProperty _uv0, _uv1, _uv2, _uv3, _colors, _bakedTint, _normals; protected override void init(SerializedProperty property) { base.init(property); _uv0 = property.FindPropertyRelative("_useUv0"); _uv1 = property.FindPropertyRelative("_useUv1"); _uv2 = property.FindPropertyRelative("_useUv2"); _uv3 = property.FindPropertyRelative("_useUv3"); _colors = property.FindPropertyRelative("_useColors"); _bakedTint = property.FindPropertyRelative("_bakedTint"); _normals = property.FindPropertyRelative("_useNormals"); drawCustom(rect => { rect.y += HEADER_HEADROOM; EditorGUI.LabelField(rect, "Mesh Settings", EditorStyles.boldLabel); }, HEADER_HEADROOM + EditorGUIUtility.singleLineHeight); increaseIndent(); drawCustom(rect => { Rect left, right; rect.SplitHorizontally(out left, out right); EditorGUI.PropertyField(left, _uv0); EditorGUI.PropertyField(right, _uv1); }, EditorGUIUtility.singleLineHeight); drawCustom(rect => { Rect left, right; rect.SplitHorizontally(out left, out right); EditorGUI.PropertyField(left, _uv2); EditorGUI.PropertyField(right, _uv3); }, EditorGUIUtility.singleLineHeight); drawCustom(rect => { Rect left, right; rect.SplitHorizontally(out left, out right); EditorGUI.PropertyField(left, _colors); if (_colors.boolValue) { EditorGUI.PropertyField(right, _bakedTint); } }, EditorGUIUtility.singleLineHeight); drawCustom(rect => { Rect left, right; rect.SplitHorizontally(out left, out right); EditorGUI.PropertyField(left, _normals); }, EditorGUIUtility.singleLineHeight); decreaseIndent(); drawCustom(rect => { rect.y += HEADER_HEADROOM; rect.height = EditorGUIUtility.singleLineHeight; EditorGUI.LabelField(rect, "Rendering Settings", EditorStyles.boldLabel); }, HEADER_HEADROOM + EditorGUIUtility.singleLineHeight); increaseIndent(); SerializedProperty shaderProp; tryGetProperty("_shader", out shaderProp); drawCustom(rect => { if (!shaderProp.hasMultipleDifferentValues) { Shader shader = shaderProp.objectReferenceValue as Shader; if (VariantEnabler.DoesShaderHaveVariantsDisabled(shader)) { Rect left, right; rect.SplitHorizontallyWithRight(out left, out right, SHADER_WARNING_FIX_WIDTH); EditorGUI.HelpBox(left, "This shader has disabled variants, and will not function until they are enabled.", MessageType.Warning); if (GUI.Button(right, "Enable")) { if (EditorUtility.DisplayDialog("Import Time Warning!", "The import time for this surface shader can take up to 2-3 minutes! Are you sure you want to enable?", "Enable", "Not right now")) { VariantEnabler.SetShaderVariantsEnabled(shader, enable: true); AssetDatabase.Refresh(); } } } } }, () => { Shader shader = shaderProp.objectReferenceValue as Shader; if (VariantEnabler.DoesShaderHaveVariantsDisabled(shader)) { return SHADER_WARNING_HEIGHT; } else { return 0; } }); drawProperty("_shader"); drawProperty("_visualLayer", includeChildren: true, disable: EditorApplication.isPlaying); drawProperty("_atlas", includeChildren: true, disable: EditorApplication.isPlaying); } } } <file_sep>/Assets/IronManUI/Scripts/Editor/ThreeDItemEditor.cs using UnityEngine; using UnityEditor; // namespace IronManUI { // [CustomEditor(typeof(ThreeDItem))] // public class ThreeDItemEditor : Editor { // Vector2 scroll; // public override void OnInspectorGUI() { // DrawDefaultInspector(); // ThreeDItem model = (this.target as ThreeDItem); // GUILayout.BeginHorizontal(); // GUILayout.Label("Model Scaling:"); // float scale = EditorGUILayout.FloatField(model.scale.x); // model.scale.Set(scale, scale, scale); // GUILayout.EndHorizontal(); // GUILayout.Label("Resource Name:"); // model.resourceName = EditorGUILayout.TextField(model.resourceName); // } // } // }<file_sep>/Assets/LeapMotion/Modules/GraphicRenderer/Scripts/Features/BlendShape/Editor/LeapBlendShapeDataDrawer.cs /****************************************************************************** * Copyright (C) Leap Motion, Inc. 2011-2018. * * Leap Motion proprietary and confidential. * * * * Use subject to the terms of the Leap Motion SDK Agreement available at * * https://developer.leapmotion.com/sdk_agreement, or another agreement * * between Leap Motion and you, your company or other organization. * ******************************************************************************/ using UnityEditor; namespace Leap.Unity.GraphicalRenderer { [CustomPropertyDrawer(typeof(LeapBlendShapeData))] public class LeapBlendShapeDataDrawer : CustomPropertyDrawerBase { protected override void init(SerializedProperty property) { base.init(property); drawProperty("_amount"); drawProperty("_type"); var typeProp = property.FindPropertyRelative("_type"); drawConditionalType("_translation", typeProp, LeapBlendShapeData.BlendShapeType.Translation); drawConditionalType("_rotation", typeProp, LeapBlendShapeData.BlendShapeType.Rotation); drawConditionalType("_scale", typeProp, LeapBlendShapeData.BlendShapeType.Scale); drawConditionalType("_transform", typeProp, LeapBlendShapeData.BlendShapeType.Transform); } private void drawConditionalType(string name, SerializedProperty typeProp, LeapBlendShapeData.BlendShapeType type) { drawPropertyConditionally(name, () => { return !typeProp.hasMultipleDifferentValues && typeProp.intValue == (int)type; }); } } } <file_sep>/Assets/IronManUI/Scripts/UI/TextBox.cs /** * Author: <NAME> * Created: 01.18.2019 * * MIT Reality Virtually Hackathon **/ using UnityEngine; using TMPro; using System; namespace IronManUI { [System.Serializable] public class TextBoxModel : IMComponentModel { public string text = "Sample text"; override public void Copy(IMComponentModel o) { var o1 = o as TextBoxModel; if (o1 != null) { text = o1.text; } } } [ExecuteInEditMode] [RequireComponent(typeof(BoxCollider))] public class TextBox : AbstractIMComponent { protected BoxCollider boxCollider; public TextMeshPro textMesh; public TextBoxModel textBoxModel; // public string text; override public IMComponentModel model { get { if (textBoxModel == null) textBoxModel = new TextBoxModel(); return textBoxModel; } } override protected void OnEnable() { base.OnEnable(); boxCollider = GetComponent<BoxCollider>(); textMesh.autoSizeTextContainer = true; } // override public void SetModel(IMComponentModel value) { // base.SetModel(value); // var model = value as TextBoxModel; // if (model != null) // text = model.text; // } // override public IMComponentModel ExtractModel() { // TextBoxModel model = base.ExtractModel() as TextBoxModel; // model.text = text; // return model; // } override protected void Update() { textMesh.text = textBoxModel.text; var bounds = textMesh.bounds; boxCollider.size = new Vector3(bounds.size.x, bounds.size.y, touchThickness); boxCollider.center = bounds.center; base.Update(); } override protected IMComponentModel CreateDefaultModel() { return new TextBoxModel(); } protected override Type GetModelType() { return typeof(TextBoxModel); } } }<file_sep>/Assets/Hover/Core/Scripts/Items/Types/IItemDataSticky.cs namespace Hover.Core.Items.Types { /*================================================================================================*/ public interface IItemDataSticky : IItemDataSelectable { } } <file_sep>/Assets/Hover/Core/Scripts/Layouts/Rect/HoverLayoutRectGroupChild.cs namespace Hover.Core.Layouts.Rect { /*================================================================================================*/ public struct HoverLayoutRectGroupChild { public ILayoutableRect Elem { get; private set; } public HoverLayoutRectRelativeSizer RelSizer { get; private set; } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public HoverLayoutRectGroupChild(ILayoutableRect pElem, HoverLayoutRectRelativeSizer pSizer) { Elem = pElem; RelSizer = pSizer; } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public float RelativeSizeX { get { return (RelSizer == null ? 1 : RelSizer.RelativeSizeX); } } /*--------------------------------------------------------------------------------------------*/ public float RelativeSizeY { get { return (RelSizer == null ? 1 : RelSizer.RelativeSizeY); } } /*--------------------------------------------------------------------------------------------*/ public float RelativePositionOffsetX { get { return (RelSizer == null ? 0 : RelSizer.RelativePositionOffsetX); } } /*--------------------------------------------------------------------------------------------*/ public float RelativePositionOffsetY { get { return (RelSizer == null ? 0 : RelSizer.RelativePositionOffsetY); } } } } <file_sep>/Assets/Hover/RendererModules/Alpha/Scripts/HoverAlphaIdleRendererUpdater.cs using Hover.Core.Renderers; using UnityEngine; namespace Hover.RendererModules.Alpha { /*================================================================================================*/ [RequireComponent(typeof(HoverIndicator))] public class HoverAlphaIdleRendererUpdater : HoverAlphaRendererUpdater { //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public override void TreeUpdate() { HoverIndicator indic = GetComponent<HoverIndicator>(); Controllers.Set(MasterAlphaName, this); MasterAlpha = Mathf.Pow(indic.HighlightProgress, 2); base.TreeUpdate(); } } } <file_sep>/Assets/Hover/Core/Scripts/Items/Types/IItemDataSlider.cs using System; using Hover.Core.Utils; namespace Hover.Core.Items.Types { /*================================================================================================*/ public interface IItemDataSlider : IItemDataSelectable<float> { string LabelFormat { get; } int Ticks { get; } int Snaps { get; } float RangeMin { get; } float RangeMax { get; } Func<IItemDataSlider, string> GetFormattedLabel { get; } bool AllowJump { get; } SliderFillType FillStartingPoint { get; } float RangeValue { get; } float SnappedValue { get; } float SnappedRangeValue { get; } float? HoverValue { get; } float? SnappedHoverValue { get; } } } <file_sep>/Assets/LeapMotion/Modules/GraphicRenderer/Scripts/Features/BlendShape/LeapBlendShapeFeature.cs /****************************************************************************** * Copyright (C) Leap Motion, Inc. 2011-2018. * * Leap Motion proprietary and confidential. * * * * Use subject to the terms of the Leap Motion SDK Agreement available at * * https://developer.leapmotion.com/sdk_agreement, or another agreement * * between Leap Motion and you, your company or other organization. * ******************************************************************************/ using System; using UnityEngine; namespace Leap.Unity.GraphicalRenderer { [LeapGraphicTag("Blend Shape", 40)] [Serializable] public class LeapBlendShapeFeature : LeapGraphicFeature<LeapBlendShapeData> { public const string FEATURE_NAME = LeapGraphicRenderer.FEATURE_PREFIX + "BLEND_SHAPES"; public override SupportInfo GetSupportInfo(LeapGraphicGroup group) { if (!group.renderingMethod.IsValidGraphic<LeapMeshGraphicBase>()) { return SupportInfo.Error("Blend shapes require a renderer that supports mesh graphics."); } else { return SupportInfo.FullSupport(); } } } } <file_sep>/Assets/LeapMotion/Modules/GraphicRenderer/Scripts/Features/Texture/LeapTextureFeature.cs /****************************************************************************** * Copyright (C) Leap Motion, Inc. 2011-2018. * * Leap Motion proprietary and confidential. * * * * Use subject to the terms of the Leap Motion SDK Agreement available at * * https://developer.leapmotion.com/sdk_agreement, or another agreement * * between Leap Motion and you, your company or other organization. * ******************************************************************************/ using System; using UnityEngine; using UnityEngine.Rendering; #if UNITY_EDITOR using UnityEditor; #endif using Leap.Unity.Attributes; namespace Leap.Unity.GraphicalRenderer { [LeapGraphicTag("Texture", 10)] [Serializable] public class LeapTextureFeature : LeapGraphicFeature<LeapTextureData> { [Delayed] [EditTimeOnly] public string propertyName = "_MainTex"; [EditTimeOnly] public UVChannelFlags channel = UVChannelFlags.UV0; } } <file_sep>/Assets/Hover/Core/Scripts/Items/HoverItemData.cs using System; using UnityEngine; using UnityEngine.Events; namespace Hover.Core.Items { /*================================================================================================*/ public abstract class HoverItemData : MonoBehaviour, IItemData { private static int ItemCount; [Serializable] public class EnabledChangedEventHandler : UnityEvent<IItemData> {} public int AutoId { get; internal set; } public bool IsVisible { get; set; } public bool IsAncestryEnabled { get; set; } //TODO: move setter to an "internal" interface public bool IsAncestryVisible { get; set; } //TODO: move setter to an "internal" interface public EnabledChangedEventHandler OnEnabledChangedEvent = new EnabledChangedEventHandler(); public event ItemEvents.EnabledChangedHandler OnEnabledChanged; [SerializeField] private string _Id; [SerializeField] private string _Label; [SerializeField] private bool _IsEnabled = true; //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ protected HoverItemData() { AutoId = ++ItemCount; Id = "Item-"+AutoId; IsAncestryEnabled = true; IsAncestryVisible = true; OnEnabledChanged += (x => { OnEnabledChangedEvent.Invoke(x); }); } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public string Id { get { return _Id; } set { _Id = value; } } /*--------------------------------------------------------------------------------------------*/ public virtual string Label { get { return _Label; } set { _Label = value; } } /*--------------------------------------------------------------------------------------------*/ public bool IsEnabled { get { return _IsEnabled; } set { if ( _IsEnabled == value ) { return; } _IsEnabled = value; OnEnabledChanged(this); } } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public void OnEnable() { OnEnabledChanged(this); //TODO: keep this? } /*--------------------------------------------------------------------------------------------*/ public void OnDisable() { OnEnabledChanged(this); //TODO: keep this? } } } <file_sep>/Assets/Hover/Core/Scripts/Layouts/Arc/HoverLayoutArcPaddingSettings.cs using System; using UnityEngine; namespace Hover.Core.Layouts.Arc { /*================================================================================================*/ [Serializable] public class HoverLayoutArcPaddingSettings { public float OuterRadius = 0; public float InnerRadius = 0; [Range(0, 180)] public float StartDegree = 0; [Range(0, 180)] public float EndDegree = 0; public float Between = 0; //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public void ClampValues(HoverLayoutArcRow pArcRow) { if ( pArcRow.ChildCount <= 0 ) { return; } float radThick = Mathf.Abs(pArcRow.OuterRadius-pArcRow.InnerRadius); ClampValues(pArcRow.ArcDegrees, radThick); Between = Mathf.Clamp(Between, 0, (pArcRow.ArcDegrees-StartDegree-EndDegree)/(pArcRow.ChildCount-1)); } /*--------------------------------------------------------------------------------------------*/ public void ClampValues(HoverLayoutArcStack pArcStack) { if ( pArcStack.ChildCount <= 0 ) { return; } float radThick = Mathf.Abs(pArcStack.OuterRadius-pArcStack.InnerRadius); ClampValues(pArcStack.ArcDegrees, radThick); Between = Mathf.Clamp(Between, 0, (radThick-InnerRadius-OuterRadius)/(pArcStack.ChildCount-1)); } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ private void ClampValues(float pArcDegrees, float pRadiusThickness) { OuterRadius = Mathf.Clamp(OuterRadius, 0, pRadiusThickness-InnerRadius); InnerRadius = Mathf.Clamp(InnerRadius, 0, pRadiusThickness); StartDegree = Mathf.Min(StartDegree, pArcDegrees); EndDegree = Mathf.Min(EndDegree, pArcDegrees-StartDegree); } } } <file_sep>/Assets/Hover/Core/Scripts/Utils/HoverSceneAdjust.cs using UnityEngine; namespace Hover.Core.Utils { /*================================================================================================*/ [ExecuteInEditMode] public abstract class HoverSceneAdjust : MonoBehaviour { private bool vIsComplete; //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public void Awake() { TrySceneUpdates(); } /*--------------------------------------------------------------------------------------------*/ public void Update() { TrySceneUpdates(); } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ private void TrySceneUpdates() { if ( vIsComplete || !IsReadyToAdjust() ) { return; } PerformAdjustments(); vIsComplete = true; //// string completeMsg = GetType().Name+" ('"+name+"') is complete."; if ( Application.isPlaying ) { enabled = false; Debug.Log(completeMsg+" Component disabled for runtime.", this); } else { Debug.Log(completeMsg, this); } } /*--------------------------------------------------------------------------------------------*/ protected void Deactivate(GameObject pObj) { pObj.SetActive(false); } /*--------------------------------------------------------------------------------------------*/ protected void Deactivate(MonoBehaviour pComp) { pComp.gameObject.SetActive(false); } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ protected abstract bool IsReadyToAdjust(); protected abstract void PerformAdjustments(); } } <file_sep>/Assets/Hover/Editor/Utils/TreeUpdaterEditor.cs using Hover.Core.Utils; using UnityEditor; using UnityEngine; namespace Hover.Editor.Utils { /*================================================================================================*/ [CanEditMultipleObjects] [CustomEditor(typeof(TreeUpdater))] public class TreeUpdaterEditor : UnityEditor.Editor { private bool vShowUpdatables; private bool vShowChildren; //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public override void OnInspectorGUI() { TreeUpdater targ = (TreeUpdater)target; int upsCount = targ.TreeUpdatablesThisFrame.Count; int childCount = targ.TreeChildrenThisFrame.Count; DrawDefaultInspector(); GUI.enabled = false; EditorGUILayout.ObjectField("Parent", targ.TreeParentThisFrame, typeof(TreeUpdater), true); EditorGUILayout.IntField("Depth Level", targ.TreeDepthLevelThisFrame); vShowUpdatables = EditorGUILayout.Foldout( vShowUpdatables, "Updatable Components ("+upsCount+")"); for ( int i = 0 ; vShowUpdatables && i < upsCount ; i++ ) { EditorGUILayout.TextField(" Component "+i, targ.gameObject.name+" ("+targ.TreeUpdatablesThisFrame[i].GetType().Name+")"); } vShowChildren = EditorGUILayout.Foldout( vShowChildren, "Children ("+childCount+")"); for ( int i = 0 ; vShowChildren && i < childCount ; i++ ) { EditorGUILayout.ObjectField(" Child "+i, targ.TreeChildrenThisFrame[i], typeof(TreeUpdater), true); } GUI.enabled = true; } } } <file_sep>/Assets/Hover/Core/Scripts/Renderers/Items/Sliders/HoverFillSliderUpdater.cs using System.Collections.Generic; using Hover.Core.Renderers.Shapes; using Hover.Core.Renderers.Utils; using Hover.Core.Utils; using UnityEngine; namespace Hover.Core.Renderers.Items.Sliders { /*================================================================================================*/ [ExecuteInEditMode] [RequireComponent(typeof(HoverFillSlider))] [RequireComponent(typeof(HoverShape))] public abstract class HoverFillSliderUpdater : MonoBehaviour, ITreeUpdateable, ISettingsController { public ISettingsControllerMap Controllers { get; private set; } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ protected HoverFillSliderUpdater() { Controllers = new SettingsControllerMap(); } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public void Start() { //do nothing... } /*--------------------------------------------------------------------------------------------*/ public void TreeUpdate() { UpdateFillMeshes(); UpdateTickMeshes(); Controllers.TryExpireControllers(); } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ protected virtual void UpdateFillMeshes() { HoverFillSlider fillSlider = gameObject.GetComponent<HoverFillSlider>(); if ( fillSlider.SegmentInfo == null ) { return; } List<SliderUtil.SegmentInfo> segInfoList = fillSlider.SegmentInfo.SegmentInfoList; int segCount = HoverFillSlider.SegmentCount; int segIndex = 0; float startPos = segInfoList[0].StartPosition; float endPos = segInfoList[segInfoList.Count-1].EndPosition; for ( int i = 0 ; i < segCount ; i++ ) { ResetFillMesh(fillSlider.GetChildMesh(i)); } for ( int i = 0 ; i < segInfoList.Count ; i++ ) { SliderUtil.SegmentInfo segInfo = segInfoList[i]; if ( segInfo.Type != SliderUtil.SegmentType.Track ) { continue; } UpdateFillMesh(fillSlider.GetChildMesh(segIndex++), segInfo, startPos, endPos); } for ( int i = 0 ; i < segCount ; i++ ) { ActivateFillMesh(fillSlider.GetChildMesh(i)); } } /*--------------------------------------------------------------------------------------------*/ protected abstract void ResetFillMesh(HoverMesh pSegmentMesh); /*--------------------------------------------------------------------------------------------*/ protected abstract void UpdateFillMesh(HoverMesh pSegmentMesh, SliderUtil.SegmentInfo pSegmentInfo, float pStartPos, float pEndPos); /*--------------------------------------------------------------------------------------------*/ protected abstract void ActivateFillMesh(HoverMesh pSegmentMesh); //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ protected virtual void UpdateTickMeshes() { HoverFillSlider fillSlider = gameObject.GetComponent<HoverFillSlider>(); if ( fillSlider.SegmentInfo == null ) { return; } List<SliderUtil.SegmentInfo> tickInfoList = fillSlider.SegmentInfo.TickInfoList; for ( int i = 0 ; i < tickInfoList.Count ; i++ ) { UpdateTickMesh(fillSlider.Ticks[i], tickInfoList[i]); } } /*--------------------------------------------------------------------------------------------*/ protected abstract void UpdateTickMesh(HoverMesh pTickMesh, SliderUtil.SegmentInfo pTickInfo); } } <file_sep>/Assets/Hover/Core/Scripts/Items/IItemData.cs using UnityEngine; namespace Hover.Core.Items { /*================================================================================================*/ public interface IItemData { event ItemEvents.EnabledChangedHandler OnEnabledChanged; GameObject gameObject { get; } int AutoId { get; } string Id { get; } string Label { get; } bool IsEnabled { get; } bool IsVisible { get; } bool IsAncestryEnabled { get; set; } bool IsAncestryVisible { get; set; } } } <file_sep>/Assets/Hover/Core/Scripts/Renderers/CanvasElements/HoverLabel.cs using Hover.Core.Utils; using UnityEngine; using UnityEngine.UI; namespace Hover.Core.Renderers.CanvasElements { /*================================================================================================*/ [ExecuteInEditMode] [RequireComponent(typeof(TreeUpdater))] [RequireComponent(typeof(Text))] public class HoverLabel : MonoBehaviour, ITreeUpdateable { public const string CanvasScaleName = "CanvasScale"; public const string SizeXName = "SizeX"; public const string SizeYName = "SizeY"; public ISettingsControllerMap Controllers { get; private set; } [DisableWhenControlled(RangeMin=0.0001f, RangeMax=1, DisplaySpecials=true)] public float CanvasScale = 0.0002f; [DisableWhenControlled(RangeMin=0)] public float SizeX = 0.1f; [DisableWhenControlled(RangeMin=0)] public float SizeY = 0.1f; [HideInInspector] [SerializeField] private bool _IsBuilt; //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public HoverLabel() { Controllers = new SettingsControllerMap(); } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public Text TextComponent { get { return GetComponent<Text>(); } } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public void Awake() { if ( !_IsBuilt ) { BuildText(); _IsBuilt = true; } } /*--------------------------------------------------------------------------------------------*/ public virtual void Start() { //do nothing... } /*--------------------------------------------------------------------------------------------*/ public void TreeUpdate() { RectTransform rectTx = TextComponent.rectTransform; rectTx.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, SizeX/CanvasScale); rectTx.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, SizeY/CanvasScale); Controllers.TryExpireControllers(); } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ private void BuildText() { Text text = TextComponent; text.text = "Label"; text.font = Resources.Load<Font>("Fonts/Tahoma"); text.fontSize = 40; text.lineSpacing = 0.75f; text.color = Color.white; text.alignment = TextAnchor.MiddleCenter; text.raycastTarget = false; text.horizontalOverflow = HorizontalWrapMode.Wrap; text.verticalOverflow = VerticalWrapMode.Overflow; } } } <file_sep>/Assets/Hover/Core/Scripts/Renderers/Items/Buttons/HoverRendererButton.cs using System; using Hover.Core.Renderers.CanvasElements; using Hover.Core.Renderers.Shapes; using Hover.Core.Utils; using UnityEngine; namespace Hover.Core.Renderers.Items.Buttons { /*================================================================================================*/ public class HoverRendererButton : HoverRenderer { [DisableWhenControlled] public HoverFillButton Fill; [DisableWhenControlled] public HoverCanvas Canvas; //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public override int GetChildFillCount() { return 1; } /*--------------------------------------------------------------------------------------------*/ public override HoverFill GetChildFill(int pIndex) { switch ( pIndex ) { case 0: return Fill; } throw new ArgumentOutOfRangeException(); } /*--------------------------------------------------------------------------------------------*/ public override int GetChildRendererCount() { return 0; } /*--------------------------------------------------------------------------------------------*/ public override HoverRenderer GetChildRenderer(int pIndex) { throw new ArgumentOutOfRangeException(); } /*--------------------------------------------------------------------------------------------*/ public override HoverCanvas GetCanvas() { return Canvas; } /*--------------------------------------------------------------------------------------------*/ public override HoverCanvasDataUpdater GetCanvasDataUpdater() { return Canvas.GetComponent<HoverCanvasDataUpdater>(); } /*--------------------------------------------------------------------------------------------*/ public override Vector3 GetCenterWorldPosition() { return GetComponent<HoverShape>().GetCenterWorldPosition(); } /*--------------------------------------------------------------------------------------------*/ public override Vector3 GetNearestWorldPosition(Vector3 pFromWorldPosition) { return GetComponent<HoverShape>().GetNearestWorldPosition(pFromWorldPosition); } /*--------------------------------------------------------------------------------------------*/ public override Vector3 GetNearestWorldPosition(Ray pFromWorldRay, out RaycastResult pRaycast) { return GetComponent<HoverShape>().GetNearestWorldPosition(pFromWorldRay, out pRaycast); } } } <file_sep>/Assets/Hover/Core/Scripts/Items/Helpers/HoverRendererProximityDebugger.cs using Hover.Core.Items.Managers; using Hover.Core.Utils; using UnityEngine; namespace Hover.Core.Items.Helpers { /*================================================================================================*/ [ExecuteInEditMode] [RequireComponent(typeof(HoverItemRendererUpdater))] [RequireComponent(typeof(HoverItemHighlightState))] public class HoverRendererProximityDebugger : MonoBehaviour, ITreeUpdateable { public Color ZeroColor = new Color(1, 0, 0, 0.2f); public Color NearColor = new Color(1, 1, 0, 0.2f); public Color FarColor = new Color(1, 1, 0, 0.8f); public Color FullColor = new Color(0.3f, 1, 0.4f, 1); //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public virtual void Start() { //do nothing... } /*--------------------------------------------------------------------------------------------*/ public virtual void TreeUpdate() { DrawProximityDebugLines(); } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ private void DrawProximityDebugLines() { if ( !Application.isPlaying ) { return; } HoverItemHighlightState.Highlight? nearHigh = GetComponent<HoverItemHighlightState>().NearestHighlight; if ( nearHigh == null ) { return; } Vector3 cursorPos = nearHigh.Value.Cursor.WorldPosition; Vector3 nearPos = nearHigh.Value.NearestWorldPos; float prog = nearHigh.Value.Progress; Color color = ZeroColor; if ( prog >= 1 ) { color = FullColor; } else if ( prog > 0 ) { color = Color.Lerp(NearColor, FarColor, prog); } Debug.DrawLine(nearPos, cursorPos, color); } } } <file_sep>/Assets/LeapMotion/Modules/GraphicRenderer/Scripts/Utility/MeshUtil.cs /****************************************************************************** * Copyright (C) Leap Motion, Inc. 2011-2018. * * Leap Motion proprietary and confidential. * * * * Use subject to the terms of the Leap Motion SDK Agreement available at * * https://developer.leapmotion.com/sdk_agreement, or another agreement * * between Leap Motion and you, your company or other organization. * ******************************************************************************/ using System; using System.Collections.Generic; using UnityEngine; using UnityEngine.Rendering; using Leap.Unity.Query; namespace Leap.Unity.GraphicalRenderer { public static class MeshUtil { public const int MAX_VERT_COUNT = 65535; public static List<UVChannelFlags> allUvChannels; static MeshUtil() { allUvChannels = new List<UVChannelFlags>(); allUvChannels.Add(UVChannelFlags.UV0); allUvChannels.Add(UVChannelFlags.UV1); allUvChannels.Add(UVChannelFlags.UV2); allUvChannels.Add(UVChannelFlags.UV3); } public static void RemapUvs(List<Vector4> uvs, Rect mapping) { RemapUvs(uvs, mapping, uvs.Count); } public static void RemapUvs(List<Vector4> uvs, Rect mapping, int lastCount) { for (int i = uvs.Count - lastCount; i < uvs.Count; i++) { Vector4 uv = uvs[i]; uv.x = mapping.x + uv.x * mapping.width; uv.y = mapping.y + uv.y * mapping.height; uvs[i] = uv; } } public static int Index(this UVChannelFlags flags) { switch (flags) { case UVChannelFlags.UV0: return 0; case UVChannelFlags.UV1: return 1; case UVChannelFlags.UV2: return 2; case UVChannelFlags.UV3: return 3; } throw new InvalidOperationException(); } } } <file_sep>/Assets/Hover/RendererModules/Alpha/Scripts/HoverAlphaFillUpdater.cs using Hover.Core.Renderers; using Hover.Core.Utils; using UnityEngine; namespace Hover.RendererModules.Alpha { /*================================================================================================*/ [ExecuteInEditMode] [RequireComponent(typeof(HoverFill))] public class HoverAlphaFillUpdater : MonoBehaviour, ITreeUpdateable, ISettingsController { public const string SortingLayerName = "SortingLayer"; public const string AlphaName = "Alpha"; public ISettingsControllerMap Controllers { get; private set; } [DisableWhenControlled(DisplaySpecials=true)] public string SortingLayer = "Default"; [DisableWhenControlled(RangeMin=0, RangeMax=1)] public float Alpha = 1; //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ protected HoverAlphaFillUpdater() { Controllers = new SettingsControllerMap(); } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public void Start() { //do nothing... } /*--------------------------------------------------------------------------------------------*/ public void TreeUpdate() { HoverFill hoverFill = GetComponent<HoverFill>(); int meshCount = hoverFill.GetChildMeshCount(); for ( int i = 0 ; i < meshCount ; i++ ) { UpdateChildMesh(hoverFill.GetChildMesh(i)); } Controllers.TryExpireControllers(); } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ private void UpdateChildMesh(HoverMesh pChildMesh) { HoverAlphaMeshUpdater meshUp = pChildMesh.GetComponent<HoverAlphaMeshUpdater>(); if ( meshUp == null ) { return; } meshUp.Controllers.Set(HoverAlphaMeshUpdater.SortingLayerName, this); meshUp.Controllers.Set(HoverAlphaMeshUpdater.AlphaName, this); meshUp.SortingLayer = SortingLayer; meshUp.Alpha = Alpha; } } } <file_sep>/Assets/Hover/Core/Scripts/Utils/HoverSceneLoader.cs using System; using UnityEngine; using UnityEngine.Events; using UnityEngine.SceneManagement; namespace Hover.Core.Utils { /*================================================================================================*/ [ExecuteInEditMode] public class HoverSceneLoader : MonoBehaviour { [Serializable] public class SceneLoadedEventHandler : UnityEvent<HoverSceneLoader> {} public string SceneFolderPath = "Hover/InputModules/NAME/Scenes/"; public string SceneName = "HoverInputModule-NAME"; [Header("Disable this setting when creating builds!")] public bool AutoLoadInEditor = false; public SceneLoadedEventHandler OnSceneLoadedEvent; [TriggerButton("Reload Scene")] public bool ClickToReloadScene; private Scene? vLoadedScene; //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public void Awake() { if ( Application.isPlaying || AutoLoadInEditor ) { //StartCoroutine(LoadWhenReady()); LoadScene(); } } /*--------------------------------------------------------------------------------------------*/ public void OnDestroy() { #if UNITY_EDITOR if ( !Application.isPlaying || vLoadedScene == null ) { return; } SceneManager.UnloadSceneAsync(SceneName); Debug.Log("Removing scene for editor: "+SceneName); #endif } /*--------------------------------------------------------------------------------------------*/ public void OnEditorTriggerButtonSelected() { LoadScene(); } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------* / private IEnumerator LoadWhenReady() { yield return new WaitUntil(() => { int sceneCount = SceneManager.sceneCount; #if UNITY_EDITOR sceneCount = UnityEditor.SceneManagement.EditorSceneManager.loadedSceneCount+1; #endif Debug.Log("TRY LOAD SCENE: "+name+"... "+sceneCount+" >= "+LoadAfterSceneCount); return (sceneCount >= LoadAfterSceneCount); }); LoadScene(); } /*--------------------------------------------------------------------------------------------*/ private void LoadScene() { if ( !Application.isPlaying ) { LoadSceneForNonplayingEditor(); return; } LoadSceneForRuntime(); } /*--------------------------------------------------------------------------------------------*/ private void LoadSceneForNonplayingEditor() { #if UNITY_EDITOR string fullPath = Application.dataPath+"/"+SceneFolderPath+SceneName+".unity"; vLoadedScene = UnityEditor.SceneManagement.EditorSceneManager.OpenScene( fullPath, UnityEditor.SceneManagement.OpenSceneMode.Additive); Debug.Log("Loaded scene for editor: "+fullPath, this); OnSceneLoadedEvent.Invoke(this); #endif } /*--------------------------------------------------------------------------------------------*/ private void LoadSceneForRuntime() { if ( SceneManager.GetSceneByName(SceneName).IsValid() ) { Debug.Log("Scene already loaded: "+SceneName, this); return; } string scenePathAndName = SceneFolderPath+SceneName; if ( SceneManager.GetSceneByName(scenePathAndName).IsValid() ) { Debug.Log("Scene already loaded: "+scenePathAndName, this); return; } SceneManager.LoadScene(scenePathAndName, LoadSceneMode.Additive); vLoadedScene = SceneManager.GetSceneByName(scenePathAndName); Debug.Log("Loaded scene: "+scenePathAndName, this); OnSceneLoadedEvent.Invoke(this); } } } <file_sep>/Assets/Hover/InputModules/Follow/Scripts/HoverInputFollow.cs using Hover.Core.Cursors; using UnityEngine; namespace Hover.InputModules.Follow { /*================================================================================================*/ [ExecuteInEditMode] public class HoverInputFollow : MonoBehaviour { public HoverCursorDataProvider CursorDataProvider; [Space(12)] public FollowCursor Look = new FollowCursor(CursorType.Look); [Space(12)] public FollowCursor LeftPalm = new FollowCursor(CursorType.LeftPalm); public FollowCursor LeftThumb = new FollowCursor(CursorType.LeftThumb); public FollowCursor LeftIndex = new FollowCursor(CursorType.LeftIndex); public FollowCursor LeftMiddle = new FollowCursor(CursorType.LeftMiddle); public FollowCursor LeftRing = new FollowCursor(CursorType.LeftRing); public FollowCursor LeftPinky = new FollowCursor(CursorType.LeftPinky); [Space(12)] public FollowCursor RightPalm = new FollowCursor(CursorType.RightPalm); public FollowCursor RightThumb = new FollowCursor(CursorType.RightThumb); public FollowCursor RightIndex = new FollowCursor(CursorType.RightIndex); public FollowCursor RightMiddle = new FollowCursor(CursorType.RightMiddle); public FollowCursor RightRing = new FollowCursor(CursorType.RightRing); public FollowCursor RightPinky = new FollowCursor(CursorType.RightPinky); //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public void Awake() { CursorUtil.FindCursorReference(this, ref CursorDataProvider, false); if ( Look.FollowTransform == null ) { Look.FollowTransform = Camera.main.transform; } } /*--------------------------------------------------------------------------------------------*/ public void Update() { if ( !CursorUtil.FindCursorReference(this, ref CursorDataProvider, true) ) { return; } if ( !Application.isPlaying ) { return; } CursorDataProvider.MarkAllCursorsUnused(); Look.UpdateData(CursorDataProvider); LeftPalm.UpdateData(CursorDataProvider); LeftThumb.UpdateData(CursorDataProvider); LeftIndex.UpdateData(CursorDataProvider); LeftMiddle.UpdateData(CursorDataProvider); LeftRing.UpdateData(CursorDataProvider); LeftPinky.UpdateData(CursorDataProvider); RightPalm.UpdateData(CursorDataProvider); RightThumb.UpdateData(CursorDataProvider); RightIndex.UpdateData(CursorDataProvider); RightMiddle.UpdateData(CursorDataProvider); RightRing.UpdateData(CursorDataProvider); RightPinky.UpdateData(CursorDataProvider); CursorDataProvider.ActivateAllCursorsBasedOnUsage(); } } } <file_sep>/Assets/IronManUI/Scripts/UI/IMComponentMenuHandler.cs /** * Author: <NAME>, <NAME> * Created: 01.20.2019 * * MIT Reality Virtually Hackathon **/ using UnityEngine; namespace IronManUI { public class IMComponentMenuHandler { public readonly AbstractIMComponent component; public IMComponentMenuHandler(AbstractIMComponent parent) { this.component = parent; } public void Update() { } public void CheckShouldTrash() { } public void AddToCurrentScene() { var newParent = PresentationManager.instance.currentSlide; if (newParent != null) component.transform.parent = newParent.transform; } public void RemoveFromCurrentScene() { var parentSlide = component.GetComponentInParent<Slide>(); if (parentSlide != null) { } } } } <file_sep>/Assets/IronManUI/Scripts/Util/IMExtensions.cs using UnityEngine; using TMPro; using System.Collections.Generic; namespace IronManUI { public static class IMExtensions { public static AbstractIMComponent GetIronManComponent(this Collider collider) { return collider.gameObject.GetComponent<AbstractIMComponent>(); } public static AbstractIMComponent GetIronManComponent(this Collision collision) { return collision.gameObject.GetComponent<AbstractIMComponent>(); } public static void DestroyAllGameObjects<T>(this T[] toDestroy) where T : Object { foreach (var o in toDestroy) Object.Destroy(o); } public static void DestroyChildren(this GameObject o) { var t = o.transform; bool editMode = Application.isEditor && !Application.isPlaying; int count = t.childCount; for (int i=0; i<count; i++) { var child = t.GetChild(i).gameObject; // child.transform.parent = null; if (editMode) Object.DestroyImmediate(child); else Object.Destroy(child.gameObject); } } //TODO Needs TLC public static Bounds GetBounds(this GameObject o) { Bounds bounds = new Bounds(); int i = 0; foreach (var renderer in o.GetComponentsInChildren<MeshRenderer>()) { if (i++ == 0) bounds = renderer.bounds; else bounds.Encapsulate(renderer.bounds); } foreach (var renderer in o.GetComponentsInChildren<TextMeshPro>()) { if (i++ == 0) bounds = renderer.bounds; else bounds.Encapsulate(renderer.bounds); } return bounds; } public static Vector3 MinValue(this Vector3 v, float min) { var outV = v; if (outV.x < min) outV.x = min; if (outV.y < min) outV.y = min; if (outV.z < min) outV.z = min; return outV; } } }<file_sep>/Assets/Hover/Editor/Utils/TriggerButtonPropertyDrawer.cs using Hover.Core.Utils; using UnityEditor; using UnityEngine; namespace Hover.Editor.Utils { /*================================================================================================*/ [CustomPropertyDrawer(typeof(TriggerButtonAttribute))] public class TriggerButtonPropertyDrawer : PropertyDrawer { //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public override void OnGUI(Rect pPosition, SerializedProperty pProp, GUIContent pLabel) { TriggerButtonAttribute attrib = (TriggerButtonAttribute)attribute; string methodName = attrib.OnSelectedMethodName; SerializedObject self = pProp.serializedObject; pPosition.x += pPosition.width*0.03f; pPosition.y += pPosition.height*0.2f; pPosition.width *= 0.94f; pPosition.height *= 0.6f; if ( GUI.Button(pPosition, attrib.ButtonLabel) ) { pProp.boolValue = true; EditorUtil.CallMethod(self, methodName); } } /*--------------------------------------------------------------------------------------------*/ public override float GetPropertyHeight(SerializedProperty pProp, GUIContent pLabel) { return base.GetPropertyHeight(pProp, pLabel)*3; } } } <file_sep>/Assets/LeapMotion/Modules/GraphicRenderer/Scripts/RenderingMethods/LeapDynamicRenderer.cs /****************************************************************************** * Copyright (C) Leap Motion, Inc. 2011-2018. * * Leap Motion proprietary and confidential. * * * * Use subject to the terms of the Leap Motion SDK Agreement available at * * https://developer.leapmotion.com/sdk_agreement, or another agreement * * between Leap Motion and you, your company or other organization. * ******************************************************************************/ using System; using System.Collections.Generic; using UnityEngine; using UnityEngine.Assertions; using Leap.Unity.Space; namespace Leap.Unity.GraphicalRenderer { [LeapGraphicTag("Dynamic")] [Serializable] public class LeapDynamicRenderer : LeapMesherBase, ISupportsAddRemove { public const string DEFAULT_SHADER = "LeapMotion/GraphicRenderer/Unlit/Dynamic Transparent"; #region PRIVATE VARIABLES //Curved space private const string CURVED_PARAMETERS = LeapGraphicRenderer.PROPERTY_PREFIX + "Curved_GraphicParameters"; private List<Matrix4x4> _curved_worldToAnchor = new List<Matrix4x4>(); private List<Vector4> _curved_graphicParameters = new List<Vector4>(); #endregion public void OnAddRemoveGraphics(List<int> dirtyIndexes) { MeshCache.Clear(); while (_meshes.Count > group.graphics.Count) { _meshes.RemoveMesh(_meshes.Count - 1); } while (_meshes.Count < group.graphics.Count) { beginMesh(); _generation.graphic = group.graphics[_meshes.Count] as LeapMeshGraphicBase; _generation.graphicIndex = _meshes.Count; _generation.graphicId = _meshes.Count; base.buildGraphic(); finishAndAddMesh(); } foreach (var dirtyIndex in dirtyIndexes) { beginMesh(_meshes[dirtyIndex]); _generation.graphic = group.graphics[dirtyIndex] as LeapMeshGraphicBase; _generation.graphicIndex = dirtyIndex; _generation.graphicId = dirtyIndex; base.buildGraphic(); finishMesh(); _generation.mesh = null; } prepareMaterial(); } public override SupportInfo GetSpaceSupportInfo(LeapSpace space) { if (space == null || space is LeapCylindricalSpace || space is LeapSphericalSpace) { return SupportInfo.FullSupport(); } else { return SupportInfo.Error("Dynamic Renderer does not support " + space.GetType().Name); } } public override void OnUpdateRenderer() { using (new ProfilerSample("Update Dynamic Renderer")) { base.OnUpdateRenderer(); using (new ProfilerSample("Check For Dirty Graphics")) { for (int i = 0; i < group.graphics.Count; i++) { var graphic = group.graphics[i]; if (graphic.isRepresentationDirty || _meshes[i] == null) { MeshCache.Clear(); beginMesh(_meshes[i]); _generation.graphic = graphic as LeapMeshGraphicBase; _generation.graphicIndex = i; _generation.graphicId = i; base.buildGraphic(); finishMesh(); _meshes[i] = _generation.mesh; _generation.mesh = null; graphic.isRepresentationDirty = false; } } } if (renderer.space == null) { using (new ProfilerSample("Draw Meshes")) { Assert.AreEqual(group.graphics.Count, _meshes.Count); for (int i = 0; i < group.graphics.Count; i++) { if (!group.graphics[i].isActiveAndEnabled) { continue; } drawMesh(_meshes[i], group.graphics[i].transform.localToWorldMatrix); } } } else if (renderer.space is LeapRadialSpace) { var curvedSpace = renderer.space as LeapRadialSpace; using (new ProfilerSample("Build Material Data And Draw Meshes")) { _curved_worldToAnchor.Clear(); _curved_graphicParameters.Clear(); for (int i = 0; i < _meshes.Count; i++) { var graphic = group.graphics[i]; if (!graphic.isActiveAndEnabled) { _curved_graphicParameters.Add(Vector4.zero); _curved_worldToAnchor.Add(Matrix4x4.identity); continue; } var transformer = graphic.anchor.transformer; Vector3 localPos = renderer.transform.InverseTransformPoint(graphic.transform.position); Matrix4x4 mainTransform = renderer.transform.localToWorldMatrix * transformer.GetTransformationMatrix(localPos); Matrix4x4 deform = renderer.transform.worldToLocalMatrix * Matrix4x4.TRS(renderer.transform.position - graphic.transform.position, Quaternion.identity, Vector3.one) * graphic.transform.localToWorldMatrix; Matrix4x4 total = mainTransform * deform; _curved_graphicParameters.Add((transformer as IRadialTransformer).GetVectorRepresentation(graphic.transform)); _curved_worldToAnchor.Add(mainTransform.inverse); //Safe to do this before we upload material data //meshes are drawn at end of frame anyway! drawMesh(_meshes[i], total); } } using (new ProfilerSample("Upload Material Data")) { _material.SetFloat(SpaceProperties.RADIAL_SPACE_RADIUS, curvedSpace.radius); _material.SetMatrixArraySafe("_GraphicRendererCurved_WorldToAnchor", _curved_worldToAnchor); _material.SetMatrix("_GraphicRenderer_LocalToWorld", renderer.transform.localToWorldMatrix); _material.SetVectorArraySafe("_GraphicRendererCurved_GraphicParameters", _curved_graphicParameters); } } } } #if UNITY_EDITOR public override void OnEnableRendererEditor() { base.OnEnableRendererEditor(); _shader = Shader.Find(DEFAULT_SHADER); } #endif protected override void prepareMaterial() { if (_shader == null) { _shader = Shader.Find(DEFAULT_SHADER); } base.prepareMaterial(); if (renderer.space != null) { if (renderer.space is LeapCylindricalSpace) { _material.EnableKeyword(SpaceProperties.CYLINDRICAL_FEATURE); } else if (renderer.space is LeapSphericalSpace) { _material.EnableKeyword(SpaceProperties.SPHERICAL_FEATURE); } } } protected override void buildGraphic() { //Always start a new mesh for each graphic if (!_generation.isGenerating) { beginMesh(); } base.buildGraphic(); finishAndAddMesh(deleteEmptyMeshes: false); } protected override bool doesRequireVertInfo() { return true; } protected override Vector3 graphicVertToMeshVert(Vector3 vertex) { return vertex; } protected override void graphicVertNormalToMeshVertNormal(Vector3 vertex, Vector3 normal, out Vector3 meshVert, out Vector3 meshNormal) { meshVert = vertex; meshNormal = normal; } protected override Vector3 blendShapeDelta(Vector3 shapeVert, Vector3 originalVert) { return shapeVert - originalVert; } } } <file_sep>/Assets/Hover/Core/Scripts/Cursors/HoverCursorFollower.cs using Hover.Core.Utils; using UnityEngine; namespace Hover.Core.Cursors { /*================================================================================================*/ [ExecuteInEditMode] public class HoverCursorFollower : MonoBehaviour, ISettingsController { public ISettingsControllerMap Controllers { get; private set; } [DisableWhenControlled(DisplaySpecials=true)] public HoverCursorDataProvider CursorDataProvider; [DisableWhenControlled] public CursorType CursorType = CursorType.LeftPalm; [DisableWhenControlled] public bool FollowCursorActive = true; public GameObject[] ObjectsToActivate; //should not include self or parent [DisableWhenControlled] public bool FollowCursorPosition = true; [DisableWhenControlled] public bool FollowCursorRotation = true; [DisableWhenControlled] public bool ScaleUsingCursorSize = false; [DisableWhenControlled] public float CursorSizeMultiplier = 1; //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public HoverCursorFollower() { Controllers = new SettingsControllerMap(); } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public ICursorData GetCursorData() { return CursorDataProvider.GetCursorData(CursorType); } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public void Awake() { if ( CursorDataProvider == null ) { CursorDataProvider = FindObjectOfType<HoverCursorDataProvider>(); } } /*--------------------------------------------------------------------------------------------*/ public void Update() { Controllers.TryExpireControllers(); if ( CursorDataProvider == null ) { Debug.LogError("Reference to "+typeof(HoverCursorDataProvider).Name+ " must be set.", this); return; } ICursorData cursor = GetCursorData(); RaycastResult? raycast = cursor.BestRaycastResult; Transform tx = gameObject.transform; if ( FollowCursorActive ) { foreach ( GameObject go in ObjectsToActivate ) { if ( go == null ) { continue; } go.SetActive(cursor.IsActive); } } if ( FollowCursorPosition ) { Controllers.Set(SettingsControllerMap.TransformPosition, this, 0); tx.position = (raycast == null ? cursor.WorldPosition : raycast.Value.WorldPosition); } if ( FollowCursorRotation ) { Controllers.Set(SettingsControllerMap.TransformRotation, this, 0); if ( raycast == null ) { tx.rotation = cursor.WorldRotation; } else { RaycastResult rc = raycast.Value; Vector3 perpDir = (cursor.RaycastLocalDirection == Vector3.up ? Vector3.right : Vector3.up); //TODO: does this work in all cases? Vector3 castUpPos = rc.WorldPosition + rc.WorldRotation*perpDir; Vector3 cursorUpPos = rc.WorldPosition + cursor.WorldRotation*perpDir; float upToPlaneDist = rc.WorldPlane.GetDistanceToPoint(cursorUpPos); Vector3 cursorUpOnPlanePos = cursorUpPos - rc.WorldPlane.normal*upToPlaneDist; Quaternion invCastRot = Quaternion.Inverse(rc.WorldRotation); Vector3 fromLocalVec = invCastRot*(castUpPos-rc.WorldPosition); Vector3 toLocalVec = invCastRot*(cursorUpOnPlanePos-rc.WorldPosition); Quaternion applyRot = Quaternion.FromToRotation(fromLocalVec, toLocalVec); //Debug.DrawLine(rc.WorldPosition, castUpPos, Color.red); //Debug.DrawLine(rc.WorldPosition, cursorUpOnPlanePos, Color.blue); tx.rotation = rc.WorldRotation*applyRot; } } if ( ScaleUsingCursorSize ) { Controllers.Set(SettingsControllerMap.TransformLocalScale, this, 0); tx.localScale = Vector3.one*(cursor.Size*CursorSizeMultiplier); } } } } <file_sep>/Assets/Hover/Core/Scripts/Items/Managers/HoverItemsRadioManager.cs using System; using System.Collections.Generic; using Hover.Core.Items.Types; using UnityEngine; namespace Hover.Core.Items.Managers { /*================================================================================================*/ [RequireComponent(typeof(HoverItemsManager))] public class HoverItemsRadioManager : MonoBehaviour { private List<HoverItem> vItemsBuffer; //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public void Awake() { vItemsBuffer = new List<HoverItem>(); HoverItemsManager itemsMan = GetComponent<HoverItemsManager>(); itemsMan.OnItemListInitialized.AddListener(AddAllItemListeners); itemsMan.OnItemAdded.AddListener(AddItemListeners); itemsMan.OnItemRemoved.AddListener(RemoveItemListeners); } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ private void AddAllItemListeners() { HoverItemsManager itemsMan = GetComponent<HoverItemsManager>(); itemsMan.FillListWithAllItems(vItemsBuffer); for ( int i = 0 ; i < vItemsBuffer.Count ; i++ ) { AddItemListeners(vItemsBuffer[i]); } } /*--------------------------------------------------------------------------------------------*/ private void AddItemListeners(HoverItem pItem) { AddRadioDataListeners(pItem); pItem.OnTypeChanged += AddRadioDataListeners; } /*--------------------------------------------------------------------------------------------*/ private void RemoveItemListeners(HoverItem pItem) { pItem.OnTypeChanged -= AddRadioDataListeners; RemoveRadioDataListeners(pItem); } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ private void AddRadioDataListeners(HoverItem pItem) { IItemDataRadio radData = (pItem.Data as IItemDataRadio); if ( radData != null ) { radData.OnValueChanged += HandleRadioValueChanged; } } /*--------------------------------------------------------------------------------------------*/ private void RemoveRadioDataListeners(HoverItem pItem) { IItemDataRadio radData = (pItem.Data as IItemDataRadio); if ( radData != null ) { radData.OnValueChanged -= HandleRadioValueChanged; } } /*--------------------------------------------------------------------------------------------*/ private void HandleRadioValueChanged(IItemDataSelectable<bool> pSelData) { IItemDataRadio radData = (IItemDataRadio)pSelData; if ( !radData.Value ) { return; } DeselectRemainingRadioGroupMembers(radData); } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ private void DeselectRemainingRadioGroupMembers(IItemDataRadio pRadioData) { HoverItemsManager itemsMan = GetComponent<HoverItemsManager>(); string groupId = pRadioData.GroupId; Func<HoverItem, bool> filter = (tryItem => { IItemDataRadio match = (tryItem.Data as IItemDataRadio); return (match != null && match != pRadioData && match.GroupId == groupId); }); itemsMan.FillListWithMatchingItems(vItemsBuffer, filter); for ( int i = 0 ; i < vItemsBuffer.Count ; i++ ) { ((IItemDataRadio)vItemsBuffer[i].Data).Value = false; } } } } <file_sep>/Assets/Hover/Core/Scripts/Cursors/HoverInteractionSettings.cs using UnityEngine; namespace Hover.Core.Cursors { /*================================================================================================*/ [ExecuteInEditMode] public class HoverInteractionSettings : MonoBehaviour, IInteractionSettings { [SerializeField] private float _HighlightDistanceMin = 0.03f; [SerializeField] private float _HighlightDistanceMax = 0.07f; [SerializeField] private float _StickyReleaseDistance = 0.05f; [SerializeField] [Range(1, 10000)] private float _SelectionMilliseconds = 400; [SerializeField] private float _IdleDistanceThreshold = 0.004f; [SerializeField] [Range(1, 10000)] private float _IdleMilliseconds = 1000; //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public float HighlightDistanceMin { get { return _HighlightDistanceMin; } set { _HighlightDistanceMin = value; } } /*--------------------------------------------------------------------------------------------*/ public float HighlightDistanceMax { get { return _HighlightDistanceMax; } set { _HighlightDistanceMax = value; } } /*--------------------------------------------------------------------------------------------*/ public float StickyReleaseDistance { get { return _StickyReleaseDistance; } set { _StickyReleaseDistance = value; } } /*--------------------------------------------------------------------------------------------*/ public float SelectionMilliseconds { get { return _SelectionMilliseconds; } set { _SelectionMilliseconds = value; } } /*--------------------------------------------------------------------------------------------*/ public float IdleDistanceThreshold { get { return _IdleDistanceThreshold; } set { _IdleDistanceThreshold = value; } } /*--------------------------------------------------------------------------------------------*/ public float IdleMilliseconds { get { return _IdleMilliseconds; } set { _IdleMilliseconds = value; } } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public void Update() { _HighlightDistanceMin = Mathf.Max(_HighlightDistanceMin, 0.0001f); _HighlightDistanceMax = Mathf.Max(_HighlightDistanceMax, _HighlightDistanceMin*1.01f); _StickyReleaseDistance = Mathf.Max(_StickyReleaseDistance, 0.0001f); _IdleDistanceThreshold = Mathf.Max(_IdleDistanceThreshold, 0); } } } <file_sep>/Assets/Hover/Core/Scripts/Items/ItemEvents.cs using Hover.Core.Items.Types; namespace Hover.Core.Items { /*================================================================================================*/ public static class ItemEvents { public delegate void EnabledChangedHandler(IItemData pItem); public delegate void SelectedHandler(IItemDataSelectable pItem); public delegate void DeselectedHandler(IItemDataSelectable pItem); public delegate void ValueChangedHandler<T>(IItemDataSelectable<T> pItem); } } <file_sep>/Assets/Hover/Core/Scripts/Items/SelectorActionType.cs namespace Hover.Core.Items { /*================================================================================================*/ public enum SelectorActionType { Default, NavigateIn, NavigateOut } } <file_sep>/Assets/Hover/Core/Scripts/Renderers/Shapes/HoverShape.cs using Hover.Core.Utils; using UnityEngine; namespace Hover.Core.Renderers.Shapes { /*================================================================================================*/ [ExecuteInEditMode] [RequireComponent(typeof(TreeUpdater))] public abstract class HoverShape : MonoBehaviour, ITreeUpdateable, ISettingsController { public ISettingsControllerMap Controllers { get; private set; } public bool DidSettingsChange { get; protected set; } [DisableWhenControlled(DisplaySpecials=true)] public bool ControlChildShapes = true; //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ protected HoverShape() { Controllers = new SettingsControllerMap(); } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public abstract Vector3 GetCenterWorldPosition(); /*--------------------------------------------------------------------------------------------*/ public abstract Vector3 GetNearestWorldPosition(Vector3 pFromWorldPosition); /*--------------------------------------------------------------------------------------------*/ public abstract Vector3 GetNearestWorldPosition(Ray pFromWorldRay, out RaycastResult pRaycast); /*--------------------------------------------------------------------------------------------*/ public abstract float GetSliderValueViaNearestWorldPosition(Vector3 pNearestWorldPosition, Transform pSliderContainerTx, HoverShape pHandleButtonShape); //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public virtual void Start() { //do nothing... } /*--------------------------------------------------------------------------------------------*/ public virtual void TreeUpdate() { DidSettingsChange = false; Controllers.TryExpireControllers(); } } } <file_sep>/Assets/PolyToolkit/Internal/ThumbnailFetcher.cs // Copyright 2017 Google Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using PolyToolkit; using UnityEngine; using UnityEngine.Networking; namespace PolyToolkitInternal { /// <summary> /// Fetches and converts a thumbnail for a particular given asset. /// </summary> public class ThumbnailFetcher { /// <summary> /// Maximum cache age for thumbnails of immutable assets. /// </summary> private const long CACHE_MAX_AGE_MILLIS = 14 * 24 * 60 * 60 * 1000L; // A fortnight. private const int MIN_REQUESTED_SIZE = 32; private const int MAX_REQUESTED_SIZE = 512; private PolyAsset asset; private PolyFetchThumbnailOptions options; private PolyApi.FetchThumbnailCallback callback; /// <summary> /// Builds a ThumbnailFetcher that will fetch the thumbnail for the given asset /// and call the given callback when done. Building this object doesn't immediately /// start the fetch. To start, call Fetch(). /// </summary> /// <param name="asset">The asset to fetch the thumbnail for.</param> /// <param name="callback">The callback to call when done. Can be null.</param> public ThumbnailFetcher(PolyAsset asset, PolyFetchThumbnailOptions options, PolyApi.FetchThumbnailCallback callback) { this.asset = asset; this.options = options ?? new PolyFetchThumbnailOptions(); this.callback = callback; } /// <summary> /// Starts fetching the thumbnail (in the background). /// </summary> public void Fetch() { if (asset.thumbnail == null || string.IsNullOrEmpty(asset.thumbnail.url)) { // Spoiler alert: if there's no thumbnail URL, our web request will fail, because // the URL is kind of an import part of a web request. // So fail early with a clear error message, rather than make a broken web request. if (callback != null) { callback(asset, PolyStatus.Error("Thumbnail URL not available for asset: {0}", asset)); } return; } // Only use cache if fetching the thumbnail for an immutable asset. long cacheAgeMaxMillis = asset.IsMutable ? 0 : CACHE_MAX_AGE_MILLIS; PolyMainInternal.Instance.webRequestManager.EnqueueRequest(MakeRequest, ProcessResponse, cacheAgeMaxMillis); } private UnityWebRequest MakeRequest() { string url = asset.thumbnail.url; // If an image size hint was provided, forward it to the server if the server supports it. if (options.requestedImageSize > 0 && url.Contains(".googleusercontent.com/")) { url += "=s" + Mathf.Clamp(options.requestedImageSize, MIN_REQUESTED_SIZE, MAX_REQUESTED_SIZE); } return PolyMainInternal.Instance.polyClient.GetRequest(url, "image/png"); } private void ProcessResponse(PolyStatus status, int responseCode, byte[] data) { if (data == null || data.Length <= 0) { status = PolyStatus.Error("Thumbnail data was null or empty."); } if (status.ok) { asset.thumbnailTexture = new Texture2D(1, 1); asset.thumbnailTexture.LoadImage(data); } else { Debug.LogWarningFormat("Failed to fetch thumbnail for asset {0} ({1}): {2}", asset.name, asset.displayName, status); } if (callback != null) { callback(asset, status); } } } } <file_sep>/Assets/LeapMotion/Modules/InteractionEngine/Scripts/UI/Anchors/Tests/AnchorScoreTest.cs /****************************************************************************** * Copyright (C) Leap Motion, Inc. 2011-2018. * * Leap Motion proprietary and confidential. * * * * Use subject to the terms of the Leap Motion SDK Agreement available at * * https://developer.leapmotion.com/sdk_agreement, or another agreement * * between Leap Motion and you, your company or other organization. * ******************************************************************************/ using System.Collections; using System.Collections.Generic; using UnityEngine; namespace Leap.Unity.Interaction { public class AnchorScoreTest : MonoBehaviour { public Transform centerPositionOneSecondLater; public Material testMaterialXY; public Material testMaterialXZ; public Material testMaterialYZ; [Range(0.10F, 0.70F)] public float maxRange = 0.30F; [Range(5F, 90F)] public float maxAngle = 60F; [Range(0f, 1f)] public float alwaysAttachDistance = 0f; [Header("Generated")] public Texture2D textureXY; public Texture2D textureXZ; public Texture2D textureYZ; public const int WIDTH = 64; void Awake() { textureXY = new Texture2D(WIDTH, WIDTH); textureXZ = new Texture2D(WIDTH, WIDTH); textureYZ = new Texture2D(WIDTH, WIDTH); testMaterialXY.mainTexture = textureXY; testMaterialXZ.mainTexture = textureXZ; testMaterialYZ.mainTexture = textureYZ; } void Update() { this.transform.position = Vector3.zero; setPixels(textureXY, Vector3.right, Vector3.up); setPixels(textureXZ, Vector3.right, Vector3.forward); setPixels(textureYZ, Vector3.up, -Vector3.forward); } Color[] _pixels = new Color[WIDTH * WIDTH]; private void setPixels(Texture2D tex, Vector3 dir1, Vector3 dir2) { float widthPerPixel = 0.5F / tex.width; float center = widthPerPixel * (tex.width / 2F); for (int k = 0; k < tex.width * tex.width; k++) { int i = k / tex.width; int j = k % tex.width; Vector3 anchObjPos = this.transform.position; Vector3 anchObjVel = centerPositionOneSecondLater.position - this.transform.position; Vector3 anchorPos = this.transform.position + (dir1 * i * widthPerPixel - (dir1 * center)) + (dir2 * j * widthPerPixel - (dir2 * center)); float score = AnchorableBehaviour.GetAnchorScore(anchObjPos, anchObjVel, anchorPos, maxRange, maxRange * 0.40F, Mathf.Cos(maxAngle * Mathf.Deg2Rad), alwaysAttachDistance); Color pixel = Color.HSVToRGB(Mathf.Lerp(1F, 0F, score), Mathf.Lerp(0F, 1F, score), Mathf.Lerp(0F, 1F, score)); _pixels[i + j * tex.width] = pixel; } tex.SetPixels(_pixels); tex.Apply(); } } } <file_sep>/Assets/LeapMotion/Modules/GraphicRenderer/Scripts/LeapGraphicGroup.cs /****************************************************************************** * Copyright (C) Leap Motion, Inc. 2011-2018. * * Leap Motion proprietary and confidential. * * * * Use subject to the terms of the Leap Motion SDK Agreement available at * * https://developer.leapmotion.com/sdk_agreement, or another agreement * * between Leap Motion and you, your company or other organization. * ******************************************************************************/ using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Assertions; #if UNITY_EDITOR using UnityEditor; #endif using Leap.Unity.Space; using Leap.Unity.Query; namespace Leap.Unity.GraphicalRenderer { [Serializable] public partial class LeapGraphicGroup : ISerializationCallbackReceiver, ILeapInternalGraphicGroup { #region INSPECTOR FIELDS [SerializeField] private string _groupName; [SerializeField] private RenderingMethodReference _renderingMethod = new RenderingMethodReference(); [SerializeField] private FeatureList _features = new FeatureList(); #endregion #region PRIVATE VARIABLES [SerializeField, HideInInspector] private LeapGraphicRenderer _renderer; [SerializeField, HideInInspector] private List<LeapGraphic> _graphics = new List<LeapGraphic>(); [SerializeField, HideInInspector] private List<SupportInfo> _supportInfo = new List<SupportInfo>(); [SerializeField, HideInInspector] private bool _addRemoveSupported; private HashSet<LeapGraphic> _toAttach = new HashSet<LeapGraphic>(); private HashSet<LeapGraphic> _toDetach = new HashSet<LeapGraphic>(); #endregion #region PUBLIC RUNTIME API public string name { get { return _groupName; } } /// <summary> /// Gets the renderer this group is attached to. /// </summary> public LeapGraphicRenderer renderer { get { return _renderer; } } /// <summary> /// Sets the renderer this group is attached to. /// </summary> LeapGraphicRenderer ILeapInternalGraphicGroup.renderer { set { _renderer = value; } } /// <summary> /// Gets the rendering method used for this group. This can only be changed /// at edit time using either the inspector interface, or the editor method /// ChangeRenderingMethod. /// </summary> public LeapRenderingMethod renderingMethod { get { return _renderingMethod.Value; } } /// <summary> /// Returns the list of features attached to this group. This can only be /// changed at edit time using either the inspector interface, or the editor /// methods AddFeature and RemoveFeature. /// </summary> public IList<LeapGraphicFeatureBase> features { get { Assert.IsNotNull(_features, "The feature list of graphic group was null!"); return _features; } } /// <summary> /// Returns the list of graphics attached to this group. This getter returns /// a regular mutable list for simplicity and efficiency, but the user is /// still not allowed to mutate this list in any way. /// </summary> public List<LeapGraphic> graphics { get { Assert.IsNotNull(_graphics, "The graphic list of graphic group was null!"); return _graphics; } } /// <summary> /// Returns the total number of graphics that will be part of this group after /// the next update cycle. Since attachments are delayed, this number can be /// larger than graphics.Count. /// </summary> public int toBeAttachedCount { get { return _graphics.Count + _toAttach.Count; } } /// <summary> /// Maps 1-to-1 with the feature list, where each element represents the /// support that feature currently has. /// </summary> public List<SupportInfo> supportInfo { get { Assert.IsNotNull(_supportInfo, "The support info list of graphic group was null!"); Assert.AreEqual(_features.Count, _supportInfo.Count, "The support info list should have the same length as the feature list."); return _supportInfo; } } /// <summary> /// Returns whether or not add/remove operations are supported at runtime by /// this group. If this returns false, TryAddGraphic and TryRemoveGraphic will /// always fail at runtime. /// </summary> public bool addRemoveSupported { get { return _addRemoveSupported; } } /// <summary> /// Tries to add the given graphic to this group. This can safely be called /// during runtime or edit time. This method can fail under the following /// conditions: /// - The graphic is already attached to this group. /// - The graphic is already attached to a different group. /// - It is runtime and add/remove is not supported by this group. /// /// At runtime the actual attachment is delayed until LateUpdate for efficiency /// reasons. Expect that even if this method returns true that the graphic will /// not actually be attached until the end of LateUpdate. /// </summary> public bool TryAddGraphic(LeapGraphic graphic) { Assert.IsNotNull(graphic); if (graphic.willbeAttached || (graphic.isAttachedToGroup && !graphic.willbeDetached)) { return false; } if (!addRemoveSupportedOrEditTime()) { return false; } #if UNITY_EDITOR if (!Application.isPlaying) { Undo.RecordObject(graphic, "Added graphic to group"); } else #endif { if (_toAttach.Contains(graphic)) { return false; } if (_toDetach.Contains(graphic)) { graphic.CancelWillBeDetached(); graphic.isRepresentationDirty = true; _toDetach.Remove(graphic); return true; } } if (_graphics.Contains(graphic)) { if (graphic.attachedGroup == null) { //detatch and re-add, it forgot it was attached! //This can easily happen at edit time due to prefab shenanigans graphic.OnDetachedFromGroup(); _graphics.Remove(graphic); } else { Debug.LogWarning("Could not add graphic because it was already a part of this group."); return false; } } #if UNITY_EDITOR if (!Application.isPlaying) { int newIndex = _graphics.Count; _graphics.Add(graphic); LeapSpaceAnchor anchor = _renderer.space == null ? null : LeapSpaceAnchor.GetAnchor(graphic.transform); RebuildFeatureData(); RebuildFeatureSupportInfo(); graphic.OnAttachedToGroup(this, anchor); if (_renderer.space != null) { _renderer.space.RebuildHierarchy(); _renderer.space.RecalculateTransformers(); } _renderer.editor.ScheduleRebuild(); } else #endif { if (_toAttach.Contains(graphic)) { return false; } graphic.NotifyWillBeAttached(this); _toAttach.Add(graphic); } return true; } public void RefreshGraphicAnchors() { foreach (var graphic in _graphics) { var anchor = _renderer.space == null ? null : LeapSpaceAnchor.GetAnchor(graphic.transform); graphic.OnUpdateAnchor(anchor); } } /// <summary> /// Tries to remove the given graphic from this group. This can safely be called /// during runtime or edit time. This method can fail under the following /// conditions: /// - The graphic is not attached to this group. /// - It is runtime and add/remove is not supported by this group. /// /// At runtime the actual detachment is delayed until LateUpdate for efficiency /// reasons. Expect that even if this method returns true that the graphic will /// not actually be detached until the end of LateUpdate. /// </summary> public bool TryRemoveGraphic(LeapGraphic graphic) { Assert.IsNotNull(graphic); if (!addRemoveSupportedOrEditTime()) { return false; } #if UNITY_EDITOR if (Application.isPlaying) #endif { if (_toDetach.Contains(graphic)) { return false; } if (_toAttach.Contains(graphic)) { graphic.CancelWillBeAttached(); graphic.isRepresentationDirty = true; _toAttach.Remove(graphic); return true; } } int graphicIndex = _graphics.IndexOf(graphic); if (graphicIndex < 0) { return false; } #if UNITY_EDITOR if (!Application.isPlaying) { Undo.RecordObject(graphic, "Removed graphic from group"); Undo.RecordObject(_renderer, "Removed graphic from group"); graphic.OnDetachedFromGroup(); _graphics.RemoveAt(graphicIndex); RebuildFeatureData(); RebuildFeatureSupportInfo(); if (_renderer.space != null) { _renderer.space.RebuildHierarchy(); _renderer.space.RecalculateTransformers(); } _renderer.editor.ScheduleRebuild(); } else #endif { if (_toDetach.Contains(graphic)) { return false; } graphic.NotifyWillBeDetached(this); _toDetach.Add(graphic); } return true; } /// <summary> /// Fills the argument list with all of the currently supported features /// of type T. Returns true if there are any supported features, and /// returns false if there are no supported features. /// </summary> public bool GetSupportedFeatures<T>(List<T> features) where T : LeapGraphicFeatureBase { features.Clear(); for (int i = 0; i < _features.Count; i++) { var feature = _features[i]; if (!(feature is T)) continue; if (_supportInfo[i].support == SupportType.Error) continue; features.Add(feature as T); } return features.Count != 0; } public void UpdateRenderer() { #if UNITY_EDITOR if (Application.isPlaying) #endif { handleRuntimeAddRemove(); } _renderingMethod.Value.OnUpdateRenderer(); foreach (var feature in _features) { feature.isDirty = false; } } public void RebuildFeatureData() { using (new ProfilerSample("Rebuild Feature Data")) { foreach (var feature in _features) { feature.ClearDataObjectReferences(); } for (int i = 0; i < _graphics.Count; i++) { var graphic = _graphics[i]; #if UNITY_EDITOR EditorUtility.SetDirty(graphic); Undo.RecordObject(graphic, "modified feature data on graphic."); #endif List<LeapFeatureData> dataList = new List<LeapFeatureData>(); foreach (var feature in _features) { var dataObj = graphic.featureData.Query().OfType(feature.GetDataObjectType()).FirstOrDefault(); if (dataObj != null) { graphic.featureData.Remove(dataObj); } else { dataObj = feature.CreateFeatureDataForGraphic(graphic); } feature.AddFeatureData(dataObj); dataList.Add(dataObj); } graphic.OnAssignFeatureData(dataList); } //Could be more efficient foreach (var feature in _features) { feature.AssignFeatureReferences(); } } } public void RebuildFeatureSupportInfo() { using (new ProfilerSample("Rebuild Support Info")) { var typeToFeatures = new Dictionary<Type, List<LeapGraphicFeatureBase>>(); foreach (var feature in _features) { Type featureType = feature.GetType(); List<LeapGraphicFeatureBase> list; if (!typeToFeatures.TryGetValue(featureType, out list)) { list = new List<LeapGraphicFeatureBase>(); typeToFeatures[featureType] = list; } list.Add(feature); } var featureToInfo = new Dictionary<LeapGraphicFeatureBase, SupportInfo>(); foreach (var pair in typeToFeatures) { var featureType = pair.Key; var featureList = pair.Value; var infoList = new List<SupportInfo>().FillEach(featureList.Count, () => SupportInfo.FullSupport()); var castList = Activator.CreateInstance(typeof(List<>).MakeGenericType(featureType)) as IList; foreach (var feature in featureList) { castList.Add(feature); } try { if (_renderingMethod.Value == null) continue; var interfaceType = typeof(ISupportsFeature<>).MakeGenericType(featureType); if (!interfaceType.IsAssignableFrom(_renderingMethod.Value.GetType())) { infoList.FillEach(() => SupportInfo.Error("This renderer does not support this feature.")); continue; } var supportDelegate = interfaceType.GetMethod("GetSupportInfo"); if (supportDelegate == null) { Debug.LogError("Could not find support delegate."); continue; } supportDelegate.Invoke(_renderingMethod.Value, new object[] { castList, infoList }); } finally { for (int i = 0; i < featureList.Count; i++) { featureToInfo[featureList[i]] = infoList[i]; } } } _supportInfo = new List<SupportInfo>(); foreach (var feature in _features) { _supportInfo.Add(feature.GetSupportInfo(this).OrWorse(featureToInfo[feature])); } } } #endregion #region LIFECYCLE CALLBACKS /// <summary> /// Specifically called during the OnEnable callback during RUNTIME ONLY /// </summary> public void OnEnable() { for (int i = 0; i < _features.Count; i++) { _features[i].AssignFeatureReferences(); _features[i].ClearDataObjectReferences(); _features[i].isDirty = true; foreach (var graphic in _graphics) { _features[i].AddFeatureData(graphic.featureData[i]); } } _renderingMethod.Value.OnEnableRenderer(); } /// <summary> /// Specifically called during the OnDisable callback during RUNTIME ONLY /// </summary> public void OnDisable() { _renderingMethod.Value.OnDisableRenderer(); } #endregion #region PRIVATE IMPLEMENTATION #if UNITY_EDITOR public LeapGraphicGroup() { editor = new EditorApi(this); } #endif private void handleRuntimeAddRemove() { if (_toAttach.Count == 0 && _toDetach.Count == 0) { return; } using (new ProfilerSample("Handle Runtime Add/Remove")) { List<int> dirtyIndexes = Pool<List<int>>.Spawn(); try { var attachEnum = _toAttach.GetEnumerator(); var detachEnum = _toDetach.GetEnumerator(); bool canAttach = attachEnum.MoveNext(); bool canDetach = detachEnum.MoveNext(); //First, we can handle pairs of adds/removes easily by simply placing //the new graphic in the same place the old graphic was. while (canAttach && canDetach) { int toDetatchIndex = _graphics.IndexOf(detachEnum.Current); _graphics[toDetatchIndex] = attachEnum.Current; var anchor = _renderer.space == null ? null : LeapSpaceAnchor.GetAnchor(attachEnum.Current.transform); detachEnum.Current.OnDetachedFromGroup(); attachEnum.Current.OnAttachedToGroup(this, anchor); dirtyIndexes.Add(toDetatchIndex); canAttach = attachEnum.MoveNext(); canDetach = detachEnum.MoveNext(); } int newGraphicStart = _graphics.Count; //Then we append all the new graphics if there are any left. This //only happens if more graphics were added than were remove this //frame. while (canAttach) { _graphics.Add(attachEnum.Current); canAttach = attachEnum.MoveNext(); } //We remove any graphics that did not have a matching add. This //only happens if more graphics were removed than were added this //frame. while (canDetach) { int toDetachIndex = _graphics.IndexOf(detachEnum.Current); dirtyIndexes.Add(toDetachIndex); _graphics[_graphics.Count - 1].isRepresentationDirty = true; _graphics.RemoveAtUnordered(toDetachIndex); detachEnum.Current.OnDetachedFromGroup(); canDetach = detachEnum.MoveNext(); } //TODO: this is gonna need to be optimized //Make sure to call this before OnAttachedToGroup or else the graphic //will not have the correct feature data when it gets attached! RebuildFeatureData(); RebuildFeatureSupportInfo(); //newGraphicStart is either less than _graphics.Count because we added //new graphics, or it is greater than _graphics.Count because we removed //some graphics. for (int i = newGraphicStart; i < _graphics.Count; i++) { var anchor = _renderer.space == null ? null : LeapSpaceAnchor.GetAnchor(attachEnum.Current.transform); _graphics[i].OnAttachedToGroup(this, anchor); } attachEnum.Dispose(); detachEnum.Dispose(); _toAttach.Clear(); _toDetach.Clear(); //Make sure the dirty indexes only point to valid graphics areas. //Could potentially be optimized, but hasnt been a bottleneck. for (int i = dirtyIndexes.Count; i-- != 0;) { if (dirtyIndexes[i] >= _graphics.Count) { dirtyIndexes.RemoveAt(i); } } if (renderer.space != null) { renderer.space.RebuildHierarchy(); renderer.space.RecalculateTransformers(); } foreach (var feature in _features) { feature.isDirty = true; } (_renderingMethod.Value as ISupportsAddRemove).OnAddRemoveGraphics(dirtyIndexes); } finally { dirtyIndexes.Clear(); Pool<List<int>>.Recycle(dirtyIndexes); } } } private bool addRemoveSupportedOrEditTime() { #if UNITY_EDITOR if (!Application.isPlaying) { return true; } #endif return _addRemoveSupported; } public void OnBeforeSerialize() { } public void OnAfterDeserialize() { if (_renderingMethod.Value == null || renderer == null) { Debug.LogWarning("The rendering group did not find the needed data! If you have a variable of type " + "LeapGraphicGroup make sure to annotate it with a [NonSerialized] attribute, or else " + "Unity will automatically create invalid instances of the class."); } else { ILeapInternalRenderingMethod renderingMethodInternal = _renderingMethod.Value; renderingMethodInternal.group = this; renderingMethodInternal.renderer = renderer; } } [Serializable] public class FeatureList : MultiTypedList<LeapGraphicFeatureBase, LeapTextureFeature, LeapSpriteFeature, LeapRuntimeTintFeature, LeapBlendShapeFeature, CustomFloatChannelFeature, CustomVectorChannelFeature, CustomColorChannelFeature, CustomMatrixChannelFeature> { } [Serializable] public class RenderingMethodReference : MultiTypedReference<LeapRenderingMethod, LeapBakedRenderer, LeapDynamicRenderer, LeapTextRenderer> { } #endregion } } <file_sep>/Assets/Hover/Core/Scripts/Items/HoverItemRendererUpdater.cs using System; using Hover.Core.Items.Managers; using Hover.Core.Items.Types; using Hover.Core.Renderers; using Hover.Core.Renderers.CanvasElements; using Hover.Core.Renderers.Items.Buttons; using Hover.Core.Renderers.Items.Sliders; using Hover.Core.Renderers.Utils; using Hover.Core.Utils; using UnityEngine; namespace Hover.Core.Items { /*================================================================================================*/ [ExecuteInEditMode] [RequireComponent(typeof(TreeUpdater))] [RequireComponent(typeof(HoverItem))] [RequireComponent(typeof(HoverItemHighlightState))] [RequireComponent(typeof(HoverItemSelectionState))] public class HoverItemRendererUpdater : MonoBehaviour, ITreeUpdateable, ISettingsController, IProximityProvider { public const string ButtonRendererName = "_ButtonRenderer"; public const string SliderRendererName = "_SliderRenderer"; public ISettingsControllerMap Controllers { get; private set; } public bool IsButtonRendererType { get; protected set; } [DisableWhenControlled(DisplaySpecials=true)] public GameObject ButtonRendererPrefab; [DisableWhenControlled] public GameObject SliderRendererPrefab; [SerializeField] [DisableWhenControlled] private Component _ButtonRenderer; [SerializeField] [DisableWhenControlled] private Component _SliderRenderer; [TriggerButton("Rebuild Item Renderer")] public bool ClickToRebuildRenderer; private GameObject vPrevButtonPrefab; private GameObject vPrevSliderPrefab; //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ protected HoverItemRendererUpdater() { Controllers = new SettingsControllerMap(); } /*--------------------------------------------------------------------------------------------*/ public HoverRendererButton ButtonRenderer { get { return (_ButtonRenderer as HoverRendererButton); } set { _ButtonRenderer = value; } } /*--------------------------------------------------------------------------------------------*/ public HoverRendererSlider SliderRenderer { get { return (_SliderRenderer as HoverRendererSlider); } set { _SliderRenderer = value; } } /*--------------------------------------------------------------------------------------------*/ public HoverRenderer ActiveRenderer { get { return ((HoverRenderer)ButtonRenderer ?? SliderRenderer); } } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public void Awake() { /*ButtonRendererPrefab = Resources.Load<GameObject>( "Prefabs/HoverAlphaButtonRenderer-Default"); SliderRendererPrefab = Resources.Load<GameObject>( "Prefabs/HoverAlphaSliderRenderer-Default");*/ vPrevButtonPrefab = ButtonRendererPrefab; vPrevSliderPrefab = SliderRendererPrefab; } /*--------------------------------------------------------------------------------------------*/ public virtual void Start() { //do nothing... } /*--------------------------------------------------------------------------------------------*/ public virtual void TreeUpdate() { HoverItem hoverItem = GetComponent<HoverItem>(); DestroyRenderersIfNecessary(); TryRebuildWithItemType(hoverItem.ItemType); //// HoverItemHighlightState highState = GetComponent<HoverItemHighlightState>(); HoverItemSelectionState selState = GetComponent<HoverItemSelectionState>(); HoverRenderer activeRenderer = ((HoverRenderer)ButtonRenderer ?? SliderRenderer); UpdateRenderer(activeRenderer, hoverItem); UpdateRendererCanvas(activeRenderer, hoverItem); UpdateRendererIndicator(activeRenderer, highState, selState); if ( ButtonRenderer != null ) { UpdateButtonSettings(highState); } if ( SliderRenderer != null ) { UpdateSliderSettings(hoverItem); UpdateSliderSettings(hoverItem, highState); } Controllers.TryExpireControllers(); } /*--------------------------------------------------------------------------------------------*/ public void OnEditorTriggerButtonSelected() { //do nothing here, check for (ClickToRebuildRenderer == true) elsewhere... } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ private void DestroyRenderersIfNecessary() { if ( ClickToRebuildRenderer || ButtonRendererPrefab != vPrevButtonPrefab ) { vPrevButtonPrefab = ButtonRendererPrefab; RendererUtil.DestroyRenderer(ButtonRenderer); ButtonRenderer = null; } if ( ClickToRebuildRenderer || SliderRendererPrefab != vPrevSliderPrefab ) { vPrevSliderPrefab = SliderRendererPrefab; RendererUtil.DestroyRenderer(SliderRenderer); SliderRenderer = null; } ClickToRebuildRenderer = false; } /*--------------------------------------------------------------------------------------------*/ private void TryRebuildWithItemType(HoverItem.HoverItemType pType) { if ( pType == HoverItem.HoverItemType.Slider ) { Controllers.Set(ButtonRendererName, this); Controllers.Unset(SliderRendererName, this); RendererUtil.DestroyRenderer(ButtonRenderer); ButtonRenderer = null; SliderRenderer = (SliderRenderer ?? FindOrBuildSlider()); IsButtonRendererType = false; } else { Controllers.Set(SliderRendererName, this); Controllers.Unset(ButtonRendererName, this); RendererUtil.DestroyRenderer(SliderRenderer); SliderRenderer = null; ButtonRenderer = (ButtonRenderer ?? FindOrBuildButton()); IsButtonRendererType = true; } } /*--------------------------------------------------------------------------------------------*/ private HoverRendererButton FindOrBuildButton() { return RendererUtil.FindOrBuildRenderer<HoverRendererButton>(gameObject.transform, ButtonRendererPrefab, "Button", typeof(HoverRendererButton)); } /*--------------------------------------------------------------------------------------------*/ private HoverRendererSlider FindOrBuildSlider() { return RendererUtil.FindOrBuildRenderer<HoverRendererSlider>(gameObject.transform, SliderRendererPrefab, "Slider", typeof(HoverRendererSlider)); } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public virtual Vector3 GetNearestWorldPosition(Vector3 pFromWorldPosition) { if ( ButtonRenderer != null ) { return ButtonRenderer.GetNearestWorldPosition(pFromWorldPosition); } if ( SliderRenderer != null ) { return SliderRenderer.GetNearestWorldPosition(pFromWorldPosition); } throw new Exception("No button or slider renderer."); } /*--------------------------------------------------------------------------------------------*/ public virtual Vector3 GetNearestWorldPosition(Ray pFromWorldRay, out RaycastResult pRaycast) { if ( ButtonRenderer != null ) { return ButtonRenderer.GetNearestWorldPosition(pFromWorldRay, out pRaycast); } if ( SliderRenderer != null ) { return SliderRenderer.GetNearestWorldPosition(pFromWorldRay, out pRaycast); } throw new Exception("No button or slider renderer."); } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ private void UpdateRenderer(HoverRenderer pRenderer, HoverItem pHoverItem) { pRenderer.Controllers.Set(HoverRenderer.IsEnabledName, this); pRenderer.IsEnabled = pHoverItem.Data.IsEnabled; } /*--------------------------------------------------------------------------------------------*/ private void UpdateRendererCanvas(HoverRenderer pRenderer, HoverItem pHoverItem) { HoverCanvasDataUpdater canvasUp = pRenderer.GetCanvasDataUpdater(); if ( canvasUp == null ) { return; } IItemData data = pHoverItem.Data; IItemDataCheckbox checkboxData = (data as IItemDataCheckbox); IItemDataRadio radioData = (data as IItemDataRadio); IItemDataSelector selectorData = (data as IItemDataSelector); IItemDataSticky stickyData = (data as IItemDataSticky); IItemDataSlider sliderData = (data as IItemDataSlider); var icon = HoverCanvasDataUpdater.IconPairType.Unspecified; if ( checkboxData != null ) { icon = (checkboxData.Value ? HoverCanvasDataUpdater.IconPairType.CheckboxOn : HoverCanvasDataUpdater.IconPairType.CheckboxOff); } else if ( radioData != null ) { icon = (radioData.Value ? HoverCanvasDataUpdater.IconPairType.RadioOn : HoverCanvasDataUpdater.IconPairType.RadioOff); } else if ( selectorData != null ) { if ( selectorData.Action == SelectorActionType.NavigateIn ) { icon = HoverCanvasDataUpdater.IconPairType.NavigateIn; } else if ( selectorData.Action == SelectorActionType.NavigateOut ) { icon = HoverCanvasDataUpdater.IconPairType.NavigateOut; } } else if ( stickyData != null ) { icon = HoverCanvasDataUpdater.IconPairType.Sticky; } else if ( sliderData != null ) { icon = HoverCanvasDataUpdater.IconPairType.Slider; } canvasUp.Controllers.Set(HoverCanvasDataUpdater.LabelTextName, this); canvasUp.Controllers.Set(HoverCanvasDataUpdater.IconTypeName, this); canvasUp.LabelText = (sliderData == null ? data.Label : sliderData.GetFormattedLabel(sliderData)); canvasUp.IconType = icon; } /*--------------------------------------------------------------------------------------------*/ private void UpdateRendererIndicator(HoverRenderer pRenderer, HoverItemHighlightState pHighState, HoverItemSelectionState pSelState) { HoverIndicator rendInd = pRenderer.GetIndicator(); rendInd.Controllers.Set(HoverIndicator.HighlightProgressName, this); rendInd.Controllers.Set(HoverIndicator.SelectionProgressName, this); rendInd.HighlightProgress = pHighState.MaxHighlightProgress; rendInd.SelectionProgress = pSelState.SelectionProgress; if ( pSelState.WasSelectedThisFrame ) { rendInd.LatestSelectionTime = DateTime.UtcNow; } } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ private void UpdateButtonSettings(HoverItemHighlightState pHighState) { ButtonRenderer.Fill.Controllers.Set(HoverFillButton.ShowEdgeName, this); ButtonRenderer.Fill.ShowEdge = (pHighState.IsNearestAcrossAllItemsForAnyCursor && pHighState.MaxHighlightProgress > 0); } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ private void UpdateSliderSettings(HoverItem pHoverItem) { IItemDataSlider data = (IItemDataSlider)pHoverItem.Data; SliderRenderer.Controllers.Set(HoverRendererSlider.HandleValueName, this); SliderRenderer.Controllers.Set(HoverRendererSlider.FillStartingPointName, this); SliderRenderer.Controllers.Set(HoverRendererSlider.ZeroValueName, this); SliderRenderer.Controllers.Set(HoverRendererSlider.AllowJumpName, this); SliderRenderer.Controllers.Set(HoverRendererSlider.TickCountName, this); SliderRenderer.HandleValue = data.SnappedValue; SliderRenderer.FillStartingPoint = data.FillStartingPoint; SliderRenderer.ZeroValue = Mathf.InverseLerp(data.RangeMin, data.RangeMax, 0); SliderRenderer.AllowJump = data.AllowJump; SliderRenderer.TickCount = data.Ticks; } /*--------------------------------------------------------------------------------------------*/ private void UpdateSliderSettings(HoverItem pHoverItem, HoverItemHighlightState pHighState) { HoverItemDataSlider data = (HoverItemDataSlider)pHoverItem.Data; HoverItemHighlightState.Highlight? high = pHighState.NearestHighlight; float highProg = pHighState.MaxHighlightProgress; bool isNearest = pHighState.IsNearestAcrossAllItemsForAnyCursor; SliderRenderer.Controllers.Set(HoverRendererSlider.JumpValueName, this); SliderRenderer.Controllers.Set(HoverRendererSlider.ShowButtonEdgesName, this); SliderRenderer.ShowButtonEdges = (isNearest && highProg > 0); if ( high == null || highProg <= 0 || !isNearest ) { data.HoverValue = null; SliderRenderer.JumpValue = -1; return; } float value = SliderRenderer.GetValueViaNearestWorldPosition(high.Value.NearestWorldPos); data.HoverValue = value; float snapValue = (float)data.SnappedHoverValue; //float easePower = (1-high.Value.Progress)*5+1; //gets "snappier" as you pull away float showValue = DisplayUtil.GetEasedValue(data.Snaps, value, snapValue, 3); SliderRenderer.JumpValue = showValue; if ( data.IsStickySelected ) { data.Value = value; SliderRenderer.Controllers.Set(HoverRendererSlider.HandleValueName, this); SliderRenderer.HandleValue = showValue; } } } } <file_sep>/Assets/Hover/RendererModules/Alpha/Scripts/HoverAlphaRendererUpdater.cs using Hover.Core.Renderers; using Hover.Core.Renderers.CanvasElements; using Hover.Core.Utils; using UnityEngine; namespace Hover.RendererModules.Alpha { /*================================================================================================*/ [ExecuteInEditMode] [RequireComponent(typeof(HoverRenderer))] public class HoverAlphaRendererUpdater : MonoBehaviour, ITreeUpdateable, ISettingsController { public const string SortingLayerName = "SortingLayer"; public const string MasterAlphaName = "MasterAlpha"; public const string EnabledAlphaName = "EnabledAlpha"; public const string DisabledAlphaName = "DisabledAlpha"; public ISettingsControllerMap Controllers { get; private set; } [DisableWhenControlled(DisplaySpecials=true)] public string SortingLayer = "Default"; [DisableWhenControlled(RangeMin=0, RangeMax=1)] public float MasterAlpha = 1; [DisableWhenControlled(RangeMin=0, RangeMax=1)] public float EnabledAlpha = 1; [DisableWhenControlled(RangeMin=0, RangeMax=1)] public float DisabledAlpha = 0.35f; //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public HoverAlphaRendererUpdater() { Controllers = new SettingsControllerMap(); } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public void Start() { //do nothing... } /*--------------------------------------------------------------------------------------------*/ public virtual void TreeUpdate() { HoverRenderer hoverRend = GetComponent<HoverRenderer>(); int childRendCount = hoverRend.GetChildRendererCount(); int childFillCount = hoverRend.GetChildFillCount(); float currAlpha = MasterAlpha*(hoverRend.IsEnabled ? EnabledAlpha : DisabledAlpha); for ( int i = 0 ; i < childRendCount ; i++ ) { UpdateChildRenderer(hoverRend.GetChildRenderer(i)); } for ( int i = 0 ; i < childFillCount ; i++ ) { UpdateChildFill(hoverRend.GetChildFill(i), currAlpha); } UpdateChildCanvas(hoverRend.GetCanvas(), currAlpha); Controllers.TryExpireControllers(); } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ private void UpdateChildRenderer(HoverRenderer pChildRend) { HoverAlphaRendererUpdater rendUp = pChildRend.GetComponent<HoverAlphaRendererUpdater>(); if ( rendUp == null ) { return; } rendUp.Controllers.Set(SortingLayerName, this); rendUp.Controllers.Set(MasterAlphaName, this); rendUp.Controllers.Set(EnabledAlphaName, this); rendUp.Controllers.Set(DisabledAlphaName, this); rendUp.SortingLayer = SortingLayer; rendUp.MasterAlpha = MasterAlpha; rendUp.EnabledAlpha = EnabledAlpha; rendUp.DisabledAlpha = DisabledAlpha; } /*--------------------------------------------------------------------------------------------*/ private void UpdateChildFill(HoverFill pChildFill, float pAlpha) { HoverAlphaFillUpdater fillUp = pChildFill.GetComponent<HoverAlphaFillUpdater>(); if ( fillUp == null ) { return; } fillUp.Controllers.Set(HoverAlphaFillUpdater.SortingLayerName, this); fillUp.Controllers.Set(HoverAlphaFillUpdater.AlphaName, this); fillUp.SortingLayer = SortingLayer; fillUp.Alpha = pAlpha; } /*--------------------------------------------------------------------------------------------*/ private void UpdateChildCanvas(HoverCanvas pChildCanvas, float pAlpha) { if ( pChildCanvas == null ) { return; } pChildCanvas.Controllers.Set(SettingsControllerMap.CanvasSortingLayer, this); pChildCanvas.Controllers.Set(SettingsControllerMap.CanvasGroupAlpha, this); pChildCanvas.CanvasComponent.sortingLayerName = SortingLayer; pChildCanvas.CanvasGroupComponent.alpha = pAlpha; } } } <file_sep>/Assets/LeapMotion/Modules/GraphicRenderer/Scripts/Graphics/ProceduralMeshGraphics/LeapPanelOutlineGraphic.cs /****************************************************************************** * Copyright (C) Leap Motion, Inc. 2011-2018. * * Leap Motion proprietary and confidential. * * * * Use subject to the terms of the Leap Motion SDK Agreement available at * * https://developer.leapmotion.com/sdk_agreement, or another agreement * * between Leap Motion and you, your company or other organization. * ******************************************************************************/ using System.Collections.Generic; using UnityEngine; using UnityEngine.Rendering; using Leap.Unity.Query; using Leap.Unity.Attributes; namespace Leap.Unity.GraphicalRenderer { /// <summary> /// The Panel Outline Graphic acts just like a Panel Graphic, but only produces quads /// for the outermost edges of the panel. /// </summary> [DisallowMultipleComponent] public class LeapPanelOutlineGraphic : LeapSlicedGraphic { #region Inspector [Header("Outline Thickness")] [Tooltip("Check this option to override the thickness of the sprite's borders with " + "a custom thickness. This will stretch the sprite's borders to match the " + "custom thickness.")] [SerializeField, EditTimeOnly] private bool _overrideSpriteBorders = false; /// <summary> /// Gets whether the Panel Outline Graphic is overriding the borders of its sprite /// data source. This property only has an effect if the graphic has a sprite set as /// its data source (instead of a texture). /// </summary> public bool overrideSpriteBorders { get { return _overrideSpriteBorders; } } [Tooltip("The local-space thickness of the panel edges that are constructed. If the" + "source data for the panel is a Sprite, this value is overridden to reflect " + "the sprite's nine-slicing.")] [MinValue(0f)] [SerializeField, EditTimeOnly] private Vector2 _thickness = new Vector2(0.01F, 0.01F); /// <summary> /// Gets the thickness of the panel edges. /// </summary> public Vector2 thickness { get { return _thickness; } } #endregion #region Unity Events protected override void OnValidate() { base.OnValidate(); RefreshMeshData(); } #endregion public override void RefreshSlicedMeshData(Vector2i resolution, RectMargins meshMargins, RectMargins uvMargins) { resolution.x = Mathf.Max(resolution.x, 4); resolution.y = Mathf.Max(resolution.y, 4); if (overrideSpriteBorders || !nineSliced) { // For this calculation, we ignore the provided meshMargins because the Outline // graphic allows the user to override its default nine-slicing behaviour for // borders. meshMargins = new RectMargins(_thickness.x, _thickness.y, _thickness.x, _thickness.y); } if (!nineSliced) { float xRatio = _thickness.x / rect.width; float yRatio = _thickness.y / rect.height; xRatio = Mathf.Clamp(xRatio, 0F, 0.5F); yRatio = Mathf.Clamp(yRatio, 0F, 0.5F); uvMargins = new RectMargins(left: xRatio, right: xRatio, top: yRatio, bottom: yRatio); } List<Vector3> verts = new List<Vector3>(); List<Vector2> uvs = new List<Vector2>(); List<int> tris = new List<int>(); for (int vy = 0; vy < resolution.y; vy++) { for (int vx = 0; vx < resolution.x; vx++) { // Outline verts only. if ((vy > 1 && vy < resolution.y - 2) && (vx > 1 && vx < resolution.x - 2)) continue; Vector2 vert; vert.x = calculateVertAxis(vx, resolution.x, rect.width, meshMargins.left, meshMargins.right, true); vert.y = calculateVertAxis(vy, resolution.y, rect.height, meshMargins.top, meshMargins.bottom, true); verts.Add(vert + new Vector2(rect.x, rect.y)); Vector2 uv; uv.x = calculateVertAxis(vx, resolution.x, 1, uvMargins.left, uvMargins.right, true); uv.y = calculateVertAxis(vy, resolution.y, 1, uvMargins.top, uvMargins.bottom, true); uvs.Add(uv); } } int indicesSkippedPerRow = resolution.x - 4; int indicesSkipped = 0; for (int vy = 0; vy < resolution.y; vy++) { for (int vx = 0; vx < resolution.x; vx++) { if (vx == resolution.x - 1 || vy == resolution.y - 1) { continue; } if ((vx == 1 && (vy > 0 && vy < resolution.y - 2)) || (vy == 1 && (vx > 0 && vx < resolution.x - 2))) { continue; } if ((vx > 1 && vx < resolution.x - 2) && (vy > 1 && vy < resolution.y - 2)) { indicesSkipped += 1; continue; } int vertIndex = vy * resolution.x + vx - indicesSkipped; int right = 1; int down; if (vy == 0 || (vy == 1 && vx < 2) || (vy == resolution.y - 3 && vx > resolution.x - 3) || (vy == resolution.y - 2)) { down = resolution.x; } else { down = resolution.x - indicesSkippedPerRow; } // Add quad tris.Add(vertIndex); tris.Add(vertIndex + right + down); tris.Add(vertIndex + right); tris.Add(vertIndex); tris.Add(vertIndex + down); tris.Add(vertIndex + right + down); } } if (mesh == null) { mesh = new Mesh(); } mesh.name = "Panel Outline Mesh"; mesh.hideFlags = HideFlags.HideAndDontSave; mesh.Clear(keepVertexLayout: false); mesh.SetVertices(verts); mesh.SetTriangles(tris, 0); mesh.SetUVs(uvChannel.Index(), uvs); mesh.RecalculateBounds(); remappableChannels = UVChannelFlags.UV0; } } } <file_sep>/Assets/Hover/Core/Scripts/Utils/DisplayUtil.cs using System; using UnityEngine; namespace Hover.Core.Utils { /*================================================================================================*/ public static class DisplayUtil { //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public static float GetEasedValue(int pSnaps, float pValue, float pSnappedValue, float pPower) { if ( pSnaps < 2 ) { return pValue; } float showVal = pSnappedValue; int snaps = pSnaps-1; float diff = pValue-showVal; int sign = Math.Sign(diff); diff = Math.Abs(diff); //between 0 and 1 diff *= snaps; if ( diff < 0.5 ) { diff *= 2; diff = (float)Math.Pow(diff, pPower); diff /= 2f; } else { diff = (diff-0.5f)*2; diff = 1-(float)Math.Pow(1-diff, pPower); diff = diff/2f+0.5f; } diff /= snaps; return showVal + diff*sign; } /*--------------------------------------------------------------------------------------------*/ public static Color FadeColor(Color pColor, float pAlpha) { Color faded = pColor; faded.a *= pAlpha; return faded; } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ //based on: http://stackoverflow.com/questions/1335426 public static Color HsvToColor(float pHue, float pSat, float pVal) { float hue60 = pHue/60f; int i = (int)Math.Floor(hue60)%6; float f = hue60 - (int)Math.Floor(hue60); float v = pVal; float p = pVal * (1-pSat); float q = pVal * (1-f*pSat); float t = pVal * (1-(1-f)*pSat); switch ( i ) { case 0: return new Color(v, t, p); case 1: return new Color(q, v, p); case 2: return new Color(p, v, t); case 3: return new Color(p, q, v); case 4: return new Color(t, p, v); case 5: return new Color(v, p, q); } return Color.black; } } } <file_sep>/Assets/Hover/Core/Scripts/Renderers/Shapes/Arc/HoverRendererIdleArcUpdater.cs using Hover.Core.Renderers.Cursors; using Hover.Core.Utils; using UnityEngine; namespace Hover.Core.Renderers.Shapes.Arc { /*================================================================================================*/ [RequireComponent(typeof(TreeUpdater))] [RequireComponent(typeof(HoverShapeArc))] [RequireComponent(typeof(HoverRendererIdle))] public class HoverRendererIdleArcUpdater : MonoBehaviour, ITreeUpdateable, ISettingsController { //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public void Start() { //do nothing... } /*--------------------------------------------------------------------------------------------*/ public void TreeUpdate() { HoverShapeArc shape = GetComponent<HoverShapeArc>(); HoverRendererIdle rend = GetComponent<HoverRendererIdle>(); float thickness = rend.DistanceThreshold/gameObject.transform.lossyScale.x; shape.Controllers.Set(HoverShapeArc.InnerRadiusName, this); shape.Controllers.Set(HoverShapeArc.InnerOffsetName, this); shape.InnerRadius = shape.OuterRadius+thickness; shape.InnerOffset = rend.CenterOffset; } } } <file_sep>/Assets/LeapMotion/Core/Scripts/Utils/Infix.cs /****************************************************************************** * Copyright (C) Leap Motion, Inc. 2011-2018. * * Leap Motion proprietary and confidential. * * * * Use subject to the terms of the Leap Motion SDK Agreement available at * * https://developer.leapmotion.com/sdk_agreement, or another agreement * * between Leap Motion and you, your company or other organization. * ******************************************************************************/ using UnityEngine; namespace Leap.Unity.Infix { /// <summary> /// Unity math operations like Vector3.Dot put in extension methods so they can be used /// in as infix operations, e.g., a.Dot(b). /// </summary> public static class Infix { #region Float /// <summary> /// Infix sugar for Mathf.Clamp01(f). /// </summary> public static float Clamped01(this float f) { return Mathf.Clamp01(f); } /// <summary> /// Infix sugar for Mathf.Clamp(f, min, max). /// </summary> public static float Clamped(this float f, float min, float max) { return Mathf.Clamp(f, min, max); } #endregion #region Vector3 /// <summary> /// Rightward syntax for applying a Quaternion rotation to this vector; literally /// returns byQuaternion * thisVector -- does NOT modify the input vector. /// </summary> public static Vector3 RotatedBy(this Vector3 thisVector, Quaternion byQuaternion) { return byQuaternion * thisVector; } /// <summary> /// Infix sugar for Vector3.MoveTowards(a, b). /// /// Returns this position moved towards the argument position, up to but no more than /// the max distance from the original position specified by maxDistanceDelta. /// </summary> public static Vector3 MovedTowards(this Vector3 thisPosition, Vector3 otherPosition, float maxDistanceDelta) { return Vector3.MoveTowards(thisPosition, otherPosition, maxDistanceDelta); } /// <summary> /// Infix sugar for Vector3.Dot(a, b). /// </summary> public static float Dot(this Vector3 a, Vector3 b) { return Vector3.Dot(a, b); } /// <summary> /// Infix sugar for Vector3.Cross(a, b). /// </summary> public static Vector3 Cross(this Vector3 a, Vector3 b) { return Vector3.Cross(a, b); } /// <summary> /// Infix sugar for Vector3.Angle(a, b). /// </summary> public static float Angle(this Vector3 a, Vector3 b) { return Vector3.Angle(a, b); } /// <summary> /// Infix sugar for Vector3.SignedAngle(a, b). /// </summary> public static float SignedAngle(this Vector3 a, Vector3 b, Vector3 axis) { float sign = Vector3.Dot(Vector3.Cross(a,b), axis) < 0f ? -1f : 1f; return sign * Vector3.Angle(a, b); } #endregion #region Quaternion /// <summary> /// Returns (this * Vector3.right), the x-axis of the rotated frame of this /// quaternion. /// </summary> public static Vector3 GetRight(this Quaternion q) { return q * Vector3.right; } /// <summary> /// Returns (this * Vector3.up), the y-axis of the rotated frame of this quaternion. /// </summary> public static Vector3 GetUp(this Quaternion q) { return q * Vector3.up; } /// <summary> /// Returns (this * Vector3.forward), the z-axis of the rotated frame of this /// quaternion. /// </summary> public static Vector3 GetForward(this Quaternion q) { return q * Vector3.forward; } #endregion } } <file_sep>/Assets/LeapMotion/Modules/GraphicRenderer/Scripts/ISupportsAddRemove.cs /****************************************************************************** * Copyright (C) Leap Motion, Inc. 2011-2018. * * Leap Motion proprietary and confidential. * * * * Use subject to the terms of the Leap Motion SDK Agreement available at * * https://developer.leapmotion.com/sdk_agreement, or another agreement * * between Leap Motion and you, your company or other organization. * ******************************************************************************/ using System.Collections.Generic; namespace Leap.Unity.GraphicalRenderer { public interface ISupportsAddRemove { /// <summary> /// Must be implemented by a renderer to report that it /// is able to support adding and removing graphics at runtime. /// /// Will be called once per frame, with a list of indexes that are /// 'dirty'. Each dirty index represents a graphic that might have /// changed completely because an ordering has changed. Dirty /// indexes will not be included for new graphics, so you will also /// need to check to see if the graphics list has increased in size. /// </summary> void OnAddRemoveGraphics(List<int> dirtyIndexes); } } <file_sep>/Assets/Hover/Core/Scripts/Renderers/Cursors/HoverRendererIdle.cs using System; using Hover.Core.Renderers.CanvasElements; using Hover.Core.Renderers.Shapes; using Hover.Core.Utils; using UnityEngine; namespace Hover.Core.Renderers.Cursors { /*================================================================================================*/ public class HoverRendererIdle : HoverRenderer { public const string CenterPositionName = "CenterPosition"; public const string DistanceThresholdName = "DistanceThreshold"; public const string TimerProgressName = "TimerProgress"; public const string IsRaycastName = "IsRaycast"; [DisableWhenControlled] public HoverFillIdle Fill; [DisableWhenControlled] public Vector3 CenterOffset; [DisableWhenControlled] public float DistanceThreshold; [DisableWhenControlled(RangeMin=0, RangeMax=1)] public float TimerProgress; [DisableWhenControlled] public bool IsRaycast; [DisableWhenControlled] public float RaycastOffsetZ = -0.001f; //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public override int GetChildFillCount() { return 1; } /*--------------------------------------------------------------------------------------------*/ public override HoverFill GetChildFill(int pIndex) { switch ( pIndex ) { case 0: return Fill; } throw new ArgumentOutOfRangeException(); } /*--------------------------------------------------------------------------------------------*/ public override int GetChildRendererCount() { return 0; } /*--------------------------------------------------------------------------------------------*/ public override HoverRenderer GetChildRenderer(int pIndex) { throw new ArgumentOutOfRangeException(); } /*--------------------------------------------------------------------------------------------*/ public override HoverCanvas GetCanvas() { return null; } /*--------------------------------------------------------------------------------------------*/ public override HoverCanvasDataUpdater GetCanvasDataUpdater() { return null; } /*--------------------------------------------------------------------------------------------*/ public override Vector3 GetCenterWorldPosition() { return transform.position; } /*--------------------------------------------------------------------------------------------*/ public override Vector3 GetNearestWorldPosition(Vector3 pFromWorldPosition) { return GetComponent<HoverShape>().GetNearestWorldPosition(pFromWorldPosition); } /*--------------------------------------------------------------------------------------------*/ public override Vector3 GetNearestWorldPosition(Ray pFromWorldRay, out RaycastResult pRaycast) { return GetComponent<HoverShape>().GetNearestWorldPosition(pFromWorldRay, out pRaycast); } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public override void TreeUpdate() { base.TreeUpdate(); UpdatePosition(); UpdateIndicator(); } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ private void UpdatePosition() { if ( !Application.isPlaying || !IsRaycast ) { return; } Controllers.Set(SettingsControllerMap.TransformLocalPosition+".z", this); Vector3 localPos = transform.localPosition; localPos.z = RaycastOffsetZ/transform.lossyScale.z; transform.localPosition = localPos; } /*--------------------------------------------------------------------------------------------*/ private void UpdateIndicator() { if ( !Application.isPlaying ) { return; } HoverIndicator idleInd = GetComponent<HoverIndicator>(); idleInd.Controllers.Set(HoverIndicator.HighlightProgressName, this); idleInd.HighlightProgress = Mathf.Lerp(0.05f, 1, TimerProgress); } } } <file_sep>/Assets/LeapMotion/Modules/GraphicRenderer/Scripts/ISupportsFeature.cs /****************************************************************************** * Copyright (C) Leap Motion, Inc. 2011-2018. * * Leap Motion proprietary and confidential. * * * * Use subject to the terms of the Leap Motion SDK Agreement available at * * https://developer.leapmotion.com/sdk_agreement, or another agreement * * between Leap Motion and you, your company or other organization. * ******************************************************************************/ using System.Collections.Generic; namespace Leap.Unity.GraphicalRenderer { public interface ISupportsFeature<T> where T : LeapGraphicFeatureBase { /// <summary> /// Must be implemented by a renderer to report what level of support /// it has for all features of this type. /// /// The 'features' list will /// contain all features requested in priority order, and the 'info' /// list will come pre-filled with full-support info items. The /// renderer must change these full-support items to a warning or /// error item to reflect what it is able to support. /// /// This method will NEVER be called if there are 0 features of type T. /// </summary> void GetSupportInfo(List<T> features, List<SupportInfo> info); } } <file_sep>/Assets/Hover/Core/Scripts/Layouts/Arc/HoverLayoutArcRelativeSizer.cs using Hover.Core.Utils; using UnityEngine; namespace Hover.Core.Layouts.Arc { /*================================================================================================*/ public class HoverLayoutArcRelativeSizer : MonoBehaviour, ISettingsController { [Range(0, 10)] public float RelativeThickness = 1; [Range(0, 10)] public float RelativeArcDegrees = 1; [Range(-2, 2)] public float RelativeRadiusOffset = 0; [Range(-2, 2)] public float RelativeStartDegreeOffset = 0; } } <file_sep>/Assets/Hover/Core/Scripts/Renderers/Helpers/ScaleViaHoverIndicator.cs using UnityEngine; namespace Hover.Core.Renderers.Helpers { /*================================================================================================*/ [ExecuteInEditMode] public class ScaleViaHoverIndicator : MonoBehaviour { public HoverIndicator Indicator; public Vector3 StartLocalScale = new Vector3(1, 1, 1); public Vector3 HighlightLocalScale = new Vector3(2, 2, 2); public Vector3 SelectionLocalScale = new Vector3(2, 2, 2); //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public void Awake() { if ( Indicator == null ) { Indicator = GetComponentInParent<HoverIndicator>(); } } /*--------------------------------------------------------------------------------------------*/ public void Update() { if ( Indicator.SelectionProgress > 0 ) { transform.localScale = Vector3.Lerp( HighlightLocalScale, SelectionLocalScale, Indicator.SelectionProgress); } else { transform.localScale = Vector3.Lerp( StartLocalScale, HighlightLocalScale, Indicator.HighlightProgress); } } } } <file_sep>/Assets/Hover/Core/Scripts/Items/Helpers/HoverItemEventReactor.cs using Hover.Core.Items.Types; using UnityEngine; namespace Hover.Core.Items.Helpers { /*================================================================================================*/ [RequireComponent(typeof(HoverItemData))] public class HoverItemEventReactor : MonoBehaviour { //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public void EnableWithBoolValue(IItemDataSelectable<bool> pItemData) { GetComponent<HoverItemData>().IsEnabled = pItemData.Value; } /*--------------------------------------------------------------------------------------------*/ public void DisableWithBoolValue(IItemDataSelectable<bool> pItemData) { GetComponent<HoverItemData>().IsEnabled = !pItemData.Value; } /*--------------------------------------------------------------------------------------------*/ public void ShowWithBoolValue(IItemDataSelectable<bool> pItemData) { GetComponent<HoverItemData>().gameObject.SetActive(pItemData.Value); } /*--------------------------------------------------------------------------------------------*/ public void HideWithBoolValue(IItemDataSelectable<bool> pItemData) { GetComponent<HoverItemData>().gameObject.SetActive(!pItemData.Value); } } } <file_sep>/Assets/Hover/Core/Scripts/Renderers/Cursors/HoverRaycastLine.cs using Hover.Core.Utils; using UnityEngine; namespace Hover.Core.Renderers.Cursors { /*================================================================================================*/ [RequireComponent(typeof(TreeUpdater))] [RequireComponent(typeof(LineRenderer))] public class HoverRaycastLine : MonoBehaviour, ITreeUpdateable { public const string RaycastWorldOriginName = "RaycastWorldOrigin"; public ISettingsControllerMap Controllers { get; private set; } [DisableWhenControlled(DisplaySpecials=true)] public Vector3 RaycastWorldOrigin; //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ protected HoverRaycastLine() { Controllers = new SettingsControllerMap(); } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public void Start() { //do nothing... } /*--------------------------------------------------------------------------------------------*/ public void TreeUpdate() { LineRenderer line = GetComponent<LineRenderer>(); line.useWorldSpace = true; line.SetPosition(0, transform.position); line.SetPosition(1, RaycastWorldOrigin); Controllers.TryExpireControllers(); } } } <file_sep>/Assets/LeapMotion/Modules/GraphicRenderer/Scripts/Utility/Editor/VariantEnabler.cs /****************************************************************************** * Copyright (C) Leap Motion, Inc. 2011-2018. * * Leap Motion proprietary and confidential. * * * * Use subject to the terms of the Leap Motion SDK Agreement available at * * https://developer.leapmotion.com/sdk_agreement, or another agreement * * between Leap Motion and you, your company or other organization. * ******************************************************************************/ using System; using System.IO; using System.Linq; using System.Text.RegularExpressions; using System.Collections.Generic; using UnityEngine; using UnityEditor; public static class VariantEnabler { public const string EARLY_OUT_KEYWORD = "#pragma"; public static Regex isSurfaceShaderRegex = new Regex(@"#pragma\s+surface\s+surf"); public static Regex disabledVariantRegex = new Regex(@"/{2,}\s*#pragma\s+shader_feature\s+_\s+GRAPHIC_RENDERER"); public static Regex enabledVariantRegex = new Regex(@"^\s*#pragma\s+shader_feature\s+_\s+GRAPHIC_RENDERER"); public static bool IsSurfaceShader(Shader shader) { ShaderInfo info; if (tryGetShaderInfo(shader, out info)) { return info.isSurfaceShader; } else { return false; } } public static bool DoesShaderHaveVariantsDisabled(Shader shader) { ShaderInfo info; if (tryGetShaderInfo(shader, out info)) { return info.doesHaveShaderVariantsDisabled; } else { return false; } } public static void SetShaderVariantsEnabled(Shader shader, bool enable) { string path = AssetDatabase.GetAssetPath(shader); if (string.IsNullOrEmpty(path)) { return; } _infoCache.Remove(path); string[] lines = File.ReadAllLines(path); using (var writer = File.CreateText(path)) { foreach (var line in lines) { if (enable && disabledVariantRegex.IsMatch(line)) { writer.WriteLine(line.Replace("/", " ")); } else if (!enable && enabledVariantRegex.IsMatch(line)) { var startEnum = line.TakeWhile(c => char.IsWhiteSpace(c)); int count = Mathf.Max(0, startEnum.Count() - 2); var start = new string(startEnum.Take(count).ToArray()); writer.WriteLine(start + "//" + line.TrimStart()); } else { writer.WriteLine(line); } } } } private static Dictionary<string, ShaderInfo> _infoCache = new Dictionary<string, ShaderInfo>(); private static bool tryGetShaderInfo(Shader shader, out ShaderInfo info) { string path = AssetDatabase.GetAssetPath(shader); if (string.IsNullOrEmpty(path)) { info = default(ShaderInfo); return false; } DateTime modifiedTime = File.GetLastWriteTime(path); if (_infoCache.TryGetValue(path, out info)) { //If the check time is newer than the modified time, return cached results if (modifiedTime < info.checkTime) { return true; } } info.isSurfaceShader = false; info.doesHaveShaderVariantsDisabled = false; info.checkTime = modifiedTime; string[] lines = File.ReadAllLines(path); foreach (var line in lines) { if (!line.Contains(EARLY_OUT_KEYWORD)) { continue; } if (disabledVariantRegex.IsMatch(line)) { info.doesHaveShaderVariantsDisabled = true; } if (isSurfaceShaderRegex.IsMatch(line)) { info.isSurfaceShader = true; } } _infoCache[path] = info; return true; } private struct ShaderInfo { public bool doesHaveShaderVariantsDisabled; public bool isSurfaceShader; public DateTime checkTime; } } <file_sep>/Assets/LeapMotion/Modules/GraphicRenderer/Scripts/LeapGraphic.cs /****************************************************************************** * Copyright (C) Leap Motion, Inc. 2011-2018. * * Leap Motion proprietary and confidential. * * * * Use subject to the terms of the Leap Motion SDK Agreement available at * * https://developer.leapmotion.com/sdk_agreement, or another agreement * * between Leap Motion and you, your company or other organization. * ******************************************************************************/ using System; using System.Collections.Generic; using UnityEngine; using UnityEngine.Assertions; using Leap.Unity; using Leap.Unity.Space; using Leap.Unity.Query; namespace Leap.Unity.GraphicalRenderer { [ExecuteInEditMode] [DisallowMultipleComponent] public abstract partial class LeapGraphic : MonoBehaviour, ISpaceComponent, ISerializationCallbackReceiver { #region INSPECTOR FIELDS [SerializeField] protected LeapSpaceAnchor _anchor; [SerializeField] protected FeatureDataList _featureData = new FeatureDataList(); [SerializeField] protected LeapGraphicRenderer _attachedRenderer; [SerializeField] protected int _attachedGroupIndex = -1; [SerializeField] protected string _favoriteGroupName; [SerializeField] protected SerializableType _preferredRendererType; #endregion #region PUBLIC API [NonSerialized] private bool _willBeAttached = false; [NonSerialized] private bool _willBeDetached = false; [NonSerialized] private LeapGraphicGroup _groupToBeAttachedTo = null; [NonSerialized] private bool _isRepresentationDirty = true; public Action<LeapGraphicGroup> OnAttachedToGroupEvent; public Action OnDetachedFromGroupEvent; /// <summary> /// An internal flag that returns true if the visual representation of /// this graphic needs to be updated. You can set this to true to request /// a regeneration of the graphic during the next update cycle of the /// renderer. Note however, that not all renderers support updating the /// representation at runtime. /// </summary> public bool isRepresentationDirty { get { return _isRepresentationDirty; } set { _isRepresentationDirty = value; } } /// <summary> /// A simple utility getter that returns true if isRepresentationDirty /// is true, OR it is currently edit time. /// </summary> public bool isRepresentationDirtyOrEditTime { get { #if UNITY_EDITOR if (!Application.isPlaying) { return true; } #endif return _isRepresentationDirty; } } /// <summary> /// Gets or sets the name of the group that this graphic likes to be /// attached to. Whenever a graphic is enabled, it will try to attach /// to its favorite group. Whenever a graphic gets attached to a group, /// that group becomes its new favorite. /// </summary> public string favoriteGroupName { get { return _favoriteGroupName; } set { _favoriteGroupName = value; } } /// <summary> /// Returns the space anchor for this graphic. This will be null if /// the graphic is not currently part of a space. The anchor cannot /// be changed dynamically at runtime. /// </summary> public LeapSpaceAnchor anchor { get { return _anchor; } } /// <summary> /// A utility getter that returns a transformer for this graphic. Even /// if the space anchor for this graphic is null, this will still return /// a valid transformer. In the null case, the transformer is always the /// identity transformer. /// </summary> public ITransformer transformer { get { return _anchor == null ? IdentityTransformer.single : _anchor.transformer; } } /// <summary> /// Returns a list of feature data attached to this graphic. If this graphic /// is attached to a group, this feature data matches 1-to-1 with the features /// attached to this group. /// </summary> public IList<LeapFeatureData> featureData { get { return _featureData; } } /// <summary> /// Returns the group this graphic is attached to. /// </summary> public LeapGraphicGroup attachedGroup { get { if (_attachedRenderer == null) { return null; } else { #if UNITY_EDITOR if (_attachedGroupIndex < 0 || _attachedGroupIndex >= _attachedRenderer.groups.Count) { _attachedRenderer = null; _attachedGroupIndex = -1; return null; } #endif return _attachedRenderer.groups[_attachedGroupIndex]; } } } /// <summary> /// Returns whether or not this graphic is attached to any group. Can still /// return false at runtime even if TryAddGraphic has just completed successfully /// due to the runtime delay for addition/removal of graphics. /// </summary> public bool isAttachedToGroup { get { return attachedGroup != null; } } /// <summary> /// Returns whether or not this graphic will be attached to a group within /// the next frame. Can only be true at runtime, since runtime is the only time /// when delayed attachment occurs. /// </summary> public bool willbeAttached { get { return _willBeAttached; } } /// <summary> /// Returns whether or not this graphic will be detached from a group /// within the next frame. Can only be true at runtime, since runtime is the /// only time when delayed detaching occurs. /// </summary> public bool willbeDetached { get { return _willBeDetached; } } /// <summary> /// Returns the type this graphic prefers to be attached to. When calling /// LeapGraphicRenderer.TryAddGraphic it will prioritize being attached to /// groups with this renderer type if possible. /// </summary> public Type preferredRendererType { get { return _preferredRendererType; } } /// <summary> /// This method tries to detach this graphic from whatever group it is /// currently attached to. It can fail if the graphic is not attached /// to any group, or if the group it is attached to does not support /// adding/removing graphics at runtime. /// </summary> public bool TryDetach() { var attachedGroup = this.attachedGroup; if (attachedGroup == null) { return false; } else { return attachedGroup.TryRemoveGraphic(this); } } /// <summary> /// Gets a single feature data object of a given type T. This will return /// null if there is no feature data object attached to this graphic of type T. /// </summary>> public T GetFeatureData<T>() where T : LeapFeatureData { return _featureData.Query().OfType<T>().FirstOrDefault(); } /// <summary> /// Called by the system to notify that this graphic will be attached within /// the next frame. This is only called at runtime. /// </summary> public virtual void NotifyWillBeAttached(LeapGraphicGroup toBeAttachedTo) { Assert.IsFalse(_willBeAttached); Assert.IsNull(_groupToBeAttachedTo); _willBeAttached = true; _groupToBeAttachedTo = toBeAttachedTo; } /// <summary> /// Called by the system to notify that a previous notification that this /// graphic would be attached has been cancelled due to a call to TryRemoveGraphic. /// </summary> public virtual void CancelWillBeAttached() { Assert.IsTrue(_willBeAttached); Assert.IsNotNull(_groupToBeAttachedTo); _willBeAttached = false; _groupToBeAttachedTo = null; } /// <summary> /// Called by the system to notify that this graphic will be detached within /// the next frame. This is only called at runtime. /// </summary> public virtual void NotifyWillBeDetached(LeapGraphicGroup toBeDetachedFrom) { Assert.IsFalse(_willBeDetached); _willBeDetached = true; } /// <summary> /// Called by the system to notify that a previous notification that this /// graphic would be detached has been cancelled due to a call to TryAddGraphic. /// </summary> public virtual void CancelWillBeDetached() { Assert.IsTrue(_willBeDetached); _willBeDetached = false; } /// <summary> /// Called by the system when this graphic is attached to a group. This method is /// invoked both at runtime and at edit time. /// </summary> public virtual void OnAttachedToGroup(LeapGraphicGroup group, LeapSpaceAnchor anchor) { #if UNITY_EDITOR editor.OnAttachedToGroup(group, anchor); #endif isRepresentationDirty = true; _willBeAttached = false; _groupToBeAttachedTo = null; _favoriteGroupName = group.name; _attachedRenderer = group.renderer; _attachedGroupIndex = _attachedRenderer.groups.IndexOf(group); _anchor = anchor; patchReferences(); if (OnAttachedToGroupEvent != null) { OnAttachedToGroupEvent(group); } } /// <summary> /// Called by graphic groups when a renderer's attached space changes. /// </summary> public void OnUpdateAnchor(LeapSpaceAnchor anchor) { _anchor = anchor; } /// <summary> /// Called by the system when this graphic is detached from a group. This method /// is invoked both at runtime and at edit time. /// </summary> public virtual void OnDetachedFromGroup() { _willBeDetached = false; _attachedRenderer = null; _attachedGroupIndex = -1; _anchor = null; for (int i = 0; i < _featureData.Count; i++) { _featureData[i].feature = null; } if (OnDetachedFromGroupEvent != null) { OnDetachedFromGroupEvent(); } } /// <summary> /// Called by the system whenever feature data is re-assigned to this graphic. This /// is only called at edit time. /// </summary> public virtual void OnAssignFeatureData(List<LeapFeatureData> data) { _featureData.Clear(); foreach (var dataObj in data) { _featureData.Add(dataObj); } } #endregion #region UNITY CALLBACKS protected virtual void Reset() { var rectTransform = GetComponent<RectTransform>(); if (rectTransform != null && Mathf.Abs(rectTransform.sizeDelta.x - 100) < Mathf.Epsilon && Mathf.Abs(rectTransform.sizeDelta.y - 100) < Mathf.Epsilon) { rectTransform.sizeDelta = Vector3.one * 0.1f; } var parentRenderer = GetComponentInParent<LeapGraphicRenderer>(); if (parentRenderer != null) { parentRenderer.TryAddGraphic(this); } } protected virtual void OnValidate() { #if UNITY_EDITOR editor.OnValidate(); #endif patchReferences(); } protected virtual void Awake() { if (isAttachedToGroup && !attachedGroup.graphics.Contains(this)) { var preferredGroup = attachedGroup; OnDetachedFromGroup(); //If this fails for any reason don't worry, we will be auto-added //to a group if we can. preferredGroup.TryAddGraphic(this); } } protected virtual void OnEnable() { patchReferences(); } protected virtual void OnDestroy() { if (Application.isPlaying && isAttachedToGroup) { TryDetach(); } } protected virtual void OnDrawGizmos() { #if UNITY_EDITOR editor.OnDrawGizmos(); #endif } #endregion #region PRIVATE IMPLEMENTATION #if UNITY_EDITOR protected LeapGraphic() { editor = new EditorApi(this); } protected LeapGraphic(EditorApi editor) { this.editor = editor; } #endif public virtual void OnBeforeSerialize() { } public virtual void OnAfterDeserialize() { for (int i = 0; i < _featureData.Count; i++) { _featureData[i].graphic = this; } } private void patchReferences() { if (isAttachedToGroup) { var group = _attachedRenderer.groups[_attachedGroupIndex]; for (int i = 0; i < _featureData.Count; i++) { _featureData[i].feature = group.features[i]; } } } private T getFeatureDataOrThrow<T>() where T : LeapFeatureData { var data = _featureData.Query().OfType<T>().FirstOrDefault(); if (data == null) { throw new Exception("There is not a feature data object of type " + typeof(T).Name + " attached to this graphic."); } return data; } [Serializable] public class FeatureDataList : MultiTypedList<LeapFeatureData, LeapTextureData, LeapSpriteData, LeapRuntimeTintData, LeapBlendShapeData, CustomFloatChannelData, CustomVectorChannelData, CustomColorChannelData, CustomMatrixChannelData> { } #endregion } } <file_sep>/Assets/LeapMotion/Modules/GraphicRenderer/Scripts/Features/Tint/LeapRuntimeTintFeature.cs /****************************************************************************** * Copyright (C) Leap Motion, Inc. 2011-2018. * * Leap Motion proprietary and confidential. * * * * Use subject to the terms of the Leap Motion SDK Agreement available at * * https://developer.leapmotion.com/sdk_agreement, or another agreement * * between Leap Motion and you, your company or other organization. * ******************************************************************************/ using System; namespace Leap.Unity.GraphicalRenderer { [LeapGraphicTag("Runtime Tint", 30)] [Serializable] public class LeapRuntimeTintFeature : LeapGraphicFeature<LeapRuntimeTintData> { public const string FEATURE_NAME = LeapGraphicRenderer.FEATURE_PREFIX + "TINTING"; } } <file_sep>/Assets/Hover/RendererModules/Opaque/Scripts/HoverOpaqueMeshUpdater.cs using System; using Hover.Core.Renderers; using Hover.Core.Utils; using UnityEngine; namespace Hover.RendererModules.Opaque { /*================================================================================================*/ [ExecuteInEditMode] [RequireComponent(typeof(HoverMesh))] public class HoverOpaqueMeshUpdater : MonoBehaviour, ITreeUpdateable, ISettingsController { public ISettingsControllerMap Controllers { get; private set; } [DisableWhenControlled] [ColorUsage(false, true, 0, 1000, 0, 1000)] public Color StandardColor = Color.gray; [DisableWhenControlled] [ColorUsage(false, true, 0, 1000, 0, 1000)] public Color SliderFillColor = Color.white; private Color vPrevColor; //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ protected HoverOpaqueMeshUpdater() { Controllers = new SettingsControllerMap(); } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public void Start() { //do nothing... } /*--------------------------------------------------------------------------------------------*/ public void TreeUpdate() { TryUpdateColor(GetComponent<HoverMesh>()); vPrevColor = StandardColor; Controllers.TryExpireControllers(); } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ private void TryUpdateColor(HoverMesh pHoverMesh) { Controllers.Set(SettingsControllerMap.MeshColors, this); Color useColor; switch ( pHoverMesh.DisplayMode ) { case HoverMesh.DisplayModeType.Standard: useColor = StandardColor; break; case HoverMesh.DisplayModeType.SliderFill: useColor = SliderFillColor; break; default: throw new Exception("Unhandled display mode: "+pHoverMesh.DisplayMode); } if ( !pHoverMesh.DidRebuildMesh && useColor == vPrevColor ) { return; } pHoverMesh.Builder.CommitColors(useColor); } } } <file_sep>/Assets/Hover/Core/Scripts/Items/Types/HoverItemDataSticky.cs using System; using UnityEngine; namespace Hover.Core.Items.Types { /*================================================================================================*/ [Serializable] public class HoverItemDataSticky : HoverItemDataSelectable, IItemDataSticky { [SerializeField] private bool _AllowIdleDeselection = false; //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ protected override bool UsesStickySelection() { return true; } /*--------------------------------------------------------------------------------------------*/ public override bool AllowIdleDeselection { get { return _AllowIdleDeselection; } set { _AllowIdleDeselection = value; } } } } <file_sep>/Assets/Hover/Core/Scripts/Items/Types/HoverItemDataSlider.cs using System; using Hover.Core.Utils; using UnityEngine; namespace Hover.Core.Items.Types { /*================================================================================================*/ [Serializable] public class HoverItemDataSlider : HoverItemDataSelectableFloat, IItemDataSlider { public Func<IItemDataSlider, string> GetFormattedLabel { get; set; } [SerializeField] private string _LabelFormat = "{0}: {1:N1}"; [SerializeField] private int _Ticks = 0; [SerializeField] private int _Snaps = 0; [SerializeField] private float _RangeMin = -100; [SerializeField] private float _RangeMax = 100; [SerializeField] private bool _AllowJump = false; [SerializeField] private SliderFillType _FillStartingPoint = SliderFillType.MinimumValue; [SerializeField] private bool _AllowIdleDeselection = false; private float? vHoverValue; private string vPrevLabel; private string vPrevLabelFormat; private float vPrevSnappedRangeValue; private string vPrevValueToLabel; //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public HoverItemDataSlider() { _Value = 0.5f; GetFormattedLabel = (s => { if ( s.Label == vPrevLabel && s.LabelFormat == vPrevLabelFormat && s.SnappedRangeValue == vPrevSnappedRangeValue ) { return vPrevValueToLabel; } vPrevLabel = s.Label; vPrevLabelFormat = s.LabelFormat; vPrevSnappedRangeValue = s.SnappedRangeValue; vPrevValueToLabel = string.Format(vPrevLabelFormat, vPrevLabel, vPrevSnappedRangeValue); //GC_ALLOC return vPrevValueToLabel; }); } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public string LabelFormat { get { return _LabelFormat; } set { _LabelFormat = value; } } /*--------------------------------------------------------------------------------------------*/ public int Ticks { get { return _Ticks; } set { _Ticks = value; } } /*--------------------------------------------------------------------------------------------*/ public int Snaps { get { return _Snaps; } set { _Snaps = value; } } /*--------------------------------------------------------------------------------------------*/ public float RangeMin { get { return _RangeMin; } set { _RangeMin = value; } } /*--------------------------------------------------------------------------------------------*/ public float RangeMax { get { return _RangeMax; } set { _RangeMax = value; } } /*--------------------------------------------------------------------------------------------*/ public bool AllowJump { get { return _AllowJump; } set { _AllowJump = value; } } /*--------------------------------------------------------------------------------------------*/ public SliderFillType FillStartingPoint { get { return _FillStartingPoint; } set { _FillStartingPoint = value; } } /*--------------------------------------------------------------------------------------------*/ public override void DeselectStickySelections() { Value = SnappedValue; base.DeselectStickySelections(); } /*--------------------------------------------------------------------------------------------*/ public override bool AllowIdleDeselection { get { return _AllowIdleDeselection; } set { _AllowIdleDeselection = value; } } /*--------------------------------------------------------------------------------------------*/ public override float Value { get { return base.Value; } set { base.Value = Math.Max(0, Math.Min(1, value)); } } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public float RangeValue { get { return Value*(RangeMax-RangeMin)+RangeMin; } } /*--------------------------------------------------------------------------------------------*/ public float SnappedValue { get { return CalcSnappedValue(Value); } } /*--------------------------------------------------------------------------------------------*/ public float SnappedRangeValue { get { return SnappedValue*(RangeMax-RangeMin)+RangeMin; } } /*--------------------------------------------------------------------------------------------*/ public float? HoverValue { get { return vHoverValue; } set { if ( value == null ) { vHoverValue = null; return; } vHoverValue = Math.Max(0, Math.Min(1, (float)value)); } } /*--------------------------------------------------------------------------------------------*/ public float? SnappedHoverValue { get { if ( HoverValue == null ) { return null; } return CalcSnappedValue((float)HoverValue); } } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ protected override bool UsesStickySelection() { return true; } /*--------------------------------------------------------------------------------------------*/ private float CalcSnappedValue(float pValue) { if ( Snaps < 2 ) { return pValue; } int s = Snaps-1; return (float)Math.Round(pValue*s)/s; } } } <file_sep>/Assets/Hover/Core/Scripts/Renderers/Utils/SliderUtil.cs using System; using System.Collections.Generic; using Hover.Core.Utils; using UnityEngine; namespace Hover.Core.Renderers.Utils { /*================================================================================================*/ public static class SliderUtil { public enum SegmentType { Track, Handle, Jump, Start, Zero, End, Tick } public enum PositionType { TrackStart, TrackEnd, HandleStart, HandleEnd, JumpStart, JumpEnd, Zero, TickStart, TickEnd } [Serializable] public struct SegmentInfo { public SegmentType Type; public PositionType StartPositionType; public PositionType EndPositionType; public float StartPosition; public float EndPosition; public bool IsFill; public bool IsHidden; } [Serializable] public struct SliderInfo { public SliderFillType FillType; public float TrackStartPosition; public float TrackEndPosition; public float HandleSize; public float HandleValue; public float JumpSize; public float JumpValue; public float ZeroValue; public int TickCount; public float TickSize; } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public static void CalculateSegments(SliderInfo pInfo, List<SegmentInfo> pSegments) { pSegments.Clear(); int mult = (pInfo.TrackStartPosition < pInfo.TrackEndPosition ? 1 : -1); float half = 0.5f*mult; float handleMinPos = pInfo.TrackStartPosition + pInfo.HandleSize*half; float handleMaxPos = pInfo.TrackEndPosition - pInfo.HandleSize*half; float handlePos = Mathf.Lerp(handleMinPos, handleMaxPos, pInfo.HandleValue); float jumpPos = Mathf.Lerp(handleMinPos, handleMaxPos, pInfo.JumpValue); float zeroPos = Mathf.Lerp(handleMinPos, handleMaxPos, pInfo.ZeroValue); bool hasJump = (pInfo.JumpSize > 0); bool isJumpTooNear = (Mathf.Abs(handlePos-jumpPos) < (pInfo.HandleSize+pInfo.JumpSize)*0.6f); var handleSeg = new SegmentInfo { Type = SegmentType.Handle, StartPositionType = PositionType.HandleStart, EndPositionType = PositionType.HandleEnd, StartPosition = handlePos-pInfo.HandleSize*half, EndPosition = handlePos+pInfo.HandleSize*half }; pSegments.Add(handleSeg); if ( hasJump && !isJumpTooNear && pInfo.JumpValue >= 0 ) { var jumpSeg = new SegmentInfo { Type = SegmentType.Jump, StartPositionType = PositionType.JumpStart, EndPositionType = PositionType.JumpEnd, StartPosition = jumpPos-pInfo.JumpSize*half, EndPosition = jumpPos+pInfo.JumpSize*half }; pSegments.Insert((handlePos*mult < jumpPos*mult ? 1 : 0), jumpSeg); } //// if ( pInfo.FillType == SliderFillType.Zero ) { var zeroSeg = new SegmentInfo { Type = SegmentType.Zero, StartPositionType = PositionType.Zero, EndPositionType = PositionType.Zero, StartPosition = zeroPos, EndPosition = zeroPos }; int zeroI; if ( zeroPos*mult < pSegments[0].StartPosition*mult ) { zeroI = 0; pSegments.Insert(zeroI, zeroSeg); } else if ( pSegments.Count > 1 && zeroPos*mult < pSegments[1].StartPosition*mult ) { zeroI = 1; pSegments.Insert(zeroI, zeroSeg); } else { zeroI = pSegments.Count; pSegments.Add(zeroSeg); } if ( zeroI > 0 ) { SegmentInfo beforeZeroSeg = pSegments[zeroI-1]; if ( zeroSeg.StartPosition*mult < beforeZeroSeg.EndPosition*mult ) { zeroSeg.StartPosition = beforeZeroSeg.EndPosition; zeroSeg.EndPosition = beforeZeroSeg.EndPosition; zeroSeg.StartPositionType = beforeZeroSeg.EndPositionType; zeroSeg.EndPositionType = beforeZeroSeg.EndPositionType; pSegments[zeroI] = zeroSeg; } } } //// var startSeg = new SegmentInfo { Type = SegmentType.Start, StartPositionType = PositionType.TrackStart, EndPositionType = PositionType.TrackStart, StartPosition = pInfo.TrackStartPosition, EndPosition = pInfo.TrackStartPosition }; var endSeg = new SegmentInfo { Type = SegmentType.End, StartPositionType = PositionType.TrackEnd, EndPositionType = PositionType.TrackEnd, StartPosition = pInfo.TrackEndPosition, EndPosition = pInfo.TrackEndPosition }; pSegments.Insert(0, startSeg); pSegments.Add(endSeg); //// bool isFilling = false; SegmentType fillToSegType; switch ( pInfo.FillType ) { case SliderFillType.Zero: fillToSegType = SegmentType.Zero; break; case SliderFillType.MinimumValue: fillToSegType = SegmentType.Start; break; case SliderFillType.MaximumValue: fillToSegType = SegmentType.End; break; default: throw new Exception("Unhandled fill type: "+pInfo.FillType); } //// for ( int i = 1 ; i < pSegments.Count ; i++ ) { SegmentInfo prevSeg = pSegments[i-1]; SegmentInfo nextSeg = pSegments[i]; if ( prevSeg.Type == SegmentType.Handle || prevSeg.Type == fillToSegType ) { isFilling = !isFilling; } var trackSeg = new SegmentInfo { Type = SegmentType.Track, StartPositionType = prevSeg.EndPositionType, EndPositionType = nextSeg.StartPositionType, StartPosition = prevSeg.EndPosition, EndPosition = nextSeg.StartPosition, IsFill = isFilling }; pSegments.Insert(i, trackSeg); i++; } } /*--------------------------------------------------------------------------------------------*/ public static void CalculateTicks(SliderInfo pInfo, List<SegmentInfo> pSliderSegments, List<SegmentInfo> pTicks) { pTicks.Clear(); if ( pInfo.TickCount <= 1 ) { return; } //// float handStart = -1; float handEnd = -1; float jumpStart = -1; float jumpEnd = -1; for ( int i = 0 ; i < pSliderSegments.Count ; i++ ) { SegmentInfo seg = pSliderSegments[i]; if ( seg.Type == SegmentType.Handle ) { handStart = seg.StartPosition; handEnd = seg.EndPosition; } if ( seg.Type == SegmentType.Jump ) { jumpStart = seg.StartPosition; jumpEnd = seg.EndPosition; } } //// int mult = (pInfo.TrackStartPosition < pInfo.TrackEndPosition ? 1 : -1); float half = 0.5f*mult; float handleMinPos = pInfo.TrackStartPosition + pInfo.HandleSize*half; float handleMaxPos = pInfo.TrackEndPosition - pInfo.HandleSize*half; for ( int i = 0 ; i < pInfo.TickCount ; i++ ) { float prog = i/(pInfo.TickCount-1f); float tickCenterPos = Mathf.Lerp(handleMinPos, handleMaxPos, prog); var tick = new SegmentInfo { Type = SegmentType.Tick, StartPositionType = PositionType.TickStart, EndPositionType = PositionType.TickEnd, StartPosition = tickCenterPos-pInfo.TickSize*half, EndPosition = tickCenterPos+pInfo.TickSize*half }; float startMult = tick.StartPosition*mult; float endMult = tick.EndPosition*mult; bool startsInHand = (startMult >= handStart*mult && startMult <= handEnd*mult); bool endsInHand = (endMult >= handStart*mult && endMult <= handEnd*mult); bool startsInJump = (startMult >= jumpStart*mult && startMult <= jumpEnd*mult); bool endsInJump = (endMult >= jumpStart*mult && endMult <= jumpEnd*mult); tick.IsHidden = ((startsInHand && endsInHand) || (startsInJump && endsInJump)); if ( startsInHand ) { tick.StartPosition = handEnd; } if ( endsInHand ) { tick.EndPosition = handStart; } if ( startsInJump ) { tick.StartPosition = jumpEnd; } if ( endsInJump ) { tick.EndPosition = jumpStart; } pTicks.Add(tick); } } } } <file_sep>/Assets/LeapMotion/Core/Examples/Example Assets/ProjectionPostProcessProvider.cs /****************************************************************************** * Copyright (C) Leap Motion, Inc. 2011-2018. * * Leap Motion proprietary and confidential. * * * * Use subject to the terms of the Leap Motion SDK Agreement available at * * https://developer.leapmotion.com/sdk_agreement, or another agreement * * between Leap Motion and you, your company or other organization. * ******************************************************************************/ using UnityEngine; namespace Leap.Unity.Examples { public class ProjectionPostProcessProvider : PostProcessProvider { [Header("Projection")] [Tooltip("The exponent of the projection of any hand distance from the approximated " + "shoulder beyond the handMergeDistance.")] [Range(0f, 5f)] public float projectionExponent = 3.50f; [Tooltip("The distance from the approximated shoulder beyond which any additional " + "distance is exponentiated by the projectionExponent.")] [Range(0f, 1f)] public float handMergeDistance = 0.30f; public override void ProcessFrame(ref Frame inputFrame) { // Calculate the position of the head and the basis to calculate shoulder position. var headPos = Camera.main.transform.position; var shoulderBasis = Quaternion.LookRotation( Vector3.ProjectOnPlane(Camera.main.transform.forward, Vector3.up), Vector3.up); foreach (var hand in inputFrame.Hands) { // Approximate shoulder position with magic values. var shoulderPos = headPos + (shoulderBasis * (new Vector3(0f, -0.2f, -0.1f) + Vector3.left * 0.1f * (hand.IsLeft ? 1f : -1f))); // Calculate the projection of the hand if it extends beyond the // handMergeDistance. var shoulderToHand = hand.PalmPosition.ToVector3() - shoulderPos; var handShoulderDist = shoulderToHand.magnitude; var projectionDistance = Mathf.Max(0f, handShoulderDist - handMergeDistance); var projectionAmount = Mathf.Pow(1 + projectionDistance, projectionExponent); hand.SetTransform(shoulderPos + shoulderToHand * projectionAmount, hand.Rotation.ToQuaternion()); } } } } <file_sep>/Assets/Hover/Core/Scripts/Items/Types/IItemDataSelectableT.cs namespace Hover.Core.Items.Types { /*================================================================================================*/ public interface IItemDataSelectable<T> : IItemDataSelectable { event ItemEvents.ValueChangedHandler<T> OnValueChanged; T Value { get; set; } } } <file_sep>/Assets/Hover/Core/Scripts/Renderers/Items/Buttons/HoverFillButton.cs using System; using Hover.Core.Renderers.Shapes; using Hover.Core.Utils; using UnityEngine; namespace Hover.Core.Renderers.Items.Buttons { /*================================================================================================*/ [RequireComponent(typeof(HoverIndicator))] [RequireComponent(typeof(HoverShape))] public class HoverFillButton : HoverFill { public const string ShowEdgeName = "ShowEdge"; [DisableWhenControlled(DisplaySpecials=true)] public HoverMesh Background; [DisableWhenControlled] public HoverMesh Highlight; [DisableWhenControlled] public HoverMesh Selection; [DisableWhenControlled] public HoverMesh Edge; [DisableWhenControlled] public bool ShowEdge = true; //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public override int GetChildMeshCount() { return 4; } /*--------------------------------------------------------------------------------------------*/ public override HoverMesh GetChildMesh(int pIndex) { switch ( pIndex ) { case 0: return Background; case 1: return Highlight; case 2: return Selection; case 3: return Edge; } throw new ArgumentOutOfRangeException(); } } } <file_sep>/Assets/Hover/Core/Scripts/Items/Types/IItemDataRadio.cs namespace Hover.Core.Items.Types { /*================================================================================================*/ public interface IItemDataRadio : IItemDataSelectable<bool> { string DefaultGroupId { get; } string GroupId { get; set; } } } <file_sep>/Assets/Hover/Core/Scripts/Renderers/Shapes/Rect/HoverRendererSliderRectUpdater.cs using Hover.Core.Renderers.Items.Buttons; using Hover.Core.Renderers.Items.Sliders; using Hover.Core.Renderers.Utils; using Hover.Core.Utils; using UnityEngine; namespace Hover.Core.Renderers.Shapes.Rect { /*================================================================================================*/ [RequireComponent(typeof(HoverRendererSliderSegments))] [RequireComponent(typeof(HoverShapeRect))] public class HoverRendererSliderRectUpdater : HoverRendererSliderUpdater { //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public override void TreeUpdate() { HoverRendererSlider rendSlider = gameObject.GetComponent<HoverRendererSlider>(); HoverShapeRect shapeRect = gameObject.GetComponent<HoverShapeRect>(); HoverShapeRect handleShapeRect = (HoverShapeRect)rendSlider.HandleButton.GetShape(); HoverShapeRect jumpShapeRect = (HoverShapeRect)rendSlider.JumpButton.GetShape(); shapeRect.SizeY = Mathf.Max(shapeRect.SizeY, handleShapeRect.SizeY); UpdateTrackShape(shapeRect, rendSlider); UpdateButtonWidth(shapeRect, handleShapeRect); UpdateButtonWidth(shapeRect, jumpShapeRect); UpdateButtonPositions(rendSlider); } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ private void UpdateTrackShape(HoverShapeRect pShapeRect, HoverRendererSlider pRendSlider) { HoverShapeRect trackShapeRect = (HoverShapeRect)pRendSlider.Track.GetShape(); trackShapeRect.Controllers.Set(HoverShapeRect.SizeXName, this); trackShapeRect.Controllers.Set(HoverShapeRect.SizeYName, this); trackShapeRect.SizeX = pShapeRect.SizeX; trackShapeRect.SizeY = pShapeRect.SizeY; } /*--------------------------------------------------------------------------------------------*/ private void UpdateButtonWidth(HoverShapeRect pShapeRect, HoverShapeRect pButtonShapeRect) { pButtonShapeRect.Controllers.Set(HoverShapeRect.SizeXName, this); pButtonShapeRect.SizeX = pShapeRect.SizeX; } /*--------------------------------------------------------------------------------------------*/ private void UpdateButtonPositions(HoverRendererSlider pRendSlider) { HoverRendererSliderSegments segs = gameObject.GetComponent<HoverRendererSliderSegments>(); for ( int i = 0 ; i < segs.SegmentInfoList.Count ; i++ ) { SliderUtil.SegmentInfo segInfo = segs.SegmentInfoList[i]; bool isHandle = (segInfo.Type == SliderUtil.SegmentType.Handle); bool isJump = (segInfo.Type == SliderUtil.SegmentType.Jump); if ( !isHandle && !isJump ) { continue; } HoverRendererButton button = (isHandle ? pRendSlider.HandleButton : pRendSlider.JumpButton); button.Controllers.Set(SettingsControllerMap.TransformLocalPosition+".y", this); Vector3 buttonLocalPos = button.transform.localPosition; buttonLocalPos.y = (segInfo.StartPosition+segInfo.EndPosition)/2; button.transform.localPosition = buttonLocalPos; } } } } <file_sep>/Assets/Hover/README.md ## Hover UI Kit Latest version: `v2.0.1B (beta)` Source code, project documentation, and software license: http://HoverVR.com Author: <NAME> (Aesthetic Interactive) - http://twitter.com/zachkinstner - http://medium.com/@zachkinstner - http://youtube.com/aestheticinteractive/videos - http://aestheticinteractive.com <file_sep>/Assets/Hover/Core/Scripts/Cursors/StickySelectionInfo.cs using UnityEngine; namespace Hover.Core.Cursors { /*================================================================================================*/ public struct StickySelectionInfo { public Vector3 ItemWorldPosition; public float SelectionProgress; } } <file_sep>/Assets/Hover/Core/Scripts/Utils/SettingsControllerMap.cs using System.Collections.Generic; using UnityEngine; namespace Hover.Core.Utils { /*================================================================================================*/ public class SettingsControllerMap : ISettingsControllerMap { public const char SpecialPrefixChar = '*'; public const string SpecialPrefix = "*"; public const string GameObjectActiveSelf = SpecialPrefix+"gameObject.activeSelf"; public const string TransformPosition = SpecialPrefix+"transform.position"; public const string TransformRotation = SpecialPrefix+"transform.rotation"; public const string TransformLocalPosition = SpecialPrefix+"transform.localPosition"; public const string TransformLocalRotation = SpecialPrefix+"transform.localRotation"; public const string TransformLocalScale = SpecialPrefix+"transform.localScale"; public const string CanvasSortingLayer = SpecialPrefix+"canvas.sortingLayer"; public const string CanvasGroupAlpha = SpecialPrefix+"canvasGroup.alpha"; public const string TextText = SpecialPrefix+"Text.text"; public const string TextAlignment = SpecialPrefix+"Text.alignment"; public const string MeshRendererSortingLayer = SpecialPrefix+"MeshRenderer.sortingLayer"; public const string MeshRendererSortingOrder = SpecialPrefix+"MeshRenderer.sortingOrder"; public const string MeshColors = SpecialPrefix+"Mesh.colors"; private class ExpirableController { public ISettingsController Controller; public int ExpireCount; } private readonly Dictionary<string, ExpirableController> vMap; private readonly List<string> vKeys; //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public SettingsControllerMap() { vMap = new Dictionary<string, ExpirableController>(); vKeys = new List<string>(); } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public void Set(string pValueName, ISettingsController pController, int pExpirationCount=1) { if ( !Application.isEditor ) { return; } ExpirableController expCont; if ( vMap.ContainsKey(pValueName) ) { expCont = vMap[pValueName]; } else { expCont = new ExpirableController(); vMap.Add(pValueName, expCont); vKeys.Add(pValueName); } expCont.Controller = pController; expCont.ExpireCount = pExpirationCount; } /*--------------------------------------------------------------------------------------------*/ public bool Unset(string pValueName, ISettingsController pController) { if ( !Application.isEditor ) { return false; } if ( vMap.ContainsKey(pValueName) && vMap[pValueName].Controller == pController ) { vMap.Remove(pValueName); vKeys.Remove(pValueName); return true; } return false; } /*--------------------------------------------------------------------------------------------*/ public void TryExpireControllers() { if ( !Application.isEditor ) { return; } for ( int i = 0 ; i < vKeys.Count ; i++ ) { ExpirableController expCont = vMap[vKeys[i]]; if ( --expCont.ExpireCount >= 0 ) { continue; } vMap.Remove(vKeys[i]); vKeys.RemoveAt(i); i--; } } #if UNITY_EDITOR //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public ISettingsController Get(string pValueName) { return (vMap.ContainsKey(pValueName) ? vMap[pValueName].Controller : null); } /*--------------------------------------------------------------------------------------------*/ public bool IsControlled(string pValueName) { ISettingsController cont = Get(pValueName); //Debug.Log(" ============ "+pValueName+" = "+ // cont+" / "+(cont == null ? "---" : cont.isActiveAndEnabled+"")); return (cont != null && cont.isActiveAndEnabled); } /*--------------------------------------------------------------------------------------------*/ public bool AreAnyControlled() { for ( int i = 0 ; i < vKeys.Count ; i++ ) { if ( IsControlled(vKeys[i]) ) { return true; } } return false; } /*--------------------------------------------------------------------------------------------*/ public int GetControlledCount(bool pSpecialsOnly=false) { int count = 0; for ( int i = 0 ; i < vKeys.Count ; i++ ) { if ( pSpecialsOnly && vKeys[i][0] != SpecialPrefixChar ) { continue; } if ( IsControlled(vKeys[i]) ) { count++; } } return count; } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public List<string> GetNewListOfControlledValueNames(bool pSpecialsOnly=false) { var list = new List<string>(); FillListWithControlledValueNames(list, pSpecialsOnly); return list; } /*--------------------------------------------------------------------------------------------*/ public void FillListWithControlledValueNames(List<string> pList, bool pSpecialsOnly=false) { pList.Clear(); for ( int i = 0 ; i < vKeys.Count ; i++ ) { string valueName = vKeys[i]; if ( pSpecialsOnly && valueName[0] != SpecialPrefixChar ) { continue; } if ( !IsControlled(valueName) ) { continue; } pList.Add(valueName); } } #endif } } <file_sep>/Assets/LeapMotion/Core/Editor/LeapServiceProviderEditor.cs /****************************************************************************** * Copyright (C) Leap Motion, Inc. 2011-2018. * * Leap Motion proprietary and confidential. * * * * Use subject to the terms of the Leap Motion SDK Agreement available at * * https://developer.leapmotion.com/sdk_agreement, or another agreement * * between Leap Motion and you, your company or other organization. * ******************************************************************************/ using UnityEngine; using UnityEditor; namespace Leap.Unity { [CustomEditor(typeof(LeapServiceProvider))] public class LeapServiceProviderEditor : CustomEditorBase<LeapServiceProvider> { protected Quaternion deviceRotation = Quaternion.identity; protected bool isVRProvider = false; protected Vector3 controllerOffset = Vector3.zero; private const float BOX_RADIUS = 0.45f; private const float BOX_WIDTH = 0.965f; private const float BOX_DEPTH = 0.6671f; protected override void OnEnable() { base.OnEnable(); specifyCustomDecorator("_frameOptimization", frameOptimizationWarning); specifyConditionalDrawing("_frameOptimization", (int)LeapServiceProvider.FrameOptimizationMode.None, "_physicsExtrapolation", "_physicsExtrapolationTime"); specifyConditionalDrawing("_physicsExtrapolation", (int)LeapServiceProvider.PhysicsExtrapolationMode.Manual, "_physicsExtrapolationTime"); deferProperty("_workerThreadProfiling"); } private void frameOptimizationWarning(SerializedProperty property) { var mode = (LeapServiceProvider.FrameOptimizationMode)property.intValue; string warningText; switch (mode) { case LeapServiceProvider.FrameOptimizationMode.ReuseUpdateForPhysics: warningText = "Reusing update frames for physics introduces a frame of latency " + "for physics interactions."; break; case LeapServiceProvider.FrameOptimizationMode.ReusePhysicsForUpdate: warningText = "This optimization REQUIRES physics framerate to match your " + "target framerate EXACTLY."; break; default: return; } EditorGUILayout.HelpBox(warningText, MessageType.Warning); } public override void OnInspectorGUI() { if (UnityEditor.PlayerSettings.virtualRealitySupported && !isVRProvider) { EditorGUILayout.HelpBox( "VR support is enabled. If your Leap is mounted to your headset, you should be " + "using LeapXRServiceProvider instead of LeapServiceProvider. (If your Leap " + "is not mounted to your headset, you can safely ignore this warning.)", MessageType.Warning); } base.OnInspectorGUI(); } public virtual void OnSceneGUI() { Vector3 origin = target.transform.TransformPoint(controllerOffset); Vector3 local_top_left, top_left, local_top_right, top_right, local_bottom_left, bottom_left, local_bottom_right, bottom_right; getLocalGlobalPoint(-1, 1, 1, out local_top_left, out top_left); getLocalGlobalPoint(1, 1, 1, out local_top_right, out top_right); getLocalGlobalPoint(-1, 1, -1, out local_bottom_left, out bottom_left); getLocalGlobalPoint(1, 1, -1, out local_bottom_right, out bottom_right); Handles.DrawLine(origin, top_left); Handles.DrawLine(origin, top_right); Handles.DrawLine(origin, bottom_left); Handles.DrawLine(origin, bottom_right); drawControllerEdge(origin, local_top_left, local_top_right); drawControllerEdge(origin, local_bottom_left, local_top_left); drawControllerEdge(origin, local_bottom_left, local_bottom_right); drawControllerEdge(origin, local_bottom_right, local_top_right); drawControllerArc(origin, local_top_left, local_bottom_left, local_top_right, local_bottom_right); drawControllerArc(origin, local_top_left, local_top_right, local_bottom_left, local_bottom_right); } private void getLocalGlobalPoint(int x, int y, int z, out Vector3 local, out Vector3 global) { local = deviceRotation * new Vector3(x * BOX_WIDTH, y * BOX_RADIUS, z * BOX_DEPTH); global = target.transform.TransformPoint(controllerOffset + BOX_RADIUS * local.normalized); } private void drawControllerEdge(Vector3 origin, Vector3 edge0, Vector3 edge1) { Vector3 right_normal = target.transform .TransformDirection(Vector3.Cross(edge0, edge1)); float right_angle = Vector3.Angle(edge0, edge1); Handles.DrawWireArc(origin, right_normal, target.transform.TransformDirection(edge0), right_angle, target.transform.lossyScale.x * BOX_RADIUS); } private void drawControllerArc(Vector3 origin, Vector3 edgeA0, Vector3 edgeA1, Vector3 edgeB0, Vector3 edgeB1) { Vector3 faceA = target.transform.rotation * Vector3.Lerp(edgeA0, edgeA1, 0.5f); Vector3 faceB = target.transform.rotation * Vector3.Lerp(edgeB0, edgeB1, 0.5f); float resolutionIncrement = 1f / 50f; for (float i = 0f; i < 1f; i += resolutionIncrement) { Vector3 begin = Vector3.Lerp(faceA, faceB, i).normalized * target.transform.lossyScale.x * BOX_RADIUS; Vector3 end = Vector3.Lerp(faceA, faceB, i + resolutionIncrement).normalized * target.transform.lossyScale.x * BOX_RADIUS; Handles.DrawLine(origin + begin, origin + end); } } } } <file_sep>/Assets/LeapMotion/Core/Scripts/Utils/LeapColor.cs /****************************************************************************** * Copyright (C) Leap Motion, Inc. 2011-2018. * * Leap Motion proprietary and confidential. * * * * Use subject to the terms of the Leap Motion SDK Agreement available at * * https://developer.leapmotion.com/sdk_agreement, or another agreement * * between Leap Motion and you, your company or other organization. * ******************************************************************************/ using UnityEngine; namespace Leap.Unity { /// <summary> /// Contains color constants like UnityEngine.Color, but for _all_ the colors you /// can think of. If you can think of a color that doesn't exist here, add it! /// /// (Note: This class exists for convenience, not runtime speed.) /// </summary> public static class LeapColor { #region Grayscale public static Color black { get { return Color.black; } } public static Color gray { get { return new Color(0.5f, 0.5f, 0.5f); } } public static Color white { get { return Color.white; } } #endregion #region Warm Colors & Browns public static Color pink { get { return new Color(255f / 255f, 0xC0 / 255f, 0xCB / 255f); } } public static Color magenta { get { return Color.magenta; } } /// <summary> /// Warning: Not VERY distinct from magenta. /// </summary> public static Color fuschia { get { return lerp(Color.magenta, Color.blue, 0.1f); } } public static Color red { get { return Color.red; } } public static Color brown { get { return new Color(0x96 / 255f, 0x4B / 255f, 0x00 / 255f); } } public static Color beige { get { return new Color(0xF5 / 255f, 0xF5 / 255f, 0xDC / 255f); } } public static Color coral { get { return new Color(0xFF / 255f, 0x7F / 255f, 0x50 / 255f); } } public static Color orange { get { return lerp(red, yellow, 0.5f); } } public static Color khaki { get { return new Color(0xC3 / 255f, 0xB0 / 255f, 0x91 / 255f); } } public static Color amber { get { return new Color(0xFF / 255f, 0xBF / 255f, 0x00 / 255f); } } public static Color yellow { get { return Color.yellow; } } public static Color gold { get { return new Color(0xD4 / 255f, 0xAF / 255f, 0x37 / 255f); } } #endregion #region Cool Colors public static Color green { get { return Color.green; } } public static Color forest { get { return new Color(0x22 / 255f, 0x8B / 255f, 0x22 / 255f); } } public static Color lime { get { return new Color(158f / 255f, 253f / 255f, 56f / 255f); } } public static Color mint { get { return new Color(0x98 / 255f, 0xFB / 255f, 0x98 / 255f); } } public static Color olive { get { return new Color(0x80 / 255f, 0x80 / 255f, 0x00 / 255f); } } public static Color jade { get { return new Color(0x00 / 255f, 0xA8 / 255f, 0x6B / 255f); } } public static Color teal { get { return new Color(0x00 / 255f, 0x80 / 255f, 0x80 / 255f); } } public static Color veridian { get { return new Color(0x40 / 255f, 0x82 / 255f, 0x6D / 255f); } } public static Color turquoise { get { return new Color(0x40 / 255f, 0xE0 / 255f, 0xD0 / 255f); } } public static Color cyan { get { return Color.cyan; } } public static Color cerulean { get { return new Color(0x00 / 255f, 0x7B / 255f, 0xA7 / 255f); } } public static Color aqua { get { return new Color(143f / 255f, 224f / 255f, 247f / 255f); } } public static Color electricBlue { get { return new Color(0x7D / 255f, 0xF9 / 255f, 0xFF / 255f); } } public static Color blue { get { return Color.blue; } } public static Color navy { get { return new Color(0x00 / 255f, 0x00 / 255f, 0x80 / 255f); } } public static Color periwinkle { get { return new Color(0xCC / 255f, 0xCC / 255f, 0xFF / 255f); } } public static Color purple { get { return lerp(magenta, blue, 0.3f); } } public static Color violet { get { return new Color(0x7F / 255f, 0x00 / 255f, 0xFF / 255f); } } public static Color lavender { get { return new Color(0xB5 / 255f, 0x7E / 255f, 0xDC / 255f); } } #endregion #region Shorthand private static Color lerp(Color a, Color b, float amount) { return Color.Lerp(a, b, amount); } #endregion } } <file_sep>/Assets/Hover/Core/Scripts/Utils/SliderFillType.cs namespace Hover.Core.Utils { /*================================================================================================*/ public enum SliderFillType { MinimumValue, Zero, MaximumValue } } <file_sep>/Assets/Hover/Core/Scripts/Items/Helpers/HoverChildItemsFinder.cs using System.Collections.Generic; using Hover.Core.Utils; using UnityEngine; namespace Hover.Core.Items.Helpers { /*================================================================================================*/ [ExecuteInEditMode] [RequireComponent(typeof(TreeUpdater))] public class HoverChildItemsFinder : MonoBehaviour, ITreeUpdateable { public List<HoverItemData> ChildItems { get; private set; } public bool FindOnlyImmediateChildren = false; public bool ForceUpdate = false; private bool vPrevAffectOnlyImmediateChildren; //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public void Start() { //do nothing... } /*--------------------------------------------------------------------------------------------*/ public void TreeUpdate() { bool isFirst = false; if ( ChildItems == null ) { ChildItems = new List<HoverItemData>(); isFirst = true; } if ( !isFirst && !ForceUpdate && FindOnlyImmediateChildren == vPrevAffectOnlyImmediateChildren ) { return; } ChildItems.Clear(); FillChildItemsList(gameObject.transform); ForceUpdate = false; vPrevAffectOnlyImmediateChildren = FindOnlyImmediateChildren; } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ private void FillChildItemsList(Transform pParentTx) { int childCount = pParentTx.childCount; for ( int i = 0 ; i < childCount ; i++ ) { Transform childTx = pParentTx.GetChild(i); HoverItemData item = childTx.GetComponent<HoverItemData>(); if ( item != null ) { ChildItems.Add(item); } if ( !FindOnlyImmediateChildren ) { FillChildItemsList(childTx); } } } } } <file_sep>/Assets/LeapMotion/Modules/GraphicRenderer/Scripts/Utility/JaggedArray.cs /****************************************************************************** * Copyright (C) Leap Motion, Inc. 2011-2018. * * Leap Motion proprietary and confidential. * * * * Use subject to the terms of the Leap Motion SDK Agreement available at * * https://developer.leapmotion.com/sdk_agreement, or another agreement * * between Leap Motion and you, your company or other organization. * ******************************************************************************/ using System; using UnityEngine; namespace Leap.Unity.GraphicalRenderer { public class JaggedArray<T> : ISerializationCallbackReceiver { [NonSerialized] private T[][] _array; [SerializeField] private T[] _data; [SerializeField] private int[] _lengths; public JaggedArray() { } public JaggedArray(int length) { _array = new T[length][]; } public JaggedArray(T[][] array) { _array = array; } public void OnAfterDeserialize() { _array = new T[_lengths.Length][]; int offset = 0; for (int i = 0; i < _lengths.Length; i++) { int length = _lengths[i]; if (length == -1) { _array[i] = null; } else { _array[i] = new T[length]; Array.Copy(_data, offset, _array[i], 0, length); offset += length; } } } public void OnBeforeSerialize() { if (_array == null) { _data = new T[0]; _lengths = new int[0]; return; } int count = 0; foreach (var child in _array) { if (child == null) continue; count += child.Length; } _data = new T[count]; _lengths = new int[_array.Length]; int offset = 0; for (int i = 0; i < _array.Length; i++) { var child = _array[i]; if (child == null) { _lengths[i] = -1; } else { Array.Copy(child, 0, _data, offset, child.Length); _lengths[i] = child.Length; offset += child.Length; } } } public T[] this[int index] { get { return _array[index]; } set { _array[index] = value; } } public static implicit operator T[][] (JaggedArray<T> jaggedArray) { return jaggedArray._array; } public static implicit operator JaggedArray<T>(T[][] array) { return new JaggedArray<T>(array); } } } <file_sep>/Assets/Hover/Core/Scripts/Renderers/Shapes/Arc/HoverMeshArc.cs using System; using Hover.Core.Utils; using UnityEngine; namespace Hover.Core.Renderers.Shapes.Arc { /*================================================================================================*/ [RequireComponent(typeof(HoverIndicator))] [RequireComponent(typeof(HoverShapeArc))] public class HoverMeshArc : HoverMesh { public enum RadiusType { Min, Selection, Highlight, Max } public const string UvInnerRadiusName = "UvInnerRadius"; public const string UvOuterRadiusName = "UvOuterRadius"; public const string UvMinArcDegreeName = "UvMinArcDegree"; public const string UvMaxArcDegreeName = "UvMaxArcDegree"; [DisableWhenControlled(RangeMin=0.05f, RangeMax=10)] public float ArcSegmentsPerDegree = 0.5f; [DisableWhenControlled] public RadiusType InnerRadiusType = RadiusType.Min; [DisableWhenControlled] public RadiusType OuterRadiusType = RadiusType.Max; [DisableWhenControlled] public bool AutoUvViaRadiusType = false; [DisableWhenControlled] public float UvInnerRadius = 0; [DisableWhenControlled] public float UvOuterRadius = 1; [DisableWhenControlled] public float UvMinArcDegree = 1; [DisableWhenControlled] public float UvMaxArcDegree = 0; private int vArcSteps; private float vPrevArcSegs; private RadiusType vPrevInnerType; private RadiusType vPrevOuterType; private bool vPrevAutoUv; private float vPrevUvInner; private float vPrevUvOuter; private float vPrevUvMinDeg; private float vPrevUvMaxDeg; //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public override bool IsMeshVisible { get { HoverShapeArc shape = GetComponent<HoverShapeArc>(); float innerRadProg = GetRadiusProgress(InnerRadiusType); float outerRadProg = GetRadiusProgress(OuterRadiusType); return (shape.OuterRadius != shape.InnerRadius && outerRadProg != innerRadProg); } } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ protected override bool ShouldUpdateMesh() { var ind = GetComponent<HoverIndicator>(); var shape = GetComponent<HoverShapeArc>(); vArcSteps = (int)Mathf.Max(2, shape.ArcDegrees*ArcSegmentsPerDegree); bool shouldUpdate = ( base.ShouldUpdateMesh() || ind.DidSettingsChange || shape.DidSettingsChange || ArcSegmentsPerDegree != vPrevArcSegs || InnerRadiusType != vPrevInnerType || OuterRadiusType != vPrevOuterType || AutoUvViaRadiusType != vPrevAutoUv || UvInnerRadius != vPrevUvInner || UvOuterRadius != vPrevUvOuter || UvMinArcDegree != vPrevUvMinDeg || UvMaxArcDegree != vPrevUvMaxDeg ); vPrevArcSegs = ArcSegmentsPerDegree; vPrevInnerType = InnerRadiusType; vPrevOuterType = OuterRadiusType; vPrevAutoUv = AutoUvViaRadiusType; vPrevUvInner = UvInnerRadius; vPrevUvOuter = UvOuterRadius; vPrevUvMinDeg = UvMinArcDegree; vPrevUvMaxDeg = UvMaxArcDegree; return shouldUpdate; } /*--------------------------------------------------------------------------------------------*/ protected int GetArcMeshSteps() { return vArcSteps; } /*--------------------------------------------------------------------------------------------*/ protected float GetRadiusProgress(RadiusType pType) { HoverIndicator ind = GetComponent<HoverIndicator>(); switch ( pType ) { case RadiusType.Min: return 0; case RadiusType.Selection: return ind.SelectionProgress; case RadiusType.Highlight: return ind.HighlightProgress; case RadiusType.Max: return 1; } throw new Exception("Unexpected type: "+pType); } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ protected override void UpdateMesh() { HoverShapeArc shape = GetComponent<HoverShapeArc>(); float innerRadProg = GetRadiusProgress(InnerRadiusType); float outerRadProg = GetRadiusProgress(OuterRadiusType); float innerRad = Mathf.Lerp(shape.InnerRadius, shape.OuterRadius, innerRadProg); float outerRad = Mathf.Lerp(shape.InnerRadius, shape.OuterRadius, outerRadProg); Vector3 innerOff = Vector3.Lerp(shape.InnerOffset, shape.OuterOffset, innerRadProg); Vector3 outerOff = Vector3.Lerp(shape.InnerOffset, shape.OuterOffset, outerRadProg); float halfRadians = shape.ArcDegrees/180*Mathf.PI/2; int steps = GetArcMeshSteps(); MeshUtil.BuildRingMesh(vMeshBuild, innerRad, outerRad, -halfRadians, halfRadians, innerOff, outerOff, steps); UpdateAutoUv(shape, innerRadProg, outerRadProg); UpdateMeshUvAndColors(steps); vMeshBuild.Commit(); vMeshBuild.CommitColors(); } /*--------------------------------------------------------------------------------------------*/ protected void UpdateAutoUv(HoverShapeArc pShapeArc, float pInnerProg, float pOuterProg) { if ( !AutoUvViaRadiusType ) { return; } Controllers.Set(UvInnerRadiusName, this); Controllers.Set(UvOuterRadiusName, this); UvInnerRadius = pInnerProg; UvOuterRadius = pOuterProg; } /*--------------------------------------------------------------------------------------------*/ protected void UpdateMeshUvAndColors(int pSteps) { for ( int i = 0 ; i < vMeshBuild.Uvs.Length ; i++ ) { int stepI = i/2; float arcProg = (float)stepI/pSteps; bool isInner = (i%2 == 0); Vector2 uv = vMeshBuild.Uvs[i]; uv.x = Mathf.Lerp(UvMinArcDegree, UvMaxArcDegree, arcProg); uv.y = (isInner ? UvInnerRadius : UvOuterRadius); vMeshBuild.Uvs[i] = uv; vMeshBuild.Colors[i] = Color.white; } } } } <file_sep>/Assets/LeapMotion/Core/Plugins/LeapCSharp/Editor/Tests/ObjectEquality.cs /****************************************************************************** * Copyright (C) Leap Motion, Inc. 2011-2018. * * Leap Motion proprietary and confidential. * * * * Use subject to the terms of the Leap Motion SDK Agreement available at * * https://developer.leapmotion.com/sdk_agreement, or another agreement * * between Leap Motion and you, your company or other organization. * ******************************************************************************/ using NUnit.Framework; namespace Leap.LeapCSharp.Tests { [TestFixture()] public class ObjectEquality { [Test()] public void Vector_ints() { Vector thisVector = new Leap.Vector(1, 2, 3); Vector thatVector = new Leap.Vector(1, 2, 3); Assert.True(thisVector.Equals(thatVector), "this.Equals(that) Vector"); //Assert.True (thisVector == thatVector, "this == that Vector"); } [Test()] public void Vector_floats() { Vector thisVector = new Leap.Vector(1.111111111111111f, 2.222222222222222f, 3.333333333333333f); Vector thatVector = new Leap.Vector(1.111111111111111f, 2.222222222222222f, 3.333333333333333f); Assert.True(thisVector.Equals(thatVector), "this.Equals(that) Vector"); //Assert.True (thisVector == thatVector, "this == that Vector"); } [Test()] public void Vector_more_floats() { Vector thisVector = new Vector(0.199821f, -0.845375f, 0.495392f); Vector thatVector = new Vector(0.199821f, -0.845375f, 0.495392f); Assert.True(thisVector.Equals(thatVector), "this.Equals(that) Vector"); //Assert.True (thisVector == thatVector, "this == that Vector"); } } } <file_sep>/Assets/LeapMotion/Core/Scripts/Utils/Enum.cs /****************************************************************************** * Copyright (C) Leap Motion, Inc. 2011-2018. * * Leap Motion proprietary and confidential. * * * * Use subject to the terms of the Leap Motion SDK Agreement available at * * https://developer.leapmotion.com/sdk_agreement, or another agreement * * between Leap Motion and you, your company or other organization. * ******************************************************************************/ using System; namespace Leap.Unity { public static class Enum<T> { public static readonly string[] names; public static readonly T[] values; static Enum() { names = (string[])Enum.GetNames(typeof(T)); values = (T[])Enum.GetValues(typeof(T)); } } } <file_sep>/Assets/Hover/Core/Scripts/Items/Managers/HoverItemsManager.cs using System; using System.Collections.Generic; using System.Linq; using UnityEngine; using UnityEngine.Events; namespace Hover.Core.Items.Managers { /*================================================================================================*/ public class HoverItemsManager : MonoBehaviour { [Serializable] public class ItemEvent : UnityEvent<HoverItem> {} public UnityEvent OnItemListInitialized; public ItemEvent OnItemAdded; public ItemEvent OnItemRemoved; private List<HoverItem> vItems; //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public void Start() { vItems = Resources.FindObjectsOfTypeAll<HoverItem>().ToList(); OnItemListInitialized.Invoke(); } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public void AddItem(HoverItem pItem) { if ( vItems == null ) { return; } if ( vItems.Contains(pItem) ) { //Debug.LogWarning("Cannot add duplicate item '"+pItem.name+"'.", pItem); return; } vItems.Add(pItem); OnItemAdded.Invoke(pItem); } /*--------------------------------------------------------------------------------------------*/ public void RemoveItem(HoverItem pItem) { if ( vItems == null ) { return; } if ( !vItems.Remove(pItem) ) { Debug.LogWarning("Cannot remove missing item '"+pItem.name+"'.", pItem); return; } OnItemRemoved.Invoke(pItem); } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public void FillListWithExistingItemComponents<T>(IList<T> pComponents) where T : Component { pComponents.Clear(); if ( vItems == null ) { return; } for ( int i = 0 ; i < vItems.Count ; i++ ) { T comp = vItems[i].GetComponent<T>(); if ( comp != null ) { pComponents.Add(comp); } } } /*--------------------------------------------------------------------------------------------*/ public void FillListWithAllItems(IList<HoverItem> pItems) { pItems.Clear(); if ( vItems == null ) { return; } for ( int i = 0 ; i < vItems.Count ; i++ ) { pItems.Add(vItems[i]); } } /*--------------------------------------------------------------------------------------------*/ public void FillListWithMatchingItems(IList<HoverItem> pMatches, Func<HoverItem, bool> pFilterFunc) { pMatches.Clear(); if ( vItems == null ) { return; } for ( int i = 0 ; i < vItems.Count ; i++ ) { HoverItem item = vItems[i]; if ( pFilterFunc(item) ) { pMatches.Add(item); } } } } } <file_sep>/Assets/Hover/Core/Scripts/Cursors/HoverIdleRendererUpdater.cs using Hover.Core.Renderers.Cursors; using Hover.Core.Renderers.Utils; using Hover.Core.Utils; using UnityEngine; namespace Hover.Core.Cursors { /*================================================================================================*/ [ExecuteInEditMode] [RequireComponent(typeof(TreeUpdater))] [RequireComponent(typeof(HoverCursorFollower))] public class HoverIdleRendererUpdater : MonoBehaviour, ITreeUpdateable, ISettingsController { public GameObject IdleRendererPrefab; public HoverRendererIdle IdleRenderer; [TriggerButton("Rebuild Idle Renderer")] public bool ClickToRebuildRenderer; private GameObject vPrevIdlePrefab; //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public void Awake() { vPrevIdlePrefab = IdleRendererPrefab; } /*--------------------------------------------------------------------------------------------*/ public virtual void Start() { //do nothing... } /*--------------------------------------------------------------------------------------------*/ public virtual void TreeUpdate() { DestroyRendererIfNecessary(); IdleRenderer = (IdleRenderer ?? FindOrBuildIdle()); ICursorData cursorData = GetComponent<HoverCursorFollower>().GetCursorData(); UpdateRenderer(cursorData); } /*--------------------------------------------------------------------------------------------*/ public void OnEditorTriggerButtonSelected() { //do nothing here, check for (ClickToRebuildRenderer == true) elsewhere... } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ private void DestroyRendererIfNecessary() { if ( ClickToRebuildRenderer || IdleRendererPrefab != vPrevIdlePrefab ) { vPrevIdlePrefab = IdleRendererPrefab; RendererUtil.DestroyRenderer(IdleRenderer); IdleRenderer = null; } ClickToRebuildRenderer = false; } /*--------------------------------------------------------------------------------------------*/ private HoverRendererIdle FindOrBuildIdle() { return RendererUtil.FindOrBuildRenderer<HoverRendererIdle>(gameObject.transform, IdleRendererPrefab, "Idle", typeof(HoverRendererIdle)); } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ private void UpdateRenderer(ICursorData pCursorData) { IdleRenderer.Controllers.Set(HoverRendererIdle.CenterPositionName, this); IdleRenderer.Controllers.Set(HoverRendererIdle.DistanceThresholdName, this); IdleRenderer.Controllers.Set(HoverRendererIdle.TimerProgressName, this); IdleRenderer.Controllers.Set(HoverRendererIdle.IsRaycastName, this); IdleRenderer.Controllers.Set(SettingsControllerMap.GameObjectActiveSelf, this); IdleRenderer.CenterOffset = transform.InverseTransformPoint(pCursorData.Idle.WorldPosition); IdleRenderer.DistanceThreshold = pCursorData.Idle.DistanceThreshold; IdleRenderer.TimerProgress = pCursorData.Idle.Progress; IdleRenderer.IsRaycast = pCursorData.IsRaycast; RendererUtil.SetActiveWithUpdate(IdleRenderer.gameObject, pCursorData.Idle.IsActive); /*Transform itemPointHold = IdleRenderer.Fill.ItemPointer.transform.parent; Transform cursPointHold = IdleRenderer.Fill.CursorPointer.transform.parent; Vector3 itemCenter = GetComponent<HoverRendererUpdater>() .ActiveRenderer.GetCenterWorldPosition(); Vector3 itemCenterLocalPos = IdleRenderer.transform .InverseTransformPoint(itemCenter); Vector3 cursorLocalPos = IdleRenderer.transform .InverseTransformPoint(pCursorData.WorldPosition); itemPointHold.localRotation = Quaternion.FromToRotation(Vector3.right, itemCenterLocalPos); cursPointHold.localRotation = Quaternion.FromToRotation(Vector3.right, cursorLocalPos);*/ } } } <file_sep>/Assets/LeapMotion/Modules/InteractionEngine/Examples/6. Dynamic UI/Tests/Scripts/WorkstationPoseTest.cs /****************************************************************************** * Copyright (C) Leap Motion, Inc. 2011-2018. * * Leap Motion proprietary and confidential. * * * * Use subject to the terms of the Leap Motion SDK Agreement available at * * https://developer.leapmotion.com/sdk_agreement, or another agreement * * between Leap Motion and you, your company or other organization. * ******************************************************************************/ using Leap.Unity.Attributes; using Leap.Unity.Interaction; using Leap.Unity.RuntimeGizmos; using System.Collections; using System.Collections.Generic; using UnityEngine; namespace Leap.Unity.Examples { [AddComponentMenu("")] [ExecuteInEditMode] public class WorkstationPoseTest : MonoBehaviour { public Transform userCamera; public Transform stationObj; public Transform stationObjOneSecLater; public float myRadius; public Transform otherOpenStationsParent; [Disable] public List<Vector3> otherOpenStationPositions = new List<Vector3>(); [Disable] public List<float> otherOpenStationRadii = new List<float>(); void Update() { if (userCamera == null) return; if (stationObj == null) return; if (stationObjOneSecLater == null) return; if (otherOpenStationsParent == null) return; refreshLists(); refreshRadius(); Vector3 targetPosition = WorkstationBehaviourExample.DefaultDetermineWorkstationPosition(userCamera.position, userCamera.rotation, stationObj.position, (stationObjOneSecLater.position - stationObj.position), myRadius, otherOpenStationPositions, otherOpenStationRadii); Quaternion targetRotation = WorkstationBehaviourExample.DefaultDetermineWorkstationRotation(userCamera.position, targetPosition); this.transform.position = targetPosition; this.transform.rotation = targetRotation; } private void refreshLists() { otherOpenStationPositions.Clear(); otherOpenStationRadii.Clear(); if (otherOpenStationsParent != null) { foreach (var child in otherOpenStationsParent.GetChildren()) { var radiusProvider = child.GetComponent<RenderWireSphere>(); if (radiusProvider != null) { otherOpenStationPositions.Add(radiusProvider.transform.position); otherOpenStationRadii.Add(radiusProvider.radius); } } } } private void refreshRadius() { var radiusProvider = GetComponent<RenderWireSphere>(); if (radiusProvider == null) return; myRadius = radiusProvider.radius; } } } <file_sep>/Assets/Hover/Core/Scripts/Items/Managers/HoverItemsHighlightManager.cs using System; using System.Collections.Generic; using Hover.Core.Cursors; using UnityEngine; namespace Hover.Core.Items.Managers { /*================================================================================================*/ [RequireComponent(typeof(HoverItemsManager))] public class HoverItemsHighlightManager : MonoBehaviour { public HoverCursorDataProvider CursorDataProvider; private List<HoverItemHighlightState> vHighStates; //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public void Awake() { if ( CursorDataProvider == null ) { CursorDataProvider = FindObjectOfType<HoverCursorDataProvider>(); } if ( CursorDataProvider == null ) { throw new ArgumentNullException("CursorDataProvider"); } vHighStates = new List<HoverItemHighlightState>(); } /*--------------------------------------------------------------------------------------------*/ public void Update() { HoverItemsManager itemsMan = GetComponent<HoverItemsManager>(); itemsMan.FillListWithExistingItemComponents(vHighStates); ResetItems(); UpdateItems(); } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ private void ResetItems() { for ( int i = 0 ; i < vHighStates.Count ; i++ ) { HoverItemHighlightState highState = vHighStates[i]; if ( highState == null ) { vHighStates.RemoveAt(i); i--; Debug.LogWarning("Found and removed a null item; use RemoveItem() instead."); continue; } highState.ResetAllNearestStates(); } } /*--------------------------------------------------------------------------------------------*/ private void UpdateItems() { List<ICursorData> cursors = CursorDataProvider.Cursors; int cursorCount = cursors.Count; for ( int i = 0 ; i < cursorCount ; i++ ) { ICursorData cursor = cursors[i]; cursor.MaxItemHighlightProgress = 0; cursor.MaxItemSelectionProgress = 0; if ( !cursor.CanCauseSelections ) { continue; } HoverItemHighlightState.Highlight? high; HoverItemHighlightState highState = FindNearestItemToCursor(cursor.Type, out high); if ( highState == null || high == null ) { continue; } highState.SetNearestAcrossAllItemsForCursor(cursor.Type); cursor.MaxItemHighlightProgress = high.Value.Progress; } } /*--------------------------------------------------------------------------------------------*/ private HoverItemHighlightState FindNearestItemToCursor(CursorType pCursorType, out HoverItemHighlightState.Highlight? pNearestHigh) { float minDist = float.MaxValue; HoverItemHighlightState nearestItem = null; pNearestHigh = null; for ( int i = 0 ; i < vHighStates.Count ; i++ ) { HoverItemHighlightState item = vHighStates[i]; if ( !item.gameObject.activeInHierarchy || item.IsHighlightPrevented ) { continue; } HoverItemHighlightState.Highlight? high = item.GetHighlight(pCursorType); if ( high == null || high.Value.Distance >= minDist ) { continue; } minDist = high.Value.Distance; nearestItem = item; pNearestHigh = high; } return nearestItem; } } } <file_sep>/Assets/Hover/Core/Scripts/Cursors/CursorUtil.cs using UnityEngine; namespace Hover.Core.Cursors { /*================================================================================================*/ public static class CursorUtil { //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public static bool FindCursorReference(MonoBehaviour pModule, ref HoverCursorDataProvider pProv, bool pShowLog) { if ( pProv != null ) { return true; } pProv = Object.FindObjectOfType<HoverCursorDataProvider>(); if ( pShowLog ) { string typeName = typeof(HoverCursorDataProvider).Name; if ( pProv == null ) { Debug.LogWarning("Could not find '"+typeName+"' reference.", pModule); } else { Debug.Log("Found '"+typeName+"' reference.", pModule); } } return (pProv != null); } } } <file_sep>/Assets/Hover/Core/Scripts/Renderers/Shapes/Rect/HoverFillButtonRectUpdater.cs using Hover.Core.Renderers.Items.Buttons; using Hover.Core.Renderers.Utils; using Hover.Core.Utils; using UnityEngine; namespace Hover.Core.Renderers.Shapes.Rect { /*================================================================================================*/ [RequireComponent(typeof(TreeUpdater))] [RequireComponent(typeof(HoverFillButton))] [RequireComponent(typeof(HoverShapeRect))] public class HoverFillButtonRectUpdater : MonoBehaviour, ITreeUpdateable, ISettingsController { public float EdgeThickness = 0.001f; //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public void Start() { //do nothing... } /*--------------------------------------------------------------------------------------------*/ public void TreeUpdate() { EdgeThickness = Mathf.Max(0, EdgeThickness); UpdateMeshes(); } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ private void UpdateMeshes() { HoverFillButton fillButton = gameObject.GetComponent<HoverFillButton>(); HoverShapeRect shapeRect = gameObject.GetComponent<HoverShapeRect>(); float totalEdgeThick = EdgeThickness*2; float insetSizeX = Mathf.Max(0, shapeRect.SizeX-totalEdgeThick); float insetSizeY = Mathf.Max(0, shapeRect.SizeY-totalEdgeThick); if ( fillButton.Background != null ) { UpdateMeshShape(fillButton.Background, insetSizeX, insetSizeY); } if ( fillButton.Highlight != null ) { UpdateMeshShape(fillButton.Highlight, insetSizeX, insetSizeY); } if ( fillButton.Selection != null ) { UpdateMeshShape(fillButton.Selection, insetSizeX, insetSizeY); } if ( fillButton.Edge != null ) { HoverIndicator meshInd = fillButton.Edge.GetComponent<HoverIndicator>(); float minSize = Mathf.Min(shapeRect.SizeX, shapeRect.SizeY); meshInd.Controllers.Set(HoverIndicator.HighlightProgressName, this); meshInd.HighlightProgress = 1-totalEdgeThick/minSize; //TODO: hack/workaround UpdateMeshShape(fillButton.Edge, shapeRect.SizeX, shapeRect.SizeY, fillButton.ShowEdge); } } /*--------------------------------------------------------------------------------------------*/ protected virtual void UpdateMeshShape(HoverMesh pMesh, float pSizeX, float pSizeY, bool pShowMesh=true) { HoverShapeRect meshShape = pMesh.GetComponent<HoverShapeRect>(); pMesh.Controllers.Set(SettingsControllerMap.GameObjectActiveSelf, this); meshShape.Controllers.Set(HoverShapeRect.SizeXName, this); meshShape.Controllers.Set(HoverShapeRect.SizeYName, this); RendererUtil.SetActiveWithUpdate(pMesh, (pShowMesh && pMesh.IsMeshVisible)); meshShape.SizeX = pSizeX; meshShape.SizeY = pSizeY; } } } <file_sep>/Assets/LeapMotion/Modules/GraphicRenderer/Scripts/EditTimeApis/LeapGraphicGroupEditorApi.cs /****************************************************************************** * Copyright (C) Leap Motion, Inc. 2011-2018. * * Leap Motion proprietary and confidential. * * * * Use subject to the terms of the Leap Motion SDK Agreement available at * * https://developer.leapmotion.com/sdk_agreement, or another agreement * * between Leap Motion and you, your company or other organization. * ******************************************************************************/ using System; using System.Collections.Generic; using UnityEngine; using UnityEngine.Assertions; #if UNITY_EDITOR using UnityEditor; #endif using Leap.Unity.Query; namespace Leap.Unity.GraphicalRenderer { public interface ILeapInternalGraphicGroup { LeapGraphicRenderer renderer { set; } } public partial class LeapGraphicGroup { #if UNITY_EDITOR public readonly EditorApi editor; public LeapGraphicGroup(LeapGraphicRenderer renderer, Type renderingMethodType) { _groupName = LeapGraphicTagAttribute.GetTagName(renderingMethodType); AssertHelper.AssertEditorOnly(); Assert.IsNotNull(renderer); Assert.IsNotNull(renderingMethodType); _renderer = renderer; editor = new EditorApi(this); editor.ChangeRenderingMethod(renderingMethodType, addFeatures: true); } public class EditorApi { private readonly LeapGraphicGroup _group; public EditorApi(LeapGraphicGroup group) { _group = group; } public void OnValidate() { if (!Application.isPlaying) { _group._addRemoveSupported = true; if (_group._renderingMethod.Value != null) { _group._addRemoveSupported &= typeof(ISupportsAddRemove).IsAssignableFrom(_group._renderingMethod.Value.GetType()); } } for (int i = _group._features.Count; i-- != 0;) { if (_group._features[i] == null) { _group._features.RemoveAt(i); } } Assert.IsNotNull(_group._renderingMethod.Value, "Rendering method of a group should never be null."); } public void OnDestroy() { if (_group._renderingMethod.Value != null) { _group._renderingMethod.Value.OnDisableRendererEditor(); } } /// <summary> /// This method changes the rendering method used for this group. You must provide the type /// of the rendering method to switch to, as well as if features should be added to match /// the existing feature data objects present in the graphics that are attached. /// /// This is an editor only method, as rendering types cannot be changed at runtime! /// </summary> public void ChangeRenderingMethod(Type renderingMethodType, bool addFeatures) { AssertHelper.AssertEditorOnly(); Assert.IsNotNull(renderingMethodType); if (_group._renderingMethod.Value != null) { _group._renderingMethod.Value.OnDisableRendererEditor(); _group._renderingMethod.Value = null; } _group._renderingMethod.Value = Activator.CreateInstance(renderingMethodType) as LeapRenderingMethod; Assert.IsNotNull(_group._renderingMethod.Value); ILeapInternalRenderingMethod renderingMethodInternal = _group._renderingMethod.Value; renderingMethodInternal.renderer = _group._renderer; renderingMethodInternal.group = _group; if (addFeatures) { List<Type> dataObjTypes = new List<Type>(); var allGraphics = _group.renderer.GetComponentsInChildren<LeapGraphic>(); foreach (var graphic in allGraphics) { if (_group._renderingMethod.Value.IsValidGraphic(graphic)) { List<Type> types = new List<Type>(); for (int i = 0; i < graphic.featureData.Count; i++) { var dataObj = graphic.featureData[i]; var dataType = dataObj.GetType(); if (!dataObjTypes.Contains(dataType)) { types.Add(dataType); } } foreach (var type in types) { if (dataObjTypes.Query().Count(t => t == type) < types.Query().Count(t => t == type)) { dataObjTypes.Add(type); } } } } foreach (var type in dataObjTypes) { var featureType = LeapFeatureData.GetFeatureType(type); if (featureType != null) { AddFeature(featureType); } } } _group._renderingMethod.Value.OnEnableRendererEditor(); OnValidate(); } /// <summary> /// Adds a feature of a specific type to this group. Even if the feature is not /// a supported feature it will still be added, it will just not be supported and /// will show up in red in the inspector. /// /// This is an editor only api, as features cannot be added/removed at runtime. /// </summary> public LeapGraphicFeatureBase AddFeature(Type featureType) { AssertHelper.AssertEditorOnly(); _group._renderer.editor.ScheduleRebuild(); Undo.RecordObject(_group.renderer, "Added feature"); var feature = Activator.CreateInstance(featureType) as LeapGraphicFeatureBase; _group._features.Add(feature); _group.RebuildFeatureData(); _group.RebuildFeatureSupportInfo(); return feature; } /// <summary> /// Removes the feature at the given index. This is an editor only api, as features /// cannot be added/removed at runtime. /// </summary> public void RemoveFeature(int featureIndex) { AssertHelper.AssertEditorOnly(); Undo.RecordObject(_group.renderer, "Removed feature"); _group._features.RemoveAt(featureIndex); _group.RebuildFeatureData(); _group.RebuildFeatureSupportInfo(); _group._renderer.editor.ScheduleRebuild(); } /// <summary> /// Forces a rebuild of all the picking meshes for all attached graphics. /// The picking meshes are used to allow graphics to be accurately picked /// even though they might be inside of warped spaces. /// </summary> public void RebuildEditorPickingMeshes() { using (new ProfilerSample("Rebuild Picking Meshes")) { foreach (var graphic in _group._graphics) { graphic.editor.RebuildEditorPickingMesh(); } } } public void ValidateGraphicList() { //Make sure there are no duplicates, that is not allowed! var set = Pool<HashSet<LeapGraphic>>.Spawn(); try { for (int i = _group._graphics.Count; i-- != 0;) { var graphic = _group._graphics[i]; if (set.Contains(graphic)) { Debug.LogWarning("Removing duplicate graphic " + graphic); _group._graphics.RemoveAt(i); } else { set.Add(graphic); } } } finally { set.Clear(); Pool<HashSet<LeapGraphic>>.Recycle(set); } for (int i = _group._graphics.Count; i-- != 0;) { if (_group._graphics[i] == null || _group.graphics[i].attachedGroup != _group) { _group._graphics.RemoveAt(i); continue; } if (!_group._graphics[i].transform.IsChildOf(_group.renderer.transform)) { _group.TryRemoveGraphic(_group._graphics[i]); continue; } } } public void UpdateRendererEditor() { AssertHelper.AssertEditorOnly(); _group._renderingMethod.Value.OnUpdateRendererEditor(); } } #endif } } <file_sep>/Assets/LeapMotion/Core/Plugins/LeapCSharp/Editor/Tests/LeapCStressTests.cs /****************************************************************************** * Copyright (C) Leap Motion, Inc. 2011-2018. * * Leap Motion proprietary and confidential. * * * * Use subject to the terms of the Leap Motion SDK Agreement available at * * https://developer.leapmotion.com/sdk_agreement, or another agreement * * between Leap Motion and you, your company or other organization. * ******************************************************************************/ using System; using NUnit.Framework; using LeapInternal; namespace Leap.LeapCSharp.Tests { [TestFixture()] public class LeapCStressTests { [Test()] public void TestCreateDestroy() { IntPtr connHandle = IntPtr.Zero; int iterations = 5000; for (int i = 0; i < iterations; i++) { //LEAP_CONNECTION_MESSAGE msg = new LEAP_CONNECTION_MESSAGE(); LeapC.CreateConnection(out connHandle); LeapC.OpenConnection(connHandle); LeapC.DestroyConnection(connHandle); } } [Test()] public void TestCreateDestroyWithConfigRequest() { IntPtr connHandle = IntPtr.Zero; int iterations = 5000; uint requestId; for (int i = 0; i < iterations; i++) { //LEAP_CONNECTION_MESSAGE msg = new LEAP_CONNECTION_MESSAGE(); LeapC.CreateConnection(out connHandle); LeapC.OpenConnection(connHandle); LeapC.RequestConfigValue(connHandle, "tracking_version", out requestId); LeapC.DestroyConnection(connHandle); } } } } <file_sep>/Assets/Hover/Core/Scripts/Items/Types/HoverItemDataRadio.cs using System; using UnityEngine; namespace Hover.Core.Items.Types { /*================================================================================================*/ [Serializable] public class HoverItemDataRadio : HoverItemDataSelectableBool, IItemDataRadio { [SerializeField] private string _DefaultGroupId; [SerializeField] private string _GroupId; //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public void InitDefaultGroupId(Transform pParentTx) { if ( pParentTx == null ) { _DefaultGroupId = "Group-Root"; return; } IItemData parentData = pParentTx.GetComponent<IItemData>(); if ( parentData != null ) { _DefaultGroupId = "Group-"+parentData.AutoId; return; } _DefaultGroupId = "Group-Instance"+pParentTx.GetInstanceID(); } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public string DefaultGroupId { get { return _DefaultGroupId; } } /*--------------------------------------------------------------------------------------------*/ public string GroupId { get { return (string.IsNullOrEmpty(_GroupId) ? _DefaultGroupId : _GroupId); } set { _GroupId = value; } } /*--------------------------------------------------------------------------------------------*/ public override void Select() { Value = true; base.Select(); } /*--------------------------------------------------------------------------------------------*/ public override bool IgnoreSelection { get { return (Value || base.IgnoreSelection); } } } } <file_sep>/Assets/Hover/Core/Scripts/Utils/MeshBuilder.cs using UnityEngine; namespace Hover.Core.Utils { /*================================================================================================*/ public class MeshBuilder { public Mesh Mesh { get; private set; } public Vector3[] Vertices { get; private set; } public Vector2[] Uvs { get; private set; } public Color[] Colors { get; private set; } public int[] Triangles { get; private set; } public int VertexIndex { get; private set; } public int UvIndex { get; private set; } public int TriangleIndex { get; private set; } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public MeshBuilder(Mesh pMesh=null) { Mesh = (pMesh ?? new Mesh()); Mesh.MarkDynamic(); if ( pMesh != null ) { Vertices = pMesh.vertices; Uvs = pMesh.uv; Colors = pMesh.colors; Triangles = pMesh.triangles; if ( Colors.Length != Vertices.Length ) { Colors = new Color[Vertices.Length]; CommitColors(Color.white); } } } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public void Resize(int pVertexCount, int pTriangleCount) { if ( Vertices == null || pVertexCount != Vertices.Length ) { Vertices = new Vector3[pVertexCount]; Uvs = new Vector2[pVertexCount]; Colors = new Color[pVertexCount]; Mesh.Clear(); } if ( Triangles == null || pTriangleCount != Triangles.Length ) { Triangles = new int[pTriangleCount]; Mesh.Clear(); } } /*--------------------------------------------------------------------------------------------*/ public void ResetIndices() { VertexIndex = 0; UvIndex = 0; TriangleIndex = 0; } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public void AddVertex(Vector3 pVertex) { Vertices[VertexIndex++] = pVertex; } /*--------------------------------------------------------------------------------------------*/ public void AddUv(Vector2 pUv) { Uvs[UvIndex++] = pUv; } /*--------------------------------------------------------------------------------------------*/ public void AddRemainingUvs(Vector2 pUv) { while ( UvIndex < Uvs.Length ) { Uvs[UvIndex++] = pUv; } } /*--------------------------------------------------------------------------------------------*/ public void AddTriangle(int pA, int pB, int pC) { Triangles[TriangleIndex++] = pA; Triangles[TriangleIndex++] = pB; Triangles[TriangleIndex++] = pC; } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public void Commit(bool pRecalcNormals=false) { Mesh.vertices = Vertices; Mesh.uv = Uvs; Mesh.triangles = Triangles; Mesh.RecalculateBounds(); if ( pRecalcNormals ) { Mesh.RecalculateNormals(); } } /*--------------------------------------------------------------------------------------------*/ public void CommitColors() { Mesh.colors = Colors; } /*--------------------------------------------------------------------------------------------*/ public void CommitColors(Color pColor) { for ( int i = 0 ; i < Colors.Length ; i++ ) { Colors[i] = pColor; } Mesh.colors = Colors; } } } <file_sep>/Assets/Hover/Editor/Utils/DisableWhenControlledPropertyDrawer.cs using System.Collections.Generic; using Hover.Core.Utils; using UnityEditor; using UnityEngine; namespace Hover.Editor.Utils { /*================================================================================================*/ [CustomPropertyDrawer(typeof(DisableWhenControlledAttribute))] public class DisableWhenControlledPropertyDrawer : PropertyDrawer { private const int MinSingleRowVector3Width = 299; private const string Vector3TypeName = "Vector3"; private const string IconTextPrefix = " _ "; private static readonly Texture2D ControlIconTex = Resources.Load<Texture2D>("Textures/ControlledPropertyIconTexture"); private static readonly Texture2D ControlIconHoverTex = Resources.Load<Texture2D>("Textures/ControlledPropertyIconHoverTexture"); private float vWidth; //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public override void OnGUI(Rect pPosition, SerializedProperty pProp, GUIContent pLabel) { DisableWhenControlledAttribute attrib = (DisableWhenControlledAttribute)attribute; string mapName = attrib.ControllerMapName; SerializedObject self = pProp.serializedObject; ISettingsControllerMap map = EditorUtil.GetControllerMap(self, mapName); bool wasEnabled = GUI.enabled; Rect propRect = pPosition; bool hasRangeMin = (attrib.RangeMin != DisableWhenControlledAttribute.NullRangeMin); bool hasRangeMax = (attrib.RangeMax != DisableWhenControlledAttribute.NullRangeMax); bool isControlled = (map != null && map.IsControlled(pProp.name)); string labelText = pLabel.text; if ( map != null && attrib.DisplaySpecials ) { List<string> specialValueNames = map.GetNewListOfControlledValueNames(true); Rect specialRect = propRect; specialRect.height = EditorGUIUtility.singleLineHeight; foreach ( string specialValueName in specialValueNames ) { DrawLinkIcon(self.targetObject, map.Get(specialValueName), specialRect); GUI.enabled = false; EditorGUI.LabelField(specialRect, IconTextPrefix+specialValueName.Substring(1)); GUI.enabled = wasEnabled; specialRect.y += specialRect.height+EditorGUIUtility.standardVerticalSpacing; } propRect.y = specialRect.y; propRect.height = specialRect.height; } if ( isControlled ) { ISettingsController settingsController = map.Get(pProp.name); DrawLinkIcon(self.targetObject, settingsController, propRect); pLabel.text = IconTextPrefix+labelText; } else { pLabel.text = labelText; } GUI.enabled = !isControlled; vWidth = pPosition.width; if ( hasRangeMin && hasRangeMax ) { EditorGUI.Slider(propRect, pProp, attrib.RangeMin, attrib.RangeMax, pLabel); } else { EditorGUI.PropertyField(propRect, pProp, pLabel, true); if ( hasRangeMin ) { pProp.floatValue = Mathf.Max(pProp.floatValue, attrib.RangeMin); } else if ( hasRangeMax ) { pProp.floatValue = Mathf.Min(pProp.floatValue, attrib.RangeMax); } } GUI.enabled = wasEnabled; } /*--------------------------------------------------------------------------------------------*/ public override float GetPropertyHeight(SerializedProperty pProp, GUIContent pLabel) { DisableWhenControlledAttribute attrib = (DisableWhenControlledAttribute)attribute; string mapName = attrib.ControllerMapName; ISettingsControllerMap map = EditorUtil.GetControllerMap(pProp.serializedObject, mapName); float propHeight = base.GetPropertyHeight(pProp, pLabel); if ( pProp.type == Vector3TypeName ) { return propHeight*(vWidth < MinSingleRowVector3Width ? 2 : 1); } if ( map == null || !attrib.DisplaySpecials ) { return propHeight; } float lineH = EditorGUIUtility.singleLineHeight+EditorGUIUtility.standardVerticalSpacing; return lineH*map.GetControlledCount(true) + propHeight; } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ private void DrawLinkIcon(Object pSelf, ISettingsController pControl, Rect pPropertyRect) { bool isSelf = ((pControl as Object) == pSelf); Rect iconRect = pPropertyRect; iconRect.x -= 26; iconRect.y += 1; iconRect.width = 40; iconRect.height = 16; GUIContent labelContent = new GUIContent(); labelContent.image = ControlIconTex; labelContent.tooltip = "Controlled by "+(isSelf ? "this component" : pControl.GetType().Name+" in \""+pControl.name+"\""); GUIStyle labelStyle = new GUIStyle(); labelStyle.imagePosition = ImagePosition.ImageOnly; labelStyle.clipping = TextClipping.Clip; labelStyle.padding = new RectOffset(15, 0, 0, 0); labelStyle.stretchWidth = true; labelStyle.stretchHeight = true; labelStyle.hover.background = ControlIconHoverTex; bool shouldPing = EditorGUI.ToggleLeft(iconRect, labelContent, false, labelStyle); if ( shouldPing ) { EditorGUIUtility.PingObject((Object)pControl); } } } } <file_sep>/Assets/LeapMotion/Modules/GraphicRenderer/Scripts/Utility/MeshCache.cs /****************************************************************************** * Copyright (C) Leap Motion, Inc. 2011-2018. * * Leap Motion proprietary and confidential. * * * * Use subject to the terms of the Leap Motion SDK Agreement available at * * https://developer.leapmotion.com/sdk_agreement, or another agreement * * between Leap Motion and you, your company or other organization. * ******************************************************************************/ using System; using System.Collections.Generic; using UnityEngine; using UnityEngine.Rendering; using Leap.Unity.Query; namespace Leap.Unity.GraphicalRenderer { public static class MeshCache { public static void Clear() { _topologyCache.Clear(); _normalCache.Clear(); _colorCache.Clear(); _uvCache.Clear(); } private static Dictionary<Mesh, CachedTopology> _topologyCache = new Dictionary<Mesh, CachedTopology>(); public static CachedTopology GetTopology(Mesh mesh) { CachedTopology topology; if (!_topologyCache.TryGetValue(mesh, out topology)) { topology.tris = mesh.GetIndices(0); topology.verts = mesh.vertices; _topologyCache[mesh] = topology; } return topology; } private static Dictionary<Mesh, Vector3[]> _normalCache = new Dictionary<Mesh, Vector3[]>(); public static Vector3[] GetNormals(Mesh mesh) { Vector3[] normals; if (!_normalCache.TryGetValue(mesh, out normals)) { normals = mesh.normals; if (normals.Length != mesh.vertexCount) { mesh.RecalculateNormals(); normals = mesh.normals; } _normalCache[mesh] = normals; } return normals; } private static Dictionary<Mesh, Color[]> _colorCache = new Dictionary<Mesh, Color[]>(); public static Color[] GetColors(Mesh mesh) { Color[] colors; if (!_colorCache.TryGetValue(mesh, out colors)) { colors = mesh.colors; if (colors.Length != mesh.vertexCount) { colors = new Color[mesh.vertexCount].Fill(Color.white); } _colorCache[mesh] = colors; } return colors; } private static Dictionary<UvKey, List<Vector4>> _uvCache = new Dictionary<UvKey, List<Vector4>>(); public static List<Vector4> GetUvs(Mesh mesh, UVChannelFlags channel) { var key = new UvKey() { mesh = mesh, channel = (int)channel }; List<Vector4> uvs; if (!_uvCache.TryGetValue(key, out uvs)) { uvs = new List<Vector4>(); mesh.GetUVs(channel.Index(), uvs); if (uvs.Count != mesh.vertexCount) { uvs.Fill(mesh.vertexCount, Vector4.zero); } _uvCache[key] = uvs; } return uvs; } public struct CachedTopology { public Vector3[] verts; public int[] tris; } private struct UvKey : IComparable<UvKey>, IEquatable<UvKey> { public Mesh mesh; public int channel; public int CompareTo(UvKey other) { if (other.mesh != mesh) return 1; if (other.channel != channel) return 1; return 0; } public override int GetHashCode() { return mesh.GetHashCode() + channel; } public bool Equals(UvKey other) { return other.mesh == mesh && other.channel == channel; } } } } <file_sep>/Assets/LeapMotion/Modules/GraphicRenderer/Scripts/Features/Tint/LeapRuntimeTintData.cs /****************************************************************************** * Copyright (C) Leap Motion, Inc. 2011-2018. * * Leap Motion proprietary and confidential. * * * * Use subject to the terms of the Leap Motion SDK Agreement available at * * https://developer.leapmotion.com/sdk_agreement, or another agreement * * between Leap Motion and you, your company or other organization. * ******************************************************************************/ using System; using UnityEngine; namespace Leap.Unity.GraphicalRenderer { public partial class LeapGraphic { /// <summary> /// Helper method to set the runtime tint color for a runtime /// tint data object attached to this graphic. This method will /// throw an exception if there is no tint data obj attached /// to this graphic. /// </summary> public void SetRuntimeTint(Color color) { getFeatureDataOrThrow<LeapRuntimeTintData>().color = color; } /// <summary> /// Overload of SetRuntimeTint that takes in a Html style string /// code that represents a color. Any string that can be parsed /// by ColorUtility.TryParseHtmlString can be used as an argument /// to this method. /// </summary> public void SetRuntimeTint(string htmlString) { SetRuntimeTint(Utils.ParseHtmlColorString(htmlString)); } /// <summary> /// Helper method to get the runtime tint color for a runtime /// tint data object attached to this graphic. This method will /// throw an exception if there is no tint data obj attached to /// this graphic. /// </summary> public Color GetRuntimeTint() { return getFeatureDataOrThrow<LeapRuntimeTintData>().color; } } [LeapGraphicTag("Runtime Tint")] [Serializable] public class LeapRuntimeTintData : LeapFeatureData { [SerializeField] private Color _color = Color.white; /// <summary> /// The runtime tint color for this tint data object. This /// represents a multiplicative tint of the graphic representation /// of this graphic. /// </summary> public Color color { get { return _color; } set { if (value != _color) { MarkFeatureDirty(); _color = value; } } } } } <file_sep>/Assets/Hover/Core/Scripts/Items/Types/HoverItemDataSelectableFloat.cs using System; using UnityEngine; using UnityEngine.Events; namespace Hover.Core.Items.Types { /*================================================================================================*/ [Serializable] public abstract class HoverItemDataSelectableFloat : HoverItemDataSelectable, IItemDataSelectable<float> { [Serializable] public class FloatValueChangedEventHandler : UnityEvent<IItemDataSelectable<float>> { } public FloatValueChangedEventHandler OnValueChangedEvent = new FloatValueChangedEventHandler(); public event ItemEvents.ValueChangedHandler<float> OnValueChanged; [SerializeField] protected float _Value = 0; //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ protected HoverItemDataSelectableFloat() { OnValueChanged += (x => { OnValueChangedEvent.Invoke(x); }); } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public virtual float Value { get { return _Value; } set { if ( value == _Value ) { return; } _Value = value; OnValueChanged(this); } } } } <file_sep>/Assets/Hover/Core/Scripts/Items/Types/HoverItemDataSelectable.cs using System; using UnityEngine.Events; namespace Hover.Core.Items.Types { /*================================================================================================*/ [Serializable] public abstract class HoverItemDataSelectable : HoverItemData, IItemDataSelectable { [Serializable] public class SelectedEventHandler : UnityEvent<IItemDataSelectable> {} public bool IsStickySelected { get; private set; } public virtual bool AllowIdleDeselection { get; set; } public SelectedEventHandler OnSelectedEvent = new SelectedEventHandler(); public SelectedEventHandler OnDeselectedEvent = new SelectedEventHandler(); public event ItemEvents.SelectedHandler OnSelected; public event ItemEvents.DeselectedHandler OnDeselected; //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ protected HoverItemDataSelectable() { OnSelected += (x => { OnSelectedEvent.Invoke(x); }); OnDeselected += (x => { OnDeselectedEvent.Invoke(x); }); } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public virtual void Select() { IsStickySelected = UsesStickySelection(); OnSelected(this); } /*--------------------------------------------------------------------------------------------*/ public virtual void DeselectStickySelections() { if ( !IsStickySelected ) { return; } IsStickySelected = false; OnDeselected(this); } /*--------------------------------------------------------------------------------------------*/ public virtual bool IgnoreSelection { get { return false; } } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ protected virtual bool UsesStickySelection() { return false; } } } <file_sep>/Assets/LeapMotion/Core/readme.txt /****************************************************************************** * Copyright (C) Leap Motion, Inc. 2011-2017. * * Leap Motion proprietary and confidential. * * * * Use subject to the terms of the Leap Motion SDK Agreement available at * * https://developer.leapmotion.com/sdk_agreement, or another agreement * * between Leap Motion and you, your company or other organization. * ******************************************************************************/ Leap Motion Core Assets These assets go along with our V3 Orion Beta. Before you begin: You first need the Leap Motion V3 Orion Beta installed from: https://developer.leapmotion.com/ Questions/Bugs/Feature Requests? Please post on https://community.leapmotion.com/c/development <file_sep>/Assets/Hover/Core/Scripts/Layouts/LayoutUtil.cs using UnityEngine; namespace Hover.Core.Layouts { /*================================================================================================*/ public static class LayoutUtil { //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public static Vector2 GetRelativeAnchorPosition(AnchorType pAnchor) { int ai = (int)pAnchor; float x = (ai%3)/2f - 0.5f; float y = (ai/3)/2f - 0.5f; return new Vector2(-x, y); } } } <file_sep>/Assets/LeapMotion/Modules/GraphicRenderer/Scripts/RenderingMethods/LeapTextRenderer.cs /****************************************************************************** * Copyright (C) Leap Motion, Inc. 2011-2018. * * Leap Motion proprietary and confidential. * * * * Use subject to the terms of the Leap Motion SDK Agreement available at * * https://developer.leapmotion.com/sdk_agreement, or another agreement * * between Leap Motion and you, your company or other organization. * ******************************************************************************/ using System; using System.Collections.Generic; using UnityEngine; #if UNITY_EDITOR using UnityEditor; #endif using Leap.Unity.Space; using Leap.Unity.Query; using Leap.Unity.Attributes; namespace Leap.Unity.GraphicalRenderer { [LeapGraphicTag("Text")] [Serializable] public class LeapTextRenderer : LeapRenderingMethod<LeapTextGraphic>, ISupportsAddRemove { public const string DEFAULT_FONT = "Arial.ttf"; public const string DEFAULT_SHADER = "LeapMotion/GraphicRenderer/Text/Dynamic"; public const float SCALE_CONSTANT = 0.001f; [EditTimeOnly, SerializeField] private Font _font; [EditTimeOnly, SerializeField] private float _dynamicPixelsPerUnit = 1.0f; [EditTimeOnly, SerializeField] public bool _useColor = true; [EditTimeOnly, SerializeField] public Color _globalTint = Color.white; [Header("Rendering Settings")] [EditTimeOnly, SerializeField] private Shader _shader; [EditTimeOnly, SerializeField] private float _scale = 1f; [SerializeField] private RendererMeshData _meshData; [SerializeField] private Material _material; //Curved space private const string CURVED_PARAMETERS = LeapGraphicRenderer.PROPERTY_PREFIX + "Curved_GraphicParameters"; private List<Matrix4x4> _curved_worldToAnchor = new List<Matrix4x4>(); private List<Vector4> _curved_graphicParameters = new List<Vector4>(); public override SupportInfo GetSpaceSupportInfo(LeapSpace space) { return SupportInfo.FullSupport(); } public void OnAddRemoveGraphics(List<int> dirtyIndexes) { while (_meshData.Count > group.graphics.Count) { _meshData.RemoveMesh(_meshData.Count - 1); } while (_meshData.Count < group.graphics.Count) { group.graphics[_meshData.Count].isRepresentationDirty = true; _meshData.AddMesh(new Mesh()); } } public override void OnEnableRenderer() { foreach (var graphic in group.graphics) { var textGraphic = graphic as LeapTextGraphic; _font.RequestCharactersInTexture(textGraphic.text); } generateMaterial(); Font.textureRebuilt += onFontTextureRebuild; } public override void OnDisableRenderer() { Font.textureRebuilt -= onFontTextureRebuild; } public override void OnUpdateRenderer() { using (new ProfilerSample("Update Text Renderer")) { ensureFontIsUpToDate(); for (int i = 0; i < group.graphics.Count; i++) { var graphic = group.graphics[i] as LeapTextGraphic; if (graphic.isRepresentationDirtyOrEditTime || graphic.HasRectChanged()) { generateTextMesh(i, graphic, _meshData[i]); } } if (renderer.space == null) { using (new ProfilerSample("Draw Meshes")) { for (int i = 0; i < group.graphics.Count; i++) { var graphic = group.graphics[i]; if (graphic.isActiveAndEnabled) { Graphics.DrawMesh(_meshData[i], graphic.transform.localToWorldMatrix, _material, 0); } } } } else if (renderer.space is LeapRadialSpace) { var curvedSpace = renderer.space as LeapRadialSpace; using (new ProfilerSample("Build Material Data And Draw Meshes")) { _curved_worldToAnchor.Clear(); _curved_graphicParameters.Clear(); for (int i = 0; i < _meshData.Count; i++) { var graphic = group.graphics[i]; if (!graphic.isActiveAndEnabled) { _curved_graphicParameters.Add(Vector4.zero); _curved_worldToAnchor.Add(Matrix4x4.identity); continue; } var transformer = graphic.anchor.transformer; Vector3 localPos = renderer.transform.InverseTransformPoint(graphic.transform.position); Matrix4x4 mainTransform = renderer.transform.localToWorldMatrix * transformer.GetTransformationMatrix(localPos); Matrix4x4 deform = renderer.transform.worldToLocalMatrix * Matrix4x4.TRS(renderer.transform.position - graphic.transform.position, Quaternion.identity, Vector3.one) * graphic.transform.localToWorldMatrix; Matrix4x4 total = mainTransform * deform; _curved_graphicParameters.Add((transformer as IRadialTransformer).GetVectorRepresentation(graphic.transform)); _curved_worldToAnchor.Add(mainTransform.inverse); Graphics.DrawMesh(_meshData[i], total, _material, 0); } } using (new ProfilerSample("Upload Material Data")) { _material.SetFloat(SpaceProperties.RADIAL_SPACE_RADIUS, curvedSpace.radius); _material.SetMatrixArraySafe("_GraphicRendererCurved_WorldToAnchor", _curved_worldToAnchor); _material.SetMatrix("_GraphicRenderer_LocalToWorld", renderer.transform.localToWorldMatrix); _material.SetVectorArraySafe("_GraphicRendererCurved_GraphicParameters", _curved_graphicParameters); } } } } #if UNITY_EDITOR public override void OnEnableRendererEditor() { base.OnEnableRendererEditor(); _font = Resources.GetBuiltinResource<Font>(DEFAULT_FONT); _shader = Shader.Find(DEFAULT_SHADER); } public override void OnUpdateRendererEditor() { base.OnUpdateRendererEditor(); if (_font == null) { _font = Resources.GetBuiltinResource<Font>(DEFAULT_FONT); } if (_shader == null) { _shader = Shader.Find(DEFAULT_SHADER); } _meshData.Validate(this); //Make sure we have enough meshes to render all our graphics while (_meshData.Count > group.graphics.Count) { UnityEngine.Object.DestroyImmediate(_meshData[_meshData.Count - 1]); _meshData.RemoveMesh(_meshData.Count - 1); } while (_meshData.Count < group.graphics.Count) { _meshData.AddMesh(new Mesh()); } generateMaterial(); PreventDuplication(ref _material); } #endif private void onFontTextureRebuild(Font font) { if (font != _font) { return; } foreach (var graphic in group.graphics) { graphic.isRepresentationDirty = true; } } private void generateMaterial() { if (_material == null) { _material = new Material(_font.material); } #if UNITY_EDITOR Undo.RecordObject(_material, "Touched material"); #endif _material.mainTexture = _font.material.mainTexture; _material.name = "Font material"; _material.shader = _shader; foreach (var keyword in _material.shaderKeywords) { _material.DisableKeyword(keyword); } if (renderer.space != null) { if (renderer.space is LeapCylindricalSpace) { _material.EnableKeyword(SpaceProperties.CYLINDRICAL_FEATURE); } else if (renderer.space is LeapSphericalSpace) { _material.EnableKeyword(SpaceProperties.SPHERICAL_FEATURE); } } if (_useColor) { _material.EnableKeyword(LeapGraphicRenderer.FEATURE_PREFIX + "VERTEX_COLORS"); } } private void ensureFontIsUpToDate() { CharacterInfo info; bool doesNeedRebuild = false; for (int i = 0; i < group.graphics.Count; i++) { var graphic = group.graphics[i] as LeapTextGraphic; int scaledFontSize = Mathf.RoundToInt(graphic.fontSize * _dynamicPixelsPerUnit); if (graphic.isRepresentationDirtyOrEditTime) { for (int j = 0; j < graphic.text.Length; j++) { char character = graphic.text[j]; if (!_font.GetCharacterInfo(character, out info, scaledFontSize, graphic.fontStyle)) { doesNeedRebuild = true; break; } } if (doesNeedRebuild) { break; } } } if (!doesNeedRebuild) { return; } for (int i = 0; i < group.graphics.Count; i++) { var graphic = group.graphics[i] as LeapTextGraphic; int scaledFontSize = Mathf.RoundToInt(graphic.fontSize * _dynamicPixelsPerUnit); graphic.isRepresentationDirty = true; _font.RequestCharactersInTexture(graphic.text, scaledFontSize, graphic.fontStyle); } } private List<TextWrapper.Line> _tempLines = new List<TextWrapper.Line>(); private List<Vector3> _verts = new List<Vector3>(); private List<Vector4> _uvs = new List<Vector4>(); private List<Color> _colors = new List<Color>(); private List<int> _tris = new List<int>(); private void generateTextMesh(int index, LeapTextGraphic graphic, Mesh mesh) { using (new ProfilerSample("Generate Text Mesh")) { mesh.Clear(keepVertexLayout: false); graphic.isRepresentationDirty = false; int scaledFontSize = Mathf.RoundToInt(graphic.fontSize * _dynamicPixelsPerUnit); //Check for characters not found in the font { HashSet<char> unfoundCharacters = null; CharacterInfo info; foreach (var character in graphic.text) { if (character == '\n') { continue; } if (unfoundCharacters != null && unfoundCharacters.Contains(character)) { continue; } if (!_font.GetCharacterInfo(character, out info, scaledFontSize, graphic.fontStyle)) { if (unfoundCharacters == null) unfoundCharacters = new HashSet<char>(); unfoundCharacters.Add(character); Debug.LogError("Could not find character [" + character + "] in font " + _font + "!"); } } } var text = graphic.text; float _charScale = this._scale * SCALE_CONSTANT / _dynamicPixelsPerUnit; float _scale = _charScale * graphic.fontSize / _font.fontSize; float lineHeight = _scale * graphic.lineSpacing * _font.lineHeight * _dynamicPixelsPerUnit; RectTransform rectTransform = graphic.transform as RectTransform; float maxWidth; if (rectTransform != null) { maxWidth = rectTransform.rect.width; } else { maxWidth = float.MaxValue; } _widthCalculator.font = _font; _widthCalculator.charScale = _charScale; _widthCalculator.fontStyle = graphic.fontStyle; _widthCalculator.scaledFontSize = scaledFontSize; TextWrapper.Wrap(text, graphic.tokens, _tempLines, _widthCalculator.func, maxWidth); float textHeight = _tempLines.Count * lineHeight; Vector3 origin = Vector3.zero; origin.y -= _font.ascent * _scale * _dynamicPixelsPerUnit; if (rectTransform != null) { origin.y -= rectTransform.rect.y; switch (graphic.verticalAlignment) { case LeapTextGraphic.VerticalAlignment.Center: origin.y -= (rectTransform.rect.height - textHeight) / 2; break; case LeapTextGraphic.VerticalAlignment.Bottom: origin.y -= (rectTransform.rect.height - textHeight); break; } } foreach (var line in _tempLines) { if (rectTransform != null) { origin.x = rectTransform.rect.x; switch (graphic.horizontalAlignment) { case LeapTextGraphic.HorizontalAlignment.Center: origin.x += (rectTransform.rect.width - line.width) / 2; break; case LeapTextGraphic.HorizontalAlignment.Right: origin.x += (rectTransform.rect.width - line.width); break; } } else { switch (graphic.horizontalAlignment) { case LeapTextGraphic.HorizontalAlignment.Left: origin.x = 0; break; case LeapTextGraphic.HorizontalAlignment.Center: origin.x = -line.width / 2; break; case LeapTextGraphic.HorizontalAlignment.Right: origin.x = -line.width; break; } } for (int i = line.start; i < line.end; i++) { char c = text[i]; CharacterInfo info; if (!_font.GetCharacterInfo(c, out info, scaledFontSize, graphic.fontStyle)) { continue; } int offset = _verts.Count; _tris.Add(offset + 0); _tris.Add(offset + 1); _tris.Add(offset + 2); _tris.Add(offset + 0); _tris.Add(offset + 2); _tris.Add(offset + 3); _verts.Add(_charScale * new Vector3(info.minX, info.maxY, 0) + origin); _verts.Add(_charScale * new Vector3(info.maxX, info.maxY, 0) + origin); _verts.Add(_charScale * new Vector3(info.maxX, info.minY, 0) + origin); _verts.Add(_charScale * new Vector3(info.minX, info.minY, 0) + origin); _uvs.Add(info.uvTopLeft); _uvs.Add(info.uvTopRight); _uvs.Add(info.uvBottomRight); _uvs.Add(info.uvBottomLeft); if (_useColor) { _colors.Append(4, _globalTint * graphic.color); } origin.x += info.advance * _charScale; } origin.y -= lineHeight; } for (int i = 0; i < _uvs.Count; i++) { Vector4 uv = _uvs[i]; uv.w = index; _uvs[i] = uv; } mesh.SetVertices(_verts); mesh.SetTriangles(_tris, 0); mesh.SetUVs(0, _uvs); if (_useColor) { mesh.SetColors(_colors); } _verts.Clear(); _uvs.Clear(); _tris.Clear(); _colors.Clear(); _tempLines.Clear(); } } private CharWidthCalculator _widthCalculator = new CharWidthCalculator(); private class CharWidthCalculator { public Font font; public int scaledFontSize; public FontStyle fontStyle; public float charScale; public Func<char, float> func; public CharWidthCalculator() { func = funcMethod; } private float funcMethod(char c) { CharacterInfo info; font.GetCharacterInfo(c, out info, scaledFontSize, fontStyle); return info.advance * charScale; } } } } <file_sep>/Assets/Hover/Core/Scripts/Renderers/CanvasElements/HoverCanvasDataUpdater.cs using System; using Hover.Core.Utils; using UnityEngine; namespace Hover.Core.Renderers.CanvasElements { /*================================================================================================*/ [RequireComponent(typeof(HoverCanvas))] public class HoverCanvasDataUpdater : MonoBehaviour, ITreeUpdateable, ISettingsController { public enum IconPairType { Unspecified, CheckboxOff, CheckboxOn, RadioOff, RadioOn, NavigateIn, NavigateOut, Sticky, Slider } public const string LabelTextName = "LabelText"; public const string IconTypeName = "IconType"; public ISettingsControllerMap Controllers { get; private set; } [DisableWhenControlled(DisplaySpecials=true)] public string LabelText; [DisableWhenControlled] public IconPairType IconType; //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ protected HoverCanvasDataUpdater() { Controllers = new SettingsControllerMap(); } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public void Start() { //do nothing... } /*--------------------------------------------------------------------------------------------*/ public void TreeUpdate() { HoverCanvas hoverCanvas = gameObject.GetComponent<HoverCanvas>(); UpdateLabel(hoverCanvas); UpdateIcons(hoverCanvas); Controllers.TryExpireControllers(); } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ private void UpdateLabel(HoverCanvas pHoverCanvas) { pHoverCanvas.Label.Controllers.Set(SettingsControllerMap.TextText, this); pHoverCanvas.Label.TextComponent.text = LabelText; } /*--------------------------------------------------------------------------------------------*/ private void UpdateIcons(HoverCanvas pHoverCanvas) { var iconOuterType = HoverIcon.IconOffset.None; var iconInnerType = HoverIcon.IconOffset.None; switch ( IconType ) { case IconPairType.Unspecified: break; case IconPairType.CheckboxOn: iconOuterType = HoverIcon.IconOffset.CheckOuter; iconInnerType = HoverIcon.IconOffset.CheckInner; break; case IconPairType.CheckboxOff: iconOuterType = HoverIcon.IconOffset.CheckOuter; break; case IconPairType.RadioOn: iconOuterType = HoverIcon.IconOffset.RadioOuter; iconInnerType = HoverIcon.IconOffset.RadioInner; break; case IconPairType.RadioOff: iconOuterType = HoverIcon.IconOffset.RadioOuter; break; case IconPairType.NavigateIn: iconOuterType = HoverIcon.IconOffset.NavigateIn; break; case IconPairType.NavigateOut: iconOuterType = HoverIcon.IconOffset.NavigateOut; break; case IconPairType.Sticky: iconOuterType = HoverIcon.IconOffset.Sticky; break; case IconPairType.Slider: iconOuterType = HoverIcon.IconOffset.Slider; break; default: throw new Exception("Unhandled icon type: "+IconType); } pHoverCanvas.IconOuter.Controllers.Set(HoverIcon.IconTypeName, this); pHoverCanvas.IconInner.Controllers.Set(HoverIcon.IconTypeName, this); pHoverCanvas.IconOuter.IconType = iconOuterType; pHoverCanvas.IconInner.IconType = iconInnerType; } } } <file_sep>/Assets/LeapMotion/Modules/GraphicRenderer/Scripts/LeapGraphicFeature.cs /****************************************************************************** * Copyright (C) Leap Motion, Inc. 2011-2018. * * Leap Motion proprietary and confidential. * * * * Use subject to the terms of the Leap Motion SDK Agreement available at * * https://developer.leapmotion.com/sdk_agreement, or another agreement * * between Leap Motion and you, your company or other organization. * ******************************************************************************/ using System; using System.Reflection; using System.Collections.Generic; using UnityEngine; using Leap.Unity.Query; namespace Leap.Unity.GraphicalRenderer { public abstract class LeapGraphicFeatureBase { [NonSerialized] private bool _isDirty = true; //everything defaults dirty at the start! //Unity cannot serialize lists of objects that have no serializable fields //when it is set to text-serialization. A feature might have no specific //data, so we add this dummy bool to ensure it gets serialized anyway [SerializeField] private bool _dummyBool; public bool isDirty { get { return _isDirty; } set { _isDirty = value; } } public bool isDirtyOrEditTime { get { #if UNITY_EDITOR if (!Application.isPlaying) { return true; } else #endif { return _isDirty; } } } public virtual SupportInfo GetSupportInfo(LeapGraphicGroup group) { return SupportInfo.FullSupport(); } public abstract void AssignFeatureReferences(); public abstract void ClearDataObjectReferences(); public abstract void AddFeatureData(LeapFeatureData data); public abstract Type GetDataObjectType(); public abstract LeapFeatureData CreateFeatureDataForGraphic(LeapGraphic graphic); } public abstract class LeapGraphicFeature<DataType> : LeapGraphicFeatureBase where DataType : LeapFeatureData, new() { /// <summary> /// A list of all feature data. /// </summary> [NonSerialized] public List<DataType> featureData = new List<DataType>(); public override void AssignFeatureReferences() { foreach (var dataObj in featureData) { dataObj.feature = this; } } public override void ClearDataObjectReferences() { featureData.Clear(); } public override void AddFeatureData(LeapFeatureData data) { this.featureData.Add(data as DataType); } public override Type GetDataObjectType() { return typeof(DataType); } public override LeapFeatureData CreateFeatureDataForGraphic(LeapGraphic graphic) { DataType data = new DataType(); data.graphic = graphic; return data; } } [Serializable] public abstract class LeapFeatureData { [NonSerialized] public LeapGraphic graphic; [NonSerialized] public LeapGraphicFeatureBase feature; public void MarkFeatureDirty() { if (feature != null) { feature.isDirty = true; } } #if UNITY_EDITOR public static Type GetFeatureType(Type dataObjType) { var allTypes = Assembly.GetAssembly(dataObjType).GetTypes(); return allTypes.Query(). Where(t => t.IsSubclassOf(typeof(LeapGraphicFeatureBase)) && t != typeof(LeapGraphicFeatureBase) && !t.IsAbstract && t.BaseType.GetGenericArguments()[0] == dataObjType). FirstOrDefault(); } #endif } } <file_sep>/Assets/Hover/Core/Scripts/Utils/TriggerButtonAttribute.cs using System; using UnityEngine; namespace Hover.Core.Utils { /*================================================================================================*/ [AttributeUsage(AttributeTargets.Field)] public class TriggerButtonAttribute : PropertyAttribute { public string ButtonLabel { get; private set; } public string OnSelectedMethodName { get; private set; } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public TriggerButtonAttribute(string pButtonLabel, string pOnSelectedMethodName="OnEditorTriggerButtonSelected") { ButtonLabel = pButtonLabel; OnSelectedMethodName = pOnSelectedMethodName; } } } <file_sep>/Assets/Hover/Core/Scripts/Cursors/FollowCursor.cs using System; using UnityEngine; namespace Hover.Core.Cursors { /*================================================================================================*/ [Serializable] public class FollowCursor { public CursorType Type { get; private set; } public Transform FollowTransform; //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public FollowCursor(CursorType pType) { Type = pType; } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public void UpdateData(HoverCursorDataProvider pCursorDataProv) { if ( !pCursorDataProv.HasCursorData(Type) ) { return; } ICursorDataForInput data = pCursorDataProv.GetCursorDataForInput(Type); if ( data == null ) { return; } if ( FollowTransform == null ) { data.SetUsedByInput(false); return; } data.SetUsedByInput(FollowTransform.gameObject.activeInHierarchy); data.SetWorldPosition(FollowTransform.position); data.SetWorldRotation(FollowTransform.rotation); } } } <file_sep>/Assets/Hover/Core/Scripts/Layouts/Rect/HoverLayoutRectRelativeSizer.cs using Hover.Core.Utils; using UnityEngine; namespace Hover.Core.Layouts.Rect { /*================================================================================================*/ public class HoverLayoutRectRelativeSizer : MonoBehaviour, ISettingsController { [Range(0, 10)] public float RelativeSizeX = 1; [Range(0, 10)] public float RelativeSizeY = 1; [Range(-2, 2)] public float RelativePositionOffsetX = 0; [Range(-2, 2)] public float RelativePositionOffsetY = 0; } } <file_sep>/Assets/Hover/Core/Scripts/Renderers/HoverMesh.cs using Hover.Core.Utils; using UnityEngine; namespace Hover.Core.Renderers { /*================================================================================================*/ [ExecuteInEditMode] [RequireComponent(typeof(TreeUpdater))] [RequireComponent(typeof(MeshRenderer))] [RequireComponent(typeof(MeshFilter))] public abstract class HoverMesh : MonoBehaviour, ITreeUpdateable, ISettingsController { public enum DisplayModeType { Standard, SliderFill } public const string DisplayModeName = "DisplayMode"; public ISettingsControllerMap Controllers { get; private set; } public MeshBuilder Builder { get { return vMeshBuild; } } public bool DidRebuildMesh { get; private set; } public abstract bool IsMeshVisible { get; } [DisableWhenControlled(DisplaySpecials=true)] public DisplayModeType DisplayMode = DisplayModeType.Standard; protected MeshBuilder vMeshBuild; protected bool vForceUpdates; //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public HoverMesh() { Controllers = new SettingsControllerMap(); } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public virtual void Awake() { CreateMaterial(); CreateMesh(); CreateMeshBuilder(); } /*--------------------------------------------------------------------------------------------*/ public virtual void Start() { //do nothing... } /*--------------------------------------------------------------------------------------------*/ public virtual void TreeUpdate() { vForceUpdates = UpdateNullScenarios(); DidRebuildMesh = false; if ( ShouldUpdateMesh() ) { DidRebuildMesh = true; UpdateMesh(); } Controllers.TryExpireControllers(); } /*--------------------------------------------------------------------------------------------*/ public virtual void OnDestroy() { DestroyImmediate(gameObject.GetComponent<MeshFilter>().sharedMesh); } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ protected virtual void CreateMaterial() { MeshRenderer meshRend = gameObject.GetComponent<MeshRenderer>(); if ( meshRend.sharedMaterial == null ) { meshRend.sharedMaterial = Resources.Load<Material>( "Materials/HoverVertexColorMaterial"); meshRend.sortingOrder = 0; } } /*--------------------------------------------------------------------------------------------*/ protected virtual void CreateMesh() { Mesh mesh = new Mesh(); mesh.name = gameObject.name+"Mesh:"+GetInstanceID(); mesh.hideFlags = HideFlags.HideAndDontSave; mesh.MarkDynamic(); gameObject.GetComponent<MeshFilter>().sharedMesh = mesh; } /*--------------------------------------------------------------------------------------------*/ protected virtual void CreateMeshBuilder() { vMeshBuild = new MeshBuilder(gameObject.GetComponent<MeshFilter>().sharedMesh); } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ protected virtual bool UpdateNullScenarios() { MeshFilter meshFilt = gameObject.GetComponent<MeshFilter>(); if ( meshFilt.sharedMesh == null ) { //can occur upon "undo" action in the editor if ( vMeshBuild == null ) { //just in case; not sure if this scenario can occur CreateMesh(); CreateMeshBuilder(); } else { meshFilt.sharedMesh = vMeshBuild.Mesh; } return true; } if ( vMeshBuild == null ) { //can occur when recompiled DLLs cause a scene "refresh" CreateMeshBuilder(); return true; } return false; } /*--------------------------------------------------------------------------------------------*/ protected virtual bool ShouldUpdateMesh() { return vForceUpdates; } /*--------------------------------------------------------------------------------------------*/ protected abstract void UpdateMesh(); } } <file_sep>/Assets/LeapMotion/Core/Scripts/Hands/HandEnableDisable.cs /****************************************************************************** * Copyright (C) Leap Motion, Inc. 2011-2018. * * Leap Motion proprietary and confidential. * * * * Use subject to the terms of the Leap Motion SDK Agreement available at * * https://developer.leapmotion.com/sdk_agreement, or another agreement * * between Leap Motion and you, your company or other organization. * ******************************************************************************/ using UnityEngine; using System.Collections; using System; using Leap; namespace Leap.Unity{ public class HandEnableDisable : HandTransitionBehavior { protected override void Awake() { base.Awake(); gameObject.SetActive(false); } protected override void HandReset() { gameObject.SetActive(true); } protected override void HandFinish() { gameObject.SetActive(false); } } } <file_sep>/Assets/Hover/RendererModules/Alpha/Scripts/HoverAlphaMeshUpdater.cs using System; using Hover.Core.Renderers; using Hover.Core.Utils; using UnityEngine; namespace Hover.RendererModules.Alpha { /*================================================================================================*/ [ExecuteInEditMode] [RequireComponent(typeof(HoverIndicator))] [RequireComponent(typeof(HoverMesh))] public class HoverAlphaMeshUpdater : MonoBehaviour, ITreeUpdateable, ISettingsController { public const string SortingLayerName = "SortingLayer"; public const string AlphaName = "Alpha"; public ISettingsControllerMap Controllers { get; private set; } [DisableWhenControlled(DisplaySpecials=true)] public string SortingLayer = "Default"; [DisableWhenControlled] public int SortingOrder = 0; [DisableWhenControlled(RangeMin=0, RangeMax=1)] public float Alpha = 1; [ColorUsage(true, true, 0, 1000, 0, 1000)] public Color StandardColor = Color.gray; [ColorUsage(true, true, 0, 1000, 0, 1000)] public Color SliderFillColor = Color.white; [ColorUsage(true, true, 0, 1000, 0, 1000)] public Color FlashColor = Color.white; [Range(0, 2000)] public float FlashColorMilliseconds = 400; private string vPrevLayer; private int vPrevOrder; private float vPrevAlpha; private Color vPrevColor; private Color vCurrColor; //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ protected HoverAlphaMeshUpdater() { Controllers = new SettingsControllerMap(); } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public void Awake() { vPrevColor = GetDisplayColor(GetComponent<HoverMesh>()); } /*--------------------------------------------------------------------------------------------*/ public void OnEnable() { vPrevColor = GetDisplayColor(GetComponent<HoverMesh>()); } /*--------------------------------------------------------------------------------------------*/ public void Start() { //do nothing... } /*--------------------------------------------------------------------------------------------*/ public void TreeUpdate() { HoverMesh hoverMesh = GetComponent<HoverMesh>(); TryUpdateLayer(hoverMesh); TryUpdateColor(hoverMesh); vPrevLayer = SortingLayer; vPrevOrder = SortingOrder; vPrevAlpha = Alpha; vPrevColor = vCurrColor; Controllers.TryExpireControllers(); } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ private void TryUpdateLayer(HoverMesh pHoverMesh) { Controllers.Set(SettingsControllerMap.MeshRendererSortingLayer, this); Controllers.Set(SettingsControllerMap.MeshRendererSortingOrder, this); if ( !pHoverMesh.DidRebuildMesh && SortingLayer == vPrevLayer && SortingOrder == vPrevOrder ) { return; } MeshRenderer meshRend = gameObject.GetComponent<MeshRenderer>(); meshRend.sortingLayerName = SortingLayer; meshRend.sortingOrder = SortingOrder; } /*--------------------------------------------------------------------------------------------*/ private void TryUpdateColor(HoverMesh pHoverMesh) { Controllers.Set(SettingsControllerMap.MeshColors, this); vCurrColor = GetDisplayColor(pHoverMesh); if ( FlashColorMilliseconds > 0 ) { TimeSpan test = DateTime.UtcNow-GetComponent<HoverIndicator>().LatestSelectionTime; if ( test.TotalMilliseconds < FlashColorMilliseconds ) { vCurrColor = Color.Lerp(FlashColor, vCurrColor, (float)test.TotalMilliseconds/FlashColorMilliseconds); } } if ( !pHoverMesh.DidRebuildMesh && Alpha == vPrevAlpha && vCurrColor == vPrevColor ) { return; } Color colorForAllVertices = DisplayUtil.FadeColor(vCurrColor, Alpha); pHoverMesh.Builder.CommitColors(colorForAllVertices); } /*--------------------------------------------------------------------------------------------*/ private Color GetDisplayColor(HoverMesh pHoverMesh) { switch ( pHoverMesh.DisplayMode ) { case HoverMesh.DisplayModeType.Standard: return StandardColor; case HoverMesh.DisplayModeType.SliderFill: return SliderFillColor; default: throw new Exception("Unhandled display mode: "+pHoverMesh.DisplayMode); } } } } <file_sep>/Assets/LeapMotion/Modules/GraphicRenderer/Scripts/RenderingMethods/AssetData/RendererTextureData.cs /****************************************************************************** * Copyright (C) Leap Motion, Inc. 2011-2018. * * Leap Motion proprietary and confidential. * * * * Use subject to the terms of the Leap Motion SDK Agreement available at * * https://developer.leapmotion.com/sdk_agreement, or another agreement * * between Leap Motion and you, your company or other organization. * ******************************************************************************/ using System; using System.Collections.Generic; using UnityEngine; using UnityEngine.Assertions; using Leap.Unity.Query; namespace Leap.Unity.GraphicalRenderer { [Serializable] public class RendererTextureData { [SerializeField] private List<NamedTexture> packedTextures = new List<NamedTexture>(); public void Clear() { foreach (var tex in packedTextures) { UnityEngine.Object.DestroyImmediate(tex.texture); } packedTextures.Clear(); } public void AssignTextures(Texture2D[] textures, string[] propertyNames) { List<NamedTexture> newList = new List<NamedTexture>(); Assert.AreEqual(textures.Length, propertyNames.Length); for (int i = 0; i < textures.Length; i++) { newList.Add(new NamedTexture() { propertyName = propertyNames[i], texture = textures[i] }); } foreach (var tex in packedTextures) { if (!newList.Query().Any(p => p.texture == tex.texture)) { UnityEngine.Object.DestroyImmediate(tex.texture); } } packedTextures = newList; } public Texture2D GetTexture(string propertyName) { return packedTextures.Query(). FirstOrDefault(p => p.propertyName == propertyName).texture; } public int Count { get { return packedTextures.Count; } } public void Validate(LeapRenderingMethod renderingMethod) { for (int i = packedTextures.Count; i-- != 0;) { NamedTexture nt = packedTextures[i]; Texture2D tex = nt.texture; if (tex == null) { packedTextures.RemoveAt(i); continue; } renderingMethod.PreventDuplication(ref tex); nt.texture = tex; packedTextures[i] = nt; } } [Serializable] public struct NamedTexture { public string propertyName; public Texture2D texture; } } } <file_sep>/Assets/Hover/Core/Scripts/Cursors/HoverCursorIdleState.cs using System; using System.Collections.Generic; using UnityEngine; namespace Hover.Core.Cursors { /*================================================================================================*/ [ExecuteInEditMode] [RequireComponent(typeof(HoverCursorData))] public class HoverCursorIdleState : MonoBehaviour, ICursorIdle { public struct HistoryRecord { public DateTime Time; public Vector3 WorldPosition; } public float Progress { get; private set; } public Vector3 WorldPosition { get; private set; } public float DistanceThreshold { get; private set; } public HoverInteractionSettings InteractionSettings; [Range(0, 3)] public float DriftStrength = 1; private readonly List<HistoryRecord> vHistory; private bool vIsActive; //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ protected HoverCursorIdleState() { vHistory = new List<HistoryRecord>(); } /*--------------------------------------------------------------------------------------------*/ public bool IsActive { get { return (vIsActive && isActiveAndEnabled); } } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public void Awake() { if ( InteractionSettings == null ) { InteractionSettings = (GetComponent<HoverInteractionSettings>() ?? FindObjectOfType<HoverInteractionSettings>()); } if ( InteractionSettings == null ) { Debug.LogWarning("Could not find 'InteractionSettings'."); } } /*--------------------------------------------------------------------------------------------*/ public void Update() { HoverCursorData data = GetComponent<HoverCursorData>(); Vector3 worldPos = (data.BestRaycastResult == null ? data.WorldPosition : data.BestRaycastResult.Value.WorldPosition); vIsActive = (data.ActiveStickySelections.Count > 0); DistanceThreshold = InteractionSettings.IdleDistanceThreshold; if ( !Application.isPlaying ) { Progress = 0.25f; WorldPosition = worldPos; return; } if ( !vIsActive ) { vHistory.Clear(); Progress = 0; WorldPosition = worldPos; return; } if ( Progress >= 1 ) { vHistory.Clear(); Progress = 0; } AddToHistory(worldPos); CalcSmoothPosition(); CullHistory(); UpdateProgress(); } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ private void AddToHistory(Vector3 pWorldPosition) { var current = new HistoryRecord { Time = DateTime.UtcNow, WorldPosition = pWorldPosition }; vHistory.Add(current); } /*--------------------------------------------------------------------------------------------*/ private void CalcSmoothPosition() { if ( vHistory.Count == 1 ) { WorldPosition = vHistory[0].WorldPosition; return; } HistoryRecord current = vHistory[vHistory.Count-1]; float maxSec = 1000f/InteractionSettings.IdleMilliseconds; float smoothing = maxSec*Time.deltaTime*DriftStrength; WorldPosition = Vector3.Lerp(WorldPosition, current.WorldPosition, smoothing); } /*--------------------------------------------------------------------------------------------*/ private void CullHistory() { HistoryRecord current = vHistory[vHistory.Count-1]; float currDistFromCenter = (current.WorldPosition-WorldPosition).magnitude; if ( currDistFromCenter > InteractionSettings.IdleDistanceThreshold ) { vHistory.Clear(); return; } float maxMs = InteractionSettings.IdleMilliseconds; int staleIndex = -1; for ( int i = vHistory.Count-2 ; i >= 0 ; i-- ) { HistoryRecord record = vHistory[i]; if ( (current.Time-record.Time).TotalMilliseconds > maxMs ) { staleIndex = i; break; } //HistoryRecord recordPrev = vHistory[i+1]; //Debug.DrawLine(recordPrev.WorldPosition, record.WorldPosition, Color.yellow); } if ( staleIndex < 0 ) { vHistory.RemoveRange(0, staleIndex+1); } } /*--------------------------------------------------------------------------------------------*/ private void UpdateProgress() { if ( vHistory.Count < 2 ) { Progress = 0; return; } HistoryRecord current = vHistory[vHistory.Count-1]; float earliestMsAgo = (float)(current.Time-vHistory[0].Time).TotalMilliseconds; Progress = Mathf.Min(1, earliestMsAgo/InteractionSettings.IdleMilliseconds); } } } <file_sep>/Assets/Hover/Core/Scripts/Renderers/Items/Sliders/HoverRendererSlider.cs using System; using Hover.Core.Renderers.CanvasElements; using Hover.Core.Renderers.Items.Buttons; using Hover.Core.Renderers.Shapes; using Hover.Core.Renderers.Utils; using Hover.Core.Utils; using UnityEngine; namespace Hover.Core.Renderers.Items.Sliders { /*================================================================================================*/ [RequireComponent(typeof(HoverRendererSliderSegments))] public class HoverRendererSlider : HoverRenderer { public const string ZeroValueName = "ZeroValue"; public const string HandleValueName = "HandleValue"; public const string JumpValueName = "JumpValue"; public const string AllowJumpName = "AllowJump"; public const string TickCountName = "TickCount"; public const string FillStartingPointName = "FillStartingPoint"; public const string ShowButtonEdgesName = "ShowButtonEdges"; [DisableWhenControlled] public GameObject Container; [DisableWhenControlled] public HoverFillSlider Track; [DisableWhenControlled] public HoverRendererButton HandleButton; [DisableWhenControlled] public HoverRendererButton JumpButton; [DisableWhenControlled(RangeMin=0, RangeMax=1)] public float ZeroValue = 0.5f; [DisableWhenControlled(RangeMin=0, RangeMax=1)] public float HandleValue = 0.5f; [DisableWhenControlled(RangeMin=0, RangeMax=1)] public float JumpValue = 0; [DisableWhenControlled] public bool AllowJump = false; [DisableWhenControlled] public int TickCount = 0; [DisableWhenControlled] public SliderFillType FillStartingPoint = SliderFillType.MinimumValue; [DisableWhenControlled] public bool ShowButtonEdges = false; //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public override int GetChildFillCount() { return 1; } /*--------------------------------------------------------------------------------------------*/ public override HoverFill GetChildFill(int pIndex) { switch ( pIndex ) { case 0: return Track; } throw new ArgumentOutOfRangeException(); } /*--------------------------------------------------------------------------------------------*/ public override int GetChildRendererCount() { return 2; } /*--------------------------------------------------------------------------------------------*/ public override HoverRenderer GetChildRenderer(int pIndex) { switch ( pIndex ) { case 0: return HandleButton; case 1: return JumpButton; } throw new ArgumentOutOfRangeException(); } /*--------------------------------------------------------------------------------------------*/ public override HoverCanvas GetCanvas() { return HandleButton.Canvas; } /*--------------------------------------------------------------------------------------------*/ public override HoverCanvasDataUpdater GetCanvasDataUpdater() { return HandleButton.Canvas.GetComponent<HoverCanvasDataUpdater>(); } /*--------------------------------------------------------------------------------------------*/ public override Vector3 GetCenterWorldPosition() { return HandleButton.GetShape().GetCenterWorldPosition(); } /*--------------------------------------------------------------------------------------------*/ public override Vector3 GetNearestWorldPosition(Vector3 pFromWorldPosition) { if ( AllowJump ) { return GetComponent<HoverShape>().GetNearestWorldPosition(pFromWorldPosition); } return HandleButton.GetShape().GetNearestWorldPosition(pFromWorldPosition); } /*--------------------------------------------------------------------------------------------*/ public override Vector3 GetNearestWorldPosition(Ray pFromWorldRay, out RaycastResult pRaycast) { if ( AllowJump ) { return GetComponent<HoverShape>().GetNearestWorldPosition(pFromWorldRay, out pRaycast); } return HandleButton.GetShape().GetNearestWorldPosition(pFromWorldRay, out pRaycast); } /*--------------------------------------------------------------------------------------------*/ public float GetValueViaNearestWorldPosition(Vector3 pNearestWorldPosition) { return GetComponent<HoverShape>().GetSliderValueViaNearestWorldPosition( pNearestWorldPosition, Container.transform, HandleButton.GetShape()); } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public override void TreeUpdate() { base.TreeUpdate(); UpdateTrack(); UpdateButtons(); } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ private void UpdateTrack() { Track.Controllers.Set(HoverFillSlider.SegmentInfoName, this); Track.SegmentInfo = gameObject.GetComponent<HoverRendererSliderSegments>(); } /*--------------------------------------------------------------------------------------------*/ private void UpdateButtons() { HoverRendererSliderSegments segs = gameObject.GetComponent<HoverRendererSliderSegments>(); HandleButton.Controllers.Set(HoverRendererButton.IsEnabledName, this); JumpButton.Controllers.Set(HoverRendererButton.IsEnabledName, this); HandleButton.Fill.Controllers.Set(HoverFillButton.ShowEdgeName, this); JumpButton.Fill.Controllers.Set(HoverFillButton.ShowEdgeName, this); HandleButton.IsEnabled = IsEnabled; JumpButton.IsEnabled = IsEnabled; HandleButton.Fill.ShowEdge = ShowButtonEdges; JumpButton.Fill.ShowEdge = ShowButtonEdges; RendererUtil.SetActiveWithUpdate(JumpButton, (AllowJump && segs.IsJumpVisible)); } } } <file_sep>/Assets/Hover/Core/Scripts/Renderers/Utils/RendererUtil.cs using System; using Hover.Core.Utils; using UnityEngine; namespace Hover.Core.Renderers.Utils { /*================================================================================================*/ public static class RendererUtil { //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public static T FindOrBuildRenderer<T>(Transform pParentTx, GameObject pPrefab, string pDisplayName, Type pDefaultType) where T : class, IGameObjectProvider { T existing = FindInImmediateChildren<T>(pParentTx); if ( existing != null ) { return existing; } return BuildRenderer<T>(pParentTx, pPrefab, pDisplayName, pDefaultType); } /*--------------------------------------------------------------------------------------------*/ private static T BuildRenderer<T>(Transform pParentTx, GameObject pPrefab, string pDisplayTypeName, Type pDefaultType) where T : class, IGameObjectProvider { if ( pPrefab != null ) { T prefabRend = TryBuildPrefabRenderer<T>(pPrefab); if ( prefabRend != null ) { prefabRend.gameObject.transform.SetParent(pParentTx, false); TreeUpdater treeUp = prefabRend.gameObject.GetComponent<TreeUpdater>(); if ( treeUp != null ) { treeUp.UpdateAtAndBelowThisLevel(); } return prefabRend; } Debug.LogError(pDisplayTypeName+" prefab '"+pPrefab.name+"' must contain a '"+ typeof(T)+"' component. ", pParentTx); } Debug.LogWarning("Could not find existing renderer, and no prefab provided.", pParentTx); return default(T); } /*--------------------------------------------------------------------------------------------*/ public static T TryBuildPrefabRenderer<T>(GameObject pPrefab) { if ( pPrefab.GetComponent<T>() == null ) { return default(T); } #if UNITY_EDITOR GameObject prefabGo = (GameObject)UnityEditor.PrefabUtility.InstantiatePrefab(pPrefab); #else GameObject prefabGo = UnityEngine.Object.Instantiate(pPrefab); #endif return prefabGo.GetComponent<T>(); } /*--------------------------------------------------------------------------------------------*/ public static void DestroyRenderer<T>(T pRenderer) where T : IGameObjectProvider { if ( pRenderer == null || pRenderer.gameObject == null ) { return; } #if UNITY_EDITOR UnityEditor.PrefabUtility.DisconnectPrefabInstance(pRenderer.gameObject); #endif if ( Application.isPlaying ) { UnityEngine.Object.Destroy(pRenderer.gameObject); } else { UnityEngine.Object.DestroyImmediate(pRenderer.gameObject, false); } } /*--------------------------------------------------------------------------------------------*/ private static T FindInImmediateChildren<T>(Transform pParentTx) where T : IGameObjectProvider { int childCount = pParentTx.childCount; for ( int i = 0 ; i < childCount ; i++ ) { Transform childTx = pParentTx.GetChild(i); T renderer = childTx.GetComponent<T>(); if ( renderer != null ) { return renderer; } } return default(T); } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public static void SetActiveWithUpdate(MonoBehaviour pBehaviour, bool pIsActive) { SetActiveWithUpdate(pBehaviour.gameObject, pIsActive); } /*--------------------------------------------------------------------------------------------*/ public static void SetActiveWithUpdate(GameObject pGameObj, bool pIsActive) { bool wasActive = pGameObj.activeSelf; pGameObj.SetActive(pIsActive); if ( pIsActive && !wasActive ) { pGameObj.SendMessage("TreeUpdate", SendMessageOptions.DontRequireReceiver); } } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public static Plane GetWorldPlane(Transform pTx) { return new Plane(pTx.rotation*Vector3.back, pTx.position); } /*--------------------------------------------------------------------------------------------*/ public static Vector3? GetNearestWorldPositionOnPlane(Ray pFromWorldRay, Plane pWorldPlane) { float enter; pWorldPlane.Raycast(pFromWorldRay, out enter); if ( enter <= 0 ) { return null; } return pFromWorldRay.GetPoint(enter); } /*--------------------------------------------------------------------------------------------*/ public static Vector3 GetNearestWorldPositionOnRectangle(Vector3 pFromWorldPosition, Transform pRectTx, float pSizeX, float pSizeY) { Vector3 fromLocalPos = pRectTx.InverseTransformPoint(pFromWorldPosition); var nearLocalPos = new Vector3( Mathf.Clamp(fromLocalPos.x, -pSizeX/2, pSizeX/2), Mathf.Clamp(fromLocalPos.y, -pSizeY/2, pSizeY/2), 0 ); return pRectTx.TransformPoint(nearLocalPos); } /*--------------------------------------------------------------------------------------------*/ public static Vector3 GetNearestWorldPositionOnArc(Vector3 pFromWorldPosition, Transform pArcTx, float pOuterRadius, float pInnerRadius, float pArcDegrees) { Vector3 fromLocalPos = pArcTx.InverseTransformPoint(pFromWorldPosition); if ( fromLocalPos.x == 0 && fromLocalPos.y == 0 ) { return pArcTx.TransformPoint(new Vector3(pInnerRadius, 0, 0)); } fromLocalPos.z = 0; float fromLocalPosMag = fromLocalPos.magnitude; Vector3 fromLocalDir = fromLocalPos/fromLocalPosMag; Quaternion fromLocalRot = Quaternion.FromToRotation(Vector3.right, fromLocalDir); float halfDeg = pArcDegrees/2; float fromRadius = Mathf.Clamp(fromLocalPosMag, pInnerRadius, pOuterRadius); float fromDeg; Vector3 fromAxis; fromLocalRot.ToAngleAxis(out fromDeg, out fromAxis); if ( fromLocalPos.x > 0 && fromDeg >= -halfDeg && fromDeg <= halfDeg ) { Quaternion nearLocalRot = Quaternion.AngleAxis(fromDeg, fromAxis); Vector3 nearLocalPos = nearLocalRot*new Vector3(fromRadius, 0, 0); return pArcTx.TransformPoint(nearLocalPos); } float rotatedDeg = -halfDeg*Mathf.Sign(fromLocalPos.y); Quaternion rotatedRot = Quaternion.AngleAxis(rotatedDeg, Vector3.forward); Vector3 fromRotatedPos = rotatedRot*fromLocalPos; fromRotatedPos.x = Mathf.Clamp(fromRotatedPos.x, pInnerRadius, pOuterRadius); fromRotatedPos.y = 0; Vector3 fromClampedRotatedPos = Quaternion.Inverse(rotatedRot)*fromRotatedPos; return pArcTx.TransformPoint(fromClampedRotatedPos); } } } <file_sep>/Assets/LeapMotion/Core/Scripts/Utils/RuntimeGizmoToggle.cs /****************************************************************************** * Copyright (C) Leap Motion, Inc. 2011-2018. * * Leap Motion proprietary and confidential. * * * * Use subject to the terms of the Leap Motion SDK Agreement available at * * https://developer.leapmotion.com/sdk_agreement, or another agreement * * between Leap Motion and you, your company or other organization. * ******************************************************************************/ using UnityEngine; using System.Collections; namespace Leap.Unity.RuntimeGizmos { /// <summary> /// This class controls the display of all the runtime gizmos /// that are either attatched to this gameObject, or a child of /// this gameObject. Enable this component to allow the gizmos /// to be drawn, and disable it to hide them. /// </summary> public class RuntimeGizmoToggle : MonoBehaviour { public void OnEnable() { } } } <file_sep>/Assets/Hover/Core/Scripts/Renderers/Shapes/Arc/HoverRendererSliderArcUpdater.cs using Hover.Core.Renderers.Items.Buttons; using Hover.Core.Renderers.Items.Sliders; using Hover.Core.Renderers.Utils; using Hover.Core.Utils; using UnityEngine; namespace Hover.Core.Renderers.Shapes.Arc { /*================================================================================================*/ [RequireComponent(typeof(HoverRendererSliderSegments))] [RequireComponent(typeof(HoverShapeArc))] public class HoverRendererSliderArcUpdater : HoverRendererSliderUpdater { //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public override void TreeUpdate() { HoverRendererSlider rendSlider = gameObject.GetComponent<HoverRendererSlider>(); HoverShapeArc shapeArc = gameObject.GetComponent<HoverShapeArc>(); HoverShapeArc handleShapeArc = (HoverShapeArc)rendSlider.HandleButton.GetShape(); HoverShapeArc jumpShapeArc = (HoverShapeArc)rendSlider.JumpButton.GetShape(); shapeArc.ArcDegrees = Mathf.Max(shapeArc.ArcDegrees, handleShapeArc.ArcDegrees); UpdateTrackShape(shapeArc, rendSlider); UpdateButtonRadii(shapeArc, handleShapeArc); UpdateButtonRadii(shapeArc, jumpShapeArc); UpdateButtonRotations(rendSlider); } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ private void UpdateTrackShape(HoverShapeArc pShapeArc, HoverRendererSlider pRendSlider) { HoverShapeArc trackShapeArc = (HoverShapeArc)pRendSlider.Track.GetShape(); trackShapeArc.Controllers.Set(HoverShapeArc.OuterRadiusName, this); trackShapeArc.Controllers.Set(HoverShapeArc.InnerRadiusName, this); trackShapeArc.Controllers.Set(HoverShapeArc.ArcDegreesName, this); trackShapeArc.OuterRadius = pShapeArc.OuterRadius; trackShapeArc.InnerRadius = pShapeArc.InnerRadius; trackShapeArc.ArcDegrees = pShapeArc.ArcDegrees; } /*--------------------------------------------------------------------------------------------*/ private void UpdateButtonRadii(HoverShapeArc pShapeArc, HoverShapeArc pButtonShapeArc) { pButtonShapeArc.Controllers.Set(HoverShapeArc.OuterRadiusName, this); pButtonShapeArc.Controllers.Set(HoverShapeArc.InnerRadiusName, this); pButtonShapeArc.OuterRadius = pShapeArc.OuterRadius; pButtonShapeArc.InnerRadius = pShapeArc.InnerRadius; } /*--------------------------------------------------------------------------------------------*/ private void UpdateButtonRotations(HoverRendererSlider pRendSlider) { HoverRendererSliderSegments segs = gameObject.GetComponent<HoverRendererSliderSegments>(); for ( int i = 0 ; i < segs.SegmentInfoList.Count ; i++ ) { SliderUtil.SegmentInfo segInfo = segs.SegmentInfoList[i]; bool isHandle = (segInfo.Type == SliderUtil.SegmentType.Handle); bool isJump = (segInfo.Type == SliderUtil.SegmentType.Jump); if ( !isHandle && !isJump ) { continue; } HoverRendererButton button = (isHandle ? pRendSlider.HandleButton : pRendSlider.JumpButton); button.Controllers.Set(SettingsControllerMap.TransformLocalRotation+".z", this); Vector3 buttonLocalEuler = button.transform.localRotation.eulerAngles; buttonLocalEuler.z = (segInfo.StartPosition+segInfo.EndPosition)/2; button.transform.localRotation = Quaternion.Euler(buttonLocalEuler); } } } } <file_sep>/Assets/Hover/Core/Scripts/Items/Types/HoverItemDataCheckbox.cs using System; namespace Hover.Core.Items.Types { /*================================================================================================*/ [Serializable] public class HoverItemDataCheckbox : HoverItemDataSelectableBool, IItemDataCheckbox { //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public override void Select() { Value = !Value; base.Select(); } } } <file_sep>/Assets/IronManUI/Scripts/UI/ThreeDItem.cs /** * Author: <NAME> * Created: 01.18.2019 * * MIT Reality Virtually Hackathon **/ using UnityEngine; using TMPro; using System; namespace IronManUI { [System.Serializable] public class ThreeDItemModel : IMComponentModel { // public float resourceScale = 1f; public Vector3 resourcePosition; public Vector3 resourceScale = Vector3.one; public string resource = ""; override public void Copy(IMComponentModel o) { var o1 = o as ThreeDItemModel; if (o1 != null) { resource = o1.resource; resourceScale = o1.resourceScale; } } } [ExecuteInEditMode] [RequireComponent(typeof(BoxCollider))] public class ThreeDItem : AbstractIMComponent { public ThreeDItemModel threeDModel; override public IMComponentModel model { get { if (threeDModel == null) threeDModel = new ThreeDItemModel(); return threeDModel; } } protected BoxCollider boxCollider; private string loadedResName; override protected void OnEnable() { base.OnEnable(); boxCollider = GetComponent<BoxCollider>(); if (boxCollider == null) boxCollider = gameObject.AddComponent<BoxCollider>(); } override protected void OnDisable() { base.OnDisable(); gameObject.DestroyChildren(); loadedResName = null; } override protected void Update() { ThreeDItemModel model = this.model as ThreeDItemModel; if (model.resource != loadedResName) { gameObject.DestroyChildren(); var resource = Resources.Load(model.resource); if (resource != null) { var obj = Instantiate(resource) as GameObject; if (obj != null) { obj.transform.parent = transform; // obj.transform.localScale = new Vector3(model.resourceScale, model.resourceScale, model.resourceScale); } } loadedResName = model.resource; // var bounds = gameObject.GetBounds(); //TODO needs help // boxCollider.size = bounds.size; // boxCollider.center = bounds.center; } if (transform.childCount > 0) { var childT = transform.GetChild(0).transform; // transform.GetChild(0).transform.localScale = new Vector3(model.resourceScale, model.resourceScale, model.resourceScale); childT.localPosition = model.resourcePosition; childT.localScale = model.resourceScale; } base.Update(); } override protected IMComponentModel CreateDefaultModel() { return new ThreeDItemModel(); } protected override Type GetModelType() { return typeof(ThreeDItemModel); } } }<file_sep>/Assets/Hover/Core/Scripts/Utils/RaycastResult.cs using UnityEngine; namespace Hover.Core.Utils { /*================================================================================================*/ public struct RaycastResult { public bool IsHit; public Vector3 WorldPosition; public Quaternion WorldRotation; public Plane WorldPlane; } } <file_sep>/Assets/Hover/Core/Scripts/Cursors/IInteractionSettings.cs namespace Hover.Core.Cursors { /*================================================================================================*/ public interface IInteractionSettings { float HighlightDistanceMin { get; set; } float HighlightDistanceMax { get; set; } float StickyReleaseDistance { get; set; } float SelectionMilliseconds { get; set; } float IdleDistanceThreshold { get; set; } float IdleMilliseconds { get; set; } } } <file_sep>/Assets/Hover/Core/Scripts/Layouts/Arc/ILayoutableArc.cs using Hover.Core.Utils; using UnityEngine; namespace Hover.Core.Layouts.Arc { /*================================================================================================*/ public interface ILayoutableArc { bool isActiveAndEnabled { get; } Transform transform { get; } ISettingsControllerMap Controllers { get; } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ void SetArcLayout(float pOuterRadius, float pInnerRadius, float pArcDegrees, ISettingsController pController); } } <file_sep>/Assets/Hover/Core/Scripts/Renderers/IGameObjectProvider.cs using UnityEngine; namespace Hover.Core.Renderers { /*================================================================================================*/ public interface IGameObjectProvider { GameObject gameObject { get; } } } <file_sep>/Assets/IronManUI/Scripts/IronManLeapManager.cs /** * Author: <NAME> * Created: 01.19.2019 * * MIT Reality Virtually Hackathon **/ using System.Collections.Generic; using UnityEngine; using Leap.Unity; using Leap.Unity.Interaction; namespace IronManUI { public class FingertipInfo { public InteractionHand hand; // public PinchDetector pinch; public Fingertip thumb, index, middle; public FingertipInfo(InteractionHand hand, Fingertip thumb, Fingertip index, Fingertip middle) { this.hand = hand; // this.pinch = pinch; this.thumb = thumb; this.index = index; this.middle = middle; } } public class IronManLeapManager : MonoBehaviour { public GameObject leapRig; public float pinchDistanceThresh = .034f; public List<FingertipInfo> fingertipInfoList = new List<FingertipInfo>(); void OnEnable() { if (leapRig == null) { Debug.LogWarning("LeapRig must be set"); return; } } void RigHands() { foreach (var hand in leapRig.GetComponentsInChildren<InteractionHand>()) { if (hand.transform.childCount < 3) continue; Debug.Log("Processing hand"); foreach (var finger in hand.transform.GetChildren()) { RigFingertip(finger.gameObject); } var thumb = hand.transform.GetChild(1).GetComponent<Fingertip>(); if (thumb == null) Debug.Log("Warning: thumb not added."); var indexFingertip = hand.transform.GetChild(2).GetComponent<Fingertip>(); if (indexFingertip == null) Debug.Log("Warning: index fingertip not added."); var flippingFingertip = hand.transform.GetChild(3).GetComponent<Fingertip>(); if (flippingFingertip == null) Debug.Log("Warning: middle fingertip not added."); // var pinchObj = new GameObject("PinchDetector-" + hand.name); // pinchObj.transform.parent = transform; // var pinchDetector = pinchObj.AddComponent<PinchDetector>(); // pinchDetector.HandModel = hand; // hand. fingertipInfoList.Add(new FingertipInfo(hand, thumb, indexFingertip, flippingFingertip)); } } void RigFingertip(GameObject finger) { finger.AddComponent<Fingertip>(); var collider = finger.GetComponent<BoxCollider>(); if (collider == null) collider = finger.AddComponent<BoxCollider>(); collider.size = new Vector3(.1f,.1f,.1f); var rigidBody = finger.GetComponent<Rigidbody>(); if (rigidBody == null) rigidBody = finger.AddComponent<Rigidbody>(); rigidBody.isKinematic = true; } void OnDisable() { fingertipInfoList.Clear(); // if (fingertipInfoList.Count == 0) // return; // foreach (var hand in leapRig.GetComponentsInChildren<InteractionHand>()) { // foreach var fingertip in hand.GetComponentsInChildren<Fingertip // } } void Update() { if (fingertipInfoList.Count == 0) { RigHands(); } foreach (var fingertipInfo in fingertipInfoList) { var indexPinchDistance = Vector3.Distance(fingertipInfo.thumb.transform.position, fingertipInfo.index.transform.position); var middlePinchDistance = Vector3.Distance(fingertipInfo.thumb.transform.position, fingertipInfo.middle.transform.position); bool indexGrabbing = indexPinchDistance < pinchDistanceThresh; bool middleGrabbing = middlePinchDistance < pinchDistanceThresh; if (indexGrabbing) middleGrabbing = false; //don't grab with both fingers // Debug.Log("Pinch distance: " + indexPinchDistance + " :: " + indexGrabbing); fingertipInfo.index.grabbing = indexGrabbing; fingertipInfo.middle.grabbing = middleGrabbing; } } } } <file_sep>/Assets/Hover/Core/Scripts/Layouts/Arc/HoverLayoutArcRow.cs using Hover.Core.Layouts.Rect; using Hover.Core.Utils; using UnityEngine; namespace Hover.Core.Layouts.Arc { /*================================================================================================*/ public class HoverLayoutArcRow : HoverLayoutArcGroup, ILayoutableArc, ILayoutableRect { public const string OuterRadiusName = "OuterRadius"; public const string InnerRadiusName = "InnerRadius"; public const string ArcDegreesName = "ArcDegrees"; public const string RectAnchorName = "RectAnchor"; public enum ArrangementType { Forward, Reverse } [DisableWhenControlled(DisplaySpecials=true)] public ArrangementType Arrangement = ArrangementType.Forward; [DisableWhenControlled(RangeMin=0)] public float OuterRadius = 0.1f; [DisableWhenControlled(RangeMin=0)] public float InnerRadius = 0.04f; [DisableWhenControlled(RangeMin=0, RangeMax=360)] public float ArcDegrees = 135; public HoverLayoutArcPaddingSettings Padding = new HoverLayoutArcPaddingSettings(); [DisableWhenControlled(RangeMin=-180, RangeMax=180)] public float StartingDegree = 0; [DisableWhenControlled] public AnchorType RectAnchor = AnchorType.MiddleCenter; private Vector2? vRectSize; //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public override void TreeUpdate() { base.TreeUpdate(); Padding.ClampValues(this); UpdateLayoutWithFixedSize(); if ( vRectSize == null ) { Controllers.Set(RectAnchorName, this); RectAnchor = AnchorType.MiddleCenter; } vRectSize = null; } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public void SetArcLayout(float pOuterRadius, float pInnerRadius, float pArcDegrees, ISettingsController pController) { Controllers.Set(OuterRadiusName, pController); Controllers.Set(InnerRadiusName, pController); Controllers.Set(ArcDegreesName, pController); OuterRadius = pOuterRadius; InnerRadius = pInnerRadius; ArcDegrees = pArcDegrees; } /*--------------------------------------------------------------------------------------------*/ public void SetRectLayout(float pSizeX, float pSizeY, ISettingsController pController) { Controllers.Set(OuterRadiusName, pController); OuterRadius = Mathf.Min(pSizeX, pSizeY)/2; vRectSize = new Vector2(pSizeX, pSizeY); } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ private void UpdateLayoutWithFixedSize() { int itemCount = vChildItems.Count; if ( itemCount == 0 ) { return; } bool isRev = (Arrangement == ArrangementType.Reverse); float relSumArcDeg = 0; float paddedOuterRadius = OuterRadius-Padding.OuterRadius; float paddedInnerRadius = InnerRadius+Padding.InnerRadius; float paddedDeg = ArcDegrees-Padding.StartDegree-Padding.EndDegree; float availDeg = paddedDeg-Padding.Between*(itemCount-1); float deg = StartingDegree - paddedDeg/2 + (Padding.StartDegree-Padding.EndDegree)/2; Vector2 anchorPos = LayoutUtil.GetRelativeAnchorPosition(RectAnchor); anchorPos.x *= (vRectSize == null ? OuterRadius*2 : ((Vector2)vRectSize).x); anchorPos.y *= (vRectSize == null ? OuterRadius*2 : ((Vector2)vRectSize).y); for ( int i = 0 ; i < itemCount ; i++ ) { HoverLayoutArcGroupChild item = vChildItems[i]; relSumArcDeg += item.RelativeArcDegrees; } for ( int i = 0 ; i < itemCount ; i++ ) { int childI = (isRev ? itemCount-i-1 : i); HoverLayoutArcGroupChild item = vChildItems[childI]; ILayoutableArc elem = item.Elem; float elemRelDeg = availDeg*item.RelativeArcDegrees/relSumArcDeg; float relInset = (paddedOuterRadius-paddedInnerRadius)*(1-item.RelativeThickness)/2; float elemThick = paddedOuterRadius-paddedInnerRadius-relInset*2; float elemRelArcDeg = availDeg*item.RelativeArcDegrees; float radiusOffset = elemThick*item.RelativeRadiusOffset; float elemStartDeg = deg + elemRelDeg/2 + elemRelArcDeg*item.RelativeStartDegreeOffset; elem.SetArcLayout( paddedOuterRadius-relInset+radiusOffset, paddedInnerRadius+relInset+radiusOffset, elemRelDeg, this ); elem.Controllers.Set(SettingsControllerMap.TransformLocalPosition+".x", this); elem.Controllers.Set(SettingsControllerMap.TransformLocalPosition+".y", this); elem.Controllers.Set(SettingsControllerMap.TransformLocalRotation, this); Vector3 localPos = elem.transform.localPosition; localPos.x = anchorPos.x; localPos.y = anchorPos.y; elem.transform.localPosition = localPos; elem.transform.localRotation = Quaternion.AngleAxis(elemStartDeg, Vector3.back); deg += elemRelDeg+Padding.Between; } } } } <file_sep>/Assets/Hover/Core/Scripts/Renderers/Shapes/Rect/HoverShapeRect.cs using Hover.Core.Layouts.Rect; using Hover.Core.Renderers.Utils; using Hover.Core.Utils; using UnityEngine; namespace Hover.Core.Renderers.Shapes.Rect { /*================================================================================================*/ public class HoverShapeRect : HoverShape, ILayoutableRect { public const string SizeXName = "SizeX"; public const string SizeYName = "SizeY"; [DisableWhenControlled(RangeMin=0)] public float SizeX = 0.1f; [DisableWhenControlled(RangeMin=0)] public float SizeY = 0.1f; public bool FlipLayoutDimensions = false; private Plane vWorldPlane; private float vPrevSizeX; private float vPrevSizeY; private bool vPrevFlip; //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public override Vector3 GetCenterWorldPosition() { return gameObject.transform.position; } /*--------------------------------------------------------------------------------------------*/ public override Vector3 GetNearestWorldPosition(Vector3 pFromWorldPosition) { return RendererUtil.GetNearestWorldPositionOnRectangle( pFromWorldPosition, gameObject.transform, SizeX, SizeY); } /*--------------------------------------------------------------------------------------------*/ public override Vector3 GetNearestWorldPosition(Ray pFromWorldRay, out RaycastResult pRaycast) { pRaycast = new RaycastResult(); Vector3? nearWorldPos = RendererUtil.GetNearestWorldPositionOnPlane(pFromWorldRay, vWorldPlane); if ( nearWorldPos == null ) { return pFromWorldRay.origin; } pRaycast.IsHit = true; pRaycast.WorldPosition = nearWorldPos.Value; pRaycast.WorldRotation = transform.rotation; pRaycast.WorldPlane = vWorldPlane; return GetNearestWorldPosition(pRaycast.WorldPosition); } /*--------------------------------------------------------------------------------------------*/ public override float GetSliderValueViaNearestWorldPosition(Vector3 pNearestWorldPosition, Transform pSliderContainerTx, HoverShape pHandleButtonShape) { HoverShapeRect buttonShapeRect = (pHandleButtonShape as HoverShapeRect); if ( buttonShapeRect == null ) { Debug.LogError("Expected slider handle to have a '"+typeof(HoverShapeRect).Name+ "' component attached to it.", this); return 0; } Vector3 nearLocalPos = pSliderContainerTx.InverseTransformPoint(pNearestWorldPosition); float halfTrackSizeY = (SizeY-buttonShapeRect.SizeY)/2; return Mathf.InverseLerp(-halfTrackSizeY, halfTrackSizeY, nearLocalPos.y); } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public void SetRectLayout(float pSizeX, float pSizeY, ISettingsController pController) { Controllers.Set(SizeXName, pController); Controllers.Set(SizeYName, pController); SizeX = (FlipLayoutDimensions ? pSizeY : pSizeX); SizeY = (FlipLayoutDimensions ? pSizeX : pSizeY); } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public override void TreeUpdate() { base.TreeUpdate(); vWorldPlane = RendererUtil.GetWorldPlane(gameObject.transform); DidSettingsChange = ( DidSettingsChange || SizeX != vPrevSizeX || SizeY != vPrevSizeY || FlipLayoutDimensions != vPrevFlip ); UpdateShapeRectChildren(); vPrevSizeX = SizeX; vPrevSizeY = SizeY; vPrevFlip = FlipLayoutDimensions; } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ private void UpdateShapeRectChildren() { if ( !ControlChildShapes ) { return; } TreeUpdater tree = GetComponent<TreeUpdater>(); for ( int i = 0 ; i < tree.TreeChildrenThisFrame.Count ; i++ ) { TreeUpdater child = tree.TreeChildrenThisFrame[i]; HoverShapeRect childRect = child.GetComponent<HoverShapeRect>(); if ( childRect == null ) { continue; } childRect.Controllers.Set(SizeXName, this); childRect.Controllers.Set(SizeYName, this); childRect.SizeX = SizeX; childRect.SizeY = SizeY; } } } } <file_sep>/Assets/Hover/Core/Scripts/Renderers/HoverIndicator.cs using System; using Hover.Core.Utils; using UnityEngine; namespace Hover.Core.Renderers { /*================================================================================================*/ [ExecuteInEditMode] [RequireComponent(typeof(TreeUpdater))] public class HoverIndicator : MonoBehaviour, ITreeUpdateable, ISettingsController { public const string HighlightProgressName = "HighlightProgress"; public const string SelectionProgressName = "SelectionProgress"; public ISettingsControllerMap Controllers { get; private set; } public bool DidSettingsChange { get; protected set; } public DateTime LatestSelectionTime { get; set; } [DisableWhenControlled(RangeMin=0, RangeMax=1, DisplaySpecials=true)] public float HighlightProgress = 0.7f; [DisableWhenControlled(RangeMin=0, RangeMax=1)] public float SelectionProgress = 0.2f; private float vPrevHigh; private float vPrevSel; //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ protected HoverIndicator() { Controllers = new SettingsControllerMap(); } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public void Start() { //do nothing... } /*--------------------------------------------------------------------------------------------*/ public void TreeUpdate() { SelectionProgress = Mathf.Min(SelectionProgress, HighlightProgress); DidSettingsChange = ( HighlightProgress != vPrevHigh || SelectionProgress != vPrevSel ); UpdateIndicatorChildren(); vPrevHigh = HighlightProgress; vPrevSel = SelectionProgress; Controllers.TryExpireControllers(); } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ private void UpdateIndicatorChildren() { TreeUpdater tree = GetComponent<TreeUpdater>(); for ( int i = 0 ; i < tree.TreeChildrenThisFrame.Count ; i++ ) { TreeUpdater child = tree.TreeChildrenThisFrame[i]; HoverIndicator childInd = child.GetComponent<HoverIndicator>(); if ( childInd == null ) { continue; } childInd.Controllers.Set(HighlightProgressName, this); childInd.Controllers.Set(SelectionProgressName, this); childInd.HighlightProgress = HighlightProgress; childInd.SelectionProgress = SelectionProgress; childInd.LatestSelectionTime = LatestSelectionTime; } } } } <file_sep>/Assets/Hover/Core/Scripts/Renderers/CanvasElements/HoverIcon.cs using Hover.Core.Utils; using UnityEngine; using UnityEngine.UI; namespace Hover.Core.Renderers.CanvasElements { /*================================================================================================*/ [ExecuteInEditMode] [RequireComponent(typeof(TreeUpdater))] [RequireComponent(typeof(RawImage))] public class HoverIcon : MonoBehaviour, ITreeUpdateable { public const string IconTypeName = "IconType"; public const string CanvasScaleName = "CanvasScale"; public const string SizeXName = "SizeX"; public const string SizeYName = "SizeY"; public enum IconOffset { None, CheckOuter, CheckInner, RadioOuter, RadioInner, NavigateIn, NavigateOut, Slider, Sticky } public ISettingsControllerMap Controllers { get; private set; } [DisableWhenControlled(DisplaySpecials=true)] public IconOffset IconType = IconOffset.CheckOuter; [DisableWhenControlled(RangeMin=0.0001f, RangeMax=1)] public float CanvasScale = 0.0002f; [DisableWhenControlled(RangeMin=0)] public float SizeX = 0.1f; [DisableWhenControlled(RangeMin=0)] public float SizeY = 0.1f; [DisableWhenControlled(RangeMin=0, RangeMax=0.01f)] public float UvInset = 0.002f; [HideInInspector] [SerializeField] private bool _IsBuilt; //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public HoverIcon() { Controllers = new SettingsControllerMap(); } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public RawImage ImageComponent { get { return GetComponent<RawImage>(); } } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public void Awake() { if ( !_IsBuilt ) { BuildIcon(); _IsBuilt = true; } } /*--------------------------------------------------------------------------------------------*/ public virtual void Start() { //do nothing... } /*--------------------------------------------------------------------------------------------*/ public void TreeUpdate() { RawImage icon = ImageComponent; RectTransform rectTx = icon.rectTransform; const float w = 1f/9; const float h = 1; icon.uvRect = new Rect((int)IconType*w+UvInset, UvInset, w-UvInset*2, h-UvInset*2); rectTx.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, SizeX/CanvasScale); rectTx.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, SizeY/CanvasScale); Controllers.TryExpireControllers(); } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ private void BuildIcon() { RawImage icon = ImageComponent; icon.material = Resources.Load<Material>("Materials/HoverStandardIconsMaterial"); icon.color = Color.white; icon.raycastTarget = false; } } } <file_sep>/Assets/LeapMotion/Modules/GraphicRenderer/Scripts/LeapGraphicRenderer.cs /****************************************************************************** * Copyright (C) Leap Motion, Inc. 2011-2018. * * Leap Motion proprietary and confidential. * * * * Use subject to the terms of the Leap Motion SDK Agreement available at * * https://developer.leapmotion.com/sdk_agreement, or another agreement * * between Leap Motion and you, your company or other organization. * ******************************************************************************/ using System; using System.Collections.Generic; using UnityEngine; using Leap.Unity.Space; using Leap.Unity.Query; using Leap.Unity.Attributes; namespace Leap.Unity.GraphicalRenderer { [ExecuteInEditMode] public partial class LeapGraphicRenderer : MonoBehaviour, ISerializationCallbackReceiver { public const string FEATURE_PREFIX = "GRAPHIC_RENDERER_"; public const string PROPERTY_PREFIX = "_GraphicRenderer"; public const string FEATURE_MOVEMENT_TRANSLATION = FEATURE_PREFIX + "MOVEMENT_TRANSLATION"; public const string FEATURE_MOVEMENT_FULL = FEATURE_PREFIX + "MOVEMENT_FULL"; #region INSPECTOR FIELDS [SerializeField] private LeapSpace _space; private bool _lastSpaceWasNull = true; [SerializeField] private List<LeapGraphicGroup> _groups = new List<LeapGraphicGroup>(); #endregion #region PUBLIC RUNTIME API /// <summary> /// Returns the leap space that is currently attached to this graphic renderer. /// </summary> public LeapSpace space { get { return _space; } } /// <summary> /// Returns a list of all graphic groups contained withinin this renderer. This getter /// returns a regular List object for simplicity and speed, but it is still not allowed /// to mutate this list in any way. /// </summary> public List<LeapGraphicGroup> groups { get { return _groups; } } /// <summary> /// Searches the group list for a group with the given name. If there is no /// group with the given name, this method will return null. /// </summary> public LeapGraphicGroup FindGroup(string name) { return _groups.Query().FirstOrDefault(g => g.name == name); } /// <summary> /// Tries to add the given graphic to any group attached to this graphic. First, it /// will try to be attached to a group that has its preferred renderer type, and if /// there are multiple such groups it will choose the group with the smallest graphic /// count. /// /// If no group has the preferred renderer type, it will try to attach to a group /// that supports this type of graphic, again choosing the group with the smallest /// graphic count. /// /// If no such group is found, the attach will fail and this method will return false. /// </summary> public bool TryAddGraphic(LeapGraphic graphic) { LeapGraphicGroup targetGroup = null; //First just try to attach to a group that is its favorite foreach (var group in groups) { if (group.name == graphic.favoriteGroupName) { if (group.TryAddGraphic(graphic)) { return true; } } } //Then try to attatch to a group that is of the preferred type //Choose the preferred group with the least graphics Type preferredType = graphic.preferredRendererType; if (preferredType != null) { foreach (var group in groups) { Type rendererType = group.renderingMethod.GetType(); if (preferredType == rendererType || rendererType.IsSubclassOf(preferredType)) { if (targetGroup == null || group.toBeAttachedCount < targetGroup.toBeAttachedCount) { targetGroup = group; } } } } if (targetGroup != null && targetGroup.TryAddGraphic(graphic)) { return true; } //If we failed, just try to attach to any group that will take us foreach (var group in groups) { if (group.renderingMethod.IsValidGraphic(graphic)) { if (targetGroup == null || group.toBeAttachedCount < targetGroup.toBeAttachedCount) { targetGroup = group; } } } if (targetGroup != null && targetGroup.TryAddGraphic(graphic)) { return true; } //Unable to find any group that would accept the graphic :( return false; } #endregion #region UNITY CALLBACKS private void OnValidate() { #if UNITY_EDITOR if (!InternalUtility.IsPrefab(this)) { if (!Application.isPlaying) { editor.ScheduleRebuild(); } editor.OnValidate(); } #endif } private void OnDestroy() { #if UNITY_EDITOR editor.OnDestroy(); #endif } private void OnEnable() { #if UNITY_EDITOR Vector2[] uv = null; foreach (var group in _groups) { foreach (var feature in group.features) { LeapSpriteFeature spriteFeature = feature as LeapSpriteFeature; if (spriteFeature != null) { foreach (var data in spriteFeature.featureData) { uv = data.sprite.uv; } } } } UnityEditor.Undo.undoRedoPerformed -= onUndoRedoPerformed; UnityEditor.Undo.undoRedoPerformed += onUndoRedoPerformed; #endif if (Application.isPlaying) { if (_space != null) { _space.RebuildHierarchy(); _space.RecalculateTransformers(); _lastSpaceWasNull = false; } foreach (var group in _groups) { group.OnEnable(); } } } private void OnDisable() { if (Application.isPlaying) { foreach (var group in _groups) { group.OnDisable(); } } #if UNITY_EDITOR UnityEditor.Undo.undoRedoPerformed += onUndoRedoPerformed; #endif } private void LateUpdate() { #if UNITY_EDITOR //No updates for prefabs! if (InternalUtility.IsPrefab(this)) { return; } if (!Application.isPlaying) { editor.DoLateUpdateEditor(); } else #endif { doLateUpdateRuntime(); } } #endregion #region PRIVATE IMPLEMENTATION private LeapGraphicRenderer() { #if UNITY_EDITOR editor = new EditorApi(this); #endif } private void doLateUpdateRuntime() { // Validate the attached space to support it changing at runtime. validateSpaceComponent(); if (_space != null) { //TODO, optimize this! Don't do it every frame for the whole thing! using (new ProfilerSample("Refresh space data")) { _space.RecalculateTransformers(); } } foreach (var group in _groups) { group.UpdateRenderer(); } } public void validateSpaceComponent() { var origSpace = _space; var spaces = Pool<List<LeapSpace>>.Spawn(); spaces.Clear(); try { GetComponents<LeapSpace>(spaces); _space = spaces.Query().FirstOrDefault(s => s.enabled); } finally { spaces.Clear(); Pool<List<LeapSpace>>.Recycle(spaces); } // Support Undo/Redo with runtime space changes in-editor bool didUndoRedo = false; #if UNITY_EDITOR if (_didUndoRedoThisFrame) { didUndoRedo = true; _didUndoRedoThisFrame = false; } #endif if (Application.isPlaying && (origSpace != _space || (_space == null && !_lastSpaceWasNull)) || didUndoRedo ) { onRuntimeSpaceChanged(); } _lastSpaceWasNull = _space == null; } #if UNITY_EDITOR private bool _didUndoRedoThisFrame = false; private void onUndoRedoPerformed() { _didUndoRedoThisFrame = true; } #endif private void onRuntimeSpaceChanged() { // The space was modified, so refresh a bunch of things.. if (_space != null) { _space.RebuildHierarchy(); _space.RecalculateTransformers(); } // Need to update material keywords appropriately. // This involves re-preparing materials, which happens OnEnable, // so we'll "power-cycle" the whole renderer for simplicity's sake. OnDisable(); OnEnable(); foreach (var group in _groups) { group.RefreshGraphicAnchors(); } } public void OnBeforeSerialize() { } public void OnAfterDeserialize() { foreach (var group in _groups) { (group as ILeapInternalGraphicGroup).renderer = this; } } #endregion } } <file_sep>/Assets/LeapMotion/Modules/InteractionEngine/Scripts/Internal/Interface/IInternalInteractionManager.cs /****************************************************************************** * Copyright (C) Leap Motion, Inc. 2011-2018. * * Leap Motion proprietary and confidential. * * * * Use subject to the terms of the Leap Motion SDK Agreement available at * * https://developer.leapmotion.com/sdk_agreement, or another agreement * * between Leap Motion and you, your company or other organization. * ******************************************************************************/ using Leap.Unity.Interaction; namespace Leap.Unity.Interaction { public interface IInternalInteractionManager { // Layers void NotifyIntObjAddedInteractionLayer(IInteractionBehaviour intObj, int layer, bool refreshImmediately = true); void NotifyIntObjRemovedInteractionLayer(IInteractionBehaviour intObj, int layer, bool refreshImmediately = true); void NotifyIntObjAddedNoContactLayer(IInteractionBehaviour intObj, int layer, bool refreshImmediately = true); void NotifyIntObjRemovedNoContactLayer(IInteractionBehaviour intObj, int layer, bool refreshImmediately = true); void RefreshLayersNow(); } public static class IInternalInteractionManagerExtensions { public static void NotifyIntObjHasNewInteractionLayer(this IInternalInteractionManager manager, IInteractionBehaviour intObj, int oldInteractionLayer, int newInteractionLayer) { manager.NotifyIntObjRemovedInteractionLayer(intObj, oldInteractionLayer, false); manager.NotifyIntObjAddedInteractionLayer(intObj, newInteractionLayer, false); manager.RefreshLayersNow(); } public static void NotifyIntObjHasNewNoContactLayer(this IInternalInteractionManager manager, IInteractionBehaviour intObj, int oldNoContactLayer, int newNoContactLayer) { manager.NotifyIntObjRemovedNoContactLayer(intObj, oldNoContactLayer, false); manager.NotifyIntObjAddedNoContactLayer(intObj, newNoContactLayer, false); manager.RefreshLayersNow(); } } } <file_sep>/Assets/Hover/Core/Scripts/Renderers/Shapes/Rect/HoverMeshRect.cs using System; using Hover.Core.Utils; using UnityEngine; namespace Hover.Core.Renderers.Shapes.Rect { /*================================================================================================*/ [RequireComponent(typeof(HoverIndicator))] [RequireComponent(typeof(HoverShapeRect))] public class HoverMeshRect : HoverMesh { public enum SizeType { Min, Selection, Highlight, Max } public const string UvTopName = "UvTop"; public const string UvBottomName = "UvBottom"; public const string UvLeftName = "UvLeft"; public const string UvRightName = "UvRight"; [DisableWhenControlled] public SizeType OuterSizeType = SizeType.Max; [DisableWhenControlled] public bool AutoUvViaSizeType = false; [DisableWhenControlled] public float UvTop = 0; [DisableWhenControlled] public float UvBottom = 1; [DisableWhenControlled] public float UvLeft = 0; [DisableWhenControlled] public float UvRight = 1; private SizeType vPrevOuterType; private bool vPrevAutoUv; private float vPrevUvTop; private float vPrevUvBottom; private float vPrevUvLeft; private float vPrevUvRight; //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public override bool IsMeshVisible { get { HoverShapeRect shape = GetComponent<HoverShapeRect>(); float outerProg = GetDimensionProgress(OuterSizeType); return (shape.SizeX != 0 && shape.SizeY != 0 && outerProg != 0); } } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ protected override bool ShouldUpdateMesh() { var ind = GetComponent<HoverIndicator>(); var shape = GetComponent<HoverShapeRect>(); bool shouldUpdate = ( base.ShouldUpdateMesh() || ind.DidSettingsChange || shape.DidSettingsChange || OuterSizeType != vPrevOuterType || AutoUvViaSizeType != vPrevAutoUv || UvTop != vPrevUvTop || UvBottom != vPrevUvBottom || UvLeft != vPrevUvLeft || UvRight != vPrevUvRight ); vPrevOuterType = OuterSizeType; vPrevAutoUv = AutoUvViaSizeType; vPrevUvTop = UvTop; vPrevUvBottom = UvBottom; vPrevUvLeft = UvLeft; vPrevUvRight = UvRight; return shouldUpdate; } /*--------------------------------------------------------------------------------------------*/ protected float GetDimensionProgress(SizeType pType) { HoverIndicator ind = GetComponent<HoverIndicator>(); switch ( pType ) { case SizeType.Min: return 0; case SizeType.Selection: return ind.SelectionProgress; case SizeType.Highlight: return ind.HighlightProgress; case SizeType.Max: return 1; } throw new Exception("Unexpected type: "+pType); } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ protected override void UpdateMesh() { HoverShapeRect shape = GetComponent<HoverShapeRect>(); float outerProg = GetDimensionProgress(OuterSizeType); float outerW; float outerH; if ( shape.SizeX >= shape.SizeY ) { outerH = shape.SizeY*outerProg; outerW = shape.SizeX-(shape.SizeY-outerH); } else { outerW = shape.SizeX*outerProg; outerH = shape.SizeY-(shape.SizeX-outerW); } MeshUtil.BuildQuadMesh(vMeshBuild, outerW, outerH); UpdateAutoUv(shape, outerW, outerH); UpdateMeshUvAndColors(); vMeshBuild.Commit(); vMeshBuild.CommitColors(); } /*--------------------------------------------------------------------------------------------*/ protected void UpdateAutoUv(HoverShapeRect pShapeRect, float pOuterW, float pOuterH) { if ( !AutoUvViaSizeType ) { return; } Controllers.Set(UvTopName, this); Controllers.Set(UvBottomName, this); Controllers.Set(UvLeftName, this); Controllers.Set(UvRightName, this); UvTop = Mathf.Lerp(0.5f, 0, pOuterH/pShapeRect.SizeY); UvBottom = 1-UvTop; UvLeft = Mathf.Lerp(0.5f, 0, pOuterW/pShapeRect.SizeX); UvRight = 1-UvLeft; } /*--------------------------------------------------------------------------------------------*/ protected void UpdateMeshUvAndColors() { for ( int i = 0 ; i < vMeshBuild.Uvs.Length ; i++ ) { Vector2 uv = vMeshBuild.Uvs[i]; uv.x = Mathf.LerpUnclamped(UvLeft, UvRight, uv.x); uv.y = Mathf.LerpUnclamped(UvTop, UvBottom, uv.y); vMeshBuild.Uvs[i] = uv; vMeshBuild.Colors[i] = Color.white; } } } } <file_sep>/Assets/Hover/Core/Scripts/Renderers/HoverRenderer.cs using Hover.Core.Renderers.CanvasElements; using Hover.Core.Renderers.Shapes; using Hover.Core.Utils; using UnityEngine; namespace Hover.Core.Renderers { /*================================================================================================*/ [ExecuteInEditMode] [RequireComponent(typeof(TreeUpdater))] [RequireComponent(typeof(HoverIndicator))] [RequireComponent(typeof(HoverShape))] public abstract class HoverRenderer : MonoBehaviour, ITreeUpdateable, ISettingsController, IGameObjectProvider { public const string IsEnabledName = "IsEnabled"; public ISettingsControllerMap Controllers { get; private set; } [DisableWhenControlled(DisplaySpecials=true)] public bool IsEnabled = true; //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ protected HoverRenderer() { Controllers = new SettingsControllerMap(); } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public HoverIndicator GetIndicator() { return gameObject.GetComponent<HoverIndicator>(); } /*--------------------------------------------------------------------------------------------*/ public HoverShape GetShape() { return gameObject.GetComponent<HoverShape>(); } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public abstract int GetChildFillCount(); /*--------------------------------------------------------------------------------------------*/ public abstract HoverFill GetChildFill(int pIndex); /*--------------------------------------------------------------------------------------------*/ public abstract int GetChildRendererCount(); /*--------------------------------------------------------------------------------------------*/ public abstract HoverRenderer GetChildRenderer(int pIndex); /*--------------------------------------------------------------------------------------------*/ public abstract HoverCanvas GetCanvas(); /*--------------------------------------------------------------------------------------------*/ public abstract HoverCanvasDataUpdater GetCanvasDataUpdater(); /*--------------------------------------------------------------------------------------------*/ public abstract Vector3 GetCenterWorldPosition(); /*--------------------------------------------------------------------------------------------*/ public abstract Vector3 GetNearestWorldPosition(Vector3 pFromWorldPosition); /*--------------------------------------------------------------------------------------------*/ public abstract Vector3 GetNearestWorldPosition(Ray pFromWorldRay, out RaycastResult pRaycast); //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public virtual void Start() { //do nothing... } /*--------------------------------------------------------------------------------------------*/ public virtual void TreeUpdate() { Controllers.TryExpireControllers(); } } } <file_sep>/Assets/LeapMotion/Modules/GraphicRenderer/Scripts/Editor/LeapGraphicPreferences.cs /****************************************************************************** * Copyright (C) Leap Motion, Inc. 2011-2018. * * Leap Motion proprietary and confidential. * * * * Use subject to the terms of the Leap Motion SDK Agreement available at * * https://developer.leapmotion.com/sdk_agreement, or another agreement * * between Leap Motion and you, your company or other organization. * ******************************************************************************/ using UnityEngine; using UnityEditor; using System; using System.IO; using System.Collections.Generic; using System.Text.RegularExpressions; namespace Leap.Unity.GraphicalRenderer { public class LeapGraphicPreferences : MonoBehaviour { public const int GRAPHIC_COUNT_SOFT_CEILING = 144; public const string LEAP_GRAPHIC_CGINC_PATH = "LeapMotion/Modules/GraphicRenderer/Resources/GraphicRenderer.cginc"; public const string LEAP_GRAPHIC_SHADER_FOLDER = "Assets/LeapMotion/Modules/GraphicRenderer/Shaders/"; private static Regex _graphicMaxRegex = new Regex(@"^#define\s+GRAPHIC_MAX\s+(\d+)\s*$"); public const string PROMPT_WHEN_GROUP_CHANGE_KEY = "LeapGraphicRenderer_ShouldPromptWhenGroupChange"; public const string PROMP_WHEN_ADD_CUSTOM_CHANNEL_LEY = "LeapGraphicRenderer_ShouldPrompWhenAddCustomChannel"; private static int _cachedGraphicMax = -1; //-1 signals dirty public static int graphicMax { get { if (_cachedGraphicMax == -1) { string errorMesage; string path; List<string> lines; int lineIndex; tryCalculateGraphicMax(out _cachedGraphicMax, out errorMesage, out path, out lines, out lineIndex); if (errorMesage != null) { _cachedGraphicMax = int.MaxValue; } } return _cachedGraphicMax; } } public static bool promptWhenGroupChange { get { return EditorPrefs.GetBool(PROMPT_WHEN_GROUP_CHANGE_KEY, true); } set { EditorPrefs.SetBool(PROMPT_WHEN_GROUP_CHANGE_KEY, value); } } public static bool promptWhenAddCustomChannel { get { return EditorPrefs.GetBool(PROMP_WHEN_ADD_CUSTOM_CHANNEL_LEY, true); } set { EditorPrefs.SetBool(PROMP_WHEN_ADD_CUSTOM_CHANNEL_LEY, value); } } [LeapPreferences("Graphic Renderer", 20)] private static void preferencesGUI() { drawGraphicMaxField(); GUIContent groupChangedContent = new GUIContent("Prompt When Group Changed", "Should the system prompt the user when they change the group of a graphic to a group with different features."); bool newPromptValue = EditorGUILayout.Toggle(groupChangedContent, promptWhenGroupChange); if (promptWhenGroupChange != newPromptValue) { promptWhenGroupChange = newPromptValue; } GUIContent addChannelContent = new GUIContent("Prompt For Custom Channel", "Should the system warn the user about writing custom shaders when they try to add a Custom Channel feature?"); bool newPromptWhenAddCustomChannelValue = EditorGUILayout.Toggle(addChannelContent, promptWhenAddCustomChannel); if (newPromptWhenAddCustomChannelValue != promptWhenAddCustomChannel) { promptWhenAddCustomChannel = newPromptWhenAddCustomChannelValue; } EditorGUILayout.Space(); GUILayout.Label("Surface-shader variant options", EditorStyles.boldLabel); EditorGUILayout.HelpBox("Using surface-shader variants can drastically increase import time! Only enable variants if you are using surface shaders with the graphic renderer.", MessageType.Info); using (new EditorGUILayout.HorizontalScope()) { if (GUILayout.Button("Enable all variants")) { setVariantsEnabledForSurfaceShaders(enable: true); } if (GUILayout.Button("Disable all variants")) { setVariantsEnabledForSurfaceShaders(enable: false); } } } private static void setVariantsEnabledForSurfaceShaders(bool enable) { foreach (var path in Directory.GetFiles(LEAP_GRAPHIC_SHADER_FOLDER, "*.shader", SearchOption.AllDirectories)) { var shader = AssetDatabase.LoadAssetAtPath<Shader>(path); if (shader == null) continue; if (VariantEnabler.IsSurfaceShader(shader)) { VariantEnabler.SetShaderVariantsEnabled(shader, enable); } } AssetDatabase.Refresh(); } private static void drawGraphicMaxField() { int graphicMax; string errorMessage; string path; List<string> lines; int lineIndex; _cachedGraphicMax = -1; if (!tryCalculateGraphicMax(out graphicMax, out errorMessage, out path, out lines, out lineIndex)) { EditorGUILayout.HelpBox(errorMessage + "\n\nRe-installing the Leap Gui package can help fix this problem.", MessageType.Warning); return; } int newGraphicMax = EditorGUILayout.DelayedIntField("Max Graphics Per-Group", graphicMax); newGraphicMax = Mathf.Min(newGraphicMax, 1023); //maximum array length for Unity shaders is 1023 if (newGraphicMax > GRAPHIC_COUNT_SOFT_CEILING && graphicMax <= GRAPHIC_COUNT_SOFT_CEILING) { if (!EditorUtility.DisplayDialog("Large Graphic Count", "Setting the graphic count larger than 144 can cause incorrect rendering " + "or shader compilation failure on certain systems, are you sure you want " + "to continue?", "Yes", "Cancel")) { return; } } if (newGraphicMax == graphicMax) { return; //Work here is done! Nothing to change! } lines[lineIndex] = lines[lineIndex].Replace(graphicMax.ToString(), newGraphicMax.ToString()); //Write the new data to the file File.WriteAllLines(path, lines.ToArray()); //Make sure to re-import all the shaders AssetDatabase.ImportAsset(LEAP_GRAPHIC_SHADER_FOLDER, ImportAssetOptions.ImportRecursive); } private static bool tryCalculateGraphicMax(out int elementMax, out string errorMessage, out string path, out List<string> lines, out int lineIndex) { elementMax = -1; errorMessage = null; lines = null; lineIndex = -1; path = Path.Combine(Application.dataPath, LEAP_GRAPHIC_CGINC_PATH); if (!File.Exists(path)) { errorMessage = "Could not locate the Leap cginclude file, was it renamed or deleted?"; return false; } lines = new List<string>(); StreamReader reader = null; try { reader = File.OpenText(path); while (true) { string line = reader.ReadLine(); if (line == null) { break; } lines.Add(line); } } catch (Exception e) { errorMessage = "Exception caught when trying to read file."; Debug.LogError(e); return false; } finally { if (reader != null) { reader.Dispose(); } } Match successMatch = null; for (int i = 0; i < lines.Count; i++) { string line = lines[i]; var match = _graphicMaxRegex.Match(line); if (match.Success) { successMatch = match; lineIndex = i; break; } } if (successMatch == null) { errorMessage = "Could not parse the file correctly, it might have been modified!"; return false; } if (!int.TryParse(successMatch.Groups[1].Value, out elementMax)) { errorMessage = "The maximum graphic value must always be an integer value!"; return false; } return true; } } } <file_sep>/Assets/Hover/Editor/EditorUtil.cs using System; using System.Reflection; using Hover.Core.Utils; using UnityEditor; using UnityEngine; using Object = UnityEngine.Object; namespace Hover.Editor { /*================================================================================================*/ public static class EditorUtil { //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public static GUIStyle GetVerticalSectionStyle() { var style = new GUIStyle(); style.padding = new RectOffset(16, 0, 0, 0); return style; } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public static ISettingsControllerMap GetControllerMap(SerializedObject pObject, string pName) { Object behaviour = pObject.targetObject; Type behaviourType = behaviour.GetType(); Type mapType = typeof(ISettingsControllerMap); PropertyInfo propInfo = behaviourType.GetProperty(pName, mapType); if ( propInfo == null ) { Debug.LogWarning( "The '"+typeof(DisableWhenControlledAttribute).Name+"' could not find "+ "a '"+pName+"' property of type '"+mapType.Name+ "' on the '"+behaviour+"' object.", behaviour); return null; } return (ISettingsControllerMap)propInfo.GetValue(behaviour, null); } /*--------------------------------------------------------------------------------------------*/ public static bool CallMethod(SerializedObject pObject, string pName) { Object behaviour = pObject.targetObject; Type behaviourType = behaviour.GetType(); MethodInfo methodInfo = behaviourType.GetMethod(pName); if ( methodInfo == null ) { Debug.LogWarning( "Could not find a method named '"+pName+"' on the '"+ behaviour+"' object.", behaviour); return false; } methodInfo.Invoke(behaviour, null); return true; } /*--------------------------------------------------------------------------------------------* / public static RangeAttribute GetFieldRangeAttribute(SerializedProperty pProp) { Object behaviour = pProp.serializedObject.targetObject; Type behaviourType = behaviour.GetType(); FieldInfo fieldInfo = behaviourType.GetField(pProp.name); object[] ranges = fieldInfo.GetCustomAttributes(typeof(RangeAttribute), false); return (ranges.Length == 0 ? null : (RangeAttribute)ranges[0]); }*/ } } <file_sep>/Assets/Hover/Core/Scripts/Utils/DisableWhenControlledAttribute.cs using System; using UnityEngine; namespace Hover.Core.Utils { /*================================================================================================*/ [AttributeUsage(AttributeTargets.Field)] public class DisableWhenControlledAttribute : PropertyAttribute { public const float NullRangeMin = float.MaxValue; public const float NullRangeMax = float.MinValue; public string ControllerMapName { get; private set; } public bool DisplaySpecials { get; set; } public float RangeMin { get; set; } public float RangeMax { get; set; } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public DisableWhenControlledAttribute(string pControllerMapName="Controllers") { ControllerMapName = pControllerMapName; RangeMin = NullRangeMin; RangeMax = NullRangeMax; } } } <file_sep>/Assets/Hover/Core/Scripts/Renderers/Cursors/HoverFillCursor.cs using System; using Hover.Core.Renderers.Shapes; using Hover.Core.Renderers.Utils; using Hover.Core.Utils; using UnityEngine; namespace Hover.Core.Renderers.Cursors { /*================================================================================================*/ [RequireComponent(typeof(HoverIndicator))] [RequireComponent(typeof(HoverShape))] public class HoverFillCursor : HoverFill { [DisableWhenControlled(DisplaySpecials=true)] public HoverMesh Background; [DisableWhenControlled] public HoverMesh Highlight; [DisableWhenControlled] public HoverMesh Selection; //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public override int GetChildMeshCount() { return 3; } /*--------------------------------------------------------------------------------------------*/ public override HoverMesh GetChildMesh(int pIndex) { switch ( pIndex ) { case 0: return Background; case 1: return Highlight; case 2: return Selection; } throw new ArgumentOutOfRangeException(); } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public override void TreeUpdate() { base.TreeUpdate(); UpdateMeshes(); } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ private void UpdateMeshes() { if ( Background != null ) { UpdateMesh(Background); } if ( Highlight != null ) { UpdateMesh(Highlight); } if ( Selection != null ) { UpdateMesh(Selection); } } /*--------------------------------------------------------------------------------------------*/ private void UpdateMesh(HoverMesh pMesh) { pMesh.Controllers.Set(SettingsControllerMap.GameObjectActiveSelf, this); RendererUtil.SetActiveWithUpdate(pMesh, pMesh.IsMeshVisible); } } } <file_sep>/Assets/Hover/Core/Scripts/Renderers/Items/Sliders/HoverRendererSliderSegments.cs using System.Collections.Generic; using Hover.Core.Renderers.Shapes; using Hover.Core.Renderers.Utils; using Hover.Core.Utils; using UnityEngine; namespace Hover.Core.Renderers.Items.Sliders { /*================================================================================================*/ [ExecuteInEditMode] [RequireComponent(typeof(TreeUpdater))] [RequireComponent(typeof(HoverRendererSlider))] [RequireComponent(typeof(HoverShape))] public abstract class HoverRendererSliderSegments : MonoBehaviour, ITreeUpdateable { public bool IsJumpVisible { get; private set; } public List<SliderUtil.SegmentInfo> SegmentInfoList; public List<SliderUtil.SegmentInfo> TickInfoList; protected SliderUtil.SliderInfo vInfo; //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public void Start() { //do nothing... } /*--------------------------------------------------------------------------------------------*/ public void TreeUpdate() { UpdateInfo(); UpdateInfoWithShape(); BuildSegments(); } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ protected virtual void UpdateInfo() { HoverRendererSlider rendSlider = gameObject.GetComponent<HoverRendererSlider>(); vInfo.FillType = rendSlider.FillStartingPoint; vInfo.HandleValue = rendSlider.HandleValue; vInfo.JumpValue = rendSlider.JumpValue; vInfo.ZeroValue = rendSlider.ZeroValue; vInfo.TickCount = rendSlider.TickCount; /*Debug.Log("INFO: "+info.TrackStartPosition+" / "+info.TrackEndPosition); foreach ( SliderUtil.Segment seg in vSegmentInfoList ) { Debug.Log(" - "+seg.Type+": "+seg.StartPosition+" / "+seg.EndPosition); }*/ } /*--------------------------------------------------------------------------------------------*/ protected abstract void UpdateInfoWithShape(); /*--------------------------------------------------------------------------------------------*/ protected virtual void BuildSegments() { SliderUtil.CalculateSegments(vInfo, SegmentInfoList); SliderUtil.CalculateTicks(vInfo, SegmentInfoList, TickInfoList); IsJumpVisible = false; for ( int i = 0 ; i < SegmentInfoList.Count ; i++ ) { SliderUtil.SegmentInfo segInfo = SegmentInfoList[i]; if ( segInfo.Type == SliderUtil.SegmentType.Jump ) { IsJumpVisible = true; break; } } } } } <file_sep>/Assets/Hover/Core/Scripts/Renderers/Shapes/Arc/HoverRendererSliderSegmentsArc.cs using Hover.Core.Renderers.Items.Sliders; using UnityEngine; namespace Hover.Core.Renderers.Shapes.Arc { /*================================================================================================*/ [RequireComponent(typeof(HoverShapeArc))] public class HoverRendererSliderSegmentsArc : HoverRendererSliderSegments { public float TickArcDegrees = 0.34f; //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ protected override void UpdateInfoWithShape() { HoverRendererSlider rendSlider = gameObject.GetComponent<HoverRendererSlider>(); HoverShapeArc shapeArc = gameObject.GetComponent<HoverShapeArc>(); HoverShapeArc handleShapeArc = (HoverShapeArc)rendSlider.HandleButton.GetShape(); HoverShapeArc jumpShapeArc = (HoverShapeArc)rendSlider.JumpButton.GetShape(); TickArcDegrees = Mathf.Max(0, TickArcDegrees); vInfo.TrackStartPosition = -shapeArc.ArcDegrees/2; vInfo.TrackEndPosition = shapeArc.ArcDegrees/2; vInfo.HandleSize = handleShapeArc.ArcDegrees; vInfo.JumpSize = (rendSlider.AllowJump ? jumpShapeArc.ArcDegrees : 0); vInfo.TickSize = TickArcDegrees; } } } <file_sep>/Assets/Hover/Core/Scripts/Utils/UnityUtil.cs using UnityEngine; namespace Hover.Core.Utils { /*================================================================================================*/ public static class UnityUtil { //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public static GameObject BuildPrefab(GameObject pPrefab) { #if UNITY_EDITOR return (GameObject)UnityEditor.PrefabUtility.InstantiatePrefab(pPrefab); #else return UnityEngine.Object.Instantiate(pPrefab); #endif } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public static GameObject FindOrAddHoverKitPrefab() { GameObject hoverKitGo = GameObject.Find("HoverKit"); if ( hoverKitGo != null ) { return hoverKitGo; } GameObject managerPrefab = Resources.Load<GameObject>("Prefabs/HoverKit"); BuildPrefab(managerPrefab); Debug.Log("Added the 'HoverKit' prefab to the scene.", managerPrefab); return managerPrefab; } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public static T FindNearbyComponent<T>(GameObject pGameObj) where T : Component { T sibling = pGameObj.GetComponent<T>(); if ( sibling != null ) { return sibling; } T child = pGameObj.GetComponentInChildren<T>(); if ( child != null ) { return child; } T parent = pGameObj.GetComponentInParent<T>(); if ( parent != null ) { return parent; } return Object.FindObjectOfType<T>(); } /*--------------------------------------------------------------------------------------------* / public static T FindComponentAll<T>(Func<T, bool> pMatchFunc) where T : Object { T[] comps = Resources.FindObjectsOfTypeAll<T>(); foreach ( T comp in comps ) { if ( pMatchFunc(comp) ) { return comp; } } Debug.LogError("Could not find a matching "+typeof(T).Name+"."); return default(T); } /*--------------------------------------------------------------------------------------------*/ public static T FindComponentAll<T>(string pName) where T : Object { T[] comps = Resources.FindObjectsOfTypeAll<T>(); foreach ( T comp in comps ) { if ( comp.name == pName ) { return comp; } } Debug.LogError("Could not find a "+typeof(T).Name+" with name '"+pName+"'."); return default(T); } } } <file_sep>/Assets/Hover/InputModules/LeapMotion/Scripts/HoverInputLeapMotion.cs #if HOVER_INPUT_LEAPMOTION using System; using System.Collections.Generic; using Hover.Core.Cursors; using Leap; using Leap.Unity; using UnityEngine; namespace Hover.InputModules.LeapMotion { /*================================================================================================*/ [ExecuteInEditMode] public class HoverInputLeapMotion : MonoBehaviour { private static readonly Quaternion RotationFix = Quaternion.Euler(90, 90, -90); public HoverCursorDataProvider CursorDataProvider; public LeapServiceProvider LeapServiceProvider; public bool UseStabilizedPositions = false; [Range(0, 0.04f)] public float ExtendFingertipDistance = 0; [Space(12)] public FollowCursor Look = new FollowCursor(CursorType.Look); //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public void Awake() { CursorUtil.FindCursorReference(this, ref CursorDataProvider, false); if ( LeapServiceProvider == null ) { LeapServiceProvider = FindObjectOfType<LeapServiceProvider>(); } if ( Look.FollowTransform == null ) { GameObject lookGo = GameObject.Find("CenterEyeAnchor"); Look.FollowTransform = (lookGo == null ? null : lookGo.transform); } } /*--------------------------------------------------------------------------------------------*/ public void Update() { if ( !CursorUtil.FindCursorReference(this, ref CursorDataProvider, true) ) { return; } if ( !Application.isPlaying ) { return; } CursorDataProvider.MarkAllCursorsUnused(); UpdateCursorsWithHands(LeapServiceProvider.CurrentFrame.Hands); Look.UpdateData(CursorDataProvider); CursorDataProvider.ActivateAllCursorsBasedOnUsage(); } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ private void UpdateCursorsWithHands(List<Hand> pLeapHands) { for ( int i = 0 ; i < pLeapHands.Count ; i++ ) { UpdateCursorsWithHand(pLeapHands[i]); } } /*--------------------------------------------------------------------------------------------*/ private void UpdateCursorsWithHand(Hand pLeapHand) { UpdateCursorsWithPalm(pLeapHand); for ( int i = 0 ; i < pLeapHand.Fingers.Count ; i++ ) { UpdateCursorsWithFinger(pLeapHand, pLeapHand.Fingers[i]); } } /*--------------------------------------------------------------------------------------------*/ private void UpdateCursorsWithPalm(Hand pLeapHand) { CursorType cursorType = (pLeapHand.IsLeft ? CursorType.LeftPalm : CursorType.RightPalm); if ( !CursorDataProvider.HasCursorData(cursorType) ) { return; } Vector palmPos = (UseStabilizedPositions ? pLeapHand.StabilizedPalmPosition : pLeapHand.PalmPosition); ICursorDataForInput data = CursorDataProvider.GetCursorDataForInput(cursorType); data.SetWorldPosition(palmPos.ToVector3()); data.SetWorldRotation(pLeapHand.Basis.CalculateRotation()*RotationFix); data.SetSize(pLeapHand.PalmWidth); data.SetTriggerStrength(pLeapHand.GrabStrength); data.SetUsedByInput(true); } /*--------------------------------------------------------------------------------------------*/ private void UpdateCursorsWithFinger(Hand pLeapHand, Finger pLeapFinger) { CursorType cursorType = GetFingerCursorType(pLeapHand.IsLeft, pLeapFinger.Type); if ( !CursorDataProvider.HasCursorData(cursorType) ) { return; } Bone distalBone = pLeapFinger.Bone(Bone.BoneType.TYPE_DISTAL); Vector3 tipWorldPos = pLeapFinger.TipPosition.ToVector3(); Vector3 boneWorldPos = distalBone.Center.ToVector3(); Vector3 extendedWorldPos = tipWorldPos; if ( ExtendFingertipDistance != 0 ) { extendedWorldPos += (tipWorldPos-boneWorldPos).normalized*ExtendFingertipDistance; } ICursorDataForInput data = CursorDataProvider.GetCursorDataForInput(cursorType); data.SetWorldPosition(extendedWorldPos); data.SetWorldRotation(distalBone.Basis.CalculateRotation()*RotationFix); data.SetSize(pLeapFinger.Width); data.SetUsedByInput(true); } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ private CursorType GetFingerCursorType(bool pIsLeft, Finger.FingerType pLeapFingerType) { switch ( pLeapFingerType ) { case Finger.FingerType.TYPE_THUMB: return (pIsLeft ? CursorType.LeftThumb : CursorType.RightThumb); case Finger.FingerType.TYPE_INDEX: return (pIsLeft ? CursorType.LeftIndex : CursorType.RightIndex); case Finger.FingerType.TYPE_MIDDLE: return (pIsLeft ? CursorType.LeftMiddle : CursorType.RightMiddle); case Finger.FingerType.TYPE_RING: return (pIsLeft ? CursorType.LeftRing : CursorType.RightRing); case Finger.FingerType.TYPE_PINKY: return (pIsLeft ? CursorType.LeftPinky : CursorType.RightPinky); } throw new Exception("Unhandled cursor combination: "+pIsLeft+" / "+pLeapFingerType); } } } #else using Hover.Core.Utils; namespace Hover.InputModules.LeapMotion { /*================================================================================================*/ public class HoverInputLeapMotion : HoverInputMissing { public override string ModuleName { get { return "LeapMotion"; } } public override string RequiredSymbol { get { return "HOVER_INPUT_LEAPMOTION"; } } } } #endif //HOVER_INPUT_LEAPMOTION <file_sep>/Assets/Hover/Core/Scripts/Renderers/Shapes/Rect/HoverRendererSliderSegmentsRect.cs using Hover.Core.Renderers.Items.Sliders; using UnityEngine; namespace Hover.Core.Renderers.Shapes.Rect { /*================================================================================================*/ [RequireComponent(typeof(HoverShapeRect))] public class HoverRendererSliderSegmentsRect : HoverRendererSliderSegments { public float TickSizeY = 0.001f; //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ protected override void UpdateInfoWithShape() { HoverRendererSlider rendSlider = gameObject.GetComponent<HoverRendererSlider>(); HoverShapeRect shapeRect = gameObject.GetComponent<HoverShapeRect>(); HoverShapeRect handleShapeRect = (HoverShapeRect)rendSlider.HandleButton.GetShape(); HoverShapeRect jumpShapeRect = (HoverShapeRect)rendSlider.JumpButton.GetShape(); TickSizeY = Mathf.Max(0, TickSizeY); vInfo.TrackStartPosition = -shapeRect.SizeY/2; vInfo.TrackEndPosition = shapeRect.SizeY/2; vInfo.HandleSize = handleShapeRect.SizeY; vInfo.JumpSize = (rendSlider.AllowJump ? jumpShapeRect.SizeY : 0); vInfo.TickSize = TickSizeY; } } } <file_sep>/Assets/LeapMotion/Modules/GraphicRenderer/Scripts/SpaceProperties.cs /****************************************************************************** * Copyright (C) Leap Motion, Inc. 2011-2018. * * Leap Motion proprietary and confidential. * * * * Use subject to the terms of the Leap Motion SDK Agreement available at * * https://developer.leapmotion.com/sdk_agreement, or another agreement * * between Leap Motion and you, your company or other organization. * ******************************************************************************/ namespace Leap.Unity.GraphicalRenderer { public static class SpaceProperties { public const string RADIAL_SPACE_RADIUS = LeapGraphicRenderer.PROPERTY_PREFIX + "RadialSpace_Radius"; public const string CYLINDRICAL_FEATURE = LeapGraphicRenderer.FEATURE_PREFIX + "CYLINDRICAL"; public const string SPHERICAL_FEATURE = LeapGraphicRenderer.FEATURE_PREFIX + "SPHERICAL"; } } <file_sep>/Assets/LeapMotion/Modules/GraphicRenderer/Scripts/Editor/LeapGraphicGroupEditor.cs /****************************************************************************** * Copyright (C) Leap Motion, Inc. 2011-2018. * * Leap Motion proprietary and confidential. * * * * Use subject to the terms of the Leap Motion SDK Agreement available at * * https://developer.leapmotion.com/sdk_agreement, or another agreement * * between Leap Motion and you, your company or other organization. * ******************************************************************************/ using System.IO; using System.Reflection; using System.Collections.Generic; using UnityEngine; using UnityEngine.Assertions; using UnityEditor; using UnityEditorInternal; using Leap.Unity; using Leap.Unity.Query; namespace Leap.Unity.GraphicalRenderer { public class LeapGuiGroupEditor { public const int BUTTON_WIDTH = 30; public const int REFRESH_WIDTH = 78; private LeapGraphicRenderer _renderer; private SerializedObject _serializedObject; private SerializedProperty _supportInfo; private SerializedProperty _groupProperty; private SerializedProperty _multiFeatureList; private SerializedProperty _multiRenderingMethod; private SerializedProperty _featureTable; private ReorderableList _featureList; private MonoScript _renderingMethodMonoScript; private List<SerializedProperty> _cachedPropertyList; private List<float> _cachedPropertyHeights; private SerializedProperty _renderingMethod; private GenericMenu _addRenderingMethodMenu; private GenericMenu _addFeatureMenu; public LeapGuiGroupEditor(LeapGraphicRenderer renderer, SerializedObject serializedObject) { _renderer = renderer; _serializedObject = serializedObject; var allTypes = Assembly.GetAssembly(typeof(LeapGraphicRenderer)).GetTypes(); var allRenderingMethods = allTypes.Query(). Where(t => !t.IsAbstract && !t.IsGenericType && t.IsSubclassOf(typeof(LeapRenderingMethod))); _addRenderingMethodMenu = new GenericMenu(); foreach (var renderingMethod in allRenderingMethods) { _addRenderingMethodMenu.AddItem(new GUIContent(LeapGraphicTagAttribute.GetTagName(renderingMethod)), false, () => { serializedObject.ApplyModifiedProperties(); Undo.RecordObject(_renderer, "Changed rendering method"); EditorUtility.SetDirty(_renderer); _renderer.editor.ChangeRenderingMethodOfSelectedGroup(renderingMethod, addFeatures: false); serializedObject.Update(); _renderer.editor.ScheduleRebuild(); _serializedObject.SetIsDifferentCacheDirty(); }); } var allFeatures = allTypes.Query(). Where(t => !t.IsAbstract && !t.IsGenericType && t.IsSubclassOf(typeof(LeapGraphicFeatureBase))).ToList(); allFeatures.Sort((a, b) => { var tagA = LeapGraphicTagAttribute.GetTag(a); var tagB = LeapGraphicTagAttribute.GetTag(b); var orderA = tagA == null ? 0 : tagA.order; var orderB = tagB == null ? 0 : tagB.order; return orderA - orderB; }); _addFeatureMenu = new GenericMenu(); foreach (var item in allFeatures.Query().WithPrevious(includeStart: true)) { var tag = LeapGraphicTagAttribute.GetTag(item.value); var order = tag == null ? 0 : tag.order; if (item.hasPrev) { var prevTag = LeapGraphicTagAttribute.GetTag(item.prev); var prevOrder = prevTag == null ? 0 : prevTag.order; if ((prevOrder / 100) != (order / 100)) { _addFeatureMenu.AddSeparator(""); } } _addFeatureMenu.AddItem(new GUIContent(tag.name), false, () => { if (item.value.ImplementsInterface(typeof(ICustomChannelFeature)) && LeapGraphicPreferences.promptWhenAddCustomChannel) { int result = EditorUtility.DisplayDialogComplex("Adding Custom Channel", "Custom channels can only be utilized by writing custom shaders, are you sure you want to continue?", "Add it", "Cancel", "Add it from now on"); switch (result) { case 0: break; case 1: return; case 2: LeapGraphicPreferences.promptWhenAddCustomChannel = false; break; } } serializedObject.ApplyModifiedProperties(); Undo.RecordObject(_renderer, "Added feature"); EditorUtility.SetDirty(_renderer); _renderer.editor.AddFeatureToSelectedGroup(item.value); _serializedObject.Update(); _serializedObject.SetIsDifferentCacheDirty(); }); } } public void Invalidate() { _featureList = null; _renderingMethodMonoScript = null; } public void DoGuiLayout(SerializedProperty groupProperty) { using (new ProfilerSample("Draw Graphic Group")) { init(groupProperty); drawRendererHeader(); drawGroupName(); drawMonoScript(); drawStatsArea(); drawSpriteWarning(); EditorGUILayout.PropertyField(_renderingMethod, includeChildren: true); EditorGUILayout.Space(); drawFeatureHeader(); _featureList.DoLayoutList(); drawWarningDialogs(); } } private void init(SerializedProperty groupProperty) { Assert.IsNotNull(groupProperty); _groupProperty = groupProperty; _multiFeatureList = _groupProperty.FindPropertyRelative("_features"); _multiRenderingMethod = _groupProperty.FindPropertyRelative("_renderingMethod"); _featureTable = MultiTypedListUtil.GetTableProperty(_multiFeatureList); Assert.IsNotNull(_featureTable); if (_featureList == null || !SerializedProperty.EqualContents(_featureList.serializedProperty, _featureTable)) { _featureList = new ReorderableList(_serializedObject, _featureTable, draggable: true, displayHeader: false, displayAddButton: false, displayRemoveButton: false); _featureList.showDefaultBackground = false; _featureList.headerHeight = 0; _featureList.elementHeight = EditorGUIUtility.singleLineHeight; _featureList.elementHeightCallback = featureHeightCallback; _featureList.drawElementCallback = drawFeatureCallback; _featureList.onReorderCallback = onReorderFeaturesCallback; } _renderingMethod = MultiTypedReferenceUtil.GetReferenceProperty(_multiRenderingMethod); _supportInfo = _groupProperty.FindPropertyRelative("_supportInfo"); _cachedPropertyList = new List<SerializedProperty>(); _cachedPropertyHeights = new List<float>(); for (int i = 0; i < _featureTable.arraySize; i++) { var idIndex = _featureTable.GetArrayElementAtIndex(i); var referenceProp = MultiTypedListUtil.GetReferenceProperty(_multiFeatureList, idIndex); _cachedPropertyList.Add(referenceProp); //Make sure to add one line for the label _cachedPropertyHeights.Add(EditorGUI.GetPropertyHeight(referenceProp) + EditorGUIUtility.singleLineHeight); } _renderingMethod = MultiTypedReferenceUtil.GetReferenceProperty(_multiRenderingMethod); if (_renderingMethodMonoScript == null) { _renderingMethodMonoScript = AssetDatabase.FindAssets(_renderingMethod.type). Query(). Where(guid => !string.IsNullOrEmpty(guid)). Select(guid => AssetDatabase.GUIDToAssetPath(guid)). Where(path => Path.GetFileNameWithoutExtension(path) == _renderingMethod.type). Select(path => AssetDatabase.LoadAssetAtPath<MonoScript>(path)). FirstOrDefault(); } } private void drawGroupName() { var nameProperty = _groupProperty.FindPropertyRelative("_groupName"); EditorGUILayout.PropertyField(nameProperty); nameProperty.stringValue = nameProperty.stringValue.Trim(); if (string.IsNullOrEmpty(nameProperty.stringValue)) { nameProperty.stringValue = "MyGroupName"; } } private void drawRendererHeader() { Rect rect = EditorGUILayout.GetControlRect(GUILayout.MaxHeight(EditorGUIUtility.singleLineHeight)); Rect left, right; rect.SplitHorizontallyWithRight(out left, out right, BUTTON_WIDTH * 2); if (!EditorApplication.isPlaying && PrefabUtility.GetPrefabType(_renderer) != PrefabType.Prefab) { var mesher = _renderer.editor.GetSelectedRenderingMethod() as LeapMesherBase; if (mesher != null) { Color prevColor = GUI.color; if (mesher.IsAtlasDirty) { GUI.color = Color.yellow; } Rect middle; left.SplitHorizontallyWithRight(out left, out middle, REFRESH_WIDTH); if (GUI.Button(middle, "Refresh Atlas", EditorStyles.miniButtonMid)) { _serializedObject.ApplyModifiedProperties(); Undo.RecordObject(_renderer, "Refreshed atlas"); EditorUtility.SetDirty(_renderer); mesher.RebuildAtlas(new ProgressBar()); _renderer.editor.ScheduleRebuild(); _serializedObject.Update(); } GUI.color = prevColor; } } EditorGUI.LabelField(left, "Renderer", EditorStyles.miniButtonLeft); using (new EditorGUI.DisabledGroupScope(EditorApplication.isPlaying)) { if (GUI.Button(right, "v", EditorStyles.miniButtonRight)) { _addRenderingMethodMenu.ShowAsContext(); } } } private void drawStatsArea() { using (new EditorGUI.DisabledGroupScope(true)) { var graphicList = _groupProperty.FindPropertyRelative("_graphics"); int count = graphicList.arraySize; EditorGUILayout.IntField("Attached Graphic Count", count); } } private void drawSpriteWarning() { var list = Pool<List<LeapGraphicFeatureBase>>.Spawn(); try { foreach (var group in _renderer.groups) { list.AddRange(group.features); } SpriteAtlasUtil.ShowInvalidSpriteWarning(list); } finally { list.Clear(); Pool<List<LeapGraphicFeatureBase>>.Recycle(list); } } private void drawMonoScript() { using (new EditorGUI.DisabledGroupScope(true)) { EditorGUILayout.ObjectField("Rendering Method", _renderingMethodMonoScript, typeof(MonoScript), allowSceneObjects: false); } } private void drawWarningDialogs() { HashSet<string> shownMessages = Pool<HashSet<string>>.Spawn(); try { for (int i = 0; i < _cachedPropertyList.Count; i++) { if (!EditorApplication.isPlaying) { var supportInfo = _supportInfo.GetArrayElementAtIndex(i); var supportProperty = supportInfo.FindPropertyRelative("support"); var messageProperty = supportInfo.FindPropertyRelative("message"); if (shownMessages.Contains(messageProperty.stringValue)) { continue; } shownMessages.Add(messageProperty.stringValue); switch ((SupportType)supportProperty.intValue) { case SupportType.Warning: EditorGUILayout.HelpBox(messageProperty.stringValue, MessageType.Warning); break; case SupportType.Error: EditorGUILayout.HelpBox(messageProperty.stringValue, MessageType.Error); break; } } } } finally { shownMessages.Clear(); Pool<HashSet<string>>.Recycle(shownMessages); } } private void drawFeatureHeader() { Rect rect = EditorGUILayout.GetControlRect(GUILayout.MaxHeight(EditorGUIUtility.singleLineHeight)); Rect left, middle, right; rect.SplitHorizontallyWithRight(out middle, out right, BUTTON_WIDTH); middle.SplitHorizontallyWithRight(out left, out middle, BUTTON_WIDTH); EditorGUI.LabelField(left, "Graphic Features", EditorStyles.miniButtonLeft); using (new EditorGUI.DisabledGroupScope(EditorApplication.isPlaying)) { EditorGUI.BeginDisabledGroup(_featureTable.arraySize == 0); if (GUI.Button(middle, "-", EditorStyles.miniButtonMid) && _featureList.index >= 0) { _serializedObject.ApplyModifiedProperties(); Undo.RecordObject(_renderer, "Removed Feature"); EditorUtility.SetDirty(_renderer); _renderer.editor.RemoveFeatureFromSelectedGroup(_featureList.index); _serializedObject.Update(); init(_groupProperty); } EditorGUI.EndDisabledGroup(); if (GUI.Button(right, "+", EditorStyles.miniButtonRight)) { _addFeatureMenu.ShowAsContext(); } } } // Feature list callbacks private void drawFeatureHeaderCallback(Rect rect) { Rect left, right; rect.SplitHorizontallyWithRight(out left, out right, BUTTON_WIDTH); EditorGUI.LabelField(left, "Graphic Features", EditorStyles.miniButtonLeft); if (GUI.Button(right, "+", EditorStyles.miniButtonRight)) { _addFeatureMenu.ShowAsContext(); } } private float featureHeightCallback(int index) { return _cachedPropertyHeights[index]; } delegate void Action<T1, T2, T3, T4, T5>(T1 t1, T2 t2, T3 t3, T4 t4, T5 t5); private void drawFeatureCallback(Rect rect, int index, bool isActive, bool isFocused) { var featureProperty = _cachedPropertyList[index]; rect = rect.SingleLine(); string featureName = LeapGraphicTagAttribute.GetTagName(featureProperty.type); int lastIndexOf = featureName.LastIndexOf('/'); if (lastIndexOf >= 0) { featureName = featureName.Substring(lastIndexOf + 1); } GUIContent featureLabel = new GUIContent(featureName); Color originalColor = GUI.color; if (!EditorApplication.isPlaying && index < _supportInfo.arraySize) { var supportInfo = _supportInfo.GetArrayElementAtIndex(index); var supportProperty = supportInfo.FindPropertyRelative("support"); var messageProperty = supportInfo.FindPropertyRelative("message"); switch ((SupportType)supportProperty.intValue) { case SupportType.Warning: GUI.color = Color.yellow; featureLabel.tooltip = messageProperty.stringValue; break; case SupportType.Error: GUI.color = Color.red; featureLabel.tooltip = messageProperty.stringValue; break; } } Vector2 size = EditorStyles.label.CalcSize(featureLabel); Rect labelRect = rect; labelRect.width = size.x; GUI.Box(labelRect, ""); EditorGUI.LabelField(labelRect, featureLabel); GUI.color = originalColor; rect = rect.NextLine().Indent(); EditorGUI.PropertyField(rect, featureProperty, includeChildren: true); } private void onReorderFeaturesCallback(ReorderableList list) { _renderer.editor.ScheduleRebuild(); } } } <file_sep>/Assets/LeapMotion/Modules/GraphicRenderer/Scripts/Utility/MaterialUtil.cs /****************************************************************************** * Copyright (C) Leap Motion, Inc. 2011-2018. * * Leap Motion proprietary and confidential. * * * * Use subject to the terms of the Leap Motion SDK Agreement available at * * https://developer.leapmotion.com/sdk_agreement, or another agreement * * between Leap Motion and you, your company or other organization. * ******************************************************************************/ using System.Collections.Generic; using UnityEngine; namespace Leap.Unity.GraphicalRenderer { public static class MaterialUtil { public static void SetFloatArraySafe(this Material material, string property, List<float> list) { if (list.Count == 0) return; material.SetFloatArray(property, list); } public static void SetVectorArraySafe(this Material material, string property, List<Vector4> list) { if (list.Count == 0) return; material.SetVectorArray(property, list); } public static void SetColorArraySafe(this Material material, string property, List<Color> list) { if (list.Count == 0) return; material.SetColorArray(property, list); } public static void SetMatrixArraySafe(this Material material, string property, List<Matrix4x4> list) { if (list.Count == 0) return; material.SetMatrixArray(property, list); } } } <file_sep>/Assets/Hover/Core/Scripts/Items/HoverItem.cs using System.Collections.Generic; using System.ComponentModel; using Hover.Core.Items.Managers; using Hover.Core.Items.Types; using Hover.Core.Utils; using UnityEngine; namespace Hover.Core.Items { /*================================================================================================*/ [ExecuteInEditMode] [RequireComponent(typeof(TreeUpdater))] public class HoverItem : MonoBehaviour, ITreeUpdateable { public enum HoverItemType { Selector = 1, Sticky, Checkbox, Radio, Slider, Text } public delegate void ItemEvent(HoverItem pItem); public ItemEvent OnTypeChanged; [SerializeField] private HoverItemType _ItemType = HoverItemType.Selector; [SerializeField] private HoverItemData _Data; private readonly List<HoverItemData> vDataComponentBuffer; private HoverItemsManager vItemsMan; private HoverItemType vPrevItemType; //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public HoverItem() { vDataComponentBuffer = new List<HoverItemData>(); } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public void Awake() { vPrevItemType = _ItemType; BuildDataIfNeeded(); UpdateItemsManager(true); } /*--------------------------------------------------------------------------------------------*/ public void Start() { //do nothing... } /*--------------------------------------------------------------------------------------------*/ public void TreeUpdate() { UpdateWithLatestItemTypeIfNeeded(); _Data.IsVisible = gameObject.activeSelf; _Data.IsAncestryVisible = gameObject.activeInHierarchy; } /*--------------------------------------------------------------------------------------------*/ public void OnDestroy() { UpdateItemsManager(false); } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public HoverItemType ItemType { get { return _ItemType; } set { _ItemType = value; } } /*--------------------------------------------------------------------------------------------*/ public HoverItemData Data { get { return _Data; } } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ private void BuildDataIfNeeded() { if ( _Data == null ) { _Data = gameObject.GetComponent<HoverItemData>(); } if ( _Data == null ) { _Data = BuildData(_ItemType); } else if ( FindDuplicateData() ) { _Data = Instantiate(_Data); //handle duplication via Unity editor } } /*--------------------------------------------------------------------------------------------*/ private void UpdateWithLatestItemTypeIfNeeded() { if ( _ItemType == vPrevItemType ) { return; } HoverItemData newData = BuildData(_ItemType); TransferData(newData); DestroyData(_Data, newData); _Data = newData; if ( OnTypeChanged != null ) { OnTypeChanged.Invoke(this); } vPrevItemType = _ItemType; } /*--------------------------------------------------------------------------------------------*/ private void UpdateItemsManager(bool pAdd) { if ( !Application.isPlaying ) { return; } vItemsMan = (vItemsMan ?? FindObjectOfType<HoverItemsManager>()); if ( vItemsMan == null ) { return; } if ( pAdd ) { vItemsMan.AddItem(this); } else { vItemsMan.RemoveItem(this); } } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ private bool FindDuplicateData() { HoverItem[] items = FindObjectsOfType<HoverItem>(); for ( int i = 0 ; i < items.Length ; i++ ) { HoverItem item = items[i]; if ( item != this && item.Data == _Data ) { return true; } } return false; } /*--------------------------------------------------------------------------------------------*/ private HoverItemData TransferData(HoverItemData pDataToFill) { HoverItemData oldData = _Data; HoverItemData newData = pDataToFill; if ( oldData == null ) { return newData; } newData.AutoId = oldData.AutoId; newData.IsAncestryEnabled = oldData.IsAncestryEnabled; newData.IsAncestryVisible = oldData.IsAncestryVisible; newData.Id = oldData.Id; newData.Label = oldData.Label; newData.IsEnabled = oldData.IsEnabled; newData.IsVisible = oldData.IsVisible; HoverItemDataSelectable oldSelData = (oldData as HoverItemDataSelectable); HoverItemDataSelectable newSelData = (newData as HoverItemDataSelectable); if ( oldSelData == null || newSelData == null ) { return newData; } newSelData.OnSelectedEvent = oldSelData.OnSelectedEvent; newSelData.OnDeselectedEvent = oldSelData.OnDeselectedEvent; //newSelData.OnSelected += oldSelData.OnSelected; //newSelData.OnDeselected += oldSelData.OnDeselected; HoverItemDataSelectableBool oldSelBoolData = (oldData as HoverItemDataSelectableBool); HoverItemDataSelectableBool newSelBoolData = (newData as HoverItemDataSelectableBool); if ( oldSelBoolData != null && newSelBoolData != null ) { newSelBoolData.Value = oldSelBoolData.Value; newSelBoolData.OnValueChangedEvent = oldSelBoolData.OnValueChangedEvent; //newSelBoolData.OnValueChanged += oldSelBoolData.OnValueChanged; } HoverItemDataSelectableFloat oldSelFloatData = (oldData as HoverItemDataSelectableFloat); HoverItemDataSelectableFloat newSelFloatData = (newData as HoverItemDataSelectableFloat); if ( oldSelFloatData != null && newSelFloatData != null ) { newSelFloatData.Value = oldSelFloatData.Value; newSelFloatData.OnValueChangedEvent = oldSelFloatData.OnValueChangedEvent; //newSelFloatData.OnValueChanged += oldSelFloatData.OnValueChanged; } return newData; } /*--------------------------------------------------------------------------------------------*/ private HoverItemData BuildData(HoverItemType pType) { switch ( pType ) { case HoverItemType.Selector: return gameObject.AddComponent<HoverItemDataSelector>(); case HoverItemType.Sticky: return gameObject.AddComponent<HoverItemDataSticky>(); case HoverItemType.Checkbox: return gameObject.AddComponent<HoverItemDataCheckbox>(); case HoverItemType.Radio: HoverItemDataRadio radioData = gameObject.AddComponent<HoverItemDataRadio>(); radioData.InitDefaultGroupId(gameObject.transform.parent); return radioData; case HoverItemType.Slider: return gameObject.AddComponent<HoverItemDataSlider>(); case HoverItemType.Text: return gameObject.AddComponent<HoverItemDataText>(); default: throw new InvalidEnumArgumentException("Unhandled type: "+pType); } } /*--------------------------------------------------------------------------------------------*/ private void DestroyData(HoverItemData pData, HoverItemData pIgnoreNewData) { gameObject.GetComponents(vDataComponentBuffer); for ( int i = 0 ; i < vDataComponentBuffer.Count ; i++ ) { HoverItemData data = vDataComponentBuffer[i]; if ( data == pIgnoreNewData ) { continue; } if ( data != pData ) { Debug.LogWarning("Removed unexpected "+typeof(HoverItemData).Name+": "+data, this); } DestroyImmediate(data, false); } } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ private IItemData[] GetChildItems() { return GetChildItemsFromGameObject(gameObject); } /*--------------------------------------------------------------------------------------------*/ private static IItemData[] GetChildItemsFromGameObject(GameObject pParentObj) { Transform tx = pParentObj.transform; int childCount = tx.childCount; var items = new List<IItemData>(); for ( int i = 0 ; i < childCount ; ++i ) { HoverItem hni = tx.GetChild(i).GetComponent<HoverItem>(); IItemData item = hni.Data; if ( !item.IsVisible ) { continue; } items.Add(item); } return items.ToArray(); } } } <file_sep>/Assets/Hover/Core/Scripts/Utils/MeshUtil.cs using System; using UnityEngine; namespace Hover.Core.Utils { /*================================================================================================*/ public static class MeshUtil { /*[Flags] public enum TabDir : uint { N = 0x01, NE = 0x02, E = 0x04, SE = 0x08, S = 0x10, SW = 0x20, W = 0x40, NW = 0x80 } private static readonly MeshBuilder TabRectBuilder = new MeshBuilder(); private static readonly List<Vector3> TabEdgePoints = new List<Vector3>(); private static readonly List<Vector3> PathSegmentDirs = new List<Vector3>(); private static readonly List<Vector3> PathSegmentTangents = new List<Vector3>(); private static readonly List<Vector3> PathVertexTangents = new List<Vector3>();*/ //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public static void BuildQuadMesh(MeshBuilder pMeshBuild, float pSizeX=1, float pSizeY=1) { float halfSizeX = pSizeX/2; float halfSizeY = pSizeY/2; pMeshBuild.Resize(4, 6); pMeshBuild.ResetIndices(); pMeshBuild.AddVertex(new Vector3( halfSizeX, halfSizeY, 0)); pMeshBuild.AddVertex(new Vector3( halfSizeX, -halfSizeY, 0)); pMeshBuild.AddVertex(new Vector3(-halfSizeX, -halfSizeY, 0)); pMeshBuild.AddVertex(new Vector3(-halfSizeX, halfSizeY, 0)); pMeshBuild.AddUv(new Vector2(1, 1)); pMeshBuild.AddUv(new Vector2(1, 0)); pMeshBuild.AddUv(new Vector2(0, 0)); pMeshBuild.AddUv(new Vector2(0, 1)); pMeshBuild.AddTriangle(0, 1, 2); pMeshBuild.AddTriangle(0, 2, 3); } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public static Vector3 GetRingPoint(float pRadius, float pAngle) { return new Vector3( Mathf.Cos(pAngle)*pRadius, Mathf.Sin(pAngle)*pRadius, 0 ); } /*--------------------------------------------------------------------------------------------*/ public static void BuildRingMesh(MeshBuilder pMeshBuild, float pInnerRadius, float pOuterRadius, float pAngle0, float pAngle1, Vector3 pInnerOffset, Vector3 pOuterOffset, int pSteps) { float angleFull = pAngle1-pAngle0; float angleInc = angleFull/pSteps; float angle = pAngle0; pMeshBuild.Resize((pSteps+1)*2, pSteps*6); pMeshBuild.ResetIndices(); for ( int i = 0 ; i <= pSteps ; ++i ) { float uvx = i/(float)pSteps; pMeshBuild.AddVertex(pInnerOffset+GetRingPoint(pInnerRadius, angle)); pMeshBuild.AddVertex(pOuterOffset+GetRingPoint(pOuterRadius, angle)); pMeshBuild.AddUv(new Vector2(uvx, 0)); pMeshBuild.AddUv(new Vector2(uvx, 1)); if ( i > 0 ) { int vi = pMeshBuild.VertexIndex; pMeshBuild.AddTriangle(vi-3, vi-4, vi-2); pMeshBuild.AddTriangle(vi-1, vi-3, vi-2); } angle += angleInc; } } /*--------------------------------------------------------------------------------------------*/ public static void BuildRingMesh(MeshBuilder pMeshBuild, float pInnerRadius, float pOuterRadius, float pAngle0, float pAngle1, int pSteps) { BuildRingMesh(pMeshBuild, pInnerRadius, pOuterRadius, pAngle0, pAngle1, Vector3.zero, Vector3.zero, pSteps); } /*--------------------------------------------------------------------------------------------*/ public static void BuildCircleMesh(MeshBuilder pMeshBuild, float pRadius, int pSteps) { const float angleFull = (float)Math.PI*2; float angleInc = angleFull/pSteps; float angle = 0; pMeshBuild.Resize(pSteps+2, pSteps*3); pMeshBuild.AddVertex(Vector3.zero); pMeshBuild.AddUv(new Vector2(0, 0)); for ( int i = 0 ; i <= pSteps ; ++i ) { pMeshBuild.AddVertex(GetRingPoint(pRadius, angle)); pMeshBuild.AddUv(new Vector2(i/(float)pSteps, 1)); if ( i > 0 ) { int vi = pMeshBuild.VertexIndex; pMeshBuild.AddTriangle(0, vi-2, vi-1); } angle += angleInc; } } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------* / public static void BuildBorderMesh(MeshBuilder pMeshBuild, float pWidth, float pHeight, float pThickness) { float innerW = pWidth/2-pThickness; float innerH = pHeight/2-pThickness; float outerW = pWidth/2; float outerH = pHeight/2; BuildHollowRectangleMesh(pMeshBuild, outerW, outerH, innerW, innerH); } /*--------------------------------------------------------------------------------------------*/ public static void BuildHollowRectangleMesh(MeshBuilder pMeshBuild, float pOuterW, float pOuterH, float pInnerW, float pInnerH) { float halfOuterW = pOuterW/2; float halfOuterH = pOuterH/2; float halfInnerW = pInnerW/2; float halfInnerH = pInnerH/2; float innerUvMaxX = 0.5f + halfInnerW/halfOuterW/2; float innerUvMinX = 0.5f - halfInnerW/halfOuterW/2; float innerUvMaxY = 0.5f + halfInnerH/halfOuterH/2; float innerUvMinY = 0.5f - halfInnerH/halfOuterH/2; pMeshBuild.Resize(8, 24); pMeshBuild.ResetIndices(); pMeshBuild.AddVertex(new Vector3( halfOuterW, halfOuterH, 0)); pMeshBuild.AddVertex(new Vector3( halfOuterW, -halfOuterH, 0)); pMeshBuild.AddVertex(new Vector3(-halfOuterW, -halfOuterH, 0)); pMeshBuild.AddVertex(new Vector3(-halfOuterW, halfOuterH, 0)); pMeshBuild.AddVertex(new Vector3( halfInnerW, halfInnerH, 0)); pMeshBuild.AddVertex(new Vector3( halfInnerW, -halfInnerH, 0)); pMeshBuild.AddVertex(new Vector3(-halfInnerW, -halfInnerH, 0)); pMeshBuild.AddVertex(new Vector3(-halfInnerW, halfInnerH, 0)); pMeshBuild.AddUv(new Vector2(1, 1)); pMeshBuild.AddUv(new Vector2(1, 0)); pMeshBuild.AddUv(new Vector2(0, 0)); pMeshBuild.AddUv(new Vector2(0, 1)); pMeshBuild.AddUv(new Vector2(innerUvMaxX, innerUvMaxY)); pMeshBuild.AddUv(new Vector2(innerUvMaxX, innerUvMinY)); pMeshBuild.AddUv(new Vector2(innerUvMinX, innerUvMinY)); pMeshBuild.AddUv(new Vector2(innerUvMinX, innerUvMaxY)); pMeshBuild.AddTriangle(0, 1, 4); pMeshBuild.AddTriangle(1, 5, 4); pMeshBuild.AddTriangle(1, 2, 5); pMeshBuild.AddTriangle(2, 6, 5); pMeshBuild.AddTriangle(2, 3, 6); pMeshBuild.AddTriangle(3, 7, 6); pMeshBuild.AddTriangle(3, 4, 7); pMeshBuild.AddTriangle(3, 0, 4); } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public static void BuildHollowRectangleTabMesh(MeshBuilder pMeshBuild, float pOuterW, float pOuterH, float pInnerW, float pInnerH, float pOuterTabPush, float pOuterTabThick, float pInnerRatio, bool pShowTabN, bool pShowTabE, bool pShowTabS, bool pShowTabW) { float halfOuterW = pOuterW/2; float halfOuterH = pOuterH/2; float halfOuterTw = Mathf.Min(pOuterTabThick, pOuterW)/2; float halfOuterTh = Mathf.Min(pOuterTabThick, pOuterH)/2; float outerToInnerW = pInnerW/pOuterW; float outerToInnerH = pInnerH/pOuterH; float innerTabPush = pOuterTabPush*pInnerRatio; float halfInnerTw = halfOuterTw*pInnerRatio; float halfInnerTh = halfOuterTh*pInnerRatio; pMeshBuild.Resize(32, 32*3); pMeshBuild.ResetIndices(); pMeshBuild.AddVertex(new Vector3( 0, halfOuterH)); //V0 (N) pMeshBuild.AddVertex(new Vector3( halfOuterTw, halfOuterH)); pMeshBuild.AddVertex(new Vector3( halfOuterW, halfOuterH)); //V2 (NE) pMeshBuild.AddVertex(new Vector3( halfOuterW, halfOuterTh)); pMeshBuild.AddVertex(new Vector3( halfOuterW, 0)); //V4 (E) pMeshBuild.AddVertex(new Vector3( halfOuterW, -halfOuterTh)); pMeshBuild.AddVertex(new Vector3( halfOuterW, -halfOuterH)); //V6 (SE) pMeshBuild.AddVertex(new Vector3( halfOuterTw,-halfOuterH)); pMeshBuild.AddVertex(new Vector3( 0, -halfOuterH)); //V8 (S) pMeshBuild.AddVertex(new Vector3(-halfOuterTw,-halfOuterH)); pMeshBuild.AddVertex(new Vector3(-halfOuterW, -halfOuterH)); //V10 (SW) pMeshBuild.AddVertex(new Vector3(-halfOuterW, -halfOuterTh)); pMeshBuild.AddVertex(new Vector3(-halfOuterW, 0)); //V12 (W) pMeshBuild.AddVertex(new Vector3(-halfOuterW, halfOuterTh)); pMeshBuild.AddVertex(new Vector3(-halfOuterW, halfOuterH)); //V14 (NW) pMeshBuild.AddVertex(new Vector3(-halfOuterTw, halfOuterH)); for ( int i = 0 ; i < 16 ; i++ ) { Vector3 vert = pMeshBuild.Vertices[i]; pMeshBuild.AddVertex(new Vector3( vert.x*outerToInnerW, vert.y*outerToInnerH )); } if ( pShowTabN ) { pMeshBuild.Vertices[ 0].y += pOuterTabPush; pMeshBuild.Vertices[16].y += innerTabPush; pMeshBuild.Vertices[31].x = -halfInnerTw; pMeshBuild.Vertices[17].x = halfInnerTw; } if ( pShowTabE ) { pMeshBuild.Vertices[ 4].x += pOuterTabPush; pMeshBuild.Vertices[20].x += innerTabPush; pMeshBuild.Vertices[19].y = halfInnerTh; pMeshBuild.Vertices[21].y = -halfInnerTh; } if ( pShowTabS ) { pMeshBuild.Vertices[ 8].y -= pOuterTabPush; pMeshBuild.Vertices[24].y -= innerTabPush; pMeshBuild.Vertices[23].x = halfInnerTw; pMeshBuild.Vertices[25].x = -halfInnerTw; } if ( pShowTabW ) { pMeshBuild.Vertices[12].x -= pOuterTabPush; pMeshBuild.Vertices[28].x -= innerTabPush; pMeshBuild.Vertices[27].y = -halfInnerTh; pMeshBuild.Vertices[29].y = halfInnerTh; } for ( int i = 0 ; i < 32 ; i++ ) { Vector3 vert = pMeshBuild.Vertices[i]; pMeshBuild.AddUv(new Vector2( vert.x/pOuterW + 0.5f, vert.y/pOuterH + 0.5f )); } for ( int i = 0 ; i < 16 ; i++ ) { int i2 = (i+1)%16; int i3 = i+16; pMeshBuild.AddTriangle(i, i2, i3); pMeshBuild.AddTriangle(i2, i2+16, i3); } } } } <file_sep>/Assets/Hover/Core/Scripts/Renderers/Helpers/ColorViaHoverIndicator.cs using UnityEngine; namespace Hover.Core.Renderers.Helpers { /*================================================================================================*/ [ExecuteInEditMode] [RequireComponent(typeof(MeshRenderer))] public class ColorViaHoverIndicator : MonoBehaviour { public HoverIndicator Indicator; public Color StartColor = new Color(1, 1, 1); public Color HighlightColor = new Color(0, 0.5f, 1); public Color SelectionColor = new Color(0, 1, 0); //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public void Awake() { if ( Indicator == null ) { Indicator = GetComponentInParent<HoverIndicator>(); } } /*--------------------------------------------------------------------------------------------*/ public void Update() { if ( !Application.isPlaying ) { return; } Material mat = GetComponent<MeshRenderer>().material; if ( Indicator.SelectionProgress > 0 ) { mat.color = Color.Lerp(HighlightColor, SelectionColor, Indicator.SelectionProgress); } else { mat.color = Color.Lerp(StartColor, HighlightColor, Indicator.HighlightProgress); } } } } <file_sep>/Assets/Hover/Core/Scripts/Layouts/AnchorType.cs namespace Hover.Core.Layouts { /*================================================================================================*/ public enum AnchorType { UpperLeft, UpperCenter, UpperRight, MiddleLeft, MiddleCenter, MiddleRight, LowerLeft, LowerCenter, LowerRight } } <file_sep>/Assets/LeapMotion/Modules/GraphicRenderer/Scripts/Features/CustomChannel/Channels/CustomMatrixChannelData.cs /****************************************************************************** * Copyright (C) Leap Motion, Inc. 2011-2018. * * Leap Motion proprietary and confidential. * * * * Use subject to the terms of the Leap Motion SDK Agreement available at * * https://developer.leapmotion.com/sdk_agreement, or another agreement * * between Leap Motion and you, your company or other organization. * ******************************************************************************/ using UnityEngine; using System; namespace Leap.Unity.GraphicalRenderer { public partial class LeapGraphic { /// <summary> /// Helper method to set the custom channel value for the given channel /// name. This method will throw an exception if there is no channel /// with the given name, if the graphic is not currently attached to a /// group, or if the channel does not match up with the data type. /// </summary> public void SetCustomChannel(string channelName, Matrix4x4 value) { GetCustomChannel<CustomMatrixChannelData>(channelName).value = value; } } [LeapGraphicTag("Matrix Channel")] [Serializable] public class CustomMatrixChannelData : CustomChannelDataBase<Matrix4x4> { } } <file_sep>/Assets/Hover/Core/Scripts/Utils/ISettingsControllerMap.cs using System.Collections.Generic; namespace Hover.Core.Utils { /*================================================================================================*/ public interface ISettingsControllerMap { //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ void Set(string pValueName, ISettingsController pController, int pExpirationCount=1); /*--------------------------------------------------------------------------------------------*/ bool Unset(string pValueName, ISettingsController pController); /*--------------------------------------------------------------------------------------------*/ void TryExpireControllers(); #if UNITY_EDITOR //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ ISettingsController Get(string pValueName); /*--------------------------------------------------------------------------------------------*/ bool IsControlled(string pValueName); /*--------------------------------------------------------------------------------------------*/ bool AreAnyControlled(); /*--------------------------------------------------------------------------------------------*/ int GetControlledCount(bool pSpecialsOnly=false); //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ List<string> GetNewListOfControlledValueNames(bool pSpecialsOnly=false); /*--------------------------------------------------------------------------------------------*/ void FillListWithControlledValueNames(List<string> pList, bool pSpecialsOnly=false); #endif } } <file_sep>/Assets/Hover/Core/Scripts/Items/Helpers/ShowViaHoverItemBoolValue.cs using Hover.Core.Items.Types; using UnityEngine; namespace Hover.Core.Items.Helpers { /*================================================================================================*/ [ExecuteInEditMode] [RequireComponent(typeof(MeshRenderer))] public class ShowViaHoverItemBoolValue : MonoBehaviour { public HoverItemDataSelectableBool Data; //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public void Awake() { if ( Data == null ) { Data = GetComponentInParent<HoverItemDataSelectableBool>(); } } /*--------------------------------------------------------------------------------------------*/ public void Update() { GetComponent<MeshRenderer>().enabled = Data.Value; } } } <file_sep>/Assets/LeapMotion/Core/Scripts/Attributes/AutoFind.cs /****************************************************************************** * Copyright (C) Leap Motion, Inc. 2011-2018. * * Leap Motion proprietary and confidential. * * * * Use subject to the terms of the Leap Motion SDK Agreement available at * * https://developer.leapmotion.com/sdk_agreement, or another agreement * * between Leap Motion and you, your company or other organization. * ******************************************************************************/ using System; namespace Leap.Unity.Attributes { [Obsolete] public enum AutoFindLocations { Object = 0x01, Children = 0x02, Parents = 0x04, Scene = 0x08, All = 0xFFFF } [Obsolete] public class AutoFindAttribute : Attribute { public readonly AutoFindLocations searchLocations; public AutoFindAttribute(AutoFindLocations searchLocations = AutoFindLocations.All) { this.searchLocations = searchLocations; } } } <file_sep>/Assets/Hover/Core/Scripts/Utils/ITreeUpdateable.cs namespace Hover.Core.Utils { /*================================================================================================*/ public interface ITreeUpdateable { bool isActiveAndEnabled { get; } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ void Start(); //forces Unity to show the "component enabled" checkbox in the inspector /*--------------------------------------------------------------------------------------------*/ void TreeUpdate(); } } <file_sep>/Assets/LeapMotion/Core/Plugins/LeapCSharp/Editor/Tests/DeviceTests.cs /****************************************************************************** * Copyright (C) Leap Motion, Inc. 2011-2018. * * Leap Motion proprietary and confidential. * * * * Use subject to the terms of the Leap Motion SDK Agreement available at * * https://developer.leapmotion.com/sdk_agreement, or another agreement * * between Leap Motion and you, your company or other organization. * ******************************************************************************/ using NUnit.Framework; using System; namespace Leap.LeapCSharp.Tests { [TestFixture()] public class DeviceTests { Controller controller; [OneTimeSetUp] public void Init() { controller = new Controller(); System.Threading.Thread.Sleep(500); } [Test] public void DeviceIsConnected() { Assert.True(controller.IsConnected, "A Leap device must be connected to successfully test LeapCSharp."); } [Test()] public void Device_operator_equals() { Device thisDevice = new Device(); Device thatDevice = new Device(); // !!!Device_operator_equals Boolean isEqual = thisDevice == thatDevice; // !!!END Assert.False(isEqual); } [Test()] public void DeviceList_operator_index() { // !!!DeviceList_operator_index DeviceList allDevices = controller.Devices; for (int index = 0; index < allDevices.Count; index++) { Console.WriteLine(allDevices[index]); } // !!!END } [Test()] public void DeviceList_isEmpty() { // !!!DeviceList_isEmpty if (!controller.Devices.IsEmpty) { Device leapDevice = controller.Devices[0]; } // !!!END } } } <file_sep>/Assets/Hover/Core/Scripts/Cursors/ICursorIdle.cs using UnityEngine; namespace Hover.Core.Cursors { /*================================================================================================*/ public interface ICursorIdle { bool IsActive { get; } float Progress { get; } Vector3 WorldPosition { get; } float DistanceThreshold { get; } } } <file_sep>/Assets/Hover/Core/Scripts/Renderers/Shapes/Rect/HoverFillSliderRectUpdater.cs using Hover.Core.Renderers.Items.Sliders; using Hover.Core.Renderers.Utils; using Hover.Core.Utils; using UnityEngine; namespace Hover.Core.Renderers.Shapes.Rect { /*================================================================================================*/ [RequireComponent(typeof(HoverShapeRect))] public class HoverFillSliderRectUpdater : HoverFillSliderUpdater { [DisableWhenControlled(RangeMin=0, DisplaySpecials=true)] public float InsetLeft = 0.01f; [DisableWhenControlled(RangeMin=0)] public float InsetRight = 0.01f; [DisableWhenControlled(RangeMin=0, RangeMax=1)] public float TickRelativeSizeX = 0.5f; [DisableWhenControlled] public bool UseTrackUv = false; private float vMeshSizeX; private float vTickSizeX; //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ protected override void UpdateFillMeshes() { HoverShapeRect shapeRect = gameObject.GetComponent<HoverShapeRect>(); vMeshSizeX = Mathf.Max(0, shapeRect.SizeX-InsetLeft-InsetRight); base.UpdateFillMeshes(); } /*--------------------------------------------------------------------------------------------*/ protected override void ResetFillMesh(HoverMesh pSegmentMesh) { HoverShapeRect meshShapeRect = pSegmentMesh.GetComponent<HoverShapeRect>(); meshShapeRect.Controllers.Set(HoverShapeRect.SizeXName, this); meshShapeRect.Controllers.Set(HoverShapeRect.SizeYName, this); meshShapeRect.SizeX = vMeshSizeX; meshShapeRect.SizeY = 0; } /*--------------------------------------------------------------------------------------------*/ protected override void UpdateFillMesh(HoverMesh pSegmentMesh, SliderUtil.SegmentInfo pSegmentInfo, float pStartPos, float pEndPos) { HoverShapeRect meshShapeRect = pSegmentMesh.GetComponent<HoverShapeRect>(); HoverMeshRect meshRect = (HoverMeshRect)pSegmentMesh; pSegmentMesh.Controllers.Set(SettingsControllerMap.TransformLocalPosition+".x", this); pSegmentMesh.Controllers.Set(SettingsControllerMap.TransformLocalPosition+".y", this); pSegmentMesh.Controllers.Set(HoverMesh.DisplayModeName, this); meshRect.Controllers.Set(HoverMeshRect.UvTopName, this); meshRect.Controllers.Set(HoverMeshRect.UvBottomName, this); meshShapeRect.SizeY = pSegmentInfo.EndPosition-pSegmentInfo.StartPosition; pSegmentMesh.DisplayMode = (pSegmentInfo.IsFill ? HoverMesh.DisplayModeType.SliderFill : HoverMesh.DisplayModeType.Standard); meshRect.UvTop = (UseTrackUv ? Mathf.InverseLerp(pStartPos, pEndPos, pSegmentInfo.StartPosition) : 0); meshRect.UvBottom = (UseTrackUv ? Mathf.InverseLerp(pStartPos, pEndPos, pSegmentInfo.EndPosition) : 1); Vector3 localPos = pSegmentMesh.transform.localPosition; localPos.x = (InsetLeft-InsetRight)/2; localPos.y = (pSegmentInfo.StartPosition+pSegmentInfo.EndPosition)/2; pSegmentMesh.transform.localPosition = localPos; } /*--------------------------------------------------------------------------------------------*/ protected override void ActivateFillMesh(HoverMesh pSegmentMesh) { HoverShapeRect meshShapeRect = pSegmentMesh.GetComponent<HoverShapeRect>(); pSegmentMesh.Controllers.Set(SettingsControllerMap.GameObjectActiveSelf, this); RendererUtil.SetActiveWithUpdate(pSegmentMesh, (meshShapeRect.SizeY > 0)); } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ protected override void UpdateTickMeshes() { HoverShapeRect shapeRect = gameObject.GetComponent<HoverShapeRect>(); vTickSizeX = Mathf.Max(0, shapeRect.SizeX-InsetLeft-InsetRight)*TickRelativeSizeX; base.UpdateTickMeshes(); } /*--------------------------------------------------------------------------------------------*/ protected override void UpdateTickMesh(HoverMesh pTickMesh, SliderUtil.SegmentInfo pTickInfo) { HoverShapeRect meshShapeRect = pTickMesh.GetComponent<HoverShapeRect>(); pTickMesh.Controllers.Set(SettingsControllerMap.GameObjectActiveSelf, this); pTickMesh.Controllers.Set(SettingsControllerMap.TransformLocalPosition+".x", this); pTickMesh.Controllers.Set(SettingsControllerMap.TransformLocalPosition+".y", this); meshShapeRect.Controllers.Set(HoverShapeRect.SizeXName, this); meshShapeRect.Controllers.Set(HoverShapeRect.SizeYName, this); meshShapeRect.SizeX = vTickSizeX; meshShapeRect.SizeY = pTickInfo.EndPosition-pTickInfo.StartPosition; Vector3 localPos = pTickMesh.transform.localPosition; localPos.x = (InsetLeft-InsetRight)/2; localPos.y = (pTickInfo.StartPosition+pTickInfo.EndPosition)/2; pTickMesh.transform.localPosition = localPos; RendererUtil.SetActiveWithUpdate(pTickMesh, !pTickInfo.IsHidden); } } } <file_sep>/Assets/Hover/Core/Scripts/Layouts/Rect/HoverLayoutRectRow.cs using Hover.Core.Utils; using UnityEngine; namespace Hover.Core.Layouts.Rect { /*================================================================================================*/ public class HoverLayoutRectRow : HoverLayoutRectGroup, ILayoutableRect { public const string SizeXName = "SizeX"; public const string SizeYName = "SizeY"; public enum ArrangementType { LeftToRight, RightToLeft, TopToBottom, BottomToTop } [DisableWhenControlled(DisplaySpecials=true)] public ArrangementType Arrangement = ArrangementType.LeftToRight; [DisableWhenControlled(RangeMin=0)] public float SizeX = 0.4f; [DisableWhenControlled(RangeMin=0)] public float SizeY = 0.08f; public HoverLayoutRectPaddingSettings Padding = new HoverLayoutRectPaddingSettings(); [DisableWhenControlled] public AnchorType Anchor = AnchorType.MiddleCenter; //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public override void TreeUpdate() { base.TreeUpdate(); Padding.ClampValues(this); UpdateLayoutWithFixedSize(); } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public void SetRectLayout(float pSizeX, float pSizeY, ISettingsController pController) { Controllers.Set(SizeXName, pController); Controllers.Set(SizeYName, pController); SizeX = pSizeX; SizeY = pSizeY; } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public bool IsHorizontal { get { return (Arrangement == ArrangementType.LeftToRight || Arrangement == ArrangementType.RightToLeft); } } /*--------------------------------------------------------------------------------------------*/ public bool IsReversed { get { return (Arrangement == ArrangementType.RightToLeft || Arrangement == ArrangementType.TopToBottom); } } /*--------------------------------------------------------------------------------------------*/ private void UpdateLayoutWithFixedSize() { int itemCount = vChildItems.Count; if ( itemCount == 0 ) { return; } bool isHoriz = IsHorizontal; bool isRev = IsReversed; Vector2 anchorPos = LayoutUtil.GetRelativeAnchorPosition(Anchor); float anchorStartX = anchorPos.x*SizeX; float anchorStartY = anchorPos.y*SizeY; float horizOuterPad = Padding.Left+Padding.Right; float vertOuterPad = Padding.Top+Padding.Bottom; float betweenSumPad = Padding.Between*(itemCount-1); float relSumX = 0; float relSumY = 0; float elemAvailSizeX; float elemAvailSizeY; float cellAvailSizeX; float cellAvailSizeY; if ( isHoriz ) { elemAvailSizeX = SizeX-horizOuterPad-betweenSumPad; elemAvailSizeY = SizeY-vertOuterPad; cellAvailSizeX = SizeX-horizOuterPad; cellAvailSizeY = elemAvailSizeY; } else { elemAvailSizeX = SizeX-horizOuterPad; elemAvailSizeY = SizeY-vertOuterPad-betweenSumPad; cellAvailSizeX = elemAvailSizeX; cellAvailSizeY = SizeY-vertOuterPad; } for ( int i = 0 ; i < itemCount ; i++ ) { HoverLayoutRectGroupChild item = vChildItems[i]; relSumX += item.RelativeSizeX; relSumY += item.RelativeSizeY; } float posX = anchorStartX - (Padding.Right-Padding.Left)/2 - (isHoriz ? cellAvailSizeX/2 : 0); float posY = anchorStartY - (Padding.Top-Padding.Bottom)/2 - (isHoriz ? 0 : cellAvailSizeY/2); for ( int i = 0 ; i < itemCount ; i++ ) { int childI = (isRev ? itemCount-i-1 : i); HoverLayoutRectGroupChild item = vChildItems[childI]; ILayoutableRect elem = item.Elem; Vector3 localPos = elem.transform.localPosition; float elemRelSizeX = elemAvailSizeX*item.RelativeSizeX/(isHoriz ? relSumX : 1); float elemRelSizeY = elemAvailSizeY*item.RelativeSizeY/(isHoriz ? 1 : relSumY); localPos.x = posX+(isHoriz ? elemRelSizeX/2 : 0)+ elemRelSizeX*item.RelativePositionOffsetX; localPos.y = posY+(isHoriz ? 0 : elemRelSizeY/2)+ elemRelSizeY*item.RelativePositionOffsetY; posX += (isHoriz ? elemRelSizeX+Padding.Between : 0); posY += (isHoriz ? 0 : elemRelSizeY+Padding.Between); elem.Controllers.Set( SettingsControllerMap.SpecialPrefix+"Transform.localPosition.x", this); elem.Controllers.Set( SettingsControllerMap.SpecialPrefix+"Transform.localPosition.y", this); elem.SetRectLayout(elemRelSizeX, elemRelSizeY, this); elem.transform.localPosition = localPos; } } } } <file_sep>/Assets/LeapMotion/Modules/GraphicRenderer/Scripts/Utility/LeapGraphicTagAttribute.cs /****************************************************************************** * Copyright (C) Leap Motion, Inc. 2011-2018. * * Leap Motion proprietary and confidential. * * * * Use subject to the terms of the Leap Motion SDK Agreement available at * * https://developer.leapmotion.com/sdk_agreement, or another agreement * * between Leap Motion and you, your company or other organization. * ******************************************************************************/ using System; using System.Linq; using System.Collections.Generic; namespace Leap.Unity.GraphicalRenderer { [AttributeUsage(AttributeTargets.Class, AllowMultiple = false)] public class LeapGraphicTagAttribute : Attribute { private static Dictionary<Type, LeapGraphicTagAttribute> _tagCache = new Dictionary<Type, LeapGraphicTagAttribute>(); private static Dictionary<string, Type> _stringTypeCache = new Dictionary<string, Type>(); public readonly string name; public readonly int order; public LeapGraphicTagAttribute(string name, int order = 0) { this.name = name; this.order = order; } public static string GetTagName(Type type) { var tag = GetTag(type); return tag == null ? type.Name : tag.name; } public static string GetTagName(string typeName) { var tag = GetTag(typeName); return tag == null ? typeName : tag.name; } public static LeapGraphicTagAttribute GetTag(Type type) { LeapGraphicTagAttribute tag; if (!_tagCache.TryGetValue(type, out tag)) { object[] attributes = type.GetCustomAttributes(typeof(LeapGraphicTagAttribute), inherit: true); if (attributes.Length == 1) { tag = attributes[0] as LeapGraphicTagAttribute; } _tagCache[type] = tag; } return tag; } public static LeapGraphicTagAttribute GetTag(string typeName) { Type type; if (!_stringTypeCache.TryGetValue(typeName, out type)) { type = typeof(LeapGraphicTagAttribute).Assembly.GetTypes().FirstOrDefault(t => t.Name == typeName); _stringTypeCache[typeName] = type; } if (type == null) { return null; } else { return GetTag(type); } } } } <file_sep>/Assets/Hover/Core/Scripts/Cursors/ICursorDataForInput.cs using UnityEngine; namespace Hover.Core.Cursors { /*================================================================================================*/ public interface ICursorDataForInput : ICursorData { GameObject gameObject { get; } Transform transform { get; } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ void SetIsRaycast(bool pIsRaycast); /*--------------------------------------------------------------------------------------------*/ void SetRaycastLocalDirection(Vector3 pRaycastLocalDirection); /*--------------------------------------------------------------------------------------------*/ void SetCapability(CursorCapabilityType pCapability); /*--------------------------------------------------------------------------------------------*/ void SetSize(float pSize); /*--------------------------------------------------------------------------------------------*/ void SetTriggerStrength(float pTriggerStrength); /*--------------------------------------------------------------------------------------------*/ void SetWorldPosition(Vector3 pWorldPosition); /*--------------------------------------------------------------------------------------------*/ void SetWorldRotation(Quaternion pWorldRotation); /*--------------------------------------------------------------------------------------------*/ void SetIdle(ICursorIdle pIdle); //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ void SetUsedByInput(bool pIsUsed); /*--------------------------------------------------------------------------------------------*/ void ActivateIfUsedByInput(); } } <file_sep>/Assets/Hover/Core/Scripts/Utils/HoverInputMissing.cs using UnityEngine; namespace Hover.Core.Utils { /*================================================================================================*/ [ExecuteInEditMode] public abstract class HoverInputMissing : MonoBehaviour { public abstract string ModuleName { get; } public abstract string RequiredSymbol { get; } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public void Start() { Debug.LogError("The '"+ModuleName+"' input module requires the '"+RequiredSymbol+"' "+ "symbol to be defined.\nAdd it to the 'Scripting Define Symbols' input "+ "in the Unity 'Player' settings.", this); } } } <file_sep>/Assets/Hover/Core/Scripts/Renderers/HoverFill.cs using Hover.Core.Renderers.Shapes; using Hover.Core.Utils; using UnityEngine; namespace Hover.Core.Renderers { /*================================================================================================*/ [ExecuteInEditMode] [RequireComponent(typeof(TreeUpdater))] [RequireComponent(typeof(HoverShape))] public abstract class HoverFill : MonoBehaviour, ITreeUpdateable, ISettingsController { public ISettingsControllerMap Controllers { get; private set; } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ protected HoverFill() { Controllers = new SettingsControllerMap(); } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public abstract int GetChildMeshCount(); /*--------------------------------------------------------------------------------------------*/ public abstract HoverMesh GetChildMesh(int pIndex); /*--------------------------------------------------------------------------------------------*/ public HoverShape GetShape() { return gameObject.GetComponent<HoverShape>(); } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public virtual void Start() { //do nothing... } /*--------------------------------------------------------------------------------------------*/ public virtual void TreeUpdate() { Controllers.TryExpireControllers(); } } } <file_sep>/Assets/LeapMotion/Modules/GraphicRenderer/Scripts/Editor/EditorPickingMeshRebuilder.cs /****************************************************************************** * Copyright (C) Leap Motion, Inc. 2011-2018. * * Leap Motion proprietary and confidential. * * * * Use subject to the terms of the Leap Motion SDK Agreement available at * * https://developer.leapmotion.com/sdk_agreement, or another agreement * * between Leap Motion and you, your company or other organization. * ******************************************************************************/ using UnityEngine; using UnityEditor; namespace Leap.Unity.GraphicalRenderer { public static class EditorPickingMeshRebuilder { [InitializeOnLoadMethod] private static void initManager() { SceneView.onSceneGUIDelegate += onSceneGui; } private static void onSceneGui(SceneView view) { if (Event.current.type != EventType.MouseDown) { return; } foreach (var graphicRenderer in Object.FindObjectsOfType<LeapGraphicRenderer>()) { graphicRenderer.editor.RebuildEditorPickingMeshes(); } } } } <file_sep>/Assets/Hover/Core/Scripts/Items/Managers/HoverItemsStickyManager.cs using System; using System.Collections.Generic; using Hover.Core.Cursors; using Hover.Core.Items.Types; using Hover.Core.Renderers; using UnityEngine; namespace Hover.Core.Items.Managers { /*================================================================================================*/ [RequireComponent(typeof(HoverItemsManager))] public class HoverItemsStickyManager : MonoBehaviour { public HoverCursorDataProvider CursorDataProvider; private List<HoverItemData> vItemDatas; //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public void Awake() { if ( CursorDataProvider == null ) { CursorDataProvider = FindObjectOfType<HoverCursorDataProvider>(); } if ( CursorDataProvider == null ) { throw new ArgumentNullException("CursorDataProvider"); } vItemDatas = new List<HoverItemData>(); } /*--------------------------------------------------------------------------------------------*/ public void Update() { GetComponent<HoverItemsManager>().FillListWithExistingItemComponents(vItemDatas); ClearCursorLists(); FillCursorLists(); } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ private void ClearCursorLists() { List<ICursorData> cursors = CursorDataProvider.Cursors; int cursorCount = cursors.Count; for ( int ci = 0 ; ci < cursorCount ; ci++ ) { cursors[ci].ActiveStickySelections.Clear(); } } /*--------------------------------------------------------------------------------------------*/ private void FillCursorLists() { for ( int i = 0 ; i < vItemDatas.Count ; i++ ) { HoverItemData data = vItemDatas[i]; IItemDataSelectable selData = (data as IItemDataSelectable); if ( selData == null || !selData.IsStickySelected || !selData.AllowIdleDeselection ) { continue; } HoverItemHighlightState highState = data.GetComponent<HoverItemHighlightState>(); if ( highState.NearestHighlight == null ) { continue; } ICursorData cursorData = highState.NearestHighlight.Value.Cursor; if ( cursorData.Idle.Progress >= 1 ) { selData.DeselectStickySelections(); continue; } HoverItemSelectionState selState = data.GetComponent<HoverItemSelectionState>(); HoverRenderer rend = data.GetComponent<HoverItemRendererUpdater>().ActiveRenderer; var info = new StickySelectionInfo { ItemWorldPosition = rend.GetCenterWorldPosition(), SelectionProgress = selState.SelectionProgress }; cursorData.ActiveStickySelections.Add(info); } } } } <file_sep>/Assets/LeapMotion/Core/Plugins/LeapCSharp/PointMapping.cs /****************************************************************************** * Copyright (C) Leap Motion, Inc. 2011-2018. * * Leap Motion proprietary and confidential. * * * * Use subject to the terms of the Leap Motion SDK Agreement available at * * https://developer.leapmotion.com/sdk_agreement, or another agreement * * between Leap Motion and you, your company or other organization. * ******************************************************************************/ namespace Leap { public struct PointMapping { public long frameId; public long timestamp; public Vector[] points; public uint[] ids; } } <file_sep>/Assets/Hover/Editor/Items/Managers/HoverItemHighlightStateEditor.cs using Hover.Core.Items.Managers; using UnityEditor; using UnityEngine; namespace Hover.Editor.Items.Managers { /*================================================================================================*/ [CanEditMultipleObjects] [CustomEditor(typeof(HoverItemHighlightState))] public class HoverItemHighlightStateEditor : UnityEditor.Editor { private string vIsHighlightOpenKey; private GUIStyle vVertStyle; private HoverItemHighlightState vTarget; //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public void OnEnable() { vIsHighlightOpenKey = "IsHighlightOpen"+target.GetInstanceID(); vVertStyle = EditorUtil.GetVerticalSectionStyle(); } /*--------------------------------------------------------------------------------------------*/ public override bool RequiresConstantRepaint() { return EditorPrefs.GetBool(vIsHighlightOpenKey); } /*--------------------------------------------------------------------------------------------*/ public override void OnInspectorGUI() { vTarget = (HoverItemHighlightState)target; DrawDefaultInspector(); DrawHighlightInfo(); } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ private void DrawHighlightInfo() { bool isHighOpen = EditorGUILayout.Foldout(EditorPrefs.GetBool(vIsHighlightOpenKey), "Item Highlight Information"); EditorPrefs.SetBool(vIsHighlightOpenKey, isHighOpen); if ( !isHighOpen ) { return; } EditorGUILayout.BeginVertical(vVertStyle); if ( !Application.isPlaying ) { EditorGUILayout.HelpBox("At runtime, this section displays live information about "+ "the relationship between the item and each available cursor. You can access this "+ "information via code.", MessageType.Info); EditorGUILayout.EndVertical(); return; } GUI.enabled = false; EditorGUILayout.Toggle("Is Highlight Prevented", vTarget.IsHighlightPrevented); EditorGUILayout.Toggle("Is Highlight Prevented (Via Any Display)", vTarget.IsHighlightPreventedViaAnyDisplay()); EditorGUILayout.Toggle("Is Nearest Across All Items (For Any Cursor)", vTarget.IsNearestAcrossAllItemsForAnyCursor); EditorGUILayout.Slider("Maximum Highlight Progress", vTarget.MaxHighlightProgress, 0, 1); GUI.enabled = true; for ( int i = 0 ; i < vTarget.Highlights.Count ; i++ ) { HoverItemHighlightState.Highlight high = vTarget.Highlights[i]; EditorGUILayout.Separator(); EditorGUILayout.LabelField(high.Cursor.Type+" Cursor", EditorStyles.boldLabel); GUI.enabled = false; EditorGUILayout.ObjectField("Data", (Object)high.Cursor, high.Cursor.GetType(), true); EditorGUILayout.Vector3Field("Nearest Position", high.NearestWorldPos); EditorGUILayout.Toggle("Is Nearest Across All Items", high.IsNearestAcrossAllItems); EditorGUILayout.FloatField("Distance", high.Distance); EditorGUILayout.Slider("Progress", high.Progress, 0, 1); GUI.enabled = true; } EditorGUILayout.EndVertical(); } } } <file_sep>/Assets/Hover/RendererModules/Alpha/Scripts/HoverAlphaFillTabUpdater.cs using Hover.Core.Renderers; using Hover.Core.Renderers.CanvasElements; using Hover.Core.Renderers.Items.Buttons; using Hover.Core.Renderers.Shapes.Rect; using Hover.Core.Renderers.Utils; using Hover.Core.Utils; using UnityEngine; namespace Hover.RendererModules.Alpha { /*================================================================================================*/ [ExecuteInEditMode] [RequireComponent(typeof(HoverShapeRect))] [RequireComponent(typeof(HoverFillButton))] [RequireComponent(typeof(HoverFillButtonRectUpdater))] public class HoverAlphaFillTabUpdater : MonoBehaviour, ITreeUpdateable, ISettingsController { public HoverCanvasDataUpdater CanvasUpdater; public float TabOutward = 0.01f; public float TabThickness = 0.025f; public bool UseItemSelectionState = true; public bool ShowTabN = true; public bool ShowTabE = false; public bool ShowTabS = false; public bool ShowTabW = false; //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ public void Start() { //do nothing... } /*--------------------------------------------------------------------------------------------*/ public void TreeUpdate() { bool isSelected = ( !UseItemSelectionState || CanvasUpdater.IconType == HoverCanvasDataUpdater.IconPairType.RadioOn || CanvasUpdater.IconType == HoverCanvasDataUpdater.IconPairType.CheckboxOn ); HoverMesh.DisplayModeType dispMode = (isSelected ? HoverMesh.DisplayModeType.SliderFill : HoverMesh.DisplayModeType.Standard); //// HoverShapeRect shapeRect = GetComponent<HoverShapeRect>(); float minOutward = -Mathf.Min(shapeRect.SizeX, shapeRect.SizeY)/2; TabOutward = Mathf.Max(TabOutward, minOutward); TabThickness = Mathf.Max(TabThickness, 0); //// HoverFillButton hoverFill = GetComponent<HoverFillButton>(); int meshCount = hoverFill.GetChildMeshCount(); for ( int i = 0 ; i < meshCount ; i++ ) { UpdateChildMesh((HoverMeshRectHollowTab)hoverFill.GetChildMesh(i), dispMode); } if ( isSelected ) { hoverFill.Controllers.Set(HoverFillButton.ShowEdgeName, this); hoverFill.ShowEdge = true; RendererUtil.SetActiveWithUpdate(hoverFill.Edge, true); } } //////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ private void UpdateChildMesh(HoverMeshRectHollowTab pChildMesh, HoverMesh.DisplayModeType pDispMode) { float highProg = pChildMesh.GetComponent<HoverIndicator>().HighlightProgress; if ( pDispMode == HoverMesh.DisplayModeType.SliderFill ) { highProg = 1; } pChildMesh.Controllers.Set(HoverMesh.DisplayModeName, this); pChildMesh.Controllers.Set(HoverMeshRectHollowTab.TabOutwardName, this); pChildMesh.Controllers.Set(HoverMeshRectHollowTab.TabThicknessName, this); pChildMesh.Controllers.Set(HoverMeshRectHollowTab.ShowTabNName, this); pChildMesh.Controllers.Set(HoverMeshRectHollowTab.ShowTabEName, this); pChildMesh.Controllers.Set(HoverMeshRectHollowTab.ShowTabSName, this); pChildMesh.Controllers.Set(HoverMeshRectHollowTab.ShowTabWName, this); pChildMesh.DisplayMode = pDispMode; pChildMesh.TabOutward = TabOutward*highProg; pChildMesh.TabThickness = TabThickness; pChildMesh.ShowTabN = ShowTabN; pChildMesh.ShowTabE = ShowTabE; pChildMesh.ShowTabS = ShowTabS; pChildMesh.ShowTabW = ShowTabW; } } } <file_sep>/Assets/LeapMotion/Modules/GraphicRenderer/Scripts/Graphics/ProceduralMeshGraphics/Editor/LeapSlicedGraphicEditor.cs /****************************************************************************** * Copyright (C) Leap Motion, Inc. 2011-2018. * * Leap Motion proprietary and confidential. * * * * Use subject to the terms of the Leap Motion SDK Agreement available at * * https://developer.leapmotion.com/sdk_agreement, or another agreement * * between Leap Motion and you, your company or other organization. * ******************************************************************************/ using System; using System.Collections.Generic; using UnityEngine; using UnityEditor; using Leap.Unity.Query; namespace Leap.Unity.GraphicalRenderer { [CanEditMultipleObjects] [CustomEditor(typeof(LeapSlicedGraphic), editorForChildClasses: true)] public class LeapSlicedGraphicEditor : LeapGraphicEditorBase<LeapSlicedGraphic> { protected override void OnEnable() { base.OnEnable(); specifyCustomDrawer("_sourceDataIndex", drawSourceData); specifyCustomDrawer("_resolution_verts_per_meter", drawResolution); specifyCustomDecorator("_size", decorateSize); specifyCustomPostDecorator("_size", postDecorateSize); specifyCustomDrawer("_nineSliced", drawSize); } public override void OnInspectorGUI() { base.OnInspectorGUI(); serializedObject.ApplyModifiedProperties(); foreach (var target in targets) { if (!target.canNineSlice) { target.nineSliced = false; } } serializedObject.Update(); } private void drawSourceData(SerializedProperty property) { serializedObject.ApplyModifiedProperties(); var mainGroup = targets.Query(). Select(t => t.attachedGroup). FirstOrDefault(g => g != null); //If no element is connected to a gui, we can't draw anything if (mainGroup == null) { return; } //If any of the elements are not connected to the same gui, we can't draw anything if (targets.Query().Any(p => p.attachedGroup != mainGroup)) { return; } var features = new List<LeapGraphicFeatureBase>(); foreach (var feature in mainGroup.features) { if (feature is LeapTextureFeature || feature is LeapSpriteFeature) { features.Add(feature); } } if (features.Count == 1) { return; } int index = -1; foreach (var target in targets) { //If any of the targets have no source data, you can't use them if (target.sourceData == null) { return; } int dataIndex = features.IndexOf(target.sourceData.feature); if (index == -1) { index = dataIndex; } else if (index != dataIndex) { index = -1; break; } } string[] options = features.Query().Select(f => { if (f is LeapTextureFeature) { return (f as LeapTextureFeature).propertyName + " (Texture)"; } else { return (f as LeapSpriteFeature).propertyName + " (Sprite)"; } }).ToArray(); EditorGUI.BeginChangeCheck(); if (index == -1) { EditorGUI.showMixedValue = true; } int newIndex = EditorGUILayout.Popup("Data Source", index, options); EditorGUI.showMixedValue = false; if (EditorGUI.EndChangeCheck()) { foreach (var target in targets) { List<LeapFeatureData> data = target.featureData.Query().Where(f => f is LeapTextureData || f is LeapSpriteData).ToList(); Undo.RecordObject(target, "Setting source data"); target.sourceData = data[newIndex]; } } serializedObject.Update(); } private void drawResolution(SerializedProperty property) { LeapPanelOutlineGraphic.ResolutionType mainType = targets[0].resolutionType; bool allSameType = targets.Query().All(p => p.resolutionType == mainType); if (!allSameType) { return; } Rect rect = EditorGUILayout.GetControlRect(); GUIContent resolutionContent = new GUIContent("Resolution"); if (mainType == LeapPanelOutlineGraphic.ResolutionType.Vertices) { resolutionContent.tooltip = "How many vertices this panel should have in the x and y direction. These values ignore the edges (0 is a valid resolution)."; } else { resolutionContent.tooltip = "How many vertices this panel should spawn relative to the width and height of the panel. The panel will always have enough vertices to form a quad."; } EditorGUI.LabelField(rect, resolutionContent); rect.x += EditorGUIUtility.labelWidth - 2; rect.width -= EditorGUIUtility.labelWidth; rect.width *= 2.0f / 3.0f; float originalWidth = EditorGUIUtility.labelWidth; EditorGUIUtility.labelWidth = 14; Rect left = rect; left.width /= 2; Rect right = left; right.x += right.width + 1; if (mainType == LeapPanelOutlineGraphic.ResolutionType.Vertices) { SerializedProperty x = serializedObject.FindProperty("_resolution_vert_x"); SerializedProperty y = serializedObject.FindProperty("_resolution_vert_y"); x.intValue = EditorGUI.IntField(left, "X", x.intValue); y.intValue = EditorGUI.IntField(right, "Y", y.intValue); } else { Vector2 value = property.vector2Value; value.x = EditorGUI.FloatField(left, "X", value.x); value.y = EditorGUI.FloatField(right, "Y", value.y); property.vector2Value = value; } EditorGUIUtility.labelWidth = originalWidth; } private void decorateSize(SerializedProperty property) { EditorGUI.BeginDisabledGroup(targets.Query().Any((t) => t.GetComponent<RectTransform>() != null)); } private void postDecorateSize(SerializedProperty property) { EditorGUI.EndDisabledGroup(); } private void drawSize(SerializedProperty property) { using (new GUILayout.HorizontalScope()) { var canAllNineSlice = targets.Query().All(p => p.canNineSlice); using (new EditorGUI.DisabledGroupScope(!canAllNineSlice)) { EditorGUILayout.PropertyField(property); } if (targets.Length == 1) { var rectTransform = target.GetComponent<RectTransform>(); if (rectTransform == null) { if (GUILayout.Button("Add Rect Transform", GUILayout.MaxWidth(150))) { Vector2 initialSize = target.rect.size; rectTransform = target.gameObject.AddComponent<RectTransform>(); rectTransform.sizeDelta = initialSize; } } } } } } } <file_sep>/Assets/Hover/Core/Scripts/Items/Types/IItemDataSelector.cs namespace Hover.Core.Items.Types { /*================================================================================================*/ public interface IItemDataSelector : IItemDataSelectable { SelectorActionType Action { get; set; } } } <file_sep>/Assets/Hover/Core/Scripts/Items/Types/IItemDataText.cs namespace Hover.Core.Items.Types { /*================================================================================================*/ public interface IItemDataText : IItemData { } }
2507f65cdc1651a3162bea28f7b609cbd05f15aa
[ "Markdown", "C#", "Text" ]
243
C#
RealityVirtually2019/IronMan
e131a5f700908743c6450bbaab82abbb1752a5d3
431b4e79118dd8de684fb9744149a467fca56351
refs/heads/master
<repo_name>markerenberg/dash-project<file_sep>/README.md # Toronto Homelessness Dashboard Dashboard application for visualizing the state of homelessness in Toronto using 2019-2021 survey data\ https://homelessness-dash.herokuapp.com/ <file_sep>/app.py # -*- coding: utf-8 -*- # ======== Dash App ======== # import os import numpy as np import pandas as pd import plotly.express as px import plotly.graph_objects as go from plotly.subplots import make_subplots import dash import dash_core_components as dcc import dash_html_components as html import dash_bootstrap_components as dbc from dash.dependencies import Input, Output from datetime import datetime # Get data files #local_path = r'C:\Users\marke\Downloads\Datasets\Toronto_Homelessness' #local_path = r'/Users/merenberg/Desktop/dash-project/underlying_data' #local_path = r'/Users/markerenberg/Documents/Github/homelessness-dash/homelessness-dash/underlying_data' ROOT_DIR = os.path.dirname(os.path.abspath(__file__)) local_path = ROOT_DIR + r'/underlying_data' sna_export = pd.read_csv(local_path+r'/sna2018opendata_export.csv').fillna(0) sna_rows = pd.read_csv(local_path+r'/sna2018opendata_keyrows.csv') sna_cols = pd.read_csv(local_path+r'/sna2018opendata_keycolumns.csv') shelter_flow = pd.read_csv(local_path+r'/toronto-shelter-system-flow-jan22.csv') occupancy_21 = pd.read_csv(local_path+r'/Daily_shelter_occupancy_current.csv') occupancy_20 = pd.read_csv(local_path+r'/daily-shelter-occupancy-2020.csv') occupancy_19 = pd.read_csv(local_path+r'/daily-shelter-occupancy-2019.csv') ################### Shelter System Flow ################### flow = shelter_flow.rename(columns={'date(mmm-yy)':'date'}) month_dict = {1:"Jan",2:"Feb",3:"Mar",4:"Apr",5:"May",6:"Jun",7:"Jul",8:"Aug",9:"Sep",10:"Oct",11:"Nov",12:"Dec"} pop_groups = ['Chronic','Refugees','Families','Youth','Single Adult','Non-refugees'] inflow = ['returned_from_housing','returned_to_shelter','newly_identified'] outflow = ['moved_to_housing','no_recent_shelter_use'] age_cols = [col for col in flow.columns if 'age' in col and col != 'population_group_percentage'] gender_cols = [col for col in flow.columns if 'gender' in col] # Create month, year, datetime columns flow['month_name'] = flow['date'].apply(lambda st: st[:3]) flow['month'] = flow['month_name'].replace(dict((y,x) for x,y in month_dict.items()),inplace=False) flow['month_str']=['0'+str(x) if len(str(x))!=2 else str(x) for x in flow.month] # add leading zeroes flow['year'] = flow['date'].apply(lambda st: int(st[len(st)-2:])) flow['year_full'] = flow['year'].apply(lambda yr: yr+2000) flow['date_full'] = flow.apply(lambda row: '20'+str(row['year'])+row['month_str']+'01',axis=1) flow['datetime'] = flow['date_full'].apply(lambda x: pd.to_datetime(str(x), format='%Y%m%d')) date_cols = ['date','month','month_name','month_str','datetime','year','year_full'] month_dict_v1 = [{'label':x, 'value':x} for x in flow['month_name'].drop_duplicates()] year_dict = [{'label':x, 'value':x} for x in flow['year_full'].drop_duplicates()] popgroup_dict = [{'label':x, 'value':x} for x in flow['population_group'].drop_duplicates() if x != "All Population"] # Line graph of Actively Experiencing Homelessness actively = flow.loc[(flow['population_group'].isin(pop_groups+['All Population'])),\ date_cols+['actively_homeless','population_group']] active_fig = px.line(actively,x="datetime",y="actively_homeless",color='population_group',\ title='Population Actively Experiencing Homelessness In Toronto Shelters') active_fig.update_xaxes(title_text='Time',\ ticktext=actively['date'], tickvals=actively['datetime']) active_fig.update_yaxes(title_text='Population Count') active_fig.update_layout(title_x=0.5,showlegend=True, \ autosize=True, height=600, width=1400) active_fig.update_traces(mode='markers+lines') active_fig.update_traces(patch={"line": {"color": "black", "width": 6, "dash": 'dot'}}, selector={"legendgroup": "All Population"}) #plotly.offline.plot(active_fig) # Grouped bar plot to show inflow vs outflow all_population = flow.loc[flow['population_group']=='All Population',:] pop_melt = pd.melt(all_population,id_vars=date_cols+['population_group'],\ value_vars=inflow+outflow,var_name='housing_status',value_name='count') pop_melt['flow_type'] = ['Inflow' if flow_type in inflow else 'Outflow' for flow_type in pop_melt['housing_status']] flow_fig = px.bar(pop_melt,x="datetime",y="count",barmode="group",\ color="flow_type",title="Toronto Shelter System Inflow vs Outflow", hover_name="housing_status",hover_data=["housing_status","flow_type","count"],\ labels={'flow_type': "Flow Type", "housing_status": "Housing Status",\ "population_group":"Population Group","datetime": "Time", "count": "Population Count"},\ color_discrete_map={'Inflow':'red','Outflow':'green'}) flow_fig.update_layout(title_x=0.5,showlegend=True, \ autosize=True, height=600, width=1400) #plotly.offline.plot(flow_fig) # Line plot of shelter flow by age age_melt = pd.melt(all_population,id_vars=date_cols+['population_group'],\ value_vars=age_cols,var_name='age_group',value_name='count') age_fig = px.line(age_melt,x="datetime",y="count",color='age_group',\ title='Active Shelter Population By Age Demographic',\ labels={'age_group': "Age Demographic","datetime":"Time","count":"Population Count"}) age_fig.update_xaxes(title_text='Time',\ ticktext=age_melt['date'], tickvals=age_melt['datetime']) age_fig.update_yaxes(title_text='Population Count') age_fig.update_layout(title_x=0.5,showlegend=True, autosize=False,width=750,\ legend=dict(orientation="h",yanchor="bottom",xanchor="left",title='',\ y=1.02,x=0.01),\ margin=dict(l=100)) age_fig.update_traces(mode='markers+lines') #plotly.offline.plot(age_fig) # Line plot of shelter flow by gender gend_melt = pd.melt(all_population,id_vars=date_cols+['population_group'],\ value_vars=gender_cols,var_name='gender_group',value_name='count') gend_melt.loc[gend_melt['gender_group']=="gender_transgender,non-binary_or_two_spirit","gender_group"]="gender_transgender" gend_fig = px.line(gend_melt,x="datetime",y="count",color='gender_group',\ title='Active Shelter Population By Gender Demographic',\ labels={'gender_group': "Gender Demographic","datetime":"Time","count":"Population Count"}) gend_fig.update_xaxes(title_text='Time',\ ticktext=gend_melt['date'], tickvals=gend_melt['datetime']) gend_fig.update_yaxes(title_text='Population Count') gend_fig.update_layout(title_x=0.5,showlegend=True, autosize=False, \ legend=dict(orientation="h", yanchor="bottom", xanchor="left", title='', \ y=1.02, x=0.01),\ margin=dict(l=100)) gend_fig.update_traces(mode='markers+lines') #plotly.offline.plot(gend_fig) ################### Street Needs Assessment ################### sna_export = sna_export.merge(sna_rows.iloc[:,:3],on='SNA RESPONSE CATEGORY') # Pivot on question-response q_cols = ['SNA RESPONSE CATEGORY','QUESTION/CATEGORY DESCRIPTION','RESPONSE'] shelter_cols = ['OUTDOORS','CITY-ADMINISTERED SHELTERS','24-HR RESPITE','VAW SHELTERS'] dem_cols = ['SINGLE ADULTS','FAMILY','YOUTH'] total_cols = ['TOTAL'] response_types = {'Total':total_cols,'Location':shelter_cols,'Demographic':dem_cols} sna_melt = sna_export.melt(id_vars=q_cols,value_vars=shelter_cols+dem_cols+['TOTAL'], var_name='GROUP',value_name='COUNT') # Track count/average responses avg_cols = [cat for cat in sna_melt['SNA RESPONSE CATEGORY'].unique() if ('AVERAGE' in cat)] cnt_cols = [cat for cat in sna_melt['SNA RESPONSE CATEGORY'].unique() if ('COUNT' in cat)] # Q1: Total Survey Count q1 = sna_melt.loc[sna_melt['SNA RESPONSE CATEGORY']=="TOTALSURVEYS",] #q1_bar = px.bar(q1.loc[q1['GROUP'].isin(shelter_cols),].sort_values('COUNT',ascending=False), # x="GROUP",y="COUNT",text="COUNT",color="GROUP", # height=500, # labels=dict(GROUP="LOCATION")) #q1_bar.update_layout(showlegend=False) #plotly.offline.plot(q1_bar) # Q4: How much time (on avg) homeless in last 12 months q4 = sna_melt.loc[sna_melt['SNA RESPONSE CATEGORY']=="4_TIMEHOMELESSAVERAGE",] #q4_line = px.line(q4.loc[q4['GROUP'].isin(shelter_cols),], # x='GROUP',y='COUNT',text='COUNT') #plotly.offline.plot(q4_line) q1_dat = q1.loc[q1['GROUP'].isin(shelter_cols),].sort_values('COUNT',ascending=False) q1_sort_order = dict(zip(q1_dat['GROUP'],list(range(1,5)))) q4_dat = q4.loc[q4['GROUP'].isin(shelter_cols),] q4_dat = q4_dat.iloc[q4_dat['GROUP'].map(q1_sort_order).argsort()] q1_bar = make_subplots(specs=[[{"secondary_y": True}]]) q1_bar.add_trace(go.Bar(x=q1_dat['GROUP'],y=q1_dat['COUNT'],text=q1_dat['COUNT'], textposition='outside', #marker_color=dict(zip(q1_dat['GROUP'], plotly.colors.qualitative.Plotly[:len(q1_dat['GROUP'])])), name='Homeless Count'), secondary_y=False ) q1_bar.add_trace(go.Scatter(x=q4_dat['GROUP'],y=q4_dat['COUNT'],text=q4_dat['COUNT'], name='Avg Homeless Duration'), secondary_y=True) q1_bar.update_yaxes(title_text="Count", secondary_y=False,title_font={"size": 12}) q1_bar.update_yaxes(title_text="Duration (Days)", secondary_y=True,title_font={"size": 12}) q1_bar.update_layout(autosize=False,height=550,width=750,margin=dict(l=100), legend=dict(orientation='h',yanchor="bottom",xanchor="right", y=1.02,x=1) ) # Q2: People staying with you q2 = sna_melt.loc[sna_melt['QUESTION/CATEGORY DESCRIPTION']=="What family members are staying with you tonight?",] q2_pie = px.pie(q2.loc[(q2['RESPONSE'].notnull())&(q2['GROUP']=="TOTAL"),], height=500, values="COUNT",names="RESPONSE") #plotly.offline.plot(q2_pie) # Q6: What happened that caused you to lose your housing most recently? q6 = sna_melt.loc[(sna_melt['QUESTION/CATEGORY DESCRIPTION']=="What happened that caused you to lose your housing most recently?")\ &(sna_melt['RESPONSE'].notnull()) \ &(sna_melt['RESPONSE']!="Other"),] q6_bar = px.bar(q6.loc[q6['GROUP'].isin(shelter_cols),].sort_values(by="COUNT",ascending=False),\ x="RESPONSE", y="COUNT", color="GROUP", \ text='COUNT') q6_bar.update_traces(marker_color='darkorange') #plotly.offline.plot(q6_bar) # Question 7: Have you stayed in an emergency shelter in the past 12 months? q7 = sna_melt.loc[(sna_melt['QUESTION/CATEGORY DESCRIPTION']=="Have you stayed in an emergency shelter in the past 12 months?")&\ (~sna_melt['RESPONSE'].isin(["Don’t know","Decline to answer"]))&\ (sna_melt['RESPONSE'].notnull()),] q7_bar = px.bar(q7.loc[q7['GROUP'].isin(shelter_cols),],\ x="RESPONSE", y="COUNT", color="GROUP", \ title="Have you stayed in an emergency shelter in the past 12 months?",\ text='COUNT') #plotly.offline.plot(q7_bar) # Question 8: Did you stay overnight at any Winter Services this past winter? q8 = sna_melt.loc[(sna_melt['QUESTION/CATEGORY DESCRIPTION']=="Did you stay overnight at any of the following Winter Services this past winter?")\ &(~sna_melt['RESPONSE'].isin(["Don’t know","Decline to answer"]))\ &(sna_melt['RESPONSE'].notnull()),] q8_bar = px.bar(q8.loc[q8['GROUP'].isin(shelter_cols),],\ x="RESPONSE", y="COUNT", color="GROUP", \ title="Did you stay overnight at any Winter Services this past winter?",\ text='COUNT') #plotly.offline.plot(q8_bar) # Q19: Health conditions q19 = sna_melt.loc[(sna_melt['SNA RESPONSE CATEGORY'].str.contains("19_"))\ &(sna_melt['RESPONSE']=='Yes'),].drop("RESPONSE",axis=1) q19['RESPONSE'] = q19['QUESTION/CATEGORY DESCRIPTION'].str[66:] q19_bar = px.bar(q19.loc[q19['GROUP'].isin(shelter_cols),].sort_values(by='COUNT',ascending=False),\ x="RESPONSE", y="COUNT", color="GROUP",\ text='COUNT') q19_bar.update_traces(marker_color='sienna') # Question 22: What would help you personally find housing? q22 = sna_melt.loc[(sna_melt['QUESTION/CATEGORY DESCRIPTION']=="Please tell me which ones would help you personally find housing.")\ &(~sna_melt['RESPONSE'].isin(["Don't know","Decline to answer"]))\ &(sna_melt['RESPONSE'].notnull()),] q22_bar = px.bar(q22.loc[q22['GROUP'].isin(shelter_cols),],\ x="RESPONSE", y="COUNT", color="GROUP", \ title="What would help you personally find housing?",\ text='COUNT') q22_bar.update_traces(marker_color='crimson') #plotly.offline.plot(q22_bar) # Question 23: In the past 6 months, have you q23 = sna_melt.loc[(sna_melt['QUESTION/CATEGORY DESCRIPTION'].str.contains("In the past 6 months, have you"))\ &(sna_melt['RESPONSE']=='Yes'),].drop("RESPONSE",axis=1) q23['RESPONSE'] = q23['QUESTION/CATEGORY DESCRIPTION'].str[32:] q23_bar = px.bar(q23.loc[q23['GROUP'].isin(shelter_cols),].sort_values(by='COUNT',ascending=False),\ x="RESPONSE", y="COUNT", color="GROUP",\ text='COUNT') q23_bar.update_yaxes(title_text="Count", title_font={"size": 12}) q23_bar.update_layout(autosize=False,height=550,width=700,margin=dict(l=100),showlegend=False) q23_bar.update_traces(marker_color='forestgreen') #plotly.offline.plot(q23_bar) ################### Daily Shelter Occupancy ################### # Merge multiple years' data, align date formats date_col = "OCCUPANCY_DATE" occupancy_19 = occupancy_19.drop("_id",axis=1) occupancy_21 = occupancy_21.drop("_id",axis=1) occupancy_19['OCCUPANCY_DATETIME'] = occupancy_19[date_col].apply(lambda dt: datetime.strptime(dt.replace("T"," "),"%Y-%m-%d %H:%M:%S")) occupancy_21['OCCUPANCY_DATETIME'] = occupancy_21[date_col].apply(lambda dt: datetime.strptime(dt.replace("T"," "),"%Y-%m-%d")) occupancy_19[date_col] = occupancy_19['OCCUPANCY_DATETIME'].apply(lambda dt: dt.strftime("%m/%d/%Y")) occupancy_21[date_col] = occupancy_21['OCCUPANCY_DATETIME'].apply(lambda dt: dt.strftime("%m/%d/%Y")) # Make changes to match 2021 occupancy data with previous years occ_21_cols = {"LOCATION_NAME": "SHELTER_NAME", "LOCATION_ADDRESS": "SHELTER_ADDRESS", "LOCATION_POSTAL_CODE": "SHELTER_POSTAL_CODE", "LOCATION_CITY": "SHELTER_CITY", "LOCATION_PROVINCE": "SHELTER_PROVINCE"} occupancy_21 = occupancy_21.rename(columns=occ_21_cols) occupancy_21.loc[occupancy_21["SECTOR"]=="Mixed Adult","SECTOR"] = "Co-ed" occupancy_bed = occupancy_21[occupancy_21["CAPACITY_TYPE"]=="Bed Based Capacity"].reset_index(drop=True) occupancy_room = occupancy_21[occupancy_21["CAPACITY_TYPE"]=="Room Based Capacity"].reset_index(drop=True) occupancy_bed["OCCUPANCY"] = occupancy_bed["OCCUPIED_BEDS"].astype("int") occupancy_bed["CAPACITY"] = occupancy_bed["CAPACITY_ACTUAL_BED"].astype("int") occupancy_room["OCCUPANCY"] = occupancy_room["OCCUPIED_ROOMS"].astype("int") occupancy_room["CAPACITY"] = occupancy_room["CAPACITY_ACTUAL_ROOM"].astype("int") # Group by shelter, merge two types of shelter data occupancy_cols = ["OCCUPANCY_DATE","ORGANIZATION_NAME","SHELTER_NAME","SHELTER_ADDRESS", "SHELTER_CITY","SHELTER_PROVINCE","SHELTER_POSTAL_CODE","PROGRAM_NAME", "SECTOR"] occupancy_21 = pd.concat([occupancy_bed[occupancy_cols+["OCCUPANCY","CAPACITY"]],\ occupancy_room[occupancy_cols+["OCCUPANCY","CAPACITY"]]],\ axis=0,ignore_index=True,sort=False) # Merge all years' occupancy data occupancy = pd.concat([occupancy_19.drop(["FACILITY_NAME","OCCUPANCY_DATETIME"],axis=1), occupancy_20.drop("FACILITY_NAME",axis=1), occupancy_21],axis=0,ignore_index=True,sort=True) # Drop null names/postal codes occupancy = occupancy[(occupancy["SHELTER_NAME"].notnull())&\ (occupancy["SHELTER_POSTAL_CODE"].notnull())].reset_index(drop=True) #ssl._create_default_https_context = ssl._create_unverified_context #nomi = pgeocode.Nominatim('ca') post_col, city_col, address_col, province_col = 'SHELTER_POSTAL_CODE', 'SHELTER_CITY', 'SHELTER_ADDRESS', 'SHELTER_PROVINCE' loc_cols = [post_col,'SHELTER_NAME','LATITUDE','LONGITUDE'] month_dict = {1:"Jan",2:"Feb",3:"Mar",4:"Apr",5:"May",6:"Jun",7:"Jul",8:"Aug",9:"Sep",10:"Oct",11:"Nov",12:"Dec"} shelter_dict = [{'label':x, 'value':x} for x in occupancy['SHELTER_NAME'].drop_duplicates()] all_shelters = occupancy['SHELTER_NAME'].drop_duplicates().to_list() all_sectors = occupancy['SECTOR'].drop_duplicates().to_list() city_dict = [{'label':x, 'value':x} for x in occupancy['SHELTER_CITY'].drop_duplicates()] sector_dict = [{'label':x, 'value':x} for x in occupancy['SECTOR'].drop_duplicates()] # Remove dashes from postal data, impute spaces if missing occupancy_ = occupancy.copy() occupancy[post_col] = occupancy[post_col].apply(lambda x: x[:3] + " " + x[3:] if len(x)==6 else x) occupancy[post_col] = occupancy[post_col].apply(lambda x: x.replace("-"," ")) # Remove typos, remove "floor" notations occupancy_[address_col] = occupancy_[address_col].apply(lambda x: x.replace("Bathrust","Bathurst")) occupancy_[address_col] = occupancy_[address_col].apply(lambda x: x.replace(", 2nd floor","")) # Create full address using city and province occupancy_["FULL_ADDRESS"] = occupancy_[address_col] + ", " + occupancy_[city_col] + ", " + occupancy_[province_col] # Read in coordinates for each shelter's address occupancy_coords = pd.read_csv(local_path+r"/occupancy_coordinates.csv") # Merge back with occupancy data occupancy_ = occupancy_.merge(occupancy_coords,how='inner',on='FULL_ADDRESS') # Previous code for extracting lat/long from postal codes #unique_postal = occupancy[post_col].drop_duplicates().to_frame() #unique_postal['LATITUDE'] = unique_postal[post_col].apply(lambda x: nomi.query_postal_code(x)['latitude']) #unique_postal['LONGITUDE'] = unique_postal[post_col].apply(lambda x: nomi.query_postal_code(x)['longitude']) #occupancy_ = occupancy_.merge(unique_postal,how='inner',on='SHELTER_POSTAL_CODE') # Create month,year columns occupancy_['MONTH'] = occupancy_['OCCUPANCY_DATE'].apply(lambda x: int(x[:2])) occupancy_['MONTH_STR']=['0'+str(x) if len(str(x))!=2 else str(x) for x in occupancy_.MONTH] # add leading zeroes occupancy_['MONTH_NAME'] = occupancy_['MONTH'].replace(month_dict,inplace=False) occupancy_['YEAR'] = occupancy_['OCCUPANCY_DATE'].apply(lambda x: int(x[6:])) occupancy_['MONTH_YEAR'] = occupancy_.apply(lambda row: row['MONTH_NAME']+"-"+str(row['YEAR']),axis=1) occupancy_['MONTH_DATE'] = occupancy_.apply(lambda row: str(row['YEAR'])+row['MONTH_STR']+'01',axis=1) occ_month_cols = ["MONTH","MONTH_STR","MONTH_NAME","YEAR","MONTH_YEAR","MONTH_DATE"] # Group by date, take sum of occupancy/capacity occ_sums = occupancy_.groupby(["OCCUPANCY_DATE"]+loc_cols,as_index=False)\ .agg({'OCCUPANCY':'sum','CAPACITY':'sum'}) occ_sums['CAPACITY_PERC'] = occ_sums['OCCUPANCY']/occ_sums['CAPACITY']*100 occ_sums['WEIGHTED_CAP'] = occ_sums['CAPACITY_PERC']*occ_sums['CAPACITY'] # Group by location (postal) and take avg across month of occupancy map_dat = occ_sums.groupby(loc_cols,as_index=False)\ .agg({'OCCUPANCY':'mean','CAPACITY':'mean','CAPACITY_PERC':'mean','WEIGHTED_CAP':'mean'}) # Need to scale bubble size scale = map_dat['CAPACITY'].max() # SHELTER MAP PLOT shelter_map = go.Figure() mapbox_key = "<KEY>" shelter_map.add_trace(go.Scattermapbox( lat=map_dat['LATITUDE'], lon=map_dat['LONGITUDE'], mode='markers', marker=go.scattermapbox.Marker( size=map_dat['CAPACITY']/scale*100, color=map_dat['CAPACITY_PERC'], colorscale=[[0, 'rgb(255,230,230)'], [1, 'rgb(255,0,0)']], cmin=50, cmax=100, opacity=0.7 ), text="Shelter Name: " + map_dat['SHELTER_NAME'].astype(str)\ + "<br><b>Avg Capacity (%): " + map_dat['CAPACITY_PERC'].astype(str)\ + "</b><br>Avg Occupancy: " + map_dat['OCCUPANCY'].astype(str), hoverinfo='text', hoverlabel= dict(bgcolor='white',\ font=dict(color='black')) ) ) shelter_map.update_layout( title="Shelter Capacity in Greater Toronto Area (2019-2021)", autosize=True, height=600, width=1400, hovermode='closest', showlegend=False, mapbox=dict( accesstoken=mapbox_key, bearing=0, center=dict( lat=43.686820, lon=-79.393590 ), pitch=0, zoom=10, style='light' ), ) #plotly.offline.plot(shelter_map) # SHELTER TREND PLOTS sec_trend = occupancy_.groupby(occ_month_cols+['SECTOR'],as_index=False)\ .agg({'OCCUPANCY':'sum','CAPACITY':'sum'}) sec_trend['CAPACITY_PERC'] = sec_trend['OCCUPANCY']/sec_trend['CAPACITY']*100 sec_trend['WEIGHTED_CAP'] = sec_trend['CAPACITY_PERC']*sec_trend['CAPACITY'] sec_trend = sec_trend.sort_values(by='MONTH_DATE') sh_trend = occupancy_.groupby(occ_month_cols+loc_cols,as_index=False)\ .agg({'OCCUPANCY':'sum','CAPACITY':'sum'}) sh_trend['CAPACITY_PERC'] = sh_trend['OCCUPANCY']/sh_trend['CAPACITY']*100 sh_trend['WEIGHTED_CAP'] = sh_trend['CAPACITY_PERC']*sh_trend['CAPACITY'] sh_trend = sh_trend.sort_values(by='MONTH_DATE') sec_trend_fig = px.line(sec_trend,x="MONTH_DATE",y='CAPACITY_PERC',color='SECTOR', line_shape='spline', range_y=[np.min(sec_trend['CAPACITY_PERC'])-5,np.max(sec_trend['CAPACITY_PERC'])+5], title='Shelter Capacity By Sector', render_mode="svg") sec_trend_fig.update_xaxes(title_text='Time', ticktext=sec_trend['MONTH_YEAR'], tickvals=sec_trend['MONTH_DATE']) sec_trend_fig.update_yaxes(title_text='Shelter Capacity (%)') sec_trend_fig.update_layout(title_x=0.5,showlegend=False, legend=dict( yanchor="top",y=0.99, xanchor="left",x=0.01)) #plotly.offline.plot(sec_trend_fig) sh_trend_fig = px.line(sh_trend,x='MONTH_DATE',y='CAPACITY_PERC',color='SHELTER_NAME', line_shape='spline', range_y=[np.min(sh_trend['CAPACITY_PERC'])-5,np.max(sh_trend['CAPACITY_PERC'])+5], title='Shelter Capacity By Shelter', render_mode="svg") sh_trend_fig.update_xaxes(title_text='Time', ticktext=sh_trend['MONTH_YEAR'], tickvals=sh_trend['MONTH_DATE']) sec_trend_fig.update_yaxes(title_text='Shelter Capacity (%)') sh_trend_fig.update_layout(title_x=0.5,showlegend=False) #plotly.offline.plot(sh_trend_fig) # Helper function to find shelter name using lat/lon def find_shelter(point): ''' takes in JSON dump from map selectedData and returns shelter name :param point: dictionary of plotly map point, including lat/lon coordinates :return: string shelter_name ''' text = point['text'] return text[(text.find("Shelter Name: ")+len("Shelter Name: ")):text.find("<br>")] ############################################################## # APP LAYOUT # ############################################################## external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css'] colors = { 'background': '#ffffff', 'text': '#404040' } #sna_bar.update_layout( # plot_bgcolor=colors['background'], # paper_bgcolor=colors['background'], # font_color=colors['text'] #) app = dash.Dash(__name__, external_stylesheets=[dbc.themes.LITERA]) #app = dash.Dash(__name__, external_stylesheets=['https://codepen.io/chriddyp/pen/bWLwgP.css']) server = app.server app.layout = html.Div(children=[ html.H1(children='Toronto Homelessness Dashboard', style={'textAlign': 'center','color': colors['text']} ), html.Br(), html.H6(children='This dashboard is a visual investigation into the current state of homelessness in the city of Toronto.', style={'textAlign': 'left','color': colors['text'],'font-weight': 'bold','text-indent': '20px'}), html.P(children='The data represented has been gathered from three sources:', style={'textAlign': 'left','color': colors['text'],'text-indent': '20px'}), html.P(children='1. Shelter System Flow: Data on who is entering and leaving the Toronto shelter system.', style={'textAlign': 'left','color': colors['text'],'text-indent': '40px'}), html.P(children='2. Daily Shelter Usage: Data on occupancy and capacity of the Toronto shelter system.', style={'textAlign': 'left','color': colors['text'],'text-indent': '40px'}), html.P(children='3. Street Needs Assessments: Point-in-time count and survey data on who is experiencing homelessness in Toronto.', style={'textAlign': 'left','color': colors['text'],'text-indent': '40px'}), html.P(children="All data has been collected by the City of Toronto, and can be found at the Housing & Homelessness Research & Reports section of the City's webpage.", style={'textAlign': 'left','color': colors['text'],'text-indent':'20px'}), html.Br(), html.H5(children='Toronto Shelter System Flow Data', style={'textAlign': 'left', 'color': colors['text'], 'font-weight': 'bold', 'text-indent': '20px'} ), html.H6( "Public data on the people experiencing homelessness who are entering/leaving the shelter system", style={'textAlign': 'left', 'text-indent': '20px'}), html.Div([ html.Div(["Filter By Year:", dcc.Checklist(id="flow_year",options=year_dict,value=[yr for yr in flow['year_full'].drop_duplicates()])], style={'textAlign':'left','float':'left','text-indent':'40px','display': 'inline-block','width':'49%'}), html.Div(["Filter By Month:", dcc.RangeSlider(id="flow_month",min=1,max=12,step=1,value=[1,12],marks=month_dict)],\ style={'textAlign':'left','float':'left','display': 'inline-block','width':'49%'})], style={'backgroundColor': 'rgb(250, 250, 250)'}, className="row"), html.Div([html.Div(["Filter By Population Group:",\ dcc.Checklist(id="flow_group",options=popgroup_dict,\ value=[sh for sh in flow['population_group'].drop_duplicates() if sh != 'All Population'])], style={'textAlign':'left','text-indent':'40px','display':'inline-block','width':'80%'}), html.H6("",style={'textAlign':'left','display':'inline-block','width':'20%'})], style={'borderBottom': 'thin lightgrey solid', 'backgroundColor': 'rgb(250, 250, 250)'}, className="row"), html.Br(), html.Div([dcc.Graph(id="active_line", figure=active_fig)], style={'textAlign': 'center'}), html.Div([dcc.Graph(id="flowtype_chart", figure=flow_fig)], style={'textAlign': 'center'}), html.Br(), html.Div([ html.Div([dcc.Graph(id="age_line",figure=age_fig)], style={'textAlign':'center','width':'52%','height':'600','display': 'inline-block'}), html.Div([dcc.Graph(id="gender_line",figure=gend_fig)], style={'textAlign':'center','width':'48%','height':'600', 'display': 'inline-block'}) ],className="row"), html.Br(), html.H5(children='Toronto Shelter Occupancy Data', style={'textAlign': 'left', 'color': colors['text'], 'font-weight': 'bold', 'text-indent': '20px'} ), html.H6( "Public data on the monthly occupancy and capacity of Toronto’s shelter system", style={'textAlign': 'left', 'text-indent': '20px'}), html.Br(), html.Div([ html.Div(["Filter By Year:", dcc.Checklist(id="shelter_year",options=[{'label':x, 'value':x} for x in occupancy_['YEAR'].drop_duplicates()],\ value=[yr for yr in occupancy_['YEAR'].drop_duplicates()])], style={'textAlign':'left','float':'left','text-indent':'40px','display': 'inline-block','width':'49%'}), html.Div(["Filter By Month:", dcc.RangeSlider(id="shelter_month",min=1,max=12,step=1,value=[1,12],marks=month_dict)],\ style={'textAlign':'left','float':'left','display': 'inline-block','width':'49%'})], style={'backgroundColor': 'rgb(250, 250, 250)'}, className="row"), html.Div([html.Div(["Filter By Sector:", dcc.Checklist(id="sector",options=sector_dict,value=[sh for sh in occupancy['SECTOR'].drop_duplicates()])], style={'textAlign':'left','float':'right','text-indent':'40px','display': 'inline-block','width':'49%'}), html.H6("",style={'textAlign':'left','display':'inline-block','width':'49%'})], style={'borderBottom': 'thin lightgrey solid', 'backgroundColor': 'rgb(250, 250, 250)'}, className="row"), html.Div([dcc.Graph(id="shelter_map",figure=shelter_map)], style={'textAlign':'center'}), # Test Pre just to see selection output #html.Div([ # dcc.Markdown("Selection Data"), # html.Pre(id='selected-data'), # html.Pre(id='selected-data-2'), # html.Pre(id='selected-data-3') #]), html.Div([ html.Div([dcc.Graph(id="sector_trend",figure=sec_trend_fig)], style={'textAlign':'center','width':'50%','height':'400','text-indent':'20px','display': 'inline-block'}), html.Div([dcc.Graph(id="shelter_trend",figure=sh_trend_fig)], style={'textAlign':'center','width':'50%','height':'400','text-indent':'10px', 'display': 'inline-block'}) ],className="row"), html.Br(), html.H5(children='Street Needs Assessment: 2018 Results', style={'textAlign': 'left', 'color': colors['text'], 'font-weight': 'bold', 'text-indent':'20px'} ), html.H6("The Streets Needs Assessment is a City-wide point-in-time count and survey of people experiencing homelessness in Toronto.", style={'textAlign':'left','text-indent':'20px'}), html.Br(), html.Div([ html.Div(["On an arbitrary night in 2018, how many people were homeless in Toronto?", dcc.Graph(id="q1_bar",figure=q1_bar)], style={'textAlign':'center','width':'48%', 'display': 'inline-block'}), html.Div(["Of those experiencing homelessness, what family members are staying with them??", dcc.Graph(id="q2_pie",figure=q2_pie)], style={'textAlign':'center','width':'48%', 'display': 'inline-block'}) ],className="row"), html.Br(), html.Div([ html.Div(["In the past 6 months, have you:", dcc.Graph(id="q23_bar",figure=q23_bar)], style={'textAlign':'center','width':'48%', 'display': 'inline-block'}), html.Div(["Do you identify as having any of the following health conditions:", dcc.Graph(id="q19_bar",figure=q19_bar)], style={'textAlign':'center','width':'48%', 'display': 'inline-block'}) ],className="row"), html.Br(), html.Div(["What happened that caused you to lose your housing most recently?", dcc.Graph(id="q6_bar",figure=q6_bar) ], style={'textAlign':'center'} ), html.Br(), html.Div(["What would help you personally find housing?", dcc.Graph(id="q22_bar",figure=q22_bar) ], style={'textAlign':'center'} ) ]) @app.callback( Output("active_line","figure"), Output("flowtype_chart","figure"), Output("age_line", "figure"), Output("gender_line", "figure"), Input("flow_year","value"), Input("flow_month","value"), Input("flow_group","value"), ) def update_flow_graphs(flow_year,flow_month,flow_group): years_to_use = [2020,2021] if flow_year == None else flow_year months_to_use = list(month_dict.keys()) if flow_month == None else list(month_dict.keys())[(flow_month[0] - 1):flow_month[-1]] selected_groups = ["All Population"] if flow_group == None else flow_group active_chart_groups = pop_groups+["All Population"] if flow_group == None else flow_group+["All Population"] # Line graph of Actively Experiencing Homelessness actively = flow.loc[(flow['population_group'].isin(active_chart_groups))& \ (flow['month'].isin(months_to_use))& \ (flow['year_full'].isin(years_to_use)), \ date_cols + ['actively_homeless', 'population_group']] active_fig = px.line(actively, x="datetime", y="actively_homeless", color='population_group', \ title='Population Actively Experiencing Homelessness In Toronto Shelters') active_fig.update_xaxes(title_text='Time', \ ticktext=actively['date'], tickvals=actively['datetime']) active_fig.update_yaxes(title_text='Population Count') active_fig.update_layout(title_x=0.5, showlegend=True, \ autosize=True, height=600, width=1400) active_fig.update_traces(mode='markers+lines', patch={"line": {"color": "black", "width": 6, "dash": 'dot'}}, selector={"legendgroup": "All Population"}) # Grouped bar plot to show inflow vs outflow all_population = flow.loc[(flow['population_group'].isin(selected_groups))&\ (flow['month'].isin(months_to_use))&\ (flow['year_full'].isin(years_to_use)), :] pop_melt = pd.melt(all_population, id_vars=date_cols + ['population_group'], \ value_vars=inflow + outflow, var_name='housing_status', value_name='count') pop_melt['flow_type'] = ['Inflow' if flow_type in inflow else 'Outflow' for flow_type in pop_melt['housing_status']] flow_fig = px.bar(pop_melt, x="datetime", y="count", barmode="group", \ color="flow_type", title="Toronto Shelter System Inflow vs Outflow", hover_name="housing_status", hover_data=["housing_status","population_group","flow_type","count"], \ labels={'flow_type': "Flow Type", "housing_status": "Housing Status",\ "population_group":"Population Group","datetime": "Time", "count": "Population Count"}, \ color_discrete_map={'Inflow': 'red', 'Outflow': 'green'}) flow_fig.update_layout(title_x=0.5, showlegend=True, \ autosize=True, height=600, width=1400) # Line plot of shelter flow by age age_grouped = all_population.groupby(date_cols,as_index=False)\ .agg({col:"sum" for col in age_cols})\ .sort_values(by="datetime") age_melt = pd.melt(age_grouped, id_vars=date_cols, \ value_vars=age_cols, var_name='age_group', value_name='count') age_fig = px.line(age_melt, x="datetime", y="count", color='age_group', \ title='Active Shelter Population By Age Demographic', \ labels={'age_group': "Age Demographic", "datetime": "Time", "count": "Population Count"}) age_fig.update_xaxes(title_text='Time', \ ticktext=age_melt['date'], tickvals=age_melt['datetime']) age_fig.update_yaxes(title_text='Population Count') age_fig.update_layout(title_x=0.5, showlegend=True, autosize=False, width=750, \ legend=dict(orientation="h", yanchor="bottom", xanchor="left", title='', \ y=1.02, x=0.01), \ margin=dict(l=100)) age_fig.update_traces(mode='markers+lines') # Line plot of shelter flow by gender gend_grouped = all_population.groupby(date_cols, as_index=False) \ .agg({col: "sum" for col in gender_cols}) \ .sort_values(by="datetime") gend_melt = pd.melt(gend_grouped, id_vars=date_cols, \ value_vars=gender_cols, var_name='gender_group', value_name='count') gend_melt.loc[gend_melt[ 'gender_group'] == "gender_transgender,non-binary_or_two_spirit", "gender_group"] = "gender_transgender" gend_fig = px.line(gend_melt, x="datetime", y="count", color='gender_group', \ title='Active Shelter Population By Gender Demographic', \ labels={'gender_group': "Gender Demographic", "datetime": "Time", "count": "Population Count"}) gend_fig.update_xaxes(title_text='Time', \ ticktext=gend_melt['date'], tickvals=gend_melt['datetime']) gend_fig.update_yaxes(title_text='Population Count') gend_fig.update_layout(title_x=0.5, showlegend=True, autosize=False, \ legend=dict(orientation="h", yanchor="bottom", xanchor="left", title='', \ y=1.02, x=0.01), \ margin=dict(l=100)) gend_fig.update_traces(mode='markers+lines') return active_fig, flow_fig, age_fig, gend_fig @app.callback( Output("q2_pie","figure"), Output("q23_bar","figure"), Output("q19_bar","figure"), Output("q6_bar","figure"), Output("q22_bar","figure"), Input("q1_bar","clickData"), Input("q1_bar","selectedData"), ) def update_street_needs(clickData,selectedData): # STREET NEEDS click_type = ["TOTAL"] if clickData==None else [clickData["points"][0]["x"]] select_type = None if selectedData == None else [point["x"] for point in selectedData["points"]] group_type = click_type if select_type == None else select_type q2_pie = px.pie(q2.loc[(q2['RESPONSE'].notnull())&\ (q2['GROUP'].isin(group_type)),], values="COUNT", names="RESPONSE") q23_bar = px.bar(q23.loc[q23['GROUP'].isin(group_type),].sort_values(by='COUNT', ascending=False), \ x="RESPONSE", y="COUNT", color="GROUP", \ text='COUNT') q19_bar = px.bar(q19.loc[q19['GROUP'].isin(group_type),].sort_values(by='COUNT', ascending=False), \ x="RESPONSE", y="COUNT", color="GROUP", \ text='COUNT') q6_bar = px.bar(q6.loc[q6['GROUP'].isin(group_type),].sort_values(by="COUNT", ascending=False), \ x="RESPONSE", y="COUNT", color="GROUP", \ text='COUNT') q22_bar = px.bar(q22.loc[q22['GROUP'].isin(group_type),].sort_values(by="COUNT", ascending=False), \ x="RESPONSE", y="COUNT", color="GROUP", \ text='COUNT') q23_bar.update_layout(margin=dict(l=100)) q23_bar.update_yaxes(title_text="Count", title_font={"size": 12}) q23_bar.update_xaxes(title_text="") q23_bar.update_layout(autosize=False, height=550, width=800, margin=dict(l=100), showlegend=False) q23_bar.update_traces(marker_color='forestgreen') q19_bar.update_yaxes(title_text="Count", title_font={"size": 12}) q19_bar.update_xaxes(title_text="") q19_bar.update_layout(autosize=False, height=550, width=725, margin=dict(l=100), showlegend=False) q19_bar.update_traces(marker_color='sienna') q6_bar.update_yaxes(title_text="Count", title_font={"size": 12}) q6_bar.update_xaxes(title_text="") q6_bar.update_layout(autosize=False, height=550, margin=dict(l=100), showlegend=False) q6_bar.update_traces(marker_color='darkorange') q22_bar.update_yaxes(title_text="Count", title_font={"size": 12}) q22_bar.update_xaxes(title_text="") q22_bar.update_layout(autosize=False, height=650, margin=dict(l=100), showlegend=False) q22_bar.update_traces(marker_color='crimson') return q2_pie, q23_bar, q19_bar, q6_bar, q22_bar @app.callback( Output("shelter_map", "figure"), Input("shelter_year", "value"), Input("shelter_month", "value"), Input("sector", "value") ) def update_shelter_map(shelter_year,shelter_month,sector): # Shelter Occupancy Map years_to_use = [2019, 2020, 2021] if shelter_year == None else shelter_year months_to_use = list(month_dict.keys()) if shelter_month == None else list(month_dict.keys())[(shelter_month[0] - 1):shelter_month[-1]] occ_sums = occupancy_[(occupancy_['YEAR'].isin(years_to_use))&\ (occupancy_['MONTH'].isin(months_to_use)) & \ (occupancy_['SECTOR'].isin(sector))] \ .groupby(["OCCUPANCY_DATE"] + loc_cols, as_index=False) \ .agg({'OCCUPANCY': 'sum', 'CAPACITY': 'sum'}) occ_sums['CAPACITY_PERC'] = occ_sums['OCCUPANCY'] / occ_sums['CAPACITY'] * 100 occ_sums['WEIGHTED_CAP'] = occ_sums['CAPACITY_PERC'] * occ_sums['CAPACITY'] map_dat = occ_sums.groupby(loc_cols, as_index=False) \ .agg({'OCCUPANCY': 'mean', 'CAPACITY': 'mean', 'CAPACITY_PERC': 'mean', 'WEIGHTED_CAP': 'mean'}) scale = map_dat['CAPACITY'].max() shelter_map = go.Figure() shelter_map.add_trace(go.Scattermapbox( lat=map_dat['LATITUDE'], lon=map_dat['LONGITUDE'], mode='markers', marker=go.scattermapbox.Marker( size=map_dat['CAPACITY'] / scale * 50, color=map_dat['CAPACITY_PERC'], colorscale=[[0, 'rgb(255,230,230)'], [1, 'rgb(255,0,0)']], cmin=50, cmax=100, opacity=0.7 ), text="Shelter Name: " + map_dat['SHELTER_NAME'].astype(str) \ + "<br><b>Avg Capacity (%): " + map_dat['CAPACITY_PERC'].astype(str) \ + "</b><br>Avg Occupancy: " + map_dat['OCCUPANCY'].astype(str), hoverinfo='text', hoverlabel=dict(bgcolor='white', font=dict(color='black')) )) shelter_map.update_layout( title="Shelter Capacity in Greater Toronto Area", autosize=True, height=600, width=1400, hovermode='closest', showlegend=False, mapbox=dict( accesstoken=mapbox_key, bearing=0, center=dict(lat=43.686820, lon=-79.393590), pitch=0, zoom=10, style='light' ), ) return shelter_map @app.callback( Output("sector_trend", "figure"), Output("shelter_trend", "figure"), Input("shelter_map", "clickData"), Input("shelter_map", "selectedData"), Input("shelter_year", "value"), Input("shelter_month", "value"), Input("sector", "value") ) def update_shelter_trend(shelterClick,shelterSelect,shelter_year,shelter_month,sector): years_to_use = [2019, 2020, 2021] if shelter_year == None else shelter_year months_to_use = list(month_dict.keys()) if shelter_month == None else list(month_dict.keys())[(shelter_month[0] - 1):shelter_month[-1]] shelter_click = all_shelters if shelterClick == None else [find_shelter(point) for point in shelterClick["points"]] shelter_select = all_shelters if shelterSelect == None else [find_shelter(point) for point in shelterSelect["points"]] shelter_names = shelter_click if shelterSelect == None else shelter_select last_copy = shelter_names.copy() if ((shelterClick != None) or (shelterSelect!=None)) else all_shelters last_selection = last_copy if ((shelterClick == None) or (shelterSelect==None)) else shelter_names selected_sector = occupancy_[occupancy_['SHELTER_NAME'].isin(last_selection)]['SECTOR'].drop_duplicates().to_list() sector = list(set(sector+selected_sector)) if ((shelterClick != None) or (shelterSelect != None)) else all_sectors if len(sector)==0 else sector # Trend Charts sec_trend = occupancy_[occupancy_['YEAR'].isin(years_to_use) & \ occupancy_['MONTH'].isin(months_to_use) & \ occupancy_['SHELTER_NAME'].isin(last_selection) & \ occupancy_['SECTOR'].isin(sector)] \ .groupby(occ_month_cols+["SECTOR"], as_index=False) \ .agg({'OCCUPANCY': 'sum', 'CAPACITY': 'sum'}) sec_trend['CAPACITY_PERC'] = sec_trend['OCCUPANCY'] / sec_trend['CAPACITY'] * 100 sec_trend['WEIGHTED_CAP'] = sec_trend['CAPACITY_PERC'] * sec_trend['CAPACITY'] sec_trend = sec_trend.sort_values(by='MONTH_DATE') sh_trend = occupancy_[occupancy_['YEAR'].isin(years_to_use) & \ occupancy_['MONTH'].isin(months_to_use) & \ occupancy_['SHELTER_NAME'].isin(last_selection) & \ occupancy_['SECTOR'].isin(sector)] \ .groupby(occ_month_cols + loc_cols, as_index=False) \ .agg({'OCCUPANCY': 'sum', 'CAPACITY': 'sum'}) sh_trend['CAPACITY_PERC'] = sh_trend['OCCUPANCY'] / sh_trend['CAPACITY'] * 100 sh_trend['WEIGHTED_CAP'] = sh_trend['CAPACITY_PERC'] * sh_trend['CAPACITY'] sh_trend = sh_trend.sort_values(by='MONTH_DATE') sector_trend = px.line(sec_trend, x="MONTH_DATE", y='CAPACITY_PERC', color='SECTOR', line_shape='spline', range_y=[np.min(sec_trend['CAPACITY_PERC']) - 5, np.max(sec_trend['CAPACITY_PERC']) + 5], title='Shelter Capacity By Sector', render_mode="svg") sector_trend.update_xaxes(title_text='Time', ticktext=sec_trend["MONTH_YEAR"], tickvals=sec_trend["MONTH_DATE"]) sector_trend.update_yaxes(title_text='Shelter Capacity (%)') sector_trend.update_layout(title_x=0.5,showlegend=False) shelter_trend = px.line(sh_trend, x="MONTH_DATE", y='CAPACITY_PERC', color='SHELTER_NAME', line_shape='spline', range_y=[np.min(sh_trend['CAPACITY_PERC']) - 5, np.max(sh_trend['CAPACITY_PERC']) + 5], title='Shelter Capacity By Shelter', render_mode="svg") shelter_trend.update_xaxes(title_text='Time', ticktext=sh_trend["MONTH_YEAR"], tickvals=sh_trend["MONTH_DATE"]) shelter_trend.update_yaxes(title_text='Shelter Capacity (%)') shelter_trend.update_layout(title_x=0.5,showlegend=False) return sector_trend,shelter_trend if __name__ == '__main__': app.run_server(debug=True)<file_sep>/requirements.txt future~=0.18.2 Pillow~=8.2.0 DateTime~=4.3 pip~=21.1.2 Brotli~=1.0.9 attrs~=21.2.0 Flask~=2.0.1 plotly~=4.14.3 Werkzeug~=2.0.1 dash~=1.20.0 requests~=2.25.1 pytz~=2021.1 click~=8.0.1 Fiona~=1.8.20 cligj~=0.7.2 munch~=2.5.0 six~=1.16.0 MarkupSafe~=2.0.1 Jinja2~=3.0.1 itsdangerous~=2.0.1 geopy~=2.2.0 geographiclib~=1.52 numpy~=1.20.3 setuptools~=57.0.0 patsy~=0.5.1 pandas~=1.2.4 scipy~=1.6.3 matplotlib~=3.4.2 yarg~=0.1.9 python-dateutil~=2.8.1 retrying~=1.3.3 pyproj~=3.3.0 certifi~=2020.12.5 chardet~=4.0.0 docopt~=0.6.2 pipreqs~=0.4.11 decorator~=5.1.0 cycler~=0.10.0 statsmodels~=0.12.2 seaborn~=0.11.1 Shapely~=1.8.0 urllib3~=1.26.5 geocoder~=1.38.1 ratelim~=0.1.6 idna~=2.10 geopandas~=0.10.2 pyparsing~=2.4.7 kiwisolver~=1.3.1 dash-bootstrap-components~=0.12.2 gunicorn~=20.1.0<file_sep>/venv/bin/gunicorn #!/Users/markerenberg/Documents/Github/homelessness-dash/homelessness-dash/venv/bin/python3 # -*- coding: utf-8 -*- import re import sys from gunicorn.app.wsgiapp import run if __name__ == '__main__': sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) sys.exit(run()) <file_sep>/data_pull.py # ======== Scrape site for data ======== # #import imports import os import time import numpy as np import pandas as pd import requests import matplotlib.pyplot as plt import seaborn as sns import plotly.express as px import plotly.graph_objects as go import plotly from datetime import datetime import time # Get data files #local_path = r'C:\Users\marke\Downloads\Datasets\Toronto_Homelessness' local_path = r'/Users/merenberg/Documents/Precision' sna_export = pd.read_csv(local_path+r'\sna2018opendata_export.csv').fillna(0) sna_rows = pd.read_csv(local_path+r'\sna2018opendata_keyrows.csv') sna_cols = pd.read_csv(local_path+r'\sna2018opendata_keycolumns.csv') shelter_flow = pd.read_csv(local_path+r'\toronto-shelter-system-flow_march4.csv') occupancy_curr = pd.read_csv(local_path+r'\Daily_shelter_occupancy_current.csv') occupancy_2020 = pd.read_csv(local_path+r'\daily-shelter-occupancy-2020.csv') summary_metrics = pd.read_csv(local_path+r'/summary_metric_changes.csv') ################### Street Needs Assessment ################### sna_export = sna_export.merge(sna_rows.iloc[:,:3],on='SNA RESPONSE CATEGORY') # Pivot on question-response q_cols = ['SNA RESPONSE CATEGORY','QUESTION/CATEGORY DESCRIPTION','RESPONSE'] shelter_cols = ['OUTDOORS','CITY-ADMINISTERED SHELTERS','24-HR RESPITE','VAW SHELTERS'] dem_cols = ['SINGLE ADULTS','FAMILY','YOUTH'] sna_melt = sna_export.melt(id_vars=q_cols,value_vars=shelter_cols+dem_cols+['TOTAL'], var_name='GROUP',value_name='COUNT') # Track count/average responses avg_cols = [cat for cat in sna_melt['SNA RESPONSE CATEGORY'].unique() if ('AVERAGE' in cat)] cnt_cols = [cat for cat in sna_melt['SNA RESPONSE CATEGORY'].unique() if ('COUNT' in cat)] # Plot bar graph of question-response q1 = sna_export[sna_export['QUESTION/CATEGORY DESCRIPTION']=='What family members are staying with you tonight?'] fig = px.bar(q1, x="RESPONSE", y=shelter_cols, title='What family members are staying with you tonight?') fig.show() q1 = sna_melt.loc[(sna_melt['QUESTION/CATEGORY DESCRIPTION']=='What family members are staying with you tonight?')\ &(~sna_melt['SNA RESPONSE CATEGORY'].isin(cnt_cols))\ &(sna_melt['GROUP'].isin(shelter_cols))] q1_bar = px.bar(q1.loc[q1['GROUP'].isin(shelter_cols),], x="RESPONSE", y="COUNT", color="GROUP", title="What family members are staying with you tonight?") #fig.show() #plotly.offline.plot(q1_bar) # Question 7: Have you stayed in an emergency shelter in the past 12 months? q7 = sna_melt.loc[(sna_melt['QUESTION/CATEGORY DESCRIPTION']=="Have you stayed in an emergency shelter in the past 12 months?")\ &(~sna_melt['RESPONSE'].isin(["Don’t know","Decline to answer"]))\ &(sna_melt['RESPONSE'].notnull()),] q7_bar = px.bar(q7.loc[q7['GROUP'].isin(shelter_cols),],\ x="RESPONSE", y="COUNT", color="GROUP", \ title="Have you stayed in an emergency shelter in the past 12 months?",\ text='COUNT') #plotly.offline.plot(q7_bar) # Question 22: What would help you find housing? q22 = sna_melt.loc[(sna_melt['QUESTION/CATEGORY DESCRIPTION']=="Please tell me which ones would help you personally find housing.")\ &(~sna_melt['RESPONSE'].isin(["Don't know","Decline to answer"]))\ &(sna_melt['RESPONSE'].notnull()),] q22_bar = px.bar(q22.loc[q22['GROUP'].isin(shelter_cols),],\ x="RESPONSE", y="COUNT", color="GROUP", \ title="What would help you personally find housing?",\ text='COUNT') #plotly.offline.plot(q22_bar) # Question 23: In the past 6 months, have you q23 = sna_melt.loc[(sna_melt['QUESTION/CATEGORY DESCRIPTION'].str.contains("In the past 6 months, have you"))\ &(sna_melt['RESPONSE']=='Yes'),].drop("RESPONSE",axis=1) q23['RESPONSE'] = q23['QUESTION/CATEGORY DESCRIPTION'].str[32:] q23_bar = px.bar(q23.loc[q23['GROUP'].isin(shelter_cols),],\ x="RESPONSE", y="COUNT", color="GROUP", \ title="In the past 6 months, you have:",\ text='COUNT') #plotly.offline.plot(q23_bar) ################### Summary Metrics ################### # COVERAGE coverage = summary_metrics.loc[summary_metrics['METRIC']=='COVERAGE',] cov_bar = go.Figure(data=[ go.Bar(name='NEW TRAIN', x=coverage.loc[coverage['FRAMEWORK']=='NEW TRAIN','PARTNER'], y=coverage.loc[coverage['FRAMEWORK']=='NEW TRAIN','VALUE'], text=coverage.loc[coverage['FRAMEWORK']=='NEW TRAIN','VALUE'].round(3), textposition='auto'), go.Bar(name='NEW OOT', x=coverage.loc[coverage['FRAMEWORK'] == 'NEW OOT', 'PARTNER'], y=coverage.loc[coverage['FRAMEWORK'] == 'NEW OOT', 'VALUE'], text=coverage.loc[coverage['FRAMEWORK']=='NEW OOT','VALUE'].round(3), textposition='auto'), go.Bar(name='OLD', x=coverage.loc[coverage['FRAMEWORK']=='OLD','PARTNER'], y=coverage.loc[coverage['FRAMEWORK']=='OLD','VALUE'], text=coverage.loc[coverage['FRAMEWORK']=='OLD','VALUE'].round(3), textposition='auto') ]) cov_bar.update_yaxes(title='Coverage') cov_bar.update_layout(barmode='group', title_text='Coverage Metrics By Partner & Framework', title_x=0.5, font=dict(size=24) ) #plotly.offline.plot(cov_bar) # ACCURACY accuracy = summary_metrics.loc[summary_metrics['METRIC']=='ACCURACY',] acc_bar = go.Figure(data=[ go.Bar(name='NEW TRAIN', x=accuracy.loc[accuracy['FRAMEWORK']=='NEW TRAIN','PARTNER'], y=accuracy.loc[accuracy['FRAMEWORK']=='NEW TRAIN','VALUE'], text=accuracy.loc[accuracy['FRAMEWORK']=='NEW TRAIN','VALUE'].round(3), textposition='auto'), go.Bar(name='NEW OOT', x=accuracy.loc[accuracy['FRAMEWORK'] == 'NEW OOT', 'PARTNER'], y=accuracy.loc[accuracy['FRAMEWORK'] == 'NEW OOT', 'VALUE'], text=accuracy.loc[accuracy['FRAMEWORK']=='NEW OOT','VALUE'].round(3), textposition='auto'), go.Bar(name='OLD', x=accuracy.loc[accuracy['FRAMEWORK']=='OLD','PARTNER'], y=accuracy.loc[accuracy['FRAMEWORK']=='OLD','VALUE'], text=accuracy.loc[accuracy['FRAMEWORK']=='OLD','VALUE'].round(3), textposition='auto') ]) acc_bar.update_yaxes(title='Accuracy') acc_bar.update_layout(barmode='group', title_text='Accuracy Metrics By Partner & Framework', title_x=0.5, font=dict(size=24) ) #plotly.offline.plot(acc_bar) # TRAIN TIME time = summary_metrics.loc[summary_metrics['METRIC']=='TRAIN TIME',] time_bar = go.Figure(data=[ go.Bar(name='NEW TRAIN', x=time.loc[time['FRAMEWORK']=='NEW TRAIN','PARTNER'], y=time.loc[time['FRAMEWORK']=='NEW TRAIN','VALUE'], text=time.loc[time['FRAMEWORK']=='NEW TRAIN','VALUE'].round(3), textposition='auto'), go.Bar(name='NEW OOT', x=time.loc[time['FRAMEWORK'] == 'NEW OOT', 'PARTNER'], y=time.loc[time['FRAMEWORK'] == 'NEW OOT', 'VALUE'], text=time.loc[time['FRAMEWORK']=='NEW OOT','VALUE'].round(3), textposition='auto'), go.Bar(name='OLD', x=time.loc[time['FRAMEWORK']=='OLD','PARTNER'], y=time.loc[time['FRAMEWORK']=='OLD','VALUE'], text=time.loc[time['FRAMEWORK']=='OLD','VALUE'].round(3), textposition='auto') ]) time_bar.update_yaxes(title='Time (minutes)') time_bar.update_layout(barmode='group', title_text='Train Time (Minutes) By Partner/Framework', title_x=0.5, font=dict(size=24) ) #plotly.offline.plot(time_bar) ################### Daily Shelter Occupancy ################### # Read in csv root_path = r'/Users/markerenberg/Documents/Github/homelessness-dash/homelessness-dash/' data_path = root_path + "underlying_data" occupancy_21 = pd.read_csv(local_path+r'/Daily_shelter_occupancy_current.csv') occupancy_20 = pd.read_csv(local_path+r'/daily-shelter-occupancy-2020.csv') occupancy_19 = pd.read_csv(local_path+r'/daily-shelter-occupancy-2019.csv') # Merge multiple years' data, align date formats date_col = "OCCUPANCY_DATE" occupancy_19 = occupancy_19.drop("_id",axis=1) occupancy_21 = occupancy_21.drop("_id",axis=1) occupancy_19['OCCUPANCY_DATETIME'] = occupancy_19[date_col].apply(lambda dt: datetime.strptime(dt.replace("T"," "),"%Y-%m-%d %H:%M:%S")) occupancy_21['OCCUPANCY_DATETIME'] = occupancy_21[date_col].apply(lambda dt: datetime.strptime(dt.replace("T"," "),"%Y-%m-%d")) occupancy_19[date_col] = occupancy_19['OCCUPANCY_DATETIME'].apply(lambda dt: dt.strftime("%m/%d/%Y")) occupancy_21[date_col] = occupancy_21['OCCUPANCY_DATETIME'].apply(lambda dt: dt.strftime("%m/%d/%Y")) # Make changes to match 2021 occupancy data with previous years occ_21_cols = {"LOCATION_NAME": "SHELTER_NAME", "LOCATION_ADDRESS": "SHELTER_ADDRESS", "LOCATION_POSTAL_CODE": "SHELTER_POSTAL_CODE", "LOCATION_CITY": "SHELTER_CITY", "LOCATION_PROVINCE": "SHELTER_PROVINCE"} occupancy_21 = occupancy_21.rename(columns=occ_21_cols) occupancy_bed = occupancy_21[occupancy_21["CAPACITY_TYPE"]=="Bed Based Capacity"].reset_index(drop=True) occupancy_room = occupancy_21[occupancy_21["CAPACITY_TYPE"]=="Room Based Capacity"].reset_index(drop=True) occupancy_bed["OCCUPANCY"] = occupancy_bed["OCCUPIED_BEDS"].astype("int") occupancy_bed["CAPACITY"] = occupancy_bed["CAPACITY_ACTUAL_BED"].astype("int") occupancy_room["OCCUPANCY"] = occupancy_room["OCCUPIED_ROOMS"].astype("int") occupancy_room["CAPACITY"] = occupancy_room["CAPACITY_ACTUAL_ROOM"].astype("int") # Group by shelter, merge two types of shelter data occupancy_cols = ["OCCUPANCY_DATE","ORGANIZATION_NAME","SHELTER_NAME","SHELTER_ADDRESS", "SHELTER_CITY","SHELTER_PROVINCE","SHELTER_POSTAL_CODE","PROGRAM_NAME", "SECTOR"] occupancy_21 = pd.concat([occupancy_bed[occupancy_cols+["OCCUPANCY","CAPACITY"]],\ occupancy_room[occupancy_cols+["OCCUPANCY","CAPACITY"]]],\ axis=0,ignore_index=True,sort=False) # Merge all years' occupancy data occupancy = pd.concat([occupancy_19.drop(["FACILITY_NAME","OCCUPANCY_DATETIME"],axis=1), occupancy_20.drop("FACILITY_NAME",axis=1), occupancy_21],axis=0,ignore_index=True,sort=True) # Drop null names/postal codes occupancy = occupancy[(occupancy["SHELTER_NAME"].notnull())&\ (occupancy["SHELTER_POSTAL_CODE"].notnull())].reset_index(drop=True) # Create mappings for data transformation post_col, city_col, address_col, province_col = 'SHELTER_POSTAL_CODE', 'SHELTER_CITY', 'SHELTER_ADDRESS', 'SHELTER_PROVINCE' loc_cols = [post_col,'SHELTER_NAME','LATITUDE','LONGITUDE'] month_dict = {1:"Jan",2:"Feb",3:"Mar",4:"Apr",5:"May",6:"Jun",7:"Jul",8:"Aug",9:"Sep",10:"Oct",11:"Nov",12:"Dec"} shelter_dict = [{'label':x, 'value':x} for x in occupancy['SHELTER_NAME'].drop_duplicates()] all_shelters = occupancy['SHELTER_NAME'].drop_duplicates().to_list() all_sectors = occupancy['SECTOR'].drop_duplicates().to_list() city_dict = [{'label':x, 'value':x} for x in occupancy['SHELTER_CITY'].drop_duplicates()] sector_dict = [{'label':x, 'value':x} for x in occupancy['SECTOR'].drop_duplicates()] # Remove dashes from postal data, impute spaces if missing occupancy_ = occupancy.copy() occupancy[post_col] = occupancy[post_col].apply(lambda x: x[:3] + " " + x[3:] if len(x)==6 else x) occupancy[post_col] = occupancy[post_col].apply(lambda x: x.replace("-"," ")) # Remove typos, remove "floor" notations occupancy_[address_col] = occupancy_[address_col].apply(lambda x: x.replace("Bathrust","Bathurst")) occupancy_[address_col] = occupancy_[address_col].apply(lambda x: x.replace(", 2nd floor","")) # Create full address using city and province occupancy_["FULL_ADDRESS"] = occupancy_[address_col] + ", " + occupancy_[city_col] + ", " + occupancy_[province_col] # Lat / long extraction using geopy from geopy.geocoders import Nominatim geolocator = Nominatim(user_agent="<EMAIL>") # Unique addresses for geocoder unique_adds = occupancy_["FULL_ADDRESS"].drop_duplicates().to_frame() # Geocode full addresses t0 = time.time() unique_adds["LOCATION"] = unique_adds["FULL_ADDRESS"].apply(lambda x: geolocator.geocode(x)) t1 = time.time() print(f"Time taken to geocode locations: {(t1-t0)/60}m") unique_adds = unique_adds[unique_adds["LOCATION"].notnull()].reset_index(drop=True) unique_adds["LATITUDE"] = unique_adds["LOCATION"].apply(lambda x: x.latitude) unique_adds["LONGITUDE"] = unique_adds["LOCATION"].apply(lambda x: x.longitude) unique_adds = unique_adds.drop("LOCATION",axis=1) # Write coordinates to CSV unique_adds.to_csv(data_path+r"/occupancy_coordinates.csv",sep=",",header=True,index=False)
a5e37ef7eb6987f2f9fd0e57198c12c3b85ccc91
[ "Markdown", "Python", "Text" ]
5
Markdown
markerenberg/dash-project
dcf422423205745bb733b8ab061f0ce40044ad83
117612e0f848ebe24a8f69fc767569e3ef12f099
refs/heads/master
<file_sep><?php //参考: https://qiita.com/SOJO/items/a42fe56334ce810b97be require_once 'phpmysql.php'; // 結果用配列 $all_result = array(); $music_result = array(); // データベース接続用インスタンス $db = new MyDB(); $offset = 0; // 重複エラーコード const DUPLICATE_CODE = 1062; function debugEcho($str){ echo $str . "\n"; } function juman($lyrics) { debugEcho("juman start."); global $all_result, $db; // 品詞(名詞=6、動詞=2、形容詞=3、副詞=8) $partOfSpeech = array(6, 2, 3, 8); // 歌詞中のアルファベット削除 $lyrics = preg_replace('/[a-zA-Z]/', ' ', $lyrics); // jumanのコマンドを実行 // EOSを除去し,改行で区切 $output = shell_exec(sprintf('echo %s | jumanpp', escapeshellarg($lyrics))); $output = array_reverse(preg_split("/EOS|\n/u", $output)); // 単語に別の意味が含まれる場合、 // 同じ単語でも @(atmark) が付いて行が別れてしまうので、 // それを合わせる処理 // 配列を逆順にしてから処理することで、複数行に及ぶものにも対応 foreach ($output as $out_key => $out_value) { if (isset($out_value[0]) && $out_value[0] == "@") { $output[$out_key+1] .= " " . $output[$out_key]; $output[$out_key] = ""; } // 必要な要素のみを切り出し $split_text = explode(" ", $output[$out_key]); if(count($split_text) >= 5){ // kakasiによる漢字、カタカナ→ひらがな変換(表記ゆれ対策) $hiragana_text = shell_exec(sprintf('echo %s | kakasi -JH -KH -s -i utf-8 -o utf-8', escapeshellarg($split_text[2]))); // 変換後の文字列中の空白削除 $hiragana_text = str_replace(array(" ", " "), "", $hiragana_text); $output[$out_key] = $split_text[1] . " " . $split_text[2] . " " . $split_text[3] . " " . $split_text[4]; foreach($partOfSpeech as $value){ if($split_text[4] == $value){ // 解析結果を追加 $all_result[] = str_replace(PHP_EOL, '', $hiragana_text . " " . $split_text[2] . " " . $split_text[3]); // 曲ごとの解析結果を追加 $music_result[] = str_replace(PHP_EOL, '', $hiragana_text . " " . $split_text[2] . " " . $split_text[3]); } } } } // 空の要素を取り除く $return_value = array_filter(array_reverse($output), 'strlen'); $return_value = array_values($return_value); // 解析結果(表層形 読み 見出し語 品詞大分類 品詞大分類ID 品詞細分類 品詞細分類ID 活用型 活用型ID 活用形 活用形ID 意味情報) //var_dump($return_value); // 曲ごとの解析結果を表示 getResult($music_result); debugEcho("juman end."); } // 曲タイトルデータを読み込む function readMusicTitle($filename){ global $db, $title; // fopenでファイルを開く(読み込みモード) $fp = fopen($filename, 'r'); debugEcho("read start."); // ループ処理 while(!feof($fp)){ // ファイルを1行読み込み $title = fgets($fp); $title = str_replace(array("\r", "\n"), '', $title); // 空行はスキップ if(strcmp("\n", $title) == 0){ continue; } // DBにSQLを送信 $db_result = $db->query("INSERT INTO music_title(title) VALUES('$title')"); //データベースに登録済みであれば重複フラグを立てる if(checkDuplicate($db_result["error"])){ debugEcho("duplicate title:" . $title); $is_duplicate = true; }else{ debugEcho("read title:" . $title); $is_duplicate = false; } // 歌詞データ読み込み readLyrics('lyrics.txt', $is_duplicate); } // ファイルを閉じる fclose($fp); debugEcho("read complete!"); } function readLyrics($filename, $flag){ global $offset; $lyrics = ''; // fopenでファイルを開く(読み込みモード) $fp = fopen($filename, 'r'); fseek($fp, $offset); // ループ処理 while(!feof($fp)){ // ファイルを1行読み込み $tmp_lyrics = fgets($fp); // 改行は曲の終わりを示す if(strcmp("\n", $tmp_lyrics) == 0){ break; }else{ // 歌詞格納 $lyrics .= $tmp_lyrics; } } // juman++による形態素解析は曲タイトルが重複していないときのみ if(!$flag){ debugEcho("read lyrics."); juman($lyrics); } $lyrics = ''; $offset = ftell($fp); // ファイルを閉じる fclose($fp); } // 解析結果を取得 function getResult($arr_result){ global $db, $title; $result = array_count_values($arr_result); arsort($result); $insert_sql = "INSERT INTO lyrics(word_hiragana, word, part_of_speech, num, title) VALUES"; // 最終結果 foreach($result as $key => $val){ $lyrics_count = $key . " " . $val; // echo $lyrics_count . "\n"; $split_lyrics = explode(" ", $lyrics_count); $insert_sql .= "('$split_lyrics[0]', '$split_lyrics[1]', '$split_lyrics[2]', '$split_lyrics[3]', '$title'), "; } // SQL文の最後をセミコロンにする $insert_sql = rtrim($insert_sql, ' '); $insert_sql = rtrim($insert_sql, ','); // echo $insert_sql; $db->query($insert_sql); } // データベース重複エラーチェック function checkDuplicate($str){ $error_str = explode(" ", $str); $error_num = rtrim($error_str[0], ':'); if($error_num == DUPLICATE_CODE){ return true; }else{ return false; } } // 処理時間計測 $time_start = microtime(true); readMusicTitle('musictitle.txt'); var_dump($db->query("SELECT word_hiragana, part_of_speech, SUM(num) AS total_num FROM lyrics GROUP BY word_hiragana, part_of_speech ORDER BY total_num DESC LIMIT 50")); // 処理時間計測 $time = microtime(true) - $time_start; echo "processing time:{$time} sec\n";<file_sep># lyrics_analyzer 歌詞を形態素解析し、その結果をデータベースに保存するプログラムです。 # 動作確認済み環境 - Mac OS 10.12.6 # 使い方 1. 歌詞データと曲タイトルデータを用意します。 歌詞データと曲タイトルデータはテキストファイルであり、以下のような形式となっていることが条件です。 ・ 歌詞データ 1曲目の歌詞 1曲目の歌詞 1曲目の歌詞 1曲目の歌詞 2曲目の歌詞 2曲目の歌詞 2曲目の歌詞 3曲目の歌詞 ・・・ ・ 曲タイトルデータ 1曲目の曲タイトル 2曲目の曲タイトル 3曲目の曲タイトル ・・・ 2. JUMAN++をインストールします。 [日本語形態素解析システム JUMAN++](http://nlp.ist.i.kyoto-u.ac.jp/index.php?JUMAN++) 3. データベースを用意します。 このプログラムではMySQLを使用しています。 4. プログラムを実行します。 歌詞を解析したい場合は、lyrics_analyze.phpを、曲タイトルを解析したい場合は、musictitle_analyze.phpを実行してください。   何かご質問などありましたら[作者Twitter](https://twitter.com/kanatano_mirai)へどうぞ。   # English This is a program that morphologically analyzes lyrics and stores the results in a database.(Japanese only) # System Requirements - Mac OS 10.12.6 # how to use 1. Prepare lyrics data and song title data. The lyrics data and song title data are text files and it must be in the following format. ・ lyrics data first song lyrics first song lyrics first song lyrics first song lyrics second song lyrics second song lyrics second song lyrics third song lyrics ・・・ ・ song title data first song title second song title third song title ・・・ 2. Install JUMAN++. [日本語形態素解析システム JUMAN++](http://nlp.ist.i.kyoto-u.ac.jp/index.php?JUMAN++) 3. Prepare the database. This program uses MySQL. 4. Run the program. If you want to analyze lyrics, please run lyrics_analyze.php, if you want to analyze the song title, please run musictitle_analyze.php. If you have any questions please to [Twitter](https://twitter.com/kanatano_mirai).
89173175a00fe5afd55328e5e9a71702deedc7bd
[ "Markdown", "PHP" ]
2
PHP
kanatanomirai/lyrics_analyzer
aa95334d990c773d34aa1136662247c732b141ce
f0fb2d085e628b8c14a5241a934073b6955440c7
refs/heads/master
<file_sep># SaldoBip! Este es un ejemplo de alternativa para consultar el saldo de su tarjeta Bip! Para consultar el saldo: ``` http://host/saldo/:NUM_TARJETA/:RUT ``` # SERVER Live demo: http://bip.apps.zsyslog.com/saldo/:NUM_TARJETA/:RUT # CLIENT Live demo: http://jcjimenez.me/bip # Install Made with Nodejs (Cheerio + Express + Request + forever) ``` # git clone https://github.com/zsyslog/saldobip.git # cd saldobip # npm install -d # node bip.js ``` Change server port if needed or configure your proxy. If you are using NGINX, you can configure a new upstream entry ``` upstream saldobip { server 127.0.0.1:6001; } ``` And then a new virtualhost: ``` server { listen SERVER_ADDRESS:80; server_name new.virtual.host.name; location / { add_header Access-Control-Allow-Origin *; # just in case!! ;) proxy_pass http://saldobip; } } ``` <file_sep>jQuery(document).ready(function() { $('.login-form input[type="text"]').on('focus', function() { $(this).removeClass('input-error'); }); $('#form-rut').Rut({ on_error: function(){ alert('Verifique que el RUT ingresado es correcto, por favor'); $('#form-rut').val(''); } }); $('.balance-form').on('submit', function(e) { $(this).find('input[type="text"]').each(function(){ if( $(this).val() == "" ) { e.preventDefault(); $(this).addClass('input-error'); } else { $(this).removeClass('input-error'); } var rut = $('#form-rut').val(); var card = $('#form-card').val(); if (card!='' && rut!=''){ $('.spinner').removeClass('hide'); var url = "http://bip.apps.zsyslog.com/saldo/" + card + "/" + rut; $.ajax({ url: url, method: "GET", success: function(data){ $('.result-data').removeClass('hide'); $('.card-balance .value').text(data.balance); $('.card-status .value').text(data.card_status); $('.card-activity .value').text(data.last_activity); $('.spinner').addClass('hide'); $('fa-credit-card').trigger('click'); }, error: function(e){ console.log(e); } }) } }); return false; }); });
7115fb7954c28bb5782e6e1224f5be77fd1f79c5
[ "Markdown", "JavaScript" ]
2
Markdown
zsyslog/saldobip
460e957269e32383412ad4f60af69be043a7dbcf
f6bb74db3b6b6d0c140a14bcd4f06cd175b83a85
refs/heads/master
<repo_name>tcdl/msb-http2bus<file_sep>/lib/middleware/normaliseQuery.js var _ = require('lodash'); var parseurl = require('parseurl'); var qs = require('querystring'); module.exports = function queryParamToObject(req, res, next) { var urlParts = parseurl(req); var result = {}; _.forEach(qs.parse(urlParts.query), function(value, key) { _.set(result,key,value); req.query = result; }); next(); }; <file_sep>/README.md # msb-http2bus [![Build Status](https://travis-ci.org/tcdl/msb-http2bus.svg)](https://travis-ci.org/tcdl/msb-http2bus) An HTTP server providing endpoints for services exposed through the [MSB](https://github.com/tcdl/msb) bus. ## Installation ``` $ npm install msb-http2bus ``` To run the server from the command line, globally install with option `-g`. ## Server Start a server with a static configuration file: ``` $ http2bus example/http2bus.json ``` Base configuration format, provided as either _json_ or _js_: ```js { channelMonitorEnabled: true, // Default: true port: 8080, // Default: 0 (random port) routes: [ { /* ... */ }, { /* ... */ } ] } ``` (All standard [MSB environment variables](https://github.com/tcdl/msb#environment-variables) should be provided for broker configuration.) ### Routes Routes are loaded as an array of configuration objects, always specifying an `http` section as well as either `bus` or `provider` section. - **http** Object An object required for all routes specifying HTTP behaviour. - **http.path** String An [Express-style path](https://github.com/pillarjs/path-to-regexp#usage) to listen on. - **http.basePath** _Optional_ URLs and redirects are relative to this path. (Default: '/') - **http.methods** _Optional_ Array The HTTP methods to listen for, e.g. `get`, `post`, `put`, `head`. (Default: `['get']`) - **http.remote** _Optional_ Boolean Route all traffic below this path, for no specific HTTP methods, to a remote router. (Default: `false`) - **http.cors** _Optional_ Object CORS middleware [configuration options](https://github.com/expressjs/cors#configuration-options). - **bus** Object Must be a valid [Requester configuration](https://github.com/tcdl/msb#class-msbrequester). - **provider** Object Dynamic routes can provided by this provider. - **provider.name** String The name corresponding to the [Routes Agent](#routes-provider-agent). #### Static Route Example For routing _GET_ requests similar to `/api/v1/example/abc123?depth=10` to `example:topic`: ```js { http: { basePath: '/api/v1/examples', path: '/:example-id', methods: ['get'] }, bus: { namespace: 'example:topic', waitForResponses: 1 } } ``` The payload placed on `example:topic` would be similar to: ```js { "method": "get", "url": "/abc123", "headers": { "content-type": "application/json" }, "params": { "example-id": "abc123" }, "query": { "depth": "10" } } ``` See [this normal responder](https://github.com/tcdl/msb#1-1-1) example. Headers provided in the responder payload are sent in the HTTP response. E.g, for a redirect: ```js response.writeHead(301, { location: '/renamed-abc123' }) ``` If the `location` header, is not fully qualified, i.e. without protocol and domain name, it will be rewritten relative to this base path specified in the route, in this case `/api/v1/examples/renamed-abc123`. #### Dynamic Routes Example To route all requests below `/api/v1/remotes` using routes configurations provided by this routes agent. ```js { http: { basePath: '/api/v1/remotes' }, provider: { name: 'remotes-example-api' } } ``` The routes loaded by the corresponding [Routes Agent](#routes-provider-agent) will be published relative to the specified `basePath`. ## Routes Agent You can provide routes to http2bus servers from remote agents on the bus. An agent must be specified as a `provider` in a route on the server. Note: an agent does not actually process any requests, it only publishes routes to the servers. For example: ```js var http2bus = require('msb-http2bus') var agent = http2bus.routesAgent.create({ name: 'remotes-example-api', ttl: 3600000 }) var routes = [{ http: { path: '/:example-id', methods: ['get'] }, bus: { namespace: 'example:topic', waitForResponses: 1 } }] agent .start() .load(routes) ``` The configuration format for routes are the same as on the http2bus server. You can dynamically change routes to be reloaded on all relevant http2bus servers: ```js agent.load([]) ``` (All standard [MSB environment variables](https://github.com/tcdl/msb#environment-variables) should be provided for broker configuration.) ## License MIT <file_sep>/test/routeHandler.test.js /* Setup */ var Lab = require('lab'); var Code = require('code'); var lab = exports.lab = Lab.script(); var describe = lab.describe; var it = lab.it; var before = lab.before; var beforeEach = lab.beforeEach; var after = lab.after; var afterEach = lab.afterEach; var expect = Code.expect; /* Modules */ var _ = require('lodash'); var simple = require('simple-mock'); var msb = require('msb'); var routeHandler = require('../lib/routeHandler'); describe('routeHandler()', function() { afterEach(function(done) { simple.restore(); done(); }); describe('for a simple 1-1 req-res route', function() { var mockReq; var mockRes; var mockNext; var mockRequester; var handlerConfig; var handler; beforeEach(function(done) { handlerConfig = { bus: { namespace: 'abc:123', waitForResponses: 1, waitForResponsesMs: 1000 }, http: { basePath: '/api' } }; handler = routeHandler(handlerConfig); mockRequester = { message: {}, responseMessages: [] }; mockRequester.on = simple.mock().returnWith(mockRequester); mockRequester.once = simple.mock().returnWith(mockRequester); mockRequester.publish = simple.mock().returnWith(mockRequester); simple.mock(msb.Requester.prototype, 'publish').returnWith(mockRequester); mockReq = { url: '/api/something', method: 'post', headers: { }, params: { }, query: { } }; mockRes = { setHeader: simple.mock(), writeHead: simple.mock(), end: simple.mock() }; mockNext = simple.mock(); done(); }); describe('for requests', function() { it('can handle a json request', function(done) { mockReq.body = '{"doc":"a"}'; mockReq.headers['content-type'] = 'application/json'; handler(mockReq, mockRes, mockNext); expect(msb.Requester.prototype.publish.callCount).equals(1); var publishPayload = msb.Requester.prototype.publish.lastCall.arg; expect(publishPayload).exists(); expect(publishPayload.body).deep.equals({ doc: 'a' }); done(); }); it('can handle a text request', function(done) { mockReq.body = 'abc'; mockReq.headers['content-type'] = 'application/text'; handler(mockReq, mockRes, mockNext); expect(msb.Requester.prototype.publish.callCount).equals(1); var publishPayload = msb.Requester.prototype.publish.lastCall.arg; expect(publishPayload).exists(); expect(publishPayload.body).deep.equals('abc'); done(); }); it('can handle a bin data request', function(done) { mockReq.body = new Buffer(24); mockReq.body.fill(0); handler(mockReq, mockRes, mockNext); expect(msb.Requester.prototype.publish.callCount).equals(1); var publishPayload = msb.Requester.prototype.publish.lastCall.arg; expect(publishPayload).exists(); expect(publishPayload.body).equals(null); expect(publishPayload.bodyBuffer).equals('AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'); done(); }); it('can modify the url for a basePath', function(done) { handler(mockReq, mockRes, mockNext); expect(msb.Requester.prototype.publish.callCount).equals(1); var publishPayload = msb.Requester.prototype.publish.lastCall.arg; expect(publishPayload).exists(); expect(publishPayload.url).equals('/something'); done(); }); it('can modify the url for a basePath at root', function(done) { mockReq.url = '/api'; handler(mockReq, mockRes, mockNext); expect(msb.Requester.prototype.publish.callCount).equals(1); var publishPayload = msb.Requester.prototype.publish.lastCall.arg; expect(publishPayload).exists(); expect(publishPayload.url).equals('/'); done(); }); it('can modify the url for a basePath at root', function(done) { mockReq.url = '/apiv2'; handler(mockReq, mockRes, mockNext); expect(msb.Requester.prototype.publish.callCount).equals(1); var publishPayload = msb.Requester.prototype.publish.lastCall.arg; expect(publishPayload).exists(); expect(publishPayload.url).equals('/v2'); done(); }); it('will ensure the request is tagged with the correlationId', function(done) { handler(mockReq, mockRes, mockNext); expect(msb.Requester.prototype.publish.callCount).equals(1); var requester = msb.Requester.prototype.publish.lastCall.context; expect(requester).exists(); expect(requester.message.tags).deep.equals([requester.message.correlationId]); done(); }); describe('where the incoming request provides tags', function() { beforeEach(function(done) { simple.mock(msb, 'Requester').returnWith(mockRequester); done(); }); it('will add header tags to configuration', function(done) { handlerConfig.bus.tags = ['pre', 'one']; mockReq.headers['x-msb-tags'] = 'one,two'; handler(mockReq, mockRes, mockNext); expect(msb.Requester.callCount).equals(1); expect(msb.Requester.lastCall.arg).exists(); expect(msb.Requester.lastCall.arg.tags).deep.equals(['one', 'two', 'pre']); done(); }); it('will add query tags to configuration', function(done) { handlerConfig.bus.tags = ['pre', 'one']; mockReq.query['_x-msb-tags'] = 'one,two'; handler(mockReq, mockRes, mockNext); expect(msb.Requester.callCount).equals(1); expect(msb.Requester.lastCall.arg).exists(); expect(msb.Requester.lastCall.arg.tags).deep.equals(['one', 'two', 'pre']); done(); }); }); it('will ensure the already tagged request is tagged with the correlationId', function(done) { handlerConfig.bus.tags = ['zzz']; handler(mockReq, mockRes, mockNext); expect(msb.Requester.prototype.publish.callCount).equals(1); var requester = msb.Requester.prototype.publish.lastCall.context; expect(requester).exists(); expect(requester.message.tags).deep.equals([requester.message.correlationId, 'zzz']); done(); }); }); describe('for responses', function() { beforeEach(function(done) { simple.mock(msb, 'Requester').returnWith(mockRequester); done(); }); it() describe('if no responses were received', function() { it('will return an empty 503 where responses are expected', function(done) { handler(mockReq, mockRes, mockNext); expect(mockRequester.once.lastCall.arg).equals('end'); var end = mockRequester.once.lastCall.args[1]; expect(end).exists(); end(); expect(mockRes.writeHead.callCount).equals(1); expect(mockRes.writeHead.lastCall.arg).equals(503); expect(mockRes.end.callCount).equals(1); done(); }); it('will return an empty 204 where responses are not expected', function(done) { handlerConfig.bus.waitForResponses = 0; handler(mockReq, mockRes, mockNext); expect(mockRequester.once.lastCall.arg).equals('end'); var end = mockRequester.once.lastCall.args[1]; expect(end).exists(); end(); expect(mockRes.writeHead.callCount).equals(1); expect(mockRes.writeHead.lastCall.arg).equals(204); expect(mockRes.end.callCount).equals(1); done(); }); it('will return a correlationId in the header', function(done) { handler(mockReq, mockRes, mockNext); mockRequester.message.correlationId = 'aCorrelationId'; expect(mockRequester.once.lastCall.arg).equal('end'); var end = mockRequester.once.lastCall.args[1]; expect(end).exist(); end(); expect(mockRes.setHeader.callCount).equals(1); expect(mockRes.setHeader.lastCall.arg).equals('x-msb-correlation-id'); expect(mockRes.setHeader.lastCall.args[1]).equals('aCorrelationId'); done(); }); }); describe('where responses were received', function() { var responseMessage; beforeEach(function(done) { responseMessage = { payload: { statusCode: 418, headers: { 'access-control-allow-origin': '*', 'access-control-allow-headers': '*', 'access-control-allow-methods': '*', 'access-control-allow-credentials': '*' } } }; mockRequester.responseMessages.push(responseMessage); done(); }); it('will return a correlationId in the header', function(done) { handler(mockReq, mockRes, mockNext); mockRequester.message.correlationId = 'aCorrelationId'; expect(mockRequester.once.lastCall.arg).equals('end'); var end = mockRequester.once.lastCall.args[1]; expect(end).exists(); end(); expect(mockRes.setHeader.callCount).equals(1); expect(mockRes.setHeader.lastCall.arg).equals('x-msb-correlation-id'); expect(mockRes.setHeader.lastCall.args[1]).equals('aCorrelationId'); done(); }); it('will use the last response received', function(done) { mockRequester.responseMessages.push({ payload: { statusCode: null } }); handler(mockReq, mockRes, mockNext); expect(mockRequester.once.lastCall.arg).equals('end'); var end = mockRequester.once.lastCall.args[1]; expect(end).exists(); end(); expect(mockRes.writeHead.callCount).equals(1); expect(mockRes.writeHead.lastCall.arg).equals(200); done(); }); it('can send an empty body', function(done) { handler(mockReq, mockRes, mockNext); expect(mockRequester.once.lastCall.arg).equals('end'); var end = mockRequester.once.lastCall.args[1]; expect(end).exists(); end(); expect(mockRes.writeHead.callCount).equals(1); expect(mockRes.writeHead.lastCall.arg).equals(418); expect(mockRes.writeHead.lastCall.args[1]).deep.equals({ 'content-length': 0 }); expect(mockRes.end.callCount).equals(1); expect(mockRes.end.lastCall.arg).equals(undefined); done(); }); it('can send a json body', function(done) { responseMessage.payload.body = { doc: 'a' }; handler(mockReq, mockRes, mockNext); expect(mockRequester.once.lastCall.arg).equals('end'); var end = mockRequester.once.lastCall.args[1]; expect(end).exists(); end(); expect(mockRes.writeHead.callCount).equals(1); expect(mockRes.writeHead.lastCall.arg).equals(418); expect(mockRes.writeHead.lastCall.args[1]).deep.equals({ 'content-type': 'application/json' }); expect(mockRes.end.callCount).equals(1); expect(mockRes.end.lastCall.arg).equals('{"doc":"a"}'); done(); }); it('can send a json body with custom content-type', function(done) { responseMessage.payload.body = { doc: 'a' }; responseMessage.payload.headers['content-type'] = 'application/x-my-custom-format'; handler(mockReq, mockRes, mockNext); expect(mockRequester.once.lastCall.arg).equals('end'); var end = mockRequester.once.lastCall.args[1]; expect(end).exists(); end(); expect(mockRes.writeHead.callCount).equals(1); expect(mockRes.writeHead.lastCall.arg).equals(418); expect(mockRes.writeHead.lastCall.args[1]).deep.equals({ 'content-type': 'application/x-my-custom-format' }); expect(mockRes.end.callCount).equals(1); expect(mockRes.end.lastCall.arg).equals('{"doc":"a"}'); done(); }); it('can send a binary body', function(done) { responseMessage.payload.bodyBuffer = 'AAAA'; handler(mockReq, mockRes, mockNext); expect(mockRequester.once.lastCall.arg).equals('end'); var end = mockRequester.once.lastCall.args[1]; expect(end).exists(); end(); expect(mockRes.writeHead.callCount).equals(1); expect(mockRes.writeHead.lastCall.arg).equals(418); expect(mockRes.writeHead.lastCall.args[1]).deep.equals({ 'content-type': 'application/octet-stream' }); expect(mockRes.end.callCount).equals(1); expect(String(mockRes.end.lastCall.arg)).equals('\u0000\u0000\u0000'); done(); }); it('can send a binary body with provided content-type', function(done) { responseMessage.payload.bodyBuffer = 'AAAA'; responseMessage.payload.headers['content-type'] = 'application/x-my-custom-format'; handler(mockReq, mockRes, mockNext); expect(mockRequester.once.lastCall.arg).equals('end'); var end = mockRequester.once.lastCall.args[1]; expect(end).exists(); end(); expect(mockRes.writeHead.callCount).equals(1); expect(mockRes.writeHead.lastCall.arg).equals(418); expect(mockRes.writeHead.lastCall.args[1]).deep.equals({ 'content-type': 'application/x-my-custom-format' }); expect(mockRes.end.callCount).equals(1); expect(String(mockRes.end.lastCall.arg)).equals('\u0000\u0000\u0000'); done(); }); it('can rewrite location header relative to basePath', function(done) { responseMessage.payload.body = 'A redirect message'; responseMessage.payload.headers.location = '/some/other'; handler(mockReq, mockRes, mockNext); expect(mockRequester.once.lastCall.arg).equals('end'); var end = mockRequester.once.lastCall.args[1]; expect(end).exists(); end(); expect(mockRes.writeHead.callCount).equals(1); expect(mockRes.writeHead.lastCall.arg).equals(418); expect(mockRes.writeHead.lastCall.args[1]).deep.equals({ 'location': '/api/some/other' }); expect(mockRes.end.callCount).equals(1); expect(String(mockRes.end.lastCall.arg)).equals('A redirect message'); done(); }); it('can skip rewriting a non path-like locaiton header', function(done) { responseMessage.payload.body = 'A redirect message'; responseMessage.payload.headers.location = 'http://google.com/some/other'; handler(mockReq, mockRes, mockNext); expect(mockRequester.once.lastCall.arg).equals('end'); var end = mockRequester.once.lastCall.args[1]; expect(end).exists(); end(); expect(mockRes.writeHead.callCount).equals(1); expect(mockRes.writeHead.lastCall.arg).equals(418); expect(mockRes.writeHead.lastCall.args[1]).deep.equals({ 'location': responseMessage.payload.headers.location }); expect(mockRes.end.callCount).equals(1); expect(String(mockRes.end.lastCall.arg)).equals('A redirect message'); done(); }); it('will not rewrite location where there is no basePath', function(done) { delete(handlerConfig.http.basePath); responseMessage.payload.body = 'A redirect message'; responseMessage.payload.headers.location = '/some/other'; handler(mockReq, mockRes, mockNext); expect(mockRequester.once.lastCall.arg).equals('end'); var end = mockRequester.once.lastCall.args[1]; expect(end).exists(); end(); expect(mockRes.writeHead.callCount).equals(1); expect(mockRes.writeHead.lastCall.arg).equals(418); expect(mockRes.writeHead.lastCall.args[1]).deep.equals({ 'location': responseMessage.payload.headers.location }); expect(mockRes.end.callCount).equals(1); expect(String(mockRes.end.lastCall.arg)).equals('A redirect message'); done(); }); }); }); }); }); <file_sep>/lib/routeHandler.js 'use strict'; var stream = require('stream'); var _ = require('lodash'); var msb = require('msb'); var helpers = require('./helpers'); var debug = require('debug')('http2bus'); /* Returns a handler that publishes incoming requests and responds where a response can be constructed. @param {object} config @param {object} config.bus @param {string} config.bus.namespace @param {number} [config.bus.responseTimeout=3000] @param {number} [config.bus.waitForResponses=-1] 0=return immediately, 1+=return after n, -1=wait until timeout */ module.exports = function(config) { return function(req, res, next) { var requesterConfig = prepareTaggedConfig(req, config.bus); var requester = new msb.Requester(requesterConfig); if (requester.message.tags) { requester.message.tags.unshift(requester.message.correlationId); } var request = { url: req.url, method: req.method, headers: req.headers, params: req.params, query: req.query, body: null, bodyBuffer: null }; if (config.http.basePath) { request.url = request.url.slice(config.http.basePath.length); if (request.url[0] !== '/') { request.url = '/' + request.url; } } if (req.body) { var textType = helpers.contentTypeIsText(req.headers['content-type'] || ''); if (textType === 'json') { request.body = JSON.parse(req.body.toString()); } else if (textType) { request.body = req.body.toString(); } else { request.bodyBuffer = req.body.toString('base64'); } } requester .publish(request) .once('error', next) .on('response', debug) .once('end', function() { res.setHeader('x-msb-correlation-id', requester.message.correlationId); if (!requester.responseMessages.length) { res.writeHead((config.bus.waitForResponses) ? 503 : 204); res.end(); return; } var response = _.last(requester.responseMessages).payload; var body = response.body; var defaultHeaders = {}; var headers = _.omit(response.headers, 'access-control-allow-origin', 'access-control-allow-headers', 'access-control-allow-methods', 'access-control-allow-credentials'); if (response.bodyBuffer) { body = new Buffer(response.bodyBuffer, 'base64'); if (!headers['content-type']) defaultHeaders['content-type'] = 'application/octet-stream'; } else if (body && !_.isString(body)) { body = JSON.stringify(body); if (!headers['content-type']) defaultHeaders['content-type'] = 'application/json'; } if (!body) defaultHeaders['content-length'] = 0; if (config.http.basePath && headers.location && headers.location[0] === '/') { headers.location = config.http.basePath + headers.location; } // Note: setHeader is required to ensure _headers are set on the res res.writeHead(response.statusCode || 200, _.defaults(defaultHeaders, headers)); res.end(body); }); }; }; function prepareTaggedConfig(req, busConfig) { var tagsHeaderArr = req.headers['x-msb-tags'] && String(req.headers['x-msb-tags']).split(','); var tagsQueryArr = req.query && req.query['_x-msb-tags'] && String(req.query['_x-msb-tags']).split(','); if (!tagsHeaderArr && !tagsQueryArr) return busConfig; return _.defaults({ tags: _.union(tagsHeaderArr, tagsQueryArr, busConfig.tags) }, busConfig); } <file_sep>/test/routesProvider.infoCenter.test.js /* Setup */ var Lab = require('lab'); var Code = require('code'); var lab = exports.lab = Lab.script(); var describe = lab.describe; var it = lab.it; var before = lab.before; var beforeEach = lab.beforeEach; var after = lab.after; var afterEach = lab.afterEach; var expect = Code.expect; /* Modules */ var _ = require('lodash'); var simple = require('simple-mock'); var routesInfoCenter = require('../lib/routesProvider/infoCenter'); var InfoCenter = require('msb/lib/infoCenter'); describe('routesInfoCenter', function() { afterEach(function(done) { simple.restore(); done(); }); describe('sharedInfoCenter()', function() { var infoCenter; beforeEach(function(done) { infoCenter = routesInfoCenter.sharedInfoCenter(); infoCenter.doc = {}; infoCenter.docInProgress = {}; done(); }); it('always returns the same infoCenter', function(done) { expect(routesInfoCenter.sharedInfoCenter()).equals(infoCenter); expect(infoCenter instanceof InfoCenter).true(); expect(infoCenter instanceof routesInfoCenter.RoutesInfoCenter).true(); done(); }); describe('onAnnouncement()', function() { it('will not make changes if there\'s not a valid payload', function(done) { simple.mock(infoCenter, 'emit'); infoCenter.docInProgress = null; infoCenter.onAnnouncement({}); expect(infoCenter.emit.callCount).equals(0); infoCenter.onAnnouncement({ payload: null }); expect(infoCenter.emit.callCount).equals(0); infoCenter.onAnnouncement({ payload: { body: null } }); expect(infoCenter.emit.callCount).equals(0); infoCenter.onAnnouncement({ payload: { body: { name: '' } } }); expect(infoCenter.emit.callCount).equals(0); var mockBody = { name: 'abc' }; infoCenter.onAnnouncement({ payload: { body: mockBody } }); expect(infoCenter.emit.callCount).equals(1); expect(infoCenter.emit.lastCall.arg).equals('updated'); expect(infoCenter.emit.lastCall.args[1]).equals(infoCenter.doc); expect(infoCenter.doc.abc).equals(mockBody); done(); }); it('should replace an existing provider with a newer version', function(done) { infoCenter.docInProgress.abc = { versionHash: 'a' }; infoCenter.doc.abc = { versionHash: '9' }; var mockBody = { name: 'abc', versionHash: 'b' }; infoCenter.onAnnouncement({ payload: { body: mockBody } }); expect(infoCenter.docInProgress.abc).equals(mockBody); expect(infoCenter.doc.abc).equals(mockBody); done(); }); it('should not replace an existing provider with an invalid version', function(done) { infoCenter.docInProgress.abc = { versionHash: 'a' }; infoCenter.doc.abc = { versionHash: '9' }; var mockBody = { name: 'abc' }; infoCenter.onAnnouncement({ payload: { body: mockBody } }); expect(infoCenter.docInProgress.abc).not.equals(mockBody); expect(infoCenter.doc.abc).not.equals(mockBody); done(); }); }); describe('onHeartbeat()', function() { it('will not make changes if there\'s not a valid payload', function(done) { simple.mock(infoCenter, 'emit'); infoCenter.onHeartbeatResponse({}); expect(infoCenter.emit.callCount).equals(0); expect(infoCenter.docInProgress.abc).not.exists(); infoCenter.onHeartbeatResponse({ body: null }); expect(infoCenter.emit.callCount).equals(0); expect(infoCenter.docInProgress.abc).not.exists(); infoCenter.onHeartbeatResponse({ body: { name: '' } }); expect(infoCenter.emit.callCount).equals(0); expect(infoCenter.docInProgress.abc).not.exists(); var mockBody = { name: 'abc' }; infoCenter.onHeartbeatResponse({ body: mockBody }); expect(infoCenter.docInProgress.abc).equals(mockBody); done(); }); it('should replace an existing provider with a newer version', function(done) { infoCenter.docInProgress.abc = { versionHash: 'a' }; var mockBody = { name: 'abc', versionHash: 'b' }; infoCenter.onHeartbeatResponse({ body: mockBody }); expect(infoCenter.docInProgress.abc).equals(mockBody); done(); }); it('should not replace an existing provider with an invalid version', function(done) { infoCenter.docInProgress.abc = { versionHash: 'a' }; var mockBody = { name: 'abc' }; infoCenter.onHeartbeatResponse({ body: mockBody }); expect(infoCenter.docInProgress.abc).not.equals(mockBody); done(); }); }); describe('onHeartbeatEnd()', function() { it('should emit an updated doc', function(done) { simple.mock(infoCenter, 'emit'); var docInProgress = infoCenter.docInProgress; infoCenter.onHeartbeatEnd(); expect(infoCenter.doc).equals(docInProgress); expect(infoCenter.docInProgress).equals(null); expect(infoCenter.emit.callCount).equals(1); expect(infoCenter.emit.lastCall.arg).equals('updated'); expect(infoCenter.emit.lastCall.args[1]).equals(docInProgress); done(); }); }); }); }); <file_sep>/test/routesProvider.agent.test.js /* Setup */ var Lab = require('lab'); var Code = require('code'); var lab = exports.lab = Lab.script(); var describe = lab.describe; var it = lab.it; var before = lab.before; var beforeEach = lab.beforeEach; var after = lab.after; var afterEach = lab.afterEach; var expect = Code.expect; /* Modules */ var _ = require('lodash'); var simple = require('simple-mock'); var routesAgent = require('../lib/routesProvider/agent'); describe('routesProvider.agent', function() { describe('an instance', function() { var agent; var updatedAt; beforeEach(function(done) { updatedAt = new Date('2014-12-15'); agent = routesAgent.create({ name: 'abcdefg', ttl: 11111, updatedAt: updatedAt }); done(); }); it('should be normally instantiated with ttl and predefined updatedAt', function(done) { expect(agent.doc.name).equals('abcdefg'); expect(agent.doc.ttl).equals(11111); expect(agent.doc.updatedAt).equals(updatedAt); done(); }); describe('load()', function() { it('should validate routes to schema', function(done) { var err; try { agent.load([ { bus: { namespace: '' }, http: {} } ]); } catch(e) { err = e; } expect(err).exists(); done(); }); it('should load routes onto agent and do a broadcast', function(done) { simple.mock(agent, 'doBroadcast').returnWith(); var returned = agent.load([ { provider: { name: 'hierarchy' }, http: { basePath: '/sub-api' } }, { bus: { namespace: 'zzz:111', tags: ['abcdefg', 'kkk'] }, http: { path: '*' } }, { bus: { namespace: 'zzz:112', tags: ['mmm'] }, http: { path: '*' } }, { bus: { namespace: 'zzz:113' }, http: { path: '*' } } ]); expect(returned).equals(agent); expect(returned.doc.versionHash).equals('14186016000007031128c41cc6409babfdbcb4c02b5a4'); expect(returned.doc.routes[1].bus.tags).deep.equals(['abcdefg', 'kkk']); expect(returned.doc.routes[2].bus.tags).deep.equals(['mmm', 'abcdefg']); expect(returned.doc.routes[3].bus.tags).deep.equals(['abcdefg']); done(); }); }); }); }); <file_sep>/app.js 'use strict'; var msb = require('msb'); var app = exports; app.config = require('./lib/config'); app.start = function(cb) { if (app.config.channelMonitorEnabled) msb.channelMonitorAgent.start(); var RouterWrapper = require('./lib/routerWrapper').RouterWrapper; app.router = new RouterWrapper(); app.router.load(app.config.routes); app.createServer() .listen(app.config.port) .once('listening', function() { app.config.port = this.address().port; if (cb) { cb(); } console.log('http2bus listening on ' + app.config.port); }); }; app.createServer = function() { var http = require('http'); var finalhandler = require('finalhandler'); return http.createServer(function(req, res) { app.router.middleware(req, res, finalhandler(req, res)); }); }; app.routesAgent = require('./lib/routesProvider/agent'); <file_sep>/lib/routerWrapper.js var _ = require('lodash'); var msb = require('msb'); var cors = require('cors'); var Router = require('router'); var routesProvider = require('./routesProvider'); var routeHandler = require('./routeHandler'); var normaliseQueryMiddleWare = require('./middleware/normaliseQuery'); var bufferRawBodyMiddleware = require('./middleware/bufferRawBody'); var wrappedRouter; function RouterWrapper() { this.middleware = this.middleware.bind(this); this._providers = []; } var routerWrapper = RouterWrapper.prototype; routerWrapper.middleware = function(req, res, next) { if (!this.wrappedRouter) return next(); this.wrappedRouter(req, res, next); }; routerWrapper.reset = function() { this.wrappedRouter = null; this._setProvidersCache(null); }; routerWrapper.load = function(routes) { var self = this; var newWrappedRouter = new Router({ mergeParams: true }); var providers = []; routes.forEach(function(route) { var path = (route.http.basePath || '') + (route.http.path || ''); if (route.provider) { var provider = self._findOrCreateProvider(route.provider); providers.push(provider); newWrappedRouter.use(path, provider.routerWrapper.middleware); return; } function mapRouteForMethod(method) { var middleware = [ cors(route.http.cors), normaliseQueryMiddleWare ]; if (msb.plugins && msb.plugins.http2busMiddleware) { middleware.push(msb.plugins.http2busMiddleware(route)); } if (method === 'put' || method === 'post' || method === 'use') { middleware.push(bufferRawBodyMiddleware(route)); } newWrappedRouter[method](path, middleware, routeHandler(route)); } if (route.http.remote) { mapRouteForMethod('use'); } else { var methods = route.http.methods || ['get']; methods.forEach(mapRouteForMethod); if (!~methods.indexOf('options')) newWrappedRouter.options(path, cors(route.http.cors)); } }); this.wrappedRouter = newWrappedRouter; this._setProvidersCache(providers); }; routerWrapper._findOrCreateProvider = function(config) { var existingProvider = _.find(this._providers, function(provider) { return provider.isProviderForConfig(config); }); return existingProvider || new routesProvider.RoutesProvider(config); }; routerWrapper._setProvidersCache = function(providers) { var providersToRemove = _.difference(this._providers, providers); providersToRemove.forEach(function(provider) { provider.release(); }); this._providers = providers; }; exports.RouterWrapper = RouterWrapper; <file_sep>/test/app.test.js 'use strict'; /* Setup */ var Lab = require('lab'); var Code = require('code'); var lab = exports.lab = Lab.script(); var describe = lab.describe; var it = lab.it; var before = lab.before; var beforeEach = lab.beforeEach; var after = lab.after; var afterEach = lab.afterEach; var expect = Code.expect; /* Modules */ var http = require('http'); var simple = require('simple-mock'); var msb = require('msb'); var app = require('../app'); var routerWrapper = require('../lib/routerWrapper'); describe('http2bus.app', function() { afterEach(function(done) { simple.restore(); done(); }); describe('start()', function() { it('should create server and listen', function(done) { var mockRouterWrapper = { load: simple.mock(), middleware: simple.mock() }; simple.mock(routerWrapper, 'RouterWrapper').returnWith(mockRouterWrapper); var mockServer = { listen: simple.mock(), once: simple.mock(), address: simple.mock() }; mockServer.listen.returnWith(mockServer); mockServer.once.callback().inThisContext(mockServer); mockServer.address.returnWith({ port: 99999 }); simple.mock(http, 'createServer').returnWith(mockServer); app.start(function() { expect(http.createServer.callCount).equals(1); expect(http.createServer.lastCall.arg).exists(); expect(mockServer.listen.called).true(); http.createServer.lastCall.arg('a', 'b'); expect(mockRouterWrapper.middleware.callCount).equals(1); expect(mockRouterWrapper.middleware.lastCall.args[0]).equals('a'); expect(mockRouterWrapper.middleware.lastCall.args[1]).equals('b'); expect(typeof mockRouterWrapper.middleware.lastCall.args[2]).equals('function'); done(); }); }); }); }); <file_sep>/lib/config.js 'use strict'; var config = exports; // Defaults config.channelMonitorEnabled = true; config.routes = []; <file_sep>/lib/routesProvider/infoCenter.js var util = require('util'); var _ = require('lodash'); var msb = require('msb'); var InfoCenter = require('msb/lib/infoCenter'); function RoutesInfoCenter(config) { RoutesInfoCenter.super_.apply(this, arguments); } util.inherits(RoutesInfoCenter, InfoCenter); var infoCenter = RoutesInfoCenter.prototype; // Overrides infoCenter.onAnnouncement = function(message) { var payload = message.payload; if (!payload || !payload.body || !payload.body.name) return; // Invalid if (this.docInProgress) mergeRoutes(this.docInProgress, payload.body); mergeRoutes(this.doc, payload.body); this.emit('updated', this.doc); }; // Overrides infoCenter.onHeartbeatResponse = function(payload, message) { if (!payload.body || !payload.body.name) return; // Invalid mergeRoutes(this.docInProgress, payload.body); }; // Overrides infoCenter.onHeartbeatEnd = function() { this.doc = this.docInProgress; this.docInProgress = null; this.emit('updated', this.doc); }; function mergeRoutes(doc, body) { if (!doc) return; if (!doc[body.name] || doc[body.name].versionHash < body.versionHash) { doc[body.name] = body; } } var sharedInfoCenter; exports.sharedInfoCenter = function() { if (sharedInfoCenter) return sharedInfoCenter; sharedInfoCenter = new RoutesInfoCenter({ announceNamespace: '_http2bus:routes:announce', heartbeatsNamespace: '_http2bus:routes:heartbeat', heartbeatTimeoutMs: 5000, heartbeatIntervalMs: 10 * 60000 }, msb.channelManager); return sharedInfoCenter; }; exports.RoutesInfoCenter = RoutesInfoCenter; <file_sep>/test/normaliseQuery.test.js 'use strict'; /* Setup */ var Lab = require('lab'); var Code = require('code'); var lab = exports.lab = Lab.script(); var describe = lab.describe; var it = lab.it; var before = lab.before; var beforeEach = lab.beforeEach; var after = lab.after; var afterEach = lab.afterEach; var expect = Code.expect; /* Modules */ var normaliseQuery = require('../lib/middleware/normaliseQuery'); /* Tests */ describe('normaliseQuery', function() { it('it should be possible to parse convert query strings to objects', function(done) { var req = { url : 'http://127.0.0.1?a=a&b.c=b_c' }; normaliseQuery(req, null, function() { expect(req.query).to.be.deep.equal({ a: 'a', b: { c: 'b_c' } }); done(); }); }); it('it should be possible to parse convert query strings to array', function(done) { var req = { url : 'http://127.0.0.1?a=a&b[0]=b&d.e=e' }; normaliseQuery(req, null, function() { expect(req.query).to.be.deep.equal({ a: 'a', b: ['b'], d: { e: 'e' } }); done(); }); }); });
72a5455eeab3d1ed53b006e7858e0ebeadd8595a
[ "JavaScript", "Markdown" ]
12
JavaScript
tcdl/msb-http2bus
dc58aa515cd031d17de6b840dbbed227d6e7cc37
b68b0403e0357a12f934f9ef5b3e6dc5628070ae
refs/heads/master
<file_sep>package com.joebee.prompter; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.HashMap; import java.util.Map; import java.util.List; import java.util.ArrayList; import java.util.Collections; import java.util.Arrays; import com.joebee.model.Player; import com.joebee.model.Players; import com.joebee.model.Team; import com.joebee.model.Teams; public class TeamBuilder { private Players mPlayers; private BufferedReader mReader; private Map<String, String> mMenu; private Teams mTeams; //Constructor public TeamBuilder(Players players, Teams teams) { mTeams = teams; mPlayers = players; mReader = new BufferedReader(new InputStreamReader(System.in)); mMenu = new HashMap<String, String>(); mMenu.put("1", "Create a new Team"); mMenu.put("2", "Add Player to Team"); mMenu.put("3", "Remove a Player from a Team"); mMenu.put("4", "Height Report per Team"); mMenu.put("5", "League Balance Report - Experience"); mMenu.put("6", "Print Team Roster"); mMenu.put("7", "Quit"); // run(); } private String promptAction() throws IOException { for (Map.Entry<String, String> option : mMenu.entrySet()) { System.out.printf("%s - %s %n", option.getKey(), option.getValue()); } System.out.printf("What do you want to do? %n"); String choice = mReader.readLine(); return choice.trim().toLowerCase(); } public void run() { String choice = ""; do { try { choice = promptAction(); switch(choice) { case "1": promptNewTeam(); break; case "2": Team chosenTeam = promptTeamList(); mPlayers.printPlayers(); Player player = promptPlayerList(mPlayers); addPlayer(chosenTeam, player); break; // String artist = promptArtist(); // Song artistSong = promptSongForArtist(artist); // mSongQueue.add(artistSong); // System.out.printf("You chose: %s %n", artistSong); // break; case "3": chosenTeam = promptTeamList(); if (chosenTeam.getTeamRoster().size() == 0) { System.out.printf("%nThere are no players on this team!%n" + "Please, start by adding players to this team first!%n"); break; } printSortedTeamPlayers(chosenTeam); ArrayList<Player> teamPlayers = chosenTeam.getTeamRoster(); player = promptPlayerList(teamPlayers); removePlayer(chosenTeam, player); break; case "4": chosenTeam = promptTeamList(); runHeightReport(chosenTeam); break; case "5": chosenTeam = promptTeamList(); runLeagueBalanceReport(chosenTeam); break; case "6": chosenTeam = promptTeamList(); printRoster(chosenTeam); break; case "7": break; default: System.out.printf("Not on the list: " + choice + ". Try again. %n"); } } catch(IOException ioe) { System.out.println("Problem with input"); ioe.printStackTrace(); } }while(!choice.equals("7")); } private void removePlayer(Team chosenTeam, Player player) { mTeams.removePlayer(chosenTeam, player); mPlayers.getPlayers().add(player); System.out.printf("%n%s %s was removed from the team \"%s\".%n", player.getFirstName(), player.getLastName(), chosenTeam.getName()); printSortedTeamPlayers(chosenTeam); } private void addPlayer(Team chosenTeam, Player player) { mTeams.addPlayer(chosenTeam, player); if (mTeams.getNumberOfTeams() == 0) { promptNewTeam(); } mPlayers.getPlayers().remove(player); System.out.printf("%n%s %s was added to the team \"%s\".%n", player.getFirstName(), player.getLastName(), chosenTeam.getName()); printSortedTeamPlayers(chosenTeam); } private void printRoster(Team chosenTeam) { System.out.printf("%nTeam Roster for team \"%s\".%n", chosenTeam.getName()); if (chosenTeam.getTeamRoster().size() == 0) { System.out.println("\nZero Players on this team!\n"); return; } System.out.printf("%nCoach - %s.%n", chosenTeam.getCoach()); System.out.printf(""); printSortedTeamPlayers(chosenTeam); System.out.println(); } private void printSortedTeamPlayers(Team chosenTeam) { String teamName = chosenTeam.getName(); System.out.printf("Current list of players for \"%s\":%n", teamName); Collections.sort(chosenTeam.getTeamRoster(), (p1, p2) -> p1.compareTo(p2)); for (Player player : chosenTeam.getTeamRoster()) { String previouslyExperienced = player.previouslyExperienced(); System.out.printf("Player #%d: %s %s - Standing at %d inches tall, and is %s%n", chosenTeam.getTeamRoster().indexOf(player) + 1, player.getFirstName(), player.getLastName(), player.getHeightInInches(), player.previouslyExperienced()); } // System.out.println(); } private void runHeightReport(Team chosenTeam) { System.out.println("Height Report for team \"" + chosenTeam.getName() + "\"\n"); if (chosenTeam.getTeamRoster().size() != 0) { for (String heightEvaluation : chosenTeam.getHeightEvaluations()) { List<Player> playersForHeight = chosenTeam.getPlayersForHeight(heightEvaluation); Collections.sort(playersForHeight, (p1, p2) -> p1.compareTo(p2)); String heightEvalString; if (heightEvaluation.equals("Below Average")) { heightEvalString = "< 39"; } else if (heightEvaluation.equals("Average")) { heightEvalString = "39 - 42"; } else { heightEvalString = "> 42"; } int playersCount = playersForHeight.size(); System.out.printf(" " + heightEvaluation + "(" + heightEvalString + " in) - " + playersCount + ""); for (Player player : playersForHeight) { System.out.printf("%n\t- " + player.getLastName() + ", " + player.getFirstName() + " (" + player.getHeightInInches() +" in)%n"); } System.out.println(); } }else { System.out.println("Zero Players on this team!"); } } private Player promptPlayerList(ArrayList<Player> teamPlayers) { int playersNumber = 0; do { System.out.printf("\nChoose the player by entering anumber: "); int playersNumberAsString = readIntLine(); playersNumber = playersNumberAsString; if (playersNumber <= 0 || playersNumber > teamPlayers.size()) { System.out.printf("Please, enter a number within the range of 1 to %d.%n", teamPlayers.size()); } } while (playersNumber <= 0 || playersNumber > teamPlayers.size()); return teamPlayers.get(playersNumber - 1); } private Player promptPlayerList(Players players) { String playersNumberAsString = ""; int playersNumber = 0; do { System.out.printf("%nPlease choose the player by using his or her number: "); playersNumber = readIntLine(); if (playersNumber <= 0 || playersNumber > players.getPlayers().size()) { System.out.printf("Please, enter a number within the range of 1 to %d.%n", players.getPlayers().size()); } } while (playersNumber <= 0 || playersNumber > players.getPlayers().size()); return players.getPlayers().get(playersNumber - 1); } private Team promptTeamList() throws IOException { System.out.println("Choose a Team:"); List<String> teamList = new ArrayList<>(); List<Team> teamArray = mTeams.getTeamList(); for(Team team : teamArray) { String name = team.getName(); String coach = team.getCoach(); String teamInfo = name + ", coached by " + coach + "."; // teamList.add(teamInfo); } int index = promptForIndex(teamList); return mTeams.getTeamList().get(index); } private int readIntLine() { int maxQuantity = 0; boolean done = false; while (!done) { try { maxQuantity = Integer.parseInt(mReader.readLine()); done = true; } catch (NumberFormatException nfe) { System.out.println("Sorry, you must enter a number! Please try again."); } catch (IOException ioe) { System.out.println("This is an IOE Error"); } } return maxQuantity; } private int promptForIndex(List<String> options) throws IOException { int counter = 1; for (String option : options) { System.out.printf("%d.) %s %n", counter, option); counter++; } System.out.print("Your choice: "); int choice = readIntLine(); return choice - 1; } public void promptNewTeam() { try { System.out.printf("%nWhat will your new team be called?%n"); String teamName = mReader.readLine(); System.out.printf("%nWho will coach this new team?%n"); String coach = mReader.readLine(); Team team = new Team(teamName, coach); mTeams.addTeam(team); System.out.printf("%nTeam %s added! %n%n", team.getName()); } catch (IOException ioe) { System.out.println("This is an error"); } } public void runLeagueBalanceReport(Team chosenTeam) { int experiencedPlayers = 0; int inexperiencedPlayers = 0; for(Player p : chosenTeam.getTeamRoster()) { if(p.isPreviousExperience() == true) { experiencedPlayers++; }else { inexperiencedPlayers++; } } System.out.println("There are " + experiencedPlayers + " experienced players and " + inexperiencedPlayers + " non-experienced players on this team."); } } <file_sep>package com.joebee.model; import java.util.ArrayList; import java.util.List; import java.util.Map; public class Teams{ private List<Team> mTeams; private Players mPlayers; private int mTotalPlayers; private int mAvailablePlayers; public Teams(Players players) { mAvailablePlayers = 0; mTeams = new ArrayList<Team>(); mPlayers = players; mAvailablePlayers = mPlayers.getPlayers().size(); } public ArrayList<Player> findTeamPlayers(Team chosenTeam) { ArrayList<Player> players = new ArrayList<>(); for (int i = 0; i < mTeams.size(); i++) { if (chosenTeam.equals(mTeams.get(i))) { players = mTeams.get(i).getTeamRoster(); } } return players; } public int getTotalAvailablePlayers() { return mTotalPlayers; } public void addTeam(Team team) { mTeams.add(team); } public List<Team> getTeamList() { return mTeams; } public void setTeams(List<Team> teams){ mTeams = teams; } public int getNumberOfTeams() { int teamNumber = mTeams.size(); return teamNumber; } public void addPlayer(Team team, Player player) { for(int i = 0; i < mTeams.size(); i++) { if (team.equals(mTeams.get(i))) { mTeams.get(i).getTeamRoster().add(player); } } } public void removePlayer(Team team, Player player) { for (int i = 0; i < mTeams.size(); i++) { if (team.equals(mTeams.get(i))) { mTeams.get(i).getTeamRoster().remove(player); } } } } <file_sep>import com.joebee.model.Player; import com.joebee.model.Players; import com.joebee.model.Teams; import com.joebee.prompter.TeamBuilder; public class LeagueManager { public static void main(String[] args) { Players players = new Players(); Teams teams = new Teams(players); TeamBuilder teamBuilder = new TeamBuilder(players, teams); teamBuilder.run(); } }
3f6cff9d3fc75605d23214319d1f7105ee2f78e4
[ "Java" ]
3
Java
JBogaert/Soccer-League-Organizer
4521c416bddbd046e304cf3c64b87f1464ca4336
82d074415fee9a2c7564e9122e53ae073e39f464
refs/heads/master
<file_sep>export default { bool: bool => bool, } <file_sep>import test from '../../test'; describe('aw-test', () => { it('should return true', () => { const bool = true; expect(test.bool(bool)).to.equal(bool); }) }) <file_sep># afterwork.js test ### Start ```npm run start``` ## Test ```npm run test``` <file_sep>import test from './test.js'; console.info('aw-test', test.bool(false));
5eb05d661f734d744d546b64723bad8d141bca7a
[ "JavaScript", "Markdown" ]
4
JavaScript
bjornwiberg/aw-test
348b50b41281b16cb0a5165423350a91cd3a339e
55e91e0d32dadc252416a82118a04b01bd42c7d5
refs/heads/master
<file_sep>import React, { Component } from 'react'; import { Switch, Route } from "react-router-dom"; import TodoList from "./TodoList"; import TodoForm from "./TodoForm"; const SwitchPages = (todoProp) => ( <Switch> <Route exact path="/" render={ props => ( <TodoList { ...props } todos={ todoProp.todos } /> )} /> <Route exact path="/todo/create" render={ props => ( <TodoForm { ...props } onFormSubmit={ (todo) => ( todoProp.onTodoSave(todo) ) } /> )} /> </Switch> ) export default SwitchPages;<file_sep>import React, { Component } from 'react'; import './TodoForm.css'; class TodoForm extends Component { constructor(props) { super(props) this.state = { name: '', category: '' } } handleInputChange = (e) => { e.preventDefault(); const { name, value } = e.target; this.setState({ [ name ]: value }); } handleFormSubmit = (e) => { e.preventDefault(); const data = this.state; this.props.onFormSubmit({ ...data }); this.handleFormClear(e); this.props.history.push('/'); } handleFormClear = (e) => { e.preventDefault(); this.setState({ name: '', category: '' }) } handleFormCancel = (e) => { e.preventDefault(); this.handleFormClear(e); this.props.history.push('/'); } render() { return ( <div className="card todo-form"> <div className="card-header" style={{ backgroundColor: 'white', height: '50px' }}> <h3 style={{ textAlign: 'center' }} >Add New Todo</h3> </div> <div className="card-body"> <form onSubmit={ this.handleFormSubmit }> <div className="form-group"> <label for="name">Todo Name:</label> <input type="text" className="form-control" id="name" name="name" value={ this.state.name } onChange={ this.handleInputChange } /> </div> <div className="form-group"> <label for="category">Category:</label> <input type="text" className="form-control" id="category" name="category" value={ this.state.category } onChange={ this.handleInputChange } /> </div> <div className="form-group"> <p className="form-control"> { this.state.timeDue } </p> </div> <div className="form-group"> <label for="category">Time Due For Completion:</label> <input type="time" className="form-control" id="time_due" name="timeDue" value={ this.state.timeDue } onChange={ this.handleInputChange } /> </div> <button className="btn btn-primary">Submit</button> <button className="btn btn-success" onClick={ this.handleFormClear } > Clear Fields </button> <button className="btn btn-danger" onClick={ this.handleFormCancel } > Cancel </button> </form> </div> </div> ) } } export default TodoForm;<file_sep>import React from 'react'; import './Todo.css' function Todo(props) { const { id, name, category, timeCreated, timeDue } = props; return ( <div className="card a-todo"> <div className="card-body"> <h4 className="card-title">{ category }</h4> <h3 className="card-text">{ name }</h3> <p className="card-text"> <span className="card-text">Created: { timeCreated }</span> <span style={{float: 'right'}} className="card-text" >Done Before: { timeDue } </span> </p> <a href="#" className="stretched-link" style={{textDecoration: 'none'}} >Full Preview</a> </div> </div> ) } export default Todo;<file_sep>import React, { Component } from 'react'; import SwitchPages from './SwitchPages'; import Navbar from "./Navbar"; import { Link } from 'react-router-dom'; class TodoApp extends Component { constructor(props) { super(props); this.state = { todos: [], nextTodoId: '' } } componentDidMount() { this.setState({ todos: [ { id: 1, name: 'Create A React Project', category: 'Learning', timeCreated: '', timeDue: '' }, { id: 2, name: '<NAME>', category: 'Domestic Duties', timeCreated: '', timeDue: '' } ], nextTodoId: 3 }) } handleTodoSave = (todo) => { this.setState((prevState, props) => { //Create the new todo first const newTodo = { ...todo, id: this.state.nextTodoId }; //Now return the changes you want in the state return { nextTodoId: prevState.nextTodoId + 1, todos: [ ...this.state.todos, newTodo ] } }) } render() { // const { todos, nextTodoId } = this.state; const s = { textDecoration: 'none', cursor: 'default', color: 'pink' } return ( <div className="App"> <Navbar /> <div> <SwitchPages { ...this.state } onTodoSave={ this.handleTodoSave } /> {/* <SwitchPages todos={ todos } nextTodoId={ nextTodoId } /> */} </div> </div> ); } } export default TodoApp; <file_sep>import React, { Component } from 'react'; import './Navbar.css'; import { NavLink } from "react-router-dom"; class Navbar extends Component { constructor(props) { super(props); this.handleClick = this.handleClick.bind(this); } handleClick = (e) => { e.target.preventDefault; } render() { const s = { textDecoration: 'none', cursor: 'default', color: 'pink' } return ( <ul class="nav nav-pills nav-justified"> <li class="nav-item"> <NavLink exact activeStyle={ s } to="/" > ToDoApp </NavLink> </li> <li class="nav-item"> <NavLink exact activeStyle={ s } to="/todo/create" > Add ToDo </NavLink> </li> </ul> ) } } export default Navbar;
a37414ab68fcd609a9e7449d53f72d7bc3339c15
[ "JavaScript" ]
5
JavaScript
adejaremola/multipage-react-todo-app
89db7c26b1efa6091cd5dce1ac6cfae840dfdc2b
0ec87378b121f8bc58f65a7c79aafcb5a55e0444
refs/heads/master
<repo_name>maratbakirov/channel9<file_sep>/SPMeta2/SimpleDemos/Demo02/Model/ContentTypes.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using SPMeta2.Definitions; using SPMeta2.Definitions.ContentTypes; using SPMeta2.Definitions.Fields; using SPMeta2.Enumerations; using SPMeta2.Standard.Definitions.Fields; using SPMeta2.Standard.Definitions.Taxonomy; using SPMeta2.Syntax.Default; namespace Model { public class ContentTypes { public static ContentTypeDefinition Item = new ContentTypeDefinition() { Id = new Guid("{C3922A2C-47E7-4033-82EB-328E7B79E466}"), Name = "DemoItem", ParentContentTypeId = BuiltInContentTypeId.Item, Group = Consts.DefaultMetadataGroup }; public static ContentTypeDefinition SubItem = new ContentTypeDefinition() { Id = new Guid("{89AFF938-01D1-4B43-BBF8-D08AF3A89F1B}"), Name = "DemoSubItem", ParentContentTypeId = Item.GetContentTypeId(), Group = Consts.DefaultMetadataGroup }; public static ContentTypeDefinition Document = new ContentTypeDefinition() { Id = new Guid("{29DB8B44-0ED9-4286-8066-B506E3B53A4E}"), Name = "DemoDocument", ParentContentTypeId = BuiltInContentTypeId.Document, Group = Consts.DefaultMetadataGroup }; public static ContentTypeDefinition SubDocument = new ContentTypeDefinition() { Id = new Guid("{377DE6EF-0929-4E1F-8EE9-F7E8D3BD628A}"), Name = "DemoSubDocument", ParentContentTypeId = Document.GetContentTypeId(), Group = Consts.DefaultMetadataGroup }; public static RemoveContentTypeLinksDefinition RemoveItemContentTypeDefinition { get { return new RemoveContentTypeLinksDefinition() { ContentTypes = new List<ContentTypeLinkValue>() { new ContentTypeLinkValue() {ContentTypeName = "Item"} } }; } } public static RemoveContentTypeLinksDefinition RemoveIDocumentContentTypeDefinition { get { return new RemoveContentTypeLinksDefinition() { ContentTypes = new List<ContentTypeLinkValue>() { new ContentTypeLinkValue() {ContentTypeName = "Document"} } }; } } } }<file_sep>/SPMeta2/SimpleDemos/Demo01/AssetProvisioning/Program.cs using System; using System.Collections.Generic; using System.Configuration; using System.IO; using System.Linq; using System.Security; using System.Text; using System.Threading.Tasks; using Microsoft.SharePoint.Client; using SPMeta2.BuiltInDefinitions; using SPMeta2.CSOM.ModelHosts; using SPMeta2.CSOM.Services; using SPMeta2.Definitions; using SPMeta2.Enumerations; using SPMeta2.Extensions; using SPMeta2.Models; using SPMeta2.Syntax.Default; namespace AssetProvisioning { public class Model { public static SecurityGroupDefinition TestSecurityGroup = new SecurityGroupDefinition() { Name = "TestSecurityGroup", Owner = "TestSecurityGroup", AllowMembersEditMembership = true, AllowRequestToJoinLeave = false, //AllowRequestToJoinLeave = true, Description = "test group", }; public static Guid MySampleContentTypeGuid = new Guid("{35CB73AD-B123-44E9-9138-8C86EEC1E87E}"); public static ContentTypeDefinition MySampleContentType = new ContentTypeDefinition() { ParentContentTypeId = BuiltInContentTypeId.Item, Name = "DemoContact", Id = MySampleContentTypeGuid, Group = "M2Demo" }; public static ModelNode BuildSiteModel() { var siteModel = SPMeta2Model.NewSiteModel( site => { site.AddSecurityGroup(TestSecurityGroup); site.AddContentType(MySampleContentType, contentype => { contentype.AddContentTypeFieldLink(BuiltInFieldId.Description); contentype.AddContentTypeFieldLink(BuiltInFieldId.StartDate); contentype.AddContentTypeFieldLink(BuiltInFieldId.EndDate); }); } ); return siteModel; } public static ModelNode BuilWebModel() { var siteModel = SPMeta2Model.NewWebModel( web=> { web.AddWebFeature(BuiltInWebFeatures.MinimalDownloadStrategy.Inherit( x => { x.Enable = false; x.ForceActivate = true; } )); } ); return siteModel; } } class Program { [STAThread] static void Main(string[] args) { try { ReadSettings(); using (ClientContext ctx = GetAuthenticatedContext()) { ctx.Load(ctx.Web); ctx.ExecuteQuery(); Console.WriteLine(ctx.Web.Url); TraceHelper.TraceInformation("Configuring site"); var provisioningService = new CSOMProvisionService(); var siteModel = Model.BuildSiteModel(); var str1 = siteModel.ToDotGraph(); var str2 = siteModel.ToPrettyPrint(); Console.WriteLine(str2); System.IO.File.WriteAllText("sitemodel.txt",str1); provisioningService.DeployModel(SiteModelHost.FromClientContext(ctx), siteModel); } using (ClientContext ctx = GetAuthenticatedContext()) { ctx.Load(ctx.Web); ctx.ExecuteQuery(); Console.WriteLine(ctx.Web.Url); TraceHelper.TraceInformation("Configuring web"); var provisioningService = new CSOMProvisionService(); var webModel = Model.BuilWebModel(); provisioningService.DeployModel(WebModelHost.FromClientContext(ctx), webModel); } } catch (Exception ex) { TraceHelper.TraceError("an error has occured, message:{0}", ex.Message); } } static bool sharepointonline; private static bool ReadSettings() { var sharepointonlinesetting = ConfigurationManager.AppSettings["SharepointOnline"]; bool.TryParse(sharepointonlinesetting, out sharepointonline); return sharepointonline; } #region auth private static ClientContext GetAuthenticatedContext() { var siteUrl = ConfigurationManager.AppSettings["siteurl"]; var context = new ClientContext(siteUrl); if (sharepointonline) { SecureString password = GetPassword(); context.Credentials = new SharePointOnlineCredentials(ConfigurationManager.AppSettings["sharepointonlinelogin"], password); } return context; } private static SecureString storedPassword = null; private static SecureString GetPassword() { if (storedPassword == null) { Console.WriteLine("Please enter your password"); storedPassword = GetConsoleSecurePassword(); Console.WriteLine(); } return storedPassword; } private static SecureString GetConsoleSecurePassword() { SecureString pwd = new SecureString(); while (true) { ConsoleKeyInfo i = Console.ReadKey(true); if (i.Key == ConsoleKey.Enter) { break; } else if (i.Key == ConsoleKey.Backspace) { pwd.RemoveAt(pwd.Length - 1); Console.Write("\b \b"); } else { pwd.AppendChar(i.KeyChar); Console.Write("*"); } } return pwd; } #endregion } } <file_sep>/SPMeta2/SimpleDemos/Demo02/AssetProvisioning/Utils/ResourceReader.cs using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace AssetProvisioning { public static class ResourceReader { public static string ReadFromResourceName(string name) { var ns = "AssetProvisioning"; using (var reader = new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream(string.Format("{0}.{1}", ns, name)))) { return reader.ReadToEnd(); } } } } <file_sep>/SPMeta2/SimpleDemos/Demo02/Model/Consts.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Model { public static class Consts { public static string DefaultMetadataGroup = "SPMeta2Demo"; } } <file_sep>/SPMeta2/SimpleDemos/Demo02/Model/Taxonomy.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using SPMeta2.Standard.Definitions.Taxonomy; namespace Model { public class Taxonomy { public static TaxonomyTermStoreDefinition TermStore = new TaxonomyTermStoreDefinition { UseDefaultSiteCollectionTermStore = true, }; public static TaxonomyTermGroupDefinition RootGroup = new TaxonomyTermGroupDefinition { Name = "RootGroup1", //Id = new Guid("{0BA27B3B-300F-48B8-AA4E-73FC1A140118}") }; public static TaxonomyTermSetDefinition Location = new TaxonomyTermSetDefinition { Name = "Location", //Id = new Guid("{85EAF349-395B-4D00-9064-5FB46A52FC98}"), LCID = 1033 }; public static TaxonomyTermDefinition RootTerm = new TaxonomyTermDefinition { Name = "Root", //Id = new Guid("{16068867-9F84-4CC1-91DC-2300026EA581}"), LCID = 1033 }; public static TaxonomyTermDefinition SubTerm1 = new TaxonomyTermDefinition { Name = "SubTerm1", //Id = new Guid("{E44898F4-D1AF-4ADB-A6CA-586E6DCBF9C3}"), LCID = 1033 }; public static TaxonomyTermDefinition SubTerm2 = new TaxonomyTermDefinition { Name = "SubTerm1.1", //Id = new Guid("{643BBA8E-2404-4352-994B-A111F01EEBB7}"), LCID = 1033 }; } } <file_sep>/SPMeta2/SimpleDemos/Demo02/AssetProvisioning/Pages.cs using System; using System.Collections.Generic; using System.Linq; using System.Resources; using System.Text; using System.Threading.Tasks; using SPMeta2.BuiltInDefinitions; using SPMeta2.Definitions; using SPMeta2.Enumerations; using SPMeta2.Models; using SPMeta2.Syntax.Default; namespace Model { public static class Pages { public static WebPartDefinition GettingStarted = new SPMeta2.Definitions.WebPartDefinition { Title = "Getting started with site", Id = "spmGettingStarted", ZoneId = "Main", ZoneIndex = 100, WebpartXmlTemplate = AssetProvisioning.ResourceReader.ReadFromResourceName("Templates.Webparts.Get started with your site.webpart") }; public static WebPartDefinition ContentEditor = new SPMeta2.Definitions.WebPartDefinition { Title = "SPMeta2 Content Editor Webpart", Id = "spmContentEditorWebpart", ZoneId = "Main", ZoneIndex = 200, WebpartXmlTemplate = AssetProvisioning.ResourceReader.ReadFromResourceName("Templates.Webparts.Content Editor.dwp") }; public static WebPartPageDefinition WebPartPage = new WebPartPageDefinition { Title = "Getting started", FileName = "Getting-Started.aspx", PageLayoutTemplate = BuiltInWebPartPageTemplates.spstd1 }; public static ModelNode BuildPagesModel() { var model = SPMeta2Model .NewWebModel(web => { web .AddList(BuiltInListDefinitions.SitePages, list => { list .AddWebPartPage(WebPartPage, page => { page .AddWebPart(GettingStarted) .AddWebPart(ContentEditor); }); }); }); return model; } } } <file_sep>/SPMeta2/SimpleDemos/Demo01/AssetProvisioning/TraceHelper.cs using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AssetProvisioning { public class TraceHelper { public static void TraceInformation(string str, params object[] args) { TraceInformation(ConsoleColor.Yellow, str, args); } public static void TraceInformation(ConsoleColor color, string str, params object[] args) { var oldColor = Console.ForegroundColor; Console.ForegroundColor = color; Trace.TraceInformation(str, args); Console.ForegroundColor = oldColor; } public static void TraceError(string str, params object[] args) { var oldColor = Console.ForegroundColor; Console.ForegroundColor = ConsoleColor.Red; Trace.TraceError(str, args); Console.ForegroundColor = oldColor; } } } <file_sep>/SPMeta2/SimpleDemos/Demo02/Model/List.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using SPMeta2.Definitions; using SPMeta2.Definitions.Fields; using SPMeta2.Enumerations; using SPMeta2.Standard.Definitions.Fields; using SPMeta2.Standard.Definitions.Taxonomy; namespace Model { public class Lists { public static ListDefinition RootListItem = new ListDefinition() { Url = "testlist", Title = "testlist", ContentTypesEnabled = true, TemplateType = BuiltInListTemplateTypeId.GenericList }; public static ListDefinition RootListLibrary= new ListDefinition() { Url = "testlibrary", Title = "testlibrary", ContentTypesEnabled = true, TemplateType = BuiltInListTemplateTypeId.DocumentLibrary }; } }<file_sep>/SPMeta2/SimpleDemos/Demo02/Model/Fields.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using SPMeta2.Definitions; using SPMeta2.Definitions.Fields; using SPMeta2.Enumerations; using SPMeta2.Standard.Definitions.Fields; using SPMeta2.Standard.Definitions.Taxonomy; namespace Model { public class Fields { public static TaxonomyFieldDefinition MyTaxonomyfield = new TaxonomyFieldDefinition { InternalName = "MyTaxonomyField2", Title = "MyTaxonomyField2", Group = Consts.DefaultMetadataGroup, Id = new Guid("{29E4CBD2-6CA7-47E7-9B5B-FF7725949D58}"), //TermSetId = Taxonomy.Location.Id, TermSetName = "Location", TermSetLCID = 1033, //TermId = Taxonomy.RootTerm.Id, UseDefaultSiteCollectionTermStore = true }; public static FieldDefinition ClientId = new FieldDefinition { Id = new Guid("1d20b513-0095-4735-a68d-c5c972494afc"), Title = "Client ID", InternalName = "clnt_ClientId", Group = Consts.DefaultMetadataGroup, FieldType = BuiltInFieldTypes.Text }; public static FieldDefinition ClientName = new TextFieldDefinition() { Id = new Guid("2a121dbf-ad68-4f2c-af49-f8671dfd4bf7"), Title = "Client Name", InternalName = "clnt_ClientName", Group = Consts.DefaultMetadataGroup }; public static FieldDefinition ClientComment = new NoteFieldDefinition() { Id = new Guid("0d122a96-24ba-4776-a68c-32cf32bb1150"), Title = "Client Comment", InternalName = "clnt_ClientComment", Group = Consts.DefaultMetadataGroup, RichText = true, RichTextMode = BuiltInRichTextMode.FullHtml }; public static FieldDefinition ClientIsNonProfit = new BooleanFieldDefinition() { Id = new Guid("f8e98eee-842c-48a3-a3ad-9a204e809256"), Title = "Client Is Non Profit", InternalName = "clnt_ClientIsNonProfit", Group = Consts.DefaultMetadataGroup, FieldType = BuiltInFieldTypes.Boolean }; public static FieldDefinition Dept = new CurrencyFieldDefinition() { Id = new Guid("c2a3f0fb-024c-43cd-8502-55ce866fb0ec"), Title = "Client Dept", InternalName = "clnt_Dept", Group = Consts.DefaultMetadataGroup, CurrencyLocaleId = 1033 }; public static FieldDefinition Loan = new CurrencyFieldDefinition { Id = new Guid("187ea759-a615-4638-9a0a-e9980327eed6"), Title = "Client Loan", InternalName = "clnt_Loan", Group = Consts.DefaultMetadataGroup, }; public static FieldDefinition Revenue = new CurrencyFieldDefinition { Id = new Guid("306dc168-bdf1-479c-9c41-40c977634dbf"), Title = "Client Revenue", InternalName = "clnt_Revenue", Group = Consts.DefaultMetadataGroup }; public static FieldDefinition ClinentLoginLink = new UserFieldDefinition() { Id = new Guid("d3526287-8657-4be5-a7de-7633441d0213"), Title = "Client Login Link", InternalName = "clnt_LoginLink", Group = Consts.DefaultMetadataGroup, AllowMultipleValues = false, SelectionMode = BuiltInFieldUserSelectionMode.PeopleOnly }; } }<file_sep>/SPMeta2/SimpleDemos/Demo02/Model.CSOM/SiteModel.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.SharePoint.Client; using SPMeta2.BuiltInDefinitions; using SPMeta2.Definitions; using SPMeta2.Definitions.Fields; using SPMeta2.Enumerations; using SPMeta2.Models; using SPMeta2.Standard.Syntax; using SPMeta2.Syntax.Default; using SPMeta2.Syntax.Default.Modern; namespace Model.CSOM { public class SiteModel { public static ModelNode BuildTaxonomyModel() { var siteModel = SPMeta2Model.NewSiteModel( site => { site.AddTaxonomyTermStore(Taxonomy.TermStore, termStore => { termStore.AddTaxonomyTermGroup(Taxonomy.RootGroup, group => { group.AddTaxonomyTermSet(Taxonomy.Location, termSet => { termSet.AddTaxonomyTerm(Taxonomy.RootTerm, term => { term.AddTaxonomyTerm(Taxonomy.SubTerm1, term1 => { term1.AddTaxonomyTerm(Taxonomy.SubTerm2); } ); } ); }); }); }); } ); return siteModel; } public static ModelNode BuildSiteFeaturesModel() { var siteModel = SPMeta2Model.NewSiteModel( site => { site.AddSiteFeature(BuiltInSiteFeatures.SharePointServerPublishingInfrastructure .Inherit( x => { x.Enable = true; x.ForceActivate = true; } )); } ); return siteModel; } public static ModelNode BuildFieldsModel() { var siteModel = SPMeta2Model.NewSiteModel( site => { site.AddField(Fields.MyTaxonomyfield); site.AddField(Fields.ClientId); site.AddField(Fields.ClientName); site.AddField(Fields.ClientComment); site.AddField(Fields.ClientIsNonProfit); site.AddField(Fields.ClinentLoginLink); site.AddField(Fields.Dept); site.AddField(Fields.Loan); site.AddField(Fields.Revenue, f => { f.OnProvisioned<FieldCurrency, CurrencyFieldDefinition>( context => { Console.WriteLine("!!!!!!!! OnProvisioninig " + context.Object.Title); }); }); } ); return siteModel; } public static ModelNode BuildContentTypesModel() { var siteModel = SPMeta2Model.NewSiteModel( site => { site.AddContentType(ContentTypes.Item, contentType => { contentType.AddContentTypeFieldLink(Fields.MyTaxonomyfield); contentType.AddContentTypeFieldLink(Fields.ClientId); contentType.AddContentTypeFieldLink(Fields.ClientName); contentType.AddContentTypeFieldLink(Fields.ClientComment); contentType.AddContentTypeFieldLink(Fields.ClientIsNonProfit); contentType.AddContentTypeFieldLink(Fields.Dept); contentType.AddContentTypeFieldLink(Fields.Loan); contentType.AddContentTypeFieldLink(Fields.Revenue); } ); site.AddContentType(ContentTypes.SubItem, contentType => { contentType.AddContentTypeFieldLink(Fields.ClinentLoginLink); }); site.AddContentType(ContentTypes.Document, contentType => { contentType.AddContentTypeFieldLink(Fields.MyTaxonomyfield); contentType.AddContentTypeFieldLink(Fields.ClientId); contentType.AddContentTypeFieldLink(Fields.ClientName); contentType.AddContentTypeFieldLink(Fields.ClientComment); contentType.AddContentTypeFieldLink(Fields.ClientIsNonProfit); contentType.AddContentTypeFieldLink(Fields.Dept); contentType.AddContentTypeFieldLink(Fields.Loan); contentType.AddContentTypeFieldLink(Fields.Revenue); } ); site.AddContentType(ContentTypes.SubDocument, contentType => { contentType.AddContentTypeFieldLink(Fields.ClinentLoginLink); }); } ); return siteModel; } public static ModelNode BuildWebRootModel() { var webModel = SPMeta2Model.NewWebModel( web => { web.AddWebFeature( BuiltInWebFeatures.MinimalDownloadStrategy.Inherit( x => { x.Enable = false; x.ForceActivate = false; }) ); web.AddList(Lists.RootListItem, list => { list.AddContentTypeLink(ContentTypes.Item); list.AddContentTypeLink(ContentTypes.SubItem); list.AddRemoveContentTypeLinks(ContentTypes.RemoveItemContentTypeDefinition); } ); web.AddList(Lists.RootListLibrary, list => { list.AddContentTypeLink(ContentTypes.Document); list.AddContentTypeLink(ContentTypes.SubDocument); list.AddRemoveContentTypeLinks(ContentTypes.RemoveIDocumentContentTypeDefinition); } ); web.AddList(BuiltInListDefinitions.SitePages, pages => { pages .AddWebPartPage(Pages.KPI) .AddWebPartPage(Pages.MyTasks) .AddWikiPage(Pages.About) .AddWikiPage(Pages.FAQ); }); } ); return webModel; } } } <file_sep>/SPMeta2/SimpleDemos/Demo02/AssetProvisioning/FIles.cs using System; using System.Collections.Generic; using System.Linq; using System.Resources; using System.Text; using System.Threading.Tasks; using SPMeta2.BuiltInDefinitions; using SPMeta2.Definitions; using SPMeta2.Models; using SPMeta2.Syntax.Default; namespace Model { public static class FIles { // Step 1, define security groups public static ModuleFileDefinition HelloModuleFile = new ModuleFileDefinition { FileName = "hello-module.txt", Content = Encoding.UTF8.GetBytes("A hello world module file provision.") }; public static ModuleFileDefinition AngularFile = new ModuleFileDefinition { FileName = "angular.min.js", Content = Encoding.UTF8.GetBytes(AssetProvisioning.ResourceReader.ReadFromResourceName("Modules.js.angular.min.js")) }; public static ModuleFileDefinition JQueryFile = new ModuleFileDefinition { FileName = "jquery-1.11.1.min.js", Content = Encoding.UTF8.GetBytes(AssetProvisioning.ResourceReader.ReadFromResourceName("Modules.js.jquery-1.11.1.min.js")) }; public static FolderDefinition JsFolder = new FolderDefinition { Name = "spmeta2-custom-js" }; public static ModelNode BuildFilesModel() { var model = SPMeta2Model .NewWebModel(web => { web .AddList(BuiltInListDefinitions.StyleLibrary, list => { list .AddModuleFile(HelloModuleFile) .AddFolder(JsFolder, folder => { folder .AddModuleFile(AngularFile) .AddModuleFile(JQueryFile); }); }); }); return model; } } } <file_sep>/SPMeta2/SimpleDemos/Demo02/Model/Pages.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using SPMeta2.Definitions; using SPMeta2.Enumerations; namespace Model { public static class Pages { #region properties public static WikiPageDefinition About = new WikiPageDefinition { Title = "About", FileName = "about.aspx" }; public static WikiPageDefinition FAQ = new WikiPageDefinition { Title = "FAQ", FileName = "FAQ.aspx" }; public static WebPartPageDefinition KPI = new WebPartPageDefinition { Title = "KPI", FileName = "KPI.aspx", PageLayoutTemplate = BuiltInWebPartPageTemplates.spstd1 }; public static WebPartPageDefinition MyTasks = new WebPartPageDefinition { Title = "MyTasks", FileName = "MyTasks.aspx", PageLayoutTemplate = BuiltInWebPartPageTemplates.spstd1 }; #endregion } }
63807e0bc6bf5c8f6e9824ca5cd1c978e212212a
[ "C#" ]
12
C#
maratbakirov/channel9
edb9c3c6ebdfca361596897a61d2c08216a422c3
9a38c99dff6e5a93b27eec5e089043497a0a6c6e
refs/heads/master
<file_sep><?php /** * @author <NAME> * @copyright 2013 Tinboat Webworks * @Project Sodapop * @version 0.0.1.3 * @link http://tinboatwebworks.com * @since 10/20/2011 */ // no direct access defined('_LOCK') or die('Restricted access'); class login extends sodapop { public function login() { global $sodapop; // Let's bring in the global app object so we can access all the environmental info... $this->sodapop = $sodapop; // And give it to this class } public function loginOutput($loginDatabase, $modData) { $cookie = $this->getCookie("sp_login"); $redirect = $modData['redirect']; global $sodapop; $this->sodapop; if ($cookie == '') { $liveUrl = $sodapop->config['liveUrl']; $modOutput = " <form name='login' class='loginForm' action='./user?action=login' method='post'> Username: <input type='text' name='username'> Password: <input type='<PASSWORD>' name='pwd'> <input type='hidden' name='redirect' value='" . $liveUrl . $redirect . "'> <input type='submit' value='Submit'>"; if ($modData['registration'] == "on") { $modOutput .= " <a href='user?action=new'>[Register]</a>"; } if ($modData['recover'] == "on") { $modOutput .= " <a href='user?action=recover'>[Recover]</a>"; } $modOutput .= " </form>"; } else { $userInfo = $this->sodapop->getUserDataById($cookie); $modOutput = "You are logged in as <b><a href='./user'>" . $userInfo['name'] . "</a></b> [<a href='./user?action=logout'>Log out</a>]"; } return $modOutput; } }<file_sep><?php echo $welcome . "<br />(" . $noTemplate . ")<br> Language: " . $language . "<br> PopTop Version: " . $appVersion; ?><file_sep><?php /** * @author <NAME> * @copyright 2013 Tinboat Webworks * @Project Sodapop * @version 0.0.1.3 * @link http://tinboatwebworks.com * @since 10/20/2011 */ // no direct access defined('_LOCK') or die('Restricted access'); class appModel extends database { public function appModel() { global $sodapop; // Let's bring in the global app object so we can access all the environmental info... $this->sodapop = $sodapop; // And give it to this class } /* * getPageListData() */ public function getPagesListData() { $query = " select * from pages order by name"; $result = $this->getData($query); $result = $this->buildResultArray($result); return $result; } /* * getModuleData() */ public function getModuleData() { $query = " select * from modules order by id"; $result = $this->getData($query); $result = $this->buildResultArray($result); return $result; } public Function switchStatus($module) { $status = $module['current']; $id = $module['id']; $query = "update modules set "; if($status == '1') { $query .= "active = '0'"; } if($status == '0') { $query .= "active = '1'"; } $query .= " where id = '$id'"; $result = $this->getData($query); } public Function updateAccessLevel($module) { $level = $module['access']; $id = $module['id']; $query = "update modules set "; $query .= "accessLevel = '$level' "; $query .= "where id = '$id'"; return $result = $this->getData($query); } public Function updatePages($values) { $values = extract($values); $updatePages = implode($pages, ","); $query = "update modules "; if ($updatePages == '0') { $query .= "set pages = '' "; } else { $query .= "set pages = '" . $updatePages ."' "; } $query .= "where id = '". $id . "'"; return $result = $this->getData($query); } public Function updateHidden($values) { $values = extract($values); $updateHidden = implode($hidden, ","); $query = "update modules "; if ($updateHidden == '0') { $query .= "set hidden = '' "; } else { $query .= "set hidden = '" . $updateHidden ."' "; } $query .= "where id = '". $id . "'"; return $result = $this->getData($query); } public Function updateParams($values) { $values = extract($values); if(!empty($params)){ $params = rawurldecode($params); $params = $this->convertParams($params); $query = "update modules "; $query .= "set params = '" . $params ."' where id= '" . $id . "'"; } else { $query = ""; } return $result = $this->getData($query); } public function convertParams($params) { $params = str_replace("\r\n", "::", $params); $params = str_replace("=", "==", $params); // $params = rtrim($params, "::"); // This is dumb, but I have to remove the trailing :: have to find a way to not have it there in the first place. return $params; } public function getTemplateData() { $query = " select * from templates where dflt = '1'"; $result = $this->getData($query); $result = $this->buildResultArray($result); //print_r($result);echo "<br />"; return $result; } public function updatePosition($values) { $values = extract($values); $query = "update modules "; $query .= "set positions = '" . $position ."' where id= '" . $id . "'"; return $result = $this->getData($query); } public function updateModuleOrder($values) { $values = extract($values); $query = "update module where id = $id set ordering = $count"; } } <file_sep><?php /** * @author <NAME> * @copyright 2011 Tinboat Webworks * @version 0.0.1.2 * @link a url * @since 10/20/2011 */ // no direct access defined('_LOCK') or die('Restricted access'); $language['404'] = "The page you are looking for does not exist."; $this->language = $language; ?><file_sep><html> <head> <link rel="stylesheet" type="text/css" media="screen" href="<? echo $sodapop->template['path'] ?>/css/style.css"> </head> <body> <br /> <div class="mainBody"> <div class="testModuleBox"> <?php $sodapop->modPosition('login'); ?> </div> <div class="menuBar"> <a href="<?php echo $sodapop->config['liveUrl']; ?>"><img src="<?php echo $sodapop->config['liveUrl']; ?>/templates/devTemplate/images/sodapopSplashLogoSmaller.png" /></a>Demonstration Site <?php $sodapop->modPosition('menu'); ?> </div> <?php $sodapop->modPosition("test"); ?> <div class="mainContent"> <? echo $sodapop->output; ?> </div> <div class="footer"> <?php echo " <div class='tempName'> " . $sodapop->language['tempName'] . ":" . $sodapop->template['name'] . " <br />" . $sodapop->language['labelVersion'] . $sodapop->config['appVersion'] . " </div>"; ?> <?php $sodapop->modPosition('footer'); ?> </div> </div> <br /> </body> </html><file_sep><?php /** * @author <NAME> * @copyright 2011 Tinboat Webworks * @version 0.0.1.2 * @link a url * @since 10/20/2011 */ // no direct access defined('_LOCK') or die('Restricted access'); $language['welcome'] = " [New text added by template]"; $language['noTemplate'] = ""; $language['tempName'] = "Template Name"; $language['whatApp'] = "App Name: "; $language['whatPage'] = "Page Name: "; $this->language = $language; ?><file_sep>-- phpMyAdmin SQL Dump -- version 3.2.4 -- http://www.phpmyadmin.net -- -- Host: localhost -- Generation Time: Oct 07, 2013 at 07:45 PM -- Server version: 5.1.44 -- PHP Version: 5.3.1 SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO"; /*!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 utf8 */; -- -- Database: `sodapop` -- -- -------------------------------------------------------- -- -- Table structure for table `app_user_users` -- CREATE TABLE IF NOT EXISTS `app_user_users` ( `id` int(100) NOT NULL AUTO_INCREMENT, `name` varchar(300) NOT NULL, `email` varchar(300) NOT NULL, `username` varchar(300) NOT NULL, `password` varchar(300) NOT NULL, `bio` varchar(10000) NOT NULL, `accessLevel` int(2) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=176 ; -- -- Dumping data for table `app_user_users` -- INSERT INTO `app_user_users` (`id`, `name`, `email`, `username`, `password`, `bio`, `accessLevel`) VALUES (175, 'Administrator', '<EMAIL>', 'adminstrator', '<PASSWORD>', 'I am the site Administrator', 5); -- -------------------------------------------------------- -- -- Table structure for table `modules` -- CREATE TABLE IF NOT EXISTS `modules` ( `id` int(100) NOT NULL AUTO_INCREMENT, `name` varchar(100) NOT NULL, `positions` varchar(100) NOT NULL, `pages` varchar(1000) NOT NULL, `hidden` varchar(1000) NOT NULL, `params` varchar(1000) NOT NULL, `ordering` int(10) NOT NULL, `active` int(1) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ; -- -- Dumping data for table `modules` -- INSERT INTO `modules` (`id`, `name`, `positions`, `pages`, `hidden`, `params`, `ordering`, `active`) VALUES (1, 'testModule', 'test', '', '', '', 3, 0), (2, 'newModule', 'test', '', 'episode', '', 2, 0), (3, 'login', 'login', '', '', 'redirect==http://localhost/~brad/git/Sodapop/sodapop/user::registration==on', 0, 1), (4, 'menu', 'menu', '', '', '', 1, 1); -- -------------------------------------------------------- -- -- Table structure for table `pages` -- CREATE TABLE IF NOT EXISTS `pages` ( `pageID` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(300) NOT NULL, `handle` varchar(11) NOT NULL, `getApp` varchar(20) NOT NULL, PRIMARY KEY (`pageID`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=9 ; -- -- Dumping data for table `pages` -- INSERT INTO `pages` (`pageID`, `name`, `handle`, `getApp`) VALUES (3, '', 'drwho', 'show'), (6, 'Home', '', 'demo'), (4, 'The Monkey Page', 'monkeys', 'demo'), (5, 'Hit The Brick Wall', 'brick-wall', 'demo'), (7, 'LAMP!', 'lamp', 'demo'), (8, 'User Page', 'user', 'user'); -- -------------------------------------------------------- -- -- Table structure for table `templates` -- CREATE TABLE IF NOT EXISTS `templates` ( `templateID` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(21) NOT NULL, `dflt` varchar(1) NOT NULL, `assigned` int(11) NOT NULL, PRIMARY KEY (`templateID`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ; -- -- Dumping data for table `templates` -- INSERT INTO `templates` (`templateID`, `name`, `dflt`, `assigned`) VALUES (3, 'default', '0', 0), (4, 'devTemplate', '1', 0); <file_sep><?php /** * @author <NAME> * @copyright 2011 Tinboat Webworks * @version 0.0.1.2 * @link a url * @since 10/20/2011 */ // no direct access defined('_LOCK') or die('Restricted access'); class menu extends sodapop { public function menu() { } public function menuOutput($sodapop) { $id = $sodapop->getCookie("sp_login"); $modOutput= "<div class='menu'> <a href='./'>" . $sodapop->language['menu0'] . " </a> | <a href='monkeys'>" . $sodapop->language['menu1'] . " </a> | <a href='brick-wall'>" . $sodapop->language['menu2'] . "</a> | <a href='lamp'>" . $sodapop->language['menu3'] . "</a>"; if ($id > 0) { $modOutput .= "| <a href='user'>Profile</a>"; } $modOutput .= "</div>"; return $modOutput; } }<file_sep><?php /** * @author <NAME> * @copyright 2013 Tinboat Webworks * @Project Sodapop * @version 0.0.1.5 * @link http://tinboatwebworks.com * @since 10/20/2011 */ // no direct access defined('_LOCK') or die('Restricted access'); $config['appName'] = "sodapop"; $config['appVersion'] = "0.0.1.5.0dev"; $config['siteName'] = "Sodapop.com"; $config['liveSite'] = "Sodapop/Sodapop0_0_1_5/sodapop/"; $config['liveUrl'] = "http://localhost/Sodapop/Sodapop0_0_1_5/sodapop/"; $config['sitePath'] = "/Applications/XAMPP/htdocs/Sodapop/Sodapop0_0_1_5/sodapop/"; $config['maintenanceMode'] = "no"; $config['testingMode'] = "no"; $config['dbName'] = "sodapop"; $config['dbServer'] = "localhost"; $config['dbUser'] = "root"; $config['dbPass'] = ""; <file_sep><?php /** * @author <NAME> * @copyright 2013 Tinboat Webworks * @Project Sodapop * @version 0.0.1.3 * @link http://tinboatwebworks.com * @since 10/20/2011 */ // no direct access defined('_LOCK') or die('Restricted access'); class appController extends sodapop { private $output; public $data; public $appModel; public $appView; public function appController($sodapop) { require_once $sodapop->pageData['filePath'] . "/model.php"; $this->appModel = new appModel; require_once $sodapop->pageData['filePath'] . "/view.php"; $this->appView = new appView(); } public function loadApp($sodapop) { $this->config = $sodapop->config; $this->appUrl = $sodapop->appUrl; $this->urlVars = $this->parseUrl('qString'); $this->pageData = $sodapop->pageData; } public function output($sodapop) { $output = $sodapop->language['whatPage'] . $this->pageData['name'] . "<br />" ; $output .= $sodapop->language['whatApp'] . $this->pageData['getApp'] ; return $output; } } ?><file_sep><?php ?> <?php echo $modOutput; ?> <file_sep><?php /** * @author <NAME> * @copyright 2011 Tinboat Webworks * @version 0.0.1.2 * @link a url * @since 10/20/2011 */ // no direct access defined('_LOCK') or die('Restricted access'); class adminMenu extends sodapop { public function adminMenu() { global $sodapop; // Let's bring in the global app object so we can access all the environmental info... $this->sodapop = $sodapop; // And give it to this class require_once $this->sodapop->config['sitePath'] . "modules/mod_adminMenu/model.php"; $this->adminMenuDatabase = new adminMenuDatabase; require_once $this->sodapop->config['sitePath'] . "modules/mod_adminMenu//view.php"; $this->adminMenuView = new adminMenuView(); } public function adminMenuOutput() { //Check their uers level to see how much access they have $id = $this->sodapop->getCookie("sp_login"); //Allow them to manage users if their user level is greater than 5 if ($this->sodapop->checkAccessLevel($id) >= 5) { $output = $this->adminMenuView->displayAdminMenu(); } else { $output = ""; } return $output; } }<file_sep><?php /** * @author <NAME> * @copyright 2013 Tinboat Webworks * @Project Sodapop * @version 0.0.1.3 * @link http://tinboatwebworks.com * @since 10/20/2011 */ // no direct access defined('_LOCK') or die('Restricted access'); class appController extends sodapop { private $output; public $data; public $appModel; public $appView; public function appController($sodapop) { require_once $sodapop->pageData['filePath'] . "/model.php"; $this->appModel = new appModel; require_once $sodapop->pageData['filePath'] . "/view.php"; $this->appView = new appView(); } public function loadApp($sodapop) { $this->config = $sodapop->config; $this->appUrl = $sodapop->appUrl; $this->urlVars = $this->parseUrl('qString'); $this->formData = $this->getFormData($_POST); $this->pageData = $sodapop->pageData; $this->redirect = $this->sodapop->config['liveUrl']; // Maybe at some point this will be a app parameter if($this->formData['email'] != "") { $addBetaTester = $this->appModel->addBetaTester($this->formData['email']); $emailData['message'] = $this->appView->buildEmail(); $emailData['email'] = $this->formData['email']; $emailData['subject'] = "Thank you for your interest in WatchWho.blue!"; echo $emailData['body']; $this->sendEmail($emailData); } } public function output($sodapop) { $output = $this->appView->buildPage(); return $output; } } ?><file_sep><?php /** * @author <NAME> * @copyright 2013 Tinboat Webworks * @Project Sodapop * @version 0.0.1.3 * @link http://tinboatwebworks.com * @since 10/20/2011 */ // no direct access defined('_LOCK') or die('Restricted access'); class sodapop { public $config; public $link; public $handle; public $qString; public $uri; public $domain; public $appUrl; public $queryString; public $part; public $string; public $appPath; public $viewApp; public $data; public $language; public $scope; public $langPath; public $templatePath; public $getApp; public $position; public $allModsData; public $i; public $modulePath; public $modDataName; public $isItThisPage; public $hideOnThisPage; public $showIt; public $pageData; public $template; public $modData; /* * sodapop() creates the model and view objects. */ public function sodapop() { require_once "./application/model/mod.sodapop.php"; $this->database = new database; require_once "./application/view/view.sodapop.php"; $this->view = new view; } /* * loadSodapop() is where we really get everything rolling. We load the language, * Config file, template, all that good stuff as well as find out what should be * happening on the requested page. */ public function loadSodapop() { $this->config = $this->database->loadConfigFile(); // $this->dbConnect = $this->dbConnect($this->config); $this->currentLanguage = $this->setLanguage(); $this->template = $this->templateLookup(); $this->template['path'] = $this->loadTemplate($this->template['name']); $this->pageData = $this->pageData($this); $this->pageData['filePath'] = $this->appFilePath(); $this->loadLanguage = $this->loadLanguage(); } /* * dbConnect() takes care of the db connection. Somebody's got to do it. */ function dbConnect($config) { /* $link = mysqli_connect( $config['dbServer'], $config['dbUser'], $config['dbPass'], $config['dbName']); if (! $link) { die("Couldn't connect to MySQL"); } or die("Couldn't open" . $config['dbName'] . ": ".mysql_error()); */ } /* * setLanguage() determines which language file to pull from... defaulting to * english. */ public function setLanguage() { /* Once cookies are working: $language = getCookie("language"); */ // but for now: $language = "english"; if (!$language) { $language = "english"; } return $language; } /* * loadLanguage() loads the language files for the application, apps and modules. * Language in the apps and template will override core language */ public function loadLanguage() { $this->langPath = $this->langPath("sodapop"); $this->langPathTem = $this->langPath("template"); $this->langPathApp = $this->langPath("app"); require_once $this->langPath; // Load Applicaiton language file require_once $this->langPathTem; // Load Template Language file require_once $this->langPathApp; // Load app Language file } /* * getDefaultTemplate loads the template that is set as default in the * tamplates table. */ public function templateLookup() { ## Let's find out which template is set to default $templatesData = $this->database->getTemplatesData(); foreach ($templatesData as $templateData) { $template['name'] = $templateData['name']; $template['id'] = $templateData['templateID']; } return $template; } /* * loadTemplate loads the current template */ public function loadTemplate($templateName) { $loadTemplate = $this->templatePath($templateName); return $loadTemplate; } /* * templatePath creates the path to the current template. If no template is * assigned, or the template file doesn't exist, its going to load a null * template */ public function templatePath($templateName) { if ($templateName == "") { ## If there is not template assinged were going to load the null template $templatePath = "./templates/null"; } elseif (!file_exists("./templates/" . $templateName)) { ## What if there is no template to match what we are looking for? Load the null template, that's what. $templatePath = "./templates/null"; } else { ## And assuming all is well, we can load the assigned template $templatePath = "./templates/" . $templateName; } return $templatePath; } /* * appData retrieves all the info from the apps table for the given handle and packs it into the $app array. If no app existis, it routes to a 404 app... */ public function pageData($sodapop) { // Get the handle $handle = $this->getHandle(); $pagesData = $this->database->getPagesData($handle); ///////XXXX////// // So what happens if there is not a app for the handle? We'll load the 404 app, that's what happens. if (!$pagesData) { $page['getApp'] = "404"; return $page; } foreach ($pagesData as $pageData) { $page['id'] = $pageData['pageID']; $page['name'] = $pageData['name']; $page['handle'] = $pageData['handle']; $page['getApp'] = $pageData['getApp']; } return $page; } //////////////////////// /* * getUserDataById($id) acceptes the user's ID number and pulls all of their user * data based on that. */ public function getUserDataById($id) { if (empty($userData)) {$userData = "";} if (isset($id)) { $getUsersByIdData = $this->database->getUsersByIdData($id); foreach ($getUsersByIdData as $getUserByIdData) { $userData['id'] = $getUserByIdData['id']; $userData['name'] = $getUserByIdData['name']; $userData['email'] = $getUserByIdData['email']; $userData['username'] = $getUserByIdData['username']; $userData['bio'] = $getUserByIdData['bio']; $userData['accessLevel'] = $getUserByIdData['accessLevel']; } } return $userData; } /* * getHandle() uses the parsUrl() function to get the app handle from the url */ public function getHandle() { $handle = $this->parseUrl('handle'); return $handle; } /* * getQsting() uses the parsUrl() function to get the app query string from the * url */ public function getQstring() { $qString = $this->parseUrl('qString'); return $qString; } /* * parseUrl() retrieves the URI and breaks it up into it's various parts */ public function parseUrl($part) { ## Get the URI for the currently requested app $uri = $_SERVER['REQUEST_URI']; ## Pull app handle and query string from domain etc list($this->domain, $this->appUrl) = array_pad(explode($this->config['liveSite'], $uri, 2), -2, null);; ## Check for a querie string in the handle if (strpos($this->appUrl, '?') !== false) { ## Separate the apps handle from the query string list($this->handle, $this->queryString) = array_pad(explode("?", $this->appUrl, 2), -2, null); } ## If there is no querie string than the handle stands alone. else $this->handle = $this->appUrl; ## Ditch the slash separator $this->handle = str_replace("/", "", $this->handle); if ($part == 'handle') { $this->string = $this->handle; } if ($part == 'qString') { $this->string = $this->queryString; $this->string = $this->getStringVars($this->string); } // print_r($this->string); return $this->string; } /* * getStringVars() takes the parameter strinf in the URL and parses out to it's * parts. It creates the variablein an array with the name and value based * on the string. So ?something=top&somethingElse=bottom would end as * $urlVals['something']='top'; $urlVals['$something']='bottom'; and then get * returned. */ public function getStringVars($string){ $string = explode("&", $string); foreach ($string as $i) { list($name, $value) = array_pad(explode("=", $i, 2), -2, null); $urlVals[$name] = $value; } return $urlVals; } public function newGetStringVariables() { $values = $_GET; return $values; } /* * loadApp() builds the path to the requested app, and then loads it up by * requiring the apps lead file. */ public function loadApp() { $appPath = "./apps/" . $this->pageData['getApp'] . "/" . $this->pageData['getApp'] . ".php"; require_once $appPath; $output = $appController->output($this); return $output; } public function appFilePath() { $appFilePath = "./apps/" . $this->pageData['getApp']; return $appFilePath; } /* * loadView() allows the app's controller to call in the apps view and push * the $data array into it. */ public function loadView() { $appPath = "./apps/" . $this->pageData['getApp'] . "/view.php"; require_once $appPath; $loadViewApp = new appView($data); $appView = $appView->buildAppView($data); return $viewApp; } /* * langPath() sets the path to the language files */ public function langPath($scope) { // Load Application Language if ($scope == "sodapop") { $langPath = "./language/lang." . $this->currentLanguage . ".php"; } // Load Template Language if ($scope == "template") { $templatePath = $this->templatePath($this->template['name']); $langPath = $templatePath . "/language/lang." . $this->currentLanguage . ".php"; } // Load app Language if ($scope == "app") { $getApp = $this->pageData['getApp']; // So, here we have to get the getApp from the database... $langPath = "./apps/" . $getApp . "/language/lang." . $this->currentLanguage . ".php"; } return $langPath; } /* * modPosition() determines which modules are assigned to the given module position */ public function modPosition($position) { // This grabs the data from the db table for the modules assigned to the // given position, including the module's name $this->allModsData = $this->modsInPosition($position); $moduleData = $this->loadModule($this->allModsData); return $moduleData; } /* * modsInPosition($position) determines which modules are to be loaded for the given position, * then processes all the info from the modules in that position loading them into * an array $mod then returning the array */ public function modsInPosition($position) { $modsInPostionData = $this->database->modsInPostionData($position); foreach ($modsInPostionData as $modInPostionData) { $i=""; $i++; $mod[$i]['id'] = $modInPostionData['id']; $mod[$i]['name'] = $modInPostionData['name']; $mod[$i]['positions'] = $modInPostionData['positions']; $mod[$i]['pages'] = $modInPostionData['pages']; $mod[$i]['hidden'] = $modInPostionData['hidden']; $mod[$i]['params'] = $modInPostionData['params']; $mod[$i]['active'] = $modInPostionData['active']; $params = explode("::", $mod[$i]['params']); foreach ($params as $k) { // list($name, $value) = array_pad(explode("=", $i, 2), -2, null); list ($name, $value) = array_pad(explode("==", $k, 2), -2, null); $mod[$i][$name] = $value; } } return $mod; } /* * loadModule() loads all the modules for the given position #on the given page */ private function loadModule() { // How many modules are in this position so we know how many times to loop $moduleCount = count($this->allModsData); // Scroll thru the modules by $i, picking out the data from each modules sub-array for ($i = 1; $i<= $moduleCount; $i++) { // Create an array of this module's data from the subaray of all the modules' data $modData = $this->allModsData[$i]; // Find out if we are supposed to show this module or not $showIt = $this->doShowModule($modData); // And show it if we are if ($showIt == true) { // get the path to the requested module then pulls it in $modulePath = $this->buildModPath($modData['name']); // Fetches the modules index file if it exists if (file_exists($modulePath)) { require $modulePath; } } } } /* * buildModPath() creates the path to the module's index app */ private function buildModPath($modDataName) { $modulePath = "./modules/mod_" . $modDataName . "/" . $modDataName . ".php"; return $modulePath; } /* * We need to find out whether or not to show the module on this app. * This is ugly and probably needs to be refactored */ private function doShowModule($modData) { // What if there is no handle? Then we will set the handle to 'home' if ($this->pageData['handle'] == "") {$this->pageData['handle'] = 'home';} // Is the current page one that the module is supposed to show up on? // we compare the current page's id to the 'pages' field in the module // to see if it's in there $isItThisPage = strpos("," . $modData['pages'], $this->pageData['id']); // Is the current page one that the module us supposed to be hidden from? // we compare the current pages's id to the 'hidden' field in the module // to see if it's in there $hideOnThisPage = strpos("," . $modData['hidden'], $this->pageData['id']); // if the module is assigned to all apps ('pages' field is blank) and the module // is not hidden from this page, then we can show the module. if (($modData['pages'] == '') && ($hideOnThisPage === false)) { $showIt = true; } // If it the module is assigned to this page, then we can show the module else if ($isItThisPage == true ) { $showIt = true; } // unless it's explicitly hidden from this page, then we won't show it. if ($hideOnThisPage == true) { $showIt = false; } // Is the module set to active? If not, then lets hide it. $isItActive = $modData['active']; if ($isItActive == '0') { $showIt = false; } return $showIt; } /* * parseModParams() was intended to parse out the parameter of the module * but I think that's currently being done in mod.sodapop.pop in getModuleData() * This method can probably be removed. * public function parseModParams($modParams) { $modParams = ''; } /* /* * getFormData() should be getting the data submitted by a form. It sends it to * scrubFormData to clean it up from injection attacks, etc. */ public function getFormData($data) { $data = $this->scrubFormData($data); return $data; } /* * scrubFormData() This needs to be built yet. It will scrub input form data to * make sure that there aren't any injection attacks, etc. */ public function scrubFormData ($data) { return $data; } /* * setaCookie(): At this point it just does the same thing as PHP setcookie, * but now we have the option doing some checking before actually setting a * cookie. */ public function setaCookie($cookieName, $userID, $duration) { setcookie($cookieName, $userID, time()+$duration); } /* * getCookie() just grabs a desired cookies value. */ public function getCookie($cookieName) { if (isset($_COOKIE[$cookieName])) { // success $cookie = $_COOKIE[$cookieName]; return $cookie; } } public function checkAccessLevel($id) { $accessLevel = $this->database->checkAccessLevelData($id); return $accessLevel; } /* * for hashing things. Right now it's just a double md5. Will probably add another * layer of SHA, any suggestion here would be appreciated. */ public function hashIt($string) { $string = md5($string); $string = md5($string); return $string; } /* * randomizedString will generate a string of random numbers up to 62 chars in length. * Default is 8 chars. I found this nice tight little function at: * http://stackoverflow.com/questions/853813/how-to-create-a-random-string-using-php * I did not write it myself. */ public function randomizedString($name_length = 8) { $alpha_numeric = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; return substr(str_shuffle($alpha_numeric), 0, $name_length); } public function getValue($key) { if (!isset($_GET[$key])) { return false; } return $_GET[$key]; } public function sendEmail($emailData) { $address = $emailData['email']; $subject = $emailData['subject']; $message = $emailData['message']; //$headers = $emailData['headers']; //$params = $emailData['params']; $sendEmail = mail($address,$subject,$message); return $emailData; } public function loadTest($fileName) { if($this->config['testingMode'] == "yes") { require_once($this->config['sitePath'] . "testing/" . $fileName .'_test.php'); } } public function output($data) { if (is_array($data)) { echo "Array: "; print_r($data); echo "<br /><br />"; } else { echo "Output: " . $data . "<br />"; } } }<file_sep><?php ?> <style> </style> <div style="float:left;"> <?php echo $modOutput; ?> </div> <file_sep><?php /** * @author <NAME> * @copyright 2013 Tinboat Webworks * @Project Sodapop * @version 0.0.1.3 * @link http://tinboatwebworks.com * @since 10/20/2011 */ // no direct access defined('_LOCK') or die('Restricted access'); class appController extends sodapop { private $output; public $data; public $appModel; public $appView; public function appController() { global $sodapop; // Let's bring in the global app object so we can access all the environmental info... $this->sodapop = $sodapop; // And give it to this class require_once $this->sodapop->pageData['filePath'] . "/model.php"; $this->appModel = new appModel; require_once $this->sodapop->pageData['filePath'] . "/view.php"; $this->appView = new appView(); } public function loadApp() { $this->config = $this->database->config; $this->appUrl = $this->sodapop->appUrl; $this->urlVars = $this->sodapop->parseUrl('qString'); $this->pageData = $this->sodapop->pageData; $this->formData = $this->getFormData($_POST); $this->templateData = $this->appModel->getTemplateData(); $this->redirect = $this->sodapop->config['liveUrl']; // Maybe at some point this will be a app parameter } public function output() { //Now we switch to the action based on the value of action //in the URL string switch ($this->urlVars['action']) { case '': $output = $this->firsttext(); break; case 'updateStatus': $output = $this->updateStatus(); break; case 'updateAccess': $output = $this->updateAccess(); break; case 'updatePages': $output = $this->updatePages(); break; case 'updateHidden': $output = $this->updateHidden(); break; case 'updateParams': $output = $this->updateParams(); break; case 'updatePosition': $output = $this->updatePosition(); break; } return $output; } public function firsttext() { $modulesData= $this->appModel->getModuleData(); $moduleList = $this->appView->buildModuleList($modulesData); $output = $this->appView->listModules($moduleList); return $output; } public function updatePages() { $values = $this->sodapop->newGetStringVariables(); $output = $this->appModel->updatePages($values); $output .= $this->firsttext(); return $output; } public function updateHidden() { $values = $this->sodapop->newGetStringVariables(); $output = $this->appModel->updateHidden($values); $output .= $this->firsttext(); return $output; } public function updateParams() { $output = $this->appModel->updateParams($this->urlVars); $output = $this->firsttext(); return $output; } public function updateStatus() { $output = $this->appModel->switchStatus($this->urlVars); $output = "update"; $output = $this->firsttext(); return $output; } public function updateAccess() { $output = $this->appModel->updateAccessLevel($this->urlVars); $output = $this->firsttext(); return $output; } /* public function dispalyParams($params) { $params = explode($params, "::"); //echo $params; } */ public function updatePosition() { $output = $this->appModel->updatePosition($this->urlVars); $output = $this->firsttext(); return $output; } } ?><file_sep><?php /** * @author <NAME> * @copyright 2013 Tinboat Webworks * @Project Sodapop * @version 0.0.1.3 * @link http://tinboatwebworks.com * @since 10/20/2011 */ // no direct access defined('_LOCK') or die('Restricted access'); ## Load module controller require_once $modulePath . "controller.php"; $login = new login(); ## Load module model require_once $modulePath . "model.php"; $loginDatabase = new loginDatabase(); ## Load module view require_once $modulePath . "view.php"; $loginView = new loginView(); ?> <file_sep><?php echo "NoNamed Template!"; ?><file_sep><?php /** * @author <NAME> * @copyright 2013 Tinboat Webworks * @Project Sodapop * @version 0.0.1.3 * @link http://tinboatwebworks.com * @since 10/20/2011 */ // no direct access defined('_LOCK') or die('Restricted access'); class appView extends view { public $data; public function appView() { global $sodapop; // Let's bring in the global app object so we can access all the environmental info... $this->sodapop = $sodapop; // And give it to this class } /* I think I can take this out, but I'm leaving it commented out till I feel safe removing it all together. public function buildViewApp($data) { $language = $this->sodapop->language; $viewApp = $data['appView']; return $viewApp; } */ /* * buildRgstnForm() builds the registration form for new registrations */ public function buildRgstnForm() { //require_once "./apps/user/assets/javascript/regFormValidation.php"; $laguage = extract($this->sodapop->language); $config = extract($this->sodapop->config); $formFields = array( 'name', 'userName', 'email', 'pwd', 'phone', 'pwdConfirm'); $form = $this->validator("Register", $formFields); $form .= " <div class='registrationForm'> <form name='Register' onsubmit='return validateFormOnSubmitRegister(this)' action='" . $liveUrl . "user?action=create' method='post'> <table class='registrationTable'> <tr> <td><label for='name'> " . $regName . " </label></td> <td><input type='text' name='name'></td> </tr> <tr> <td><label for='username'> " . $regUsrname . "(5-15 chars) </label></td> <td> <input type='text' name='username'> </td> </tr> <tr> <td><label for='email'> " . $regEmail . " </label></td> <td> <input type='text' name='email'> </td> </tr> <tr> <td><label for='pwd'> " . $regPwd . "(7-15 chars)</label> </td> <td> <input type='password' name='pwd'> </td> </tr> <tr> <td><label for='pwdConfirm'> " . $regCnfPwd . " </label></td> <td> <input type='text' name='pwdConfirm'> </td> </tr> <tr> <td> <input name='redirect' type='hidden' value='" . $liveUrl . "user'> <input name='Submit' type='submit' value='" . $regSubmit . "'> </td> </tr> </table> </form> </div>"; return $form; } /* * buildRecoverPassword() builds the form that asks for users email address for password recovery */ public function buildRecoverPassword() { // get the language and config date $laguage = extract($this->sodapop->language); $config = extract($this->sodapop->config); $form = " <div class='passwordRecover'> <form name='recover' action='" . $liveUrl . "user?action=tokenplease' method='post'> <table class='recoverTable'> <tr> <td><label for='name'> " . $emailForRecover . " </label></td> <td><input type='email' name='recoveryEmail'></td> </tr> <tr> <td> <input type='hidden' name='sendToken' value='yes'> <input name='Submit' type='submit' value='" . $submitForRecover . "'> </td> </tr> </table> </form> </div>"; return $form; } /* * buildAskForToken() builds the form that asks for the token that was emailed for password recovery */ public function buildAskForToken() { // get the language and config date $laguage = extract($this->sodapop->language); $config = extract($this->sodapop->config); $form = " <div class='passwordRecoverToken'> <p class='tokenIntro'>" . $tokenSentRecover . "</p><br /> <form name='recoverToken' action='" . $liveUrl . "user?action=checktoken' method='post'> <table class='recoverTable'> <tr> <td><label for='recoverTokan'> " . $tokenForRecover . " </label></td> <td><input type='text' name='token'></td> </tr> <tr> <td> <input name='Submit' type='submit' value='" . $submittokenForRecover . "'> </td> </td> </tr> </table> </form> </div>"; return $form; } public function askForNewPassword($token) { // get the language and config date $laguage = extract($this->sodapop->language); $config = extract($this->sodapop->config); // This is where we tell the validator class what fields we want to validate $formFields = array ( pwd, pwdConfirm ); // loading the validator $output = $this->validator("newPassword", $formFields); // The form $output .= " <div class='askForNewPassword'> <p class='tokenIntro'>" . $askForNewPassword . "</p><br /> <form name='newPassword' onsubmit='return validateFormOnSubmitnewPassword(this)' action='" . $liveUrl . "user?action=updatePassword' method='post'> <table class='recoverTable'> <tr> <td><label for='recoverTokan'> " . $passwordLabel . " </label></td> <td><input type='password' name='pwd'></td> </tr> <tr> <td><label for='recoverTokan'> " . $passwordLabelConfirm . " </label></td> <td><input type='password' name='pwdConfirm'></td> </tr> <tr> <td> <input type='hidden' name='token' value='" . $token . "'> <input type='hidden' name='setPass' value='yes'> <input name='Submit' type='submit' value='" . $submittokenForRecover . "'> </td> </td> </tr> </table> </form> </div>"; return $output; } /* * buildProfile() builds the profile page. It's super simple here, but could be expanded * by greated an html.profile.php file and requiring it, or something like that, to * make it more fancy for your own purposes. */ public function buildProfile() { // print_r($this->sodapop->language); $output = ""; $cookie = $this->sodapop->getCookie("sp_login"); $userInfo = $this->sodapop->getUserDataById($cookie); $language = extract($this->sodapop->language, EXTR_PREFIX_ALL, "LANG"); $config = extract($this->sodapop->config, EXTR_PREFIX_ALL, "CONFIG"); if (!empty($userInfo)) { $userInfo = extract($userInfo, EXTR_PREFIX_ALL, "USERINFO"); } // If we don't find a cookie, let's ask them to log in if (!$cookie) { $output = $LANG_pleaseLogIn; } // If we do find a cookie... else { //Check their uers level to see how much access they have $id = $this->sodapop->getCookie("sp_login"); /* */ //Allow them to manage things if their user level is greater than 5 if ($this->sodapop->checkAccessLevel($id) >= 5) { $output .= "<a href='" . $CONFIG_liveUrl . "user?action=mangeusers'>Manage Users</a><br />"; $output .= "<a href='" . $CONFIG_liveUrl . "modulemanager'>Manage Modules</a><br />"; } // Build the users profile view $output .= "<h1>" . $LANG_profileTitle . "</h1> "; $output .= "<div class='profileData'><table>"; $output .= "<tr><td><strong>" . $LANG_profileName . "</strong> </td><td>" . $USERINFO_name . "</td></tr>"; $output .= "<tr><td><strong>" . $LANG_profileUsrName . "</strong> </td><td>" . $USERINFO_username . "</td></tr>"; $output .= "<tr><td><strong>" . $LANG_profileEmail . "</strong> </td><td>" . $USERINFO_email . "</td></tr>"; $output .= "<tr><td><strong>" . $LANG_profileBio . "</strong> </td><td>" . $USERINFO_bio . "</td></tr>"; $output .= "</table></div>"; $output .= "<br /><br /><a href='" . $CONFIG_liveUrl . "user?action=logout'>" . $LANG_profileLogout . "</a> | <a href='" . $CONFIG_liveUrl . "user?action=edit'>" . $LANG_profileEdit . "</a> | </a> <a href='" . $CONFIG_liveUrl . "user?action=delete'>" . $LANG_profileDelete . "</a>"; } return $output; } /* * buildEditProfile() creates the form that lets the user update their user info */ public function buildEditProfile() { $cookie = $this->sodapop->getCookie("sp_login"); $userInfo = $this->sodapop->getUserDataById($cookie); $userInfo = extract($userInfo, EXTR_PREFIX_ALL, "USERINFO"); $laguage = extract($this->sodapop->language, EXTR_PREFIX_ALL, "LANG"); $config = extract($this->sodapop->config, EXTR_PREFIX_ALL, "CONFIG"); // Let's make sure they are logged in, just to be safe if (!$cookie) { $output = "Please log in."; } //If they are logged in... else { // Set up the fields to send to the validator $formFields = array ( 'name', 'userName', 'email' ); // Build the validator $output = $this->validator("Edit", $formFields); // if the URL is telling us to update if ( isset($this->sodapop->string['update'])) { // Make sure the email isn't already in use if ($this->sodapop->string['dupEmail'] == '1') { $output .= "<span class='alert'>" . $LANG_emailUpdateNope . "<span><br/>"; } // And also that the name is unique if ($this->sodapop->string['dupName'] == '1') { $output .= "<span class='alert'>" . $LANG_usernameUpdateNope . "<span><br/>"; } } // Ok, now lets build the form to give then to update their profile if (!isset($liveURL)) {$liveUrl = "";} $output .= "<h1>" . $LANG_profileEditTitle . "</h1> "; $output .= " <div class='registrationForm'> <form name='Register' onsubmit='return validateFormOnSubmitEdit(this)' action='" . $CONFIG_liveUrl . "user?action=update' method='post'> <table class='registrationTable'> <tr> <td><label for='name'> " . $LANG_profileName . " </label></td> <td><input type='text' name='name' value='" . $USERINFO_name . "'></td> </tr> <tr> <td><label for='username'> " . $LANG_profileUsrName . " </label></td> <td> <input type='text' name='username' value='" . $USERINFO_username . "'> </td> </tr> <tr> <td><label for='email'> " . $LANG_profileEmail . " </label></td> <td> <input type='text' name='email' value='" . $USERINFO_email . "'> </td> </tr> <tr> <td><label for='pwd'> " . $LANG_profilePwd . "</label> </td> <td> <input type='text' name='pwd' value=''> </td> </tr> <tr> <td><label for='pwd'> " . $LANG_profileBio . "</label> </td> <td> <textarea name='bio' rows='4' cols='50'>" . $USERINFO_bio . "</textarea> </td> </tr> <tr> <td> <input name='redirect' type='hidden' value='" . $liveUrl . "user'> <input name='id' type='hidden' value='" . $USERINFO_id . "'> <input name='Submit' type='submit' value='" . $LANG_editSubmit . "'> <a href='" . $CONFIG_liveUrl . "user'>" . $LANG_editCancel . "</a></td> </tr> </table> </form> </div>"; } return $output; } /* * buildUserList() will get the data of each user and compile the view output for the Manage Users * view. ## This view building should really be moved to te view.php object, and the logic probably * moved to the controller, but it's hear for now */ public function buildUserList($usersData) { foreach ($usersData as $userData) { ; $userData = extract($userData); if(empty($output)){$output ="";} $output .="<form name='Manage' onsubmit='return validateFormOnSubmitmanageUsers(this)' action='" . $this->sodapop->config['liveUrl'] . "user?action=mangeusers&do=update' method='post'>"; $output .="<tr>"; $output .="<td>" .$id . "</td>"; $output .="<td><input type='text' name='name' value='" . $name . "'></td>"; $output .="<td><input type='text' name='email' value='" . $email . "'></td>"; $output .="<td><input type='text' name='username' value='" . $username . "'></td>"; $output .="<td><input type='text' name='pwd' value=''></td>"; $output .="<td><select name='accessLevel'><option>" . $accessLevel . "</option><option>1</option><option>2</option><option>3</option><option>4</option><option>5</option><option>6</option><option>7</option><option>8</option><option>9</option><option>11</option></td>"; $output .="<td><input name='id' type='hidden' value='" .$id . "'><input name='Submit' type='submit' value='Update'></form></td>"; $output .="<form name='Delete' action='" . $this->sodapop->config['liveUrl'] . "user?action=mangeusers&do=delete' method='post'>"; $output .="<td><input name='id' type='hidden' value='" .$id . "'><input name='Submit' type='submit' value='Delete'></form></td>"; $output .="</tr>"; $output .=""; } return $output; } /* * listUsers() is going to build the list of users for the Manage Users view. */ public function listUsers($userList) { if(empty($output)){$output ="";} // Tell the validator which fields we want to validate $formFields = array ( 'name', 'userName', 'email', 'password'); // build the validation script $output .= $this->validator("manageUsers", $formFields); // And build the list of users. $output .= "<table width='100%'> <tr> <td>ID</td> <td>Name</td> <td>Email</td> <td>User Name</td> <td>Password</td> <td>Access Level</td> <td></td> <td></td> </tr>" . $userList . " <tr> <td><form name='Manage' onsubmit='return validateFormOnSubmitmanageUsers(this)' action='" . $this->sodapop->config['liveUrl'] . "user?action=mangeusers&do=new' method='post'></td> <td><input type='text' name='name' value=''></td> <td><input type='text' name='email' value=''></td> <td><input type='text' name='username' value=''></td> <td><input type='text' name='pwd' value=''></td> <td><input type='text' name='accessLevel' value='' size='2'></td> <td><input type='submit' name='add' value='Add'></td> <td></td> </tr> </table>"; return $output; } /* * validator() builds the validation javascript based on the fields that are sent into * it in a $fields array. If a field is requested, then validator validates that * field. You have to pass the $formName into it as well, so the JS method * can differentiate itself in case the validation srcipt appears mulitple times * on a page. */ public function validator($formName, $fields) { $fields = $this->getFields($fields); $validator = ' <script type="text/javascript"> function validateFormOnSubmit' . $formName . '(theForm) { var reason = ""; '; if (isset($fields['name'])) { if ($fields['name'] == '1') { $validator .= ' reason += validateName(theForm.name);'; } } if (isset($fields['userName'])) { if ($fields['userName'] == '1') { $validator .= ' reason += validateUsername(theForm.username);'; } } if (isset($fields['pwd'])) { if ($fields['pwd'] == '1') { $validator .= ' reason += validatePassword(theForm.pwd);'; } } if (isset($fields['pwdConfirm'])) { if ($fields['pwdConfirm'] == '1') { $validator .= ' reason += validatePasswordConfirm(theForm.pwdConfirm, theForm.pwd);'; } } if (isset($fields['email'])) { if ($fields['email'] == '1') { $validator .= ' reason += validateEmail(theForm.email);'; } } if (isset($fields['phone'])) { if ($fields['phone'] == '1') { $validator .= ' reason += validatePhone(theForm.phone);'; } } $laguage = extract($this->sodapop->language, EXTR_PREFIX_ALL, "LANG"); $validator .= ' if (reason != "") { alert("' . $LANG_validateError . '" + reason); return false; } return true; } function validateEmpty(fld) { var error = ""; if (fld.value.length == 0) { fld.style.background = \'Yellow\'; error = "' . $LANG_validateReqField . '" } else { fld.style.background = \'White\'; } return error; } function validateName(fld) { var error = ""; var illegalChars = /\W/; // allow letters, numbers, and underscores if (fld.value == "") { fld.style.background = "Yellow"; error = "'. $LANG_validateNoName .'"; } else { fld.style.background = "White"; } return error; } function validateUsername(fld) { var error = ""; var illegalChars = /\W/; // allow letters, numbers, and underscores if (fld.value == "") { fld.style.background = "Yellow"; error = "' . $LANG_validateNoName . '"; } else if ((fld.value.length < 5) || (fld.value.length > 15)) { fld.style.background = "Yellow"; error = "' . $LANG_validateUsrNmLgth . '"; } else if (illegalChars.test(fld.value)) { fld.style.background = "Yellow"; error = "' . $LANG_validateUsrIllChars . '"; } else { fld.style.background = "White"; } return error; } function validatePassword(fld) { var error = ""; var illegalChars = /[\W_]/; // allow only letters and numbers if (fld.value == "") { fld.style.background = \'Yellow\'; error = "' . $LANG_validateNoPwd . '"; } else if ((fld.value.length < 7) || (fld.value.length > 15)) { error = "' . $LANG_validatePwdLgth . '"; fld.style.background = \'Yellow\'; } else if (illegalChars.test(fld.value)) { error = "' . $LANG_validatePwdIllChrs . '"; fld.style.background = \'Yellow\'; } else if (!((fld.value.search(/(a-z)+/)) && (fld.value.search(/(0-9)+/)))) { error = "' . $LANG_validatePwdOneNmrl . '"; fld.style.background = \'Yellow\'; } else { fld.style.background = \'White\'; } return error; } function validatePasswordConfirm(fld, chk) { var error = ""; var illegalChars = /[\W_]/; // allow only letters and numbers if (fld.value == "") { fld.style.background = "Yellow"; error = "' . $LANG_validateNoCnfPwd . '"; } else if (fld.value != chk.value) { error = "' . $LANG_validatePwdNoMch . '"; fld.style.background = "Yellow"; } else { fld.style.background = "White"; } return error; } function trim(s) { return s.replace(/^\s+|\s+$/, \'\'); } function validateEmail(fld) { var error=""; var tfld = trim(fld.value); // value of field with whitespace trimmed off var emailFilter = /^[^@]+@[^@.]+\.[^@]*\w\w$/ ; var illegalChars= /[\(\)\<\>\,\;\:\\\"\[\]]/ ; if (fld.value == "") { fld.style.background = \'Yellow\'; error = "' . $LANG_validateNoEml . '"; } else if (!emailFilter.test(tfld)) { //test email for illegal characters fld.style.background = \'Yellow\'; error = "' . $LANG_validateVldEml . '"; } else if (fld.value.match(illegalChars)) { fld.style.background = \'Yellow\'; error = "' . $LANG_validateEmlIllChrs . '"; } else { fld.style.background = \'White\'; } return error; } function validatePhone(fld) { var error = ""; var stripped = fld.value.replace(/[\(\)\.\-\ ]/g, \'\'); if (fld.value == "") { error = "' . $LANG_validateNoPhn . '"; fld.style.background = "Yellow"; } else if (isNaN(parseInt(stripped))) { error = "' . $LANG_validatePhnIllChrs . '"; fld.style.background = "Yellow"; } else if (!(stripped.length == 10)) { error = "' . $LANG_validatePhnLgth . '"; fld.style.background = "Yellow"; } return error; } </script> '; return $validator; } /* * getFields() parses the $fields array for validator() so that it knows which fields * to validate. */ public function getFields($checkFields) { foreach ($checkFields as $i) { $fields[$i] = '1'; } return $fields; } } <file_sep><?php $form = ' <script type="text/javascript"> <!-- // This validation code thanks to http://webcheatsheet.com/javascript/form_validation.php function validateFormOnSubmit(theForm) { var reason = ""; reason += validateUsername(theForm.username); reason += validatePassword(theForm.pwd); reason += validateEmail(theForm.email); reason += validatePhone(theForm.phone); reason += validateEmpty(theForm.from); if (reason != "") { alert("Some fields need correction:\n" + reason); return false; } return false; } function validateEmpty(fld) { var error = ""; if (fld.value.length == 0) { fld.style.background = \'Yellow\'; error = "The required field has not been filled in.\n" } else { fld.style.background = \'White\'; } return error; } function validateUsername(fld) { var error = ""; var illegalChars = /\W/; // allow letters, numbers, and underscores if (fld.value == "") { fld.style.background = \'Yellow\'; error = "You didn\'t enter a username.\n"; } else if ((fld.value.length < 5) || (fld.value.length > 15)) { fld.style.background = \'Yellow\'; error = \"The username is the wrong length.\n\"; } else if (illegalChars.test(fld.value)) { fld.style.background = \'Yellow\'; error = \"The username contains illegal characters.\n\"; } else { fld.style.background = \'White\'; } return error; } function validatePassword(fld) { var error = ""; var illegalChars = /[\W_]/; // allow only letters and numbers if (fld.value == "") { fld.style.background = \'Yellow\'; error = "You didn\'t enter a password.\n"; } else if ((fld.value.length < 7) || (fld.value.length > 15)) { error = "The password is the wrong length. \n"; fld.style.background = \'Yellow\'; } else if (illegalChars.test(fld.value)) { error = "The password contains illegal characters.\n"; fld.style.background = \'Yellow\'; } else if (!((fld.value.search(/(a-z)+/)) && (fld.value.search(/(0-9)+/)))) { error = "The password must contain at least one numeral.\n"; fld.style.background = \'Yellow\'; } else { fld.style.background = \'White\'; } return error; } function trim(s) { return s.replace(/^\s+|\s+$/, \'\'); } function validateEmail(fld) { var error=""; var tfld = trim(fld.value); // value of field with whitespace trimmed off var emailFilter = /^[^@]+@[^@.]+\.[^@]*\w\w$/ ; var illegalChars= /[\(\)\<\>\,\;\:\\\"\[\]]/ ; if (fld.value == "") { fld.style.background = \'Yellow\'; error = "You didn\'t enter an email address.\n"; } else if (!emailFilter.test(tfld)) { //test email for illegal characters fld.style.background = \'Yellow\'; error = "Please enter a valid email address.\n"; } else if (fld.value.match(illegalChars)) { fld.style.background = \'Yellow\'; error = "The email address contains illegal characters.\n"; } else { fld.style.background = \'White\'; } return error; } //--> </script> '; <file_sep><?php /** * @author <NAME> * @copyright 2011 Tinboat Webworks * @version 0.0.1.2 * @link a url * @since 10/20/2011 */ // no direct access defined('_LOCK') or die('Restricted access'); class menuDatabase extends Database{ public function menuDatabase() { } } ?><file_sep><?php /** * @author <NAME> * @copyright 2013 Tinboat Webworks * @Project Sodapop * @version 0.0.1.3 * @link http://tinboatwebworks.com * @since 10/20/2011 */ // no direct access defined('_LOCK') or die('Restricted access'); class appController extends sodapop { private $output; public $data; public $appModel; public $appView; public function appController() { global $sodapop; // Let's bring in the global app object so we can access all the environmental info... $this->sodapop = $sodapop; // And give it to this class require_once $this->sodapop->pageData['filePath'] . "/model.php"; $this->appModel = new appModel; require_once $this->sodapop->pageData['filePath'] . "/view.php"; $this->appView = new appView(); $test = $sodapop->loadTest("user_controller"); // $test = $sodapop->loadTest("user_" . $_SERVER["PHP_SELF"]); } public function loadApp() { //$this->config = $this->database->config; <-- I had it as this but I think it should be --v $this->config = $this->sodapop->config; $this->appUrl = $this->sodapop->appUrl; $this->urlVars = $this->sodapop->parseUrl('qString'); $this->pageData = $this->sodapop->pageData; $this->formData = $this->getFormData($_POST); $this->redirect = $this->sodapop->config['liveUrl']; // Maybe at some point this will be a app parameter } public function output() { //Now we switch to the action based on the value of action //in the URL string if (isset($this->urlVars['action'])){ switch ($this->urlVars['action']) { // If there is no string at all, we just attempt to log in case 'login': $output = $this->logIn(); break; // log out when action = logout case 'logout': $output = $this->logOut(); break; // We want to create a new user, so this outputs the registration //form case 'new': $output = $this->newUser(); break; // There we are going to process the form and store the users data case 'create': $output = $this->createUser(); break; // If we want to edit our profile case 'edit': $output = $this->editProfile(); break; // updating profiles from user management list case 'update': $output = $this->updateProfile(); break; // Start the process of recovering a lost password case 'recover': $output = $this->recoverPassword(); break; // Ask for the token in password recovery process case 'tokenplease': $output = $this->dealWithToken(); break; // Check the token and ask for a new password during password recovery case 'checktoken': $output = $this->checkToken(); break; // Update the password during password recovery case 'updatePassword': $output = $this->updatePassword(); break; // Delete a use from the user manager list case 'delete': $output = $this->deleteUser(); break; // Loads the user manager page case 'mangeusers': $output = $this->manageUsers(); break; } } // just show the logged-in users provile else { $output = $this->showProfile(); } return $output; } /* * logIn() processes the login data, determines if it's legit, and sets the cookie * if everythings is kosher. Then redirects to the redirect URL as set in the Login * plugin. */ public function logIn() { $checkPass = $this->appModel->getPassword($this->formData['username']); $comparePass = $this->comparePassword($this->formData['pwd'], $checkPass); if ($comparePass == '1') { $this->processUser($this->formData['username']); } elseif (isset($this->creatingUser)) { $this->processUser($this->formData['username']); } else { $output = $this->sodapop->language['didNotPass']; $output = $output . $this->sodapop->language['thankYou']; return $output; } } /* * processUser() Pushes the user's data to the database, sets the cookie */ public function processUser($name){ $this->userData = $this->appModel->getUserData($name); $setCookie = $this->setaCookie('sp_login', $this->userData['id'], 3600); header('Location: ' . $this->formData['redirect']); } /* * logOut() deletes the cookie and redirects to the home page of the site */ public function logout() { $setCookie = $this->setaCookie('sp_login', $userData['id'], -3600); header('Location: ' . $this->redirect); } /* * newUswer generates the form that to allow a new user to register and provides the * form validation. */ public function newUser() { $output =""; $output = $this->sodapop->language['newUser']; $output = $output . $this->appView->buildRgstnForm($this->sodapop); return $output; } /* * deleteUser will allow a logged-in user to delete their own profile. */ public function deleteUser() { $this->appModel->deleteUserData(); $this->logout(); } public function createUser() { if(empty($output)){$output = "";} $confirmUnique = $this->appModel->confirmUnique($this->formData); if ($confirmUnique == 'yes') { $this->appModel->putUserData($this->formData); $output = $output . "Creating your account!!!"; $this->creatingUser = "1"; $this->login(); } else {$output = $output . "email and username must be unique!";} return $output; } /* * Compare password makes sure that the password provided on login matches the users * password in the database. */ public function comparePassword($password, $checkPass) { $match = ""; $password = $this->hashIt($password); // echo "<br />password: " . $password . "<br />checkpass: " . $checkPass; if ($password == $checkPass) { $match = "1"; } // echo "match: " . $match; return $match; } /* * showProfile() shows current user's profile */ public function showProfile() { $output = $this->appView->buildProfile(); return $output; } /* * editProfile() shows the form for the user to edit their profile */ public function editProfile() { $output = $this->appView->buildEditProfile(); return $output; } /* * updateProfile() Is going to update the user's profile */ public function updateProfile() { // Check to make sure the username and email are unique $this->formData['unique'] = $this->confirmUniqueUpdate($this->formData); $output = $this->appModel->updateUserData($this->formData); //If there is form data if ($output) { $string = "update=nope"; if($output['email'] == 'email') { $string .= "&dupEmail=1"; } if($output['username'] == 'username') { $string .= "&dupName=1"; } header('Location: ' . $this->sodapop->config['liveUrl'] . 'user?action=edit&' . $string); } else { header('Location: ' . $this->sodapop->config['liveUrl'] . 'user'); } } /****************************** * PASSWORD RECOVERY ******************************/ /* * recoverPassword() Is going to present the form to get the password recovery process rolling. */ public function recoverPassword() { if(isset($this->formData['recoveryEmail'])) { $recoverEmail = $this->formData['recoveryEmail']; } if (!isset($step)) { if(empty($output)){$output = "";} $output .= $this->appView->buildRecoverPassword(); } return $output; } /* * dealWithToken() Is going to generate the token and email it. Then it's going to * ask the user for the token */ public function dealWithToken() { if(empty($output)) {$output = "";} // get the variables from the form data extract($this->formData); // First lets see if we were sent here by the recovery form. If we were // we need to generate the token, post it to the db, and send out the email. if ($sendToken == "yes") { // Make sure there is a matching user $userData = $this->appModel->getUserDatafromEmail($recoveryEmail); if (!$userData) { // If there isn't a matching user, we'll let them know $output .= $this->sodapop->language['NoMatchingAccount'] . "<br />"; // then let them try again $output .= $this->appView->buildRecoverPassword(); return $output; } // If there is a matching user, lets generate the token $userData['token'] = $this->sodapop->randomizedString(32); // Then stick the token in the database $output .= $this->appModel->updateUserData($userData); // And email the token to the user's email address $output .= $this->emailToken($userData); $output .= "<span style='color:gray; font-size:10px; font-family:courier;'>" . $userData['token'] . "</span>"; } // Ask the user for the token $output .= $this->appView->buildAskForToken(); return $output; } /* * checkToken() is going to compare the token to the database to see if there is a match. * If there is we will go ahead and ask the user for their new password. */ public function checkToken() { //Extract form data to get the token from the form data from the form in the previous step extract($this->formData); // Check db to make sure token exists if ($token) { // and get the user's id if it does $id = $this->appModel->checkForToken($token); } // If we couldn't find a matching token, let them know and... if (!$id) { $output = "Invalid token."; // ...allow them to try again $output .= $this->appView->buildAskForToken(); return $output; } // if we do have a matching token, then let's ask then for their new password if ($id) { // offer form to input new password $output .= $this->appView->askForNewPassword($token); // Still need to validate form } return $output; } /* * updatePassword() is going to push the new password to the database and let them know * we're all done. */ public function updatePassword() { $data['token'] = $this->formData['token']; $data['password'] = $this->sodapop->hashit($this->formData['pwd']); $data['emptyToken'] = ""; if($data['token']) { // Let's let them know we've updated their password and invite them to log in $output = $this->sodapop->language[updatingPasswordMessage]; // And send their new password to the database. $output .= $this->appModel->updateNewPassword($data); } // Uh oh... are they hitting the page without going through the password recovery process? Tell them nope. else { $output = $this->sodapop->language['youDontHaveAToken']; } return $output; } /* * emailToken() assembles the data to send to the email function which will send it out to the user */ public function emailToken($data) { $emailData['email'] = $data['email']; $emailData['subject'] = "Your Password Token from " . $this->sodapop->config['siteName']; $emailData['message'] = "You have requested a token to reset your password at " . $this->sodapop->config['siteName'] . ".\n"; $emailData['message'] .= "Your token is: " . $data['token'] . "\n"; $emailData['message'] .= "You can submit this token to reset your password at: \n"; $emailData['message'] .= $this->sodapop->config['liveUrl'] . "user?action=tokenplease \n"; $emailData['message'] .= "\n"; $emailData['message'] .= "Thanks much!\n"; $emailData['message'] .= "\n"; $emailData['message'] .= "The staff of " . $this->sodapop->config['siteName']; $this->sodapop->sendEmail($emailData); } /****************************** * MANAGE USERS ******************************/ /* * manageUsers() outputs a list of all users, and allows admins to manage them */ public function manageUsers() { if(isset($this->urlVars['do'])){ // Are we updating edited user data? If so, lets push the new data to the db if($this->urlVars['do'] == 'update') { $this->appModel->updateUserData($this->formData); } // Are we adding a new user? Let's send this new users data to the db if($this->urlVars['do'] == 'new') { //Make sure the user is unique. $confirmUnique = $this->appModel->confirmUnique($this->formData); //and if it is, update the db if ($confirmUnique == 'yes') { $this->appModel->putUserData($this->formData); } } //Are we deleting a user? if($this->urlVars['do'] == 'delete') { // Remove their data from the db $this->appModel->deleteUserData($this->formData['id']); } } //Get their id to make sure they are allowed to manage user data (must have an access //of 5 or greater (will probably be changed to 10 or greater) $id = $this->sodapop->getCookie("sp_login"); //If they are greater than level 5, show them the list if ($this->sodapop->checkAccessLevel($id) >= 5) { $usersListData = $this->appModel->userListData(); $userList = $this->appView->buildUserList($usersListData); $output = $this->appView->listUsers($userList); } // But if they aren't they can't come in. else { $output = $this->sodapop->language['cannotView']; } return $output; } public function confirmUniqueUpdate($formData) { $id = $formData['id']; $usersData = $this->appModel->getUserDataForUnique($id); foreach ($usersData as $userData) { $existingUser['email'] = $userData['email']; $existingUser['username'] = $userData['username']; if (($formData['email'] == $existingUser['email']) || ($formData['username'] == $existingUser['username'])) { if ($formData['email'] == $existingUser['email']) { $confirmUnique['email'] = "email"; } if ($formData['username'] == $existingUser['username']) { $confirmUnique['username'] = "username"; } } } if ($confirmUnique == ''){ $confirmUnique = 'yes'; } return $confirmUnique; } } ?><file_sep><?php $language['welcome'] .= " [New text added by template]"; $language['noTemplate'] = "No Template Assigned"; ?><file_sep><?php echo $modOutput; <file_sep><?php /** * @author <NAME> * @copyright 2011 Tinboat Webworks * @version 0.0.1.2 * @link a url * @since 10/20/2011 */ // no direct access defined('_LOCK') or die('Restricted access'); $language['welcome'] = " [New text added by template]"; $language['noTemplate'] = ""; $language['labelVersion'] = "sodapop version: "; $language['tempName'] = "Template Name"; $language['menu0'] = "Home"; $language['menu1'] = "Monkeys"; $language['menu2'] = "Brick Wall"; $language['menu3'] = "Lamp"; $language['menu4'] = "Modules"; $this->language = $language; ?><file_sep><?php /** * @author <NAME> * @copyright 2011 Tinboat Webworks * @version 0.0.1.2 * @link a url * @since 10/20/2011 */ // no direct access defined('_LOCK') or die('Restricted access'); $language['didPass'] = "Successfully logged in. "; $language['didNotPass'] = "Password Does Not Match. "; $language['thankYou'] = "Thank you for attempting to log in."; $language['newUser'] = "Welcome - lets create your account!"; $language['tempName'] = "Template Name"; $language['whatApp'] = "App Name: "; $language['pleaseLogIn'] = "Please log in."; // Registration Form Language $language['regName'] = "Name: "; $language['regUsrname'] = "Username: "; $language['regEmail'] = "Email: "; $language['regPwd'] = "Password: "; $language['regCnfPwd'] = "Confirm Password: "; $language['regSubmit'] = "Register"; $language['editSubmit'] = "Update"; $language['noUpdate'] = "That email address or username is already in use."; $language['emailUpdateNope'] = "That email address is already in use."; $language['usernameUpdateNope'] = "That user name address is already in use."; $language['profileEditTitle'] = "Edit Profile:"; // Registration For Profile Page $language['profileTitle'] = "Profile:"; $language['profileUsrName'] = "Your User Name: "; $language['profileName'] = "Your Name: "; $language['profileEmail'] = "Your Email Address: "; $language['profileLogout'] = "Log Out"; $language['profileEdit'] = "Edit Info"; $language['profileDelete'] = "Delete Account"; $language['profilePwd'] = "Your Password:"; $language['profileBio'] = "Biography:"; $language['editCancel'] = "Cancel"; $language['passwordUpdated']= "Your password has been updated. You may now log in with your new password."; // Recover Password Language $language['emailForRecover'] = "Enter your email address:"; $language['tokenForRecover'] = "Enter the token:"; $language['tokenSentRecover'] = "An email has been sent with a token"; $language['submitForRecover'] = "Submit"; $language['submittokenForRecover'] = "Submit"; $language['NoMatchingAccount'] = "No Matching Account with that email address."; $language['askForNewPassword'] = "Token Accepted. Please enter your new password."; $language['passwordLabel'] = "Your New Password: "; $language['passwordLabelConfirm'] = "Confirm Password: "; $language['updatingPasswordMessage'] = "Updating password... [bleep] [bleep] [bleep]<br />"; $language['youDontHaveAToken'] = "Are you trying to recover yourpassword? If so, <a href='/user?action=recover'>try here</a>."; $language['cannotView'] = "You cannot view this page."; // Validator errors (Not using these yet...) $language['validateError'] = "Some fields need correction:\n\n"; $language['validateReqField'] = "The required field has not been filled in.\n"; $language['validateNoName'] = "You didn\'t enter your name.\n"; $language['validateUsrIllChars'] = "The username contains illegal characters.\n"; $language['validateNoUsrNm'] = "You didn\'t enter a username.\n"; $language['validateUsrNmLgth'] = "The username is the wrong length.\n"; $language['validateUsrNmIllChrs'] = "The username contains illegal characters.\n"; $language['validateNoPwd'] = "You didn\'t enter a password.\n"; $language['validatePwdLgth'] = "The password is the wrong length. \n"; $language['validatePwdIllChrs'] = "The password contains illegal characters.\n"; $language['validatePwdOneNmrl'] = "The password must contain at least one numeral.\n"; $language['validateNoCnfPwd'] = "You didn\'t enter a confirmation password.\n"; $language['validatePwdNoMch'] = "The passwords do not match. \n"; $language['validateNoEml'] = "You didn\'t enter an email address.\n"; $language['validateVldEml'] = "Please enter a valid email address.\n"; $language['validateEmlIllChrs'] = "The email address contains illegal characters.\n"; $language['validateNoPhn'] = "You didn\'t enter a phone number. \n "; $language['validatePhnIllChrs'] = "The phone number contains illegal characters. \n"; $language['validatePhnLgth'] = "The phone number is the wrong length. Make sure you included an area code.\n"; $this->language = $language; ?><file_sep><?php /** * @author <NAME> * @copyright 2013 Tinboat Webworks * @Project Sodapop * @version 0.0.1.3 * @link http://tinboatwebworks.com * @since 10/20/2011 */ // no direct access defined('_LOCK') or die('Restricted access'); $modulePath = "./modules/mod_" . $modData['name'] . "/"; global $config; ## bootstrap and load the module require $modulePath . "utilities/loader.php"; $modOutput = $menu->menuOutput($this); ## Load template ## require $modulePath . "template/index.php"; ?><file_sep><?php /** * @author <NAME> * @copyright 2011 Tinboat Webworks * @version 0.0.1.2 * @link a url * @since 10/20/2011 */ // no direct access defined('_LOCK') or die('Restricted access'); class adminMenuView extends view { public function adminMenuView() { } public function displayAdminMenu() { $output = " <div style='float: left; margin-left: 50px;'><strong>Manage: <a href='" . $this->sodapop->config['liveUrl'] . "modulemanager'>Modules</a> | <a href='" . $this->sodapop->config['liveUrl'] . "user?action=mangeusers'>Users</a></strong></div>"; return $output; } }<file_sep><?php /** * @author <NAME> * @copyright 2013 Tinboat Webworks * @Project Sodapop * @version 0.0.1.3 * @link http://tinboatwebworks.com * @since 10/20/2011 */ // no direct access defined('_LOCK') or die('Restricted access'); class view { public $templatePath; public $loadTemplate; public $templateName; public $template; /* * */ public function view() { } public function displaySodapop($sodapop) { require_once $sodapop->template['path'] . "/index.php"; } } ?><file_sep><?php /** * @author <NAME> * @copyright 2013 Tinboat Webworks * @Project Sodapop * @version 0.0.1.3 * @link http://tinboatwebworks.com * @since 10/20/2011 */ // no direct access defined('_LOCK') or die('Restricted access'); class appView extends view { public $data; public function appView() { global $sodapop; // Let's bring in the global app object so we can access all the environmental info... $this->sodapop = $sodapop; // And give it to this class require_once $this->sodapop->pageData['filePath'] . "/model.php"; $this->appModel = new appModel; } /* * buildModuleList() */ public function buildModuleList($modulesData) { foreach($modulesData as $moduleData) { $modulePositions = $this->listModulePositions($moduleData); $moduleData = extract($moduleData); if($active=='1') {$activeStatus = "Y";} else {$activeStatus = "N";} $selectsForAccess = $this->selectSelector($accessLevel); $selectAll = $this->selectAll($pages); $selectNone = $this->selectAll($hidden); $params = $this->dispalyParams($params); $moduleList .="<tr>"; $moduleList .="<td>" .$id . "</td>"; $moduleList .="<td>" . $name . "</td>"; $moduleList .="<td><form action='?action=updatePositions' method='GET'>"; $moduleList .="<input type='hidden' name='action' value='updatePosition'>"; $moduleList .="<input type='hidden' name='id' value='". $id ."'>"; $moduleList .="<select name='position'>"; $moduleList .= $modulePositions; $moduleList .="</select><input type='submit' value='update'></form></td>"; $moduleList .="<td>" . $ordering . "</td>"; $moduleList .="<td><form action='?action=updatePages&current=" . $active . "&id=" . $id . "' method='GET'>"; $moduleList .="<input type='hidden' name='action' value='updatePages'>"; $moduleList .="<input type='hidden' name='id' value='". $id ."'>"; $moduleList .="<select name='pages[]' multiple>"; $moduleList .= "<option value='0' " . $selectAll . ">All</option>"; $moduleList .= $this->buildPageList($pages); $moduleList .="</select><input type='submit' value='update'></form></td>"; $moduleList .="<td><form action='?action=updateHidden&current=" . $active . "&id=" . $id . "' method='GET'>"; $moduleList .="<input type='hidden' name='action' value='updateHidden'>"; $moduleList .="<input type='hidden' name='id' value='". $id ."'>"; $moduleList .="<select name='hidden[]' multiple>"; $moduleList .= "<option value='0' " . $selectNone . ">None</option>"; $moduleList .= $this->buildPageList($hidden); $moduleList .="</select><input type='submit' value='update'></form></td>"; // $moduleList .="<td>" . $hidden . "</td>"; $moduleList .="<td><form action='?action=updateParams' method='GET'>"; $moduleList .="<input type='hidden' name='action' value='updateParams'>"; $moduleList .="<input type='hidden' name='id' value='". $id ."'>"; $moduleList .="<textarea name='params' rows='3'>" . $params."</textarea>"; $moduleList .="<input type='submit' value='update'></form></td>"; $moduleList .="<td><a href='?action=updateStatus&current=" . $active . "&id=" . $id . "'>" . $activeStatus . "</a></td>"; $moduleList .="<td><form action='?action=updateAccess' method='GET'>"; $moduleList .="<input type='hidden' name='action' value='updateAccess'>"; $moduleList .="<input type='hidden' name='id' value='". $id ."'>"; $moduleList .="<select onchange='this.form.submit()' name='access'>"; $moduleList .=" <option" . $selectsForAccess['1'] . ">1</option> <option" . $selectsForAccess['2'] . ">2</option> <option" . $selectsForAccess['3'] . ">3</option> <option" . $selectsForAccess['4'] . ">4</option> <option" . $selectsForAccess['5'] . ">5</option> <option" . $selectsForAccess['6'] . ">6</option> <option" . $selectsForAccess['7'] . ">7</option> <option" . $selectsForAccess['8'] . ">8</option> <option" . $selectsForAccess['9'] . ">9</option> <option" . $selectsForAccess['10'] . ">10</option>"; $moduleList .="</select></form></td>"; $moduleList .="</tr>"; $level = ""; } return $moduleList; } public function selectSelector($accessLevel) { $output[$accessLevel] = " selected='selected' "; return $output; } public function selectAll($pages) { if (!$pages) { $output = "selected='selected'"; } else { $output = ""; } return $output; } /* public function selectNone($pages) { if ($pages) { $output = "<option value='0'>None</option> "; } else { $output = "<option value='0' selected='selected'>None</option> "; } return $output; } */ public function whichPagesSelector($pages) { $pages = explode("," ,$pages); foreach ($pages as $page) { $pageSelector[$page] = " selected='selected' "; } return $pageSelector; } /* * buildPageList() */ public function buildPageList($pages) { $pagesListData = $this->appModel->getPagesListData(); foreach($pagesListData as $pageListData) { $selectsForPages = $this->whichPagesSelector($pages); $pageListData = extract($pageListData); $output .= "<option " . $selectsForPages[$pageID] . " value='" . $pageID . "'>" . $name . "</option> "; } return $output; } public function listModules($moduleList) { $id = $this->sodapop->getCookie("sp_login"); if ($this->sodapop->checkAccessLevel($id) < 5) { $output = "No Dice"; } else { $output = "Module Manager"; // And build the list of users. $output .= "<table width='100%'> <tr> <td><strong>ID</strong></td> <td><strong>Name</strong></td> <td><strong>Position</strong></td> <td><strong>Order</strong></td> <td><strong>Pages</strong></td> <td><strong>Hidden</strong></td> <td><strong>Parameters</strong></td> <td><strong>Active</strong></td> <td><strong>Access</strong></td> </tr>" . $moduleList . " </table>"; } return $output; } public function dispalyParams($params) { if (empty($output)) {$output = "";} if(!empty($params)){ $params = explode("::", $params); foreach ($params as $param) { $param = explode("==", $param); $output .= $param[0] . "=" . $param[1] . "\r\n"; } } $output = rtrim($output, "\r\n"); // This is dumb, but I have to remove the trailing \r\n have to find a way to not have it there in the first place. return $output; } public function listModulePositions($moduleData) { if (empty($output)) {$output = "";} $templateData = $this->appModel->getTemplateData(); $positions = explode(":", $templateData[1]['positions']); foreach ($positions as $position ) { $output .= "<option "; if($position == $moduleData['positions']) { $output .= " selected = 'selected' "; } $output .= "value='" . $position . "'>" . $position . "</option>"; } return $output; } } <file_sep><?php /** * @author <NAME> * @copyright 2013 Tinboat Webworks * @Project Sodapop * @version 0.0.1.3 * @link http://tinboatwebworks.com * @since 10/20/2011 */ // no direct access defined('_LOCK') or die('Restricted access'); ## Load module controller require_once $modulePath . "controller.php"; $menu = new menu(); ## Load module model require_once $modulePath . "model.php"; $menuDatabase = new menuDatabase(); ## Load module view require_once $modulePath . "view.php"; $menuView = new menuView(); ?> <file_sep><?php /** * @author <NAME> * @copyright 2011 Tinboat Webworks * @version 0.0.1.3 * @link a url * @since 9/20/2013 */ /* * The first thing we want to do is set a lock constant. Every file will check * against this constant to make it is being loaded by the Sodapop application and * not by some other means. */ define('_LOCK', 1 ); /* * Now to get things started we are going to require the application class and then * instantiate the controller objext */ require_once "./application/controller/class.sodapop.php"; $sodapop = new Sodapop(); /* * Now we run loadSodapop to do all of of the bootstrap stuff like grabing the config * file and firing up the database, grabing the language files, etc. */ $loadSodapop = $sodapop->loadSodapop(); /* * $sodapop->$output hits loadApp to load the current pages app. * It contains all the output data for the current app as calculated by the * loadApp method on the sodapop controller object. The app's output can then be * passed along to the template. */ $sodapop->output = $sodapop->loadApp(); /* * Finally we push all of the $sodapop data - including the output - to the template * via the view object to display the application in the browser. */ $displaySodapop = $sodapop->view->displaySodapop($sodapop); /* * And that's it! That's all we needed to do. Thanks for using Sodapop! */<file_sep><?php /** * @author <NAME> * @copyright 2013 Tinboat Webworks * @Project Sodapop * @version 0.0.1.3 * @link http://tinboatwebworks.com * @since 10/20/2011 */ // no direct access defined('_LOCK') or die('Restricted access'); class database { private $result; private $query; private $template; private $row; private $handle; private $page; private $i; private $mod; public $sodapop; public function database() { global $sodapop; $this->sodapop; } /* * loadConfigFile() grabs the config file and generates the config array $sodapop->config */ public function loadConfigFile() { require "./utilities/configuration.php"; return $config; } /* * getData performs the basic db query, and add scrubbing for sql injection * protection. */ public function getData($query) { ##### ## Add some sql injection protection here? Scrub the $query before ## sending it to the db ##### $config = $this->loadConfigFile(); $this->config = $config; $con = mysqli_connect( $config['dbServer'], $config['dbUser'], $config['dbPass'], $config['dbName']); // echo $config['dbServer'].",".$config['dbUser'].",".$config['dbPass'].",".$config['dbName']; $result = mysqli_query($con, $query) or die("Couldn't execute this query"); return $result; } /* * getDefaultTemplate loads the template that is set as default in the * tamplates table. */ public function getTemplatesData() { ## Let's find out which template is set to default $query = " select * from templates where dflt = '1'"; $result = $this->getData($query); $result = $this->buildResultArray($result); return $result; } /* * appData retrieves all the info from the apps table for the given handle and packs it into the $app array. If no app existis, it routes to a 404 app... */ public function getPagesData($handle) { // Get the app data from the table for this handle $query = " select * from pages where handle = '$handle'"; $result = $this->getData($query); $result = $this->buildResultArray($result); return $result; } /* * modsInPosition($position) determines which modules are to be loaded for the given position, * then processes all the info from the modules in that position loading them into * an array $mod then returning the array */ public function modsInPostionData($position) { $query = " select * from modules where positions = '$position' order by ordering"; $result = $this->getData($query); $result = $this->buildResultArray($result); return $result; } /* * modsInPosition($position) determines which modules are to be loaded for the given position, * then processes all the info from the modules in that position loading them into * an array $mod then returning the array */ public function modsOnPageData($page) { $query = " select * from modules where page = '$position' order by ordering"; $result = $this->getData($query); $result = $this->buildResultArray($result); return $result; } /* * getUserDataById($id) acceptes the user's ID number and pulls all of their user * data based on that. */ public function getUsersByIdData($id) { $query = " select * from app_user_users where id = '$id'"; $result = $this->getData($query); $result = $this->buildResultArray($result); return $result; } /* * getUserDataById($id) acceptes the user's ID number and pulls all of their user * data based on that. */ public function checkAccessLevelData($id) { $query = " select accessLevel from app_user_users where id = '$id'"; $result = $this->getData($query); $result = $this->buildResultArray($result); return $result; } /* * getModuleData($id) pulls module data from the db based on the modules ID number * then returns an array of that data. * public function getModuleData($id) { $query = " select * from modules where id = '$id'"; $result = $this->getData($query); while ($row= mysql_fetch_array($result, MYSQL_ASSOC)) { $moduleData['id'] = $row['id']; $moduleData['name'] = $row['name']; $moduleData['positions'] = $row['positions']; $moduleData['pages'] = $row['pages']; $moduleData['hidden'] = $row['hidden']; $moduleData['params'] = $row['params']; $moduleData['ordering'] = $row['ordering']; $moduleData['active'] = $row['active']; } return $moduleData; } */ public Function buildResultArray($result) { while ($row= mysqli_fetch_array($result, MYSQL_ASSOC)) { if(empty($i)) {$i="";} $i++; $thisResult[$i] = $row; } if (empty($thisResult)) {$thisResult = "";} return $thisResult; } } <file_sep><?php /** * @author <NAME> * @copyright 2013 Tinboat Webworks * @Project Sodapop * @version 0.0.1.3 * @link http://tinboatwebworks.com * @since 10/20/2011 */ // no direct access defined('_LOCK') or die('Restricted access'); class appModel extends database { public function appModel() { global $sodapop; // Let's bring in the global app object so we can access all the environmental info... $this->sodapop = $sodapop; // And give it to this class $test = $sodapop->loadTest("user_model"); } /* * getPassword() will retrieve the password of the given user */ public function getPassword($user) { $query = " select * from app_user_users where username = '$user'"; $result = $this->getData($query); while ($row= mysqli_fetch_array($result, MYSQL_ASSOC)) { $password = $row['password']; } return $password; } /* * getPassword() will will pull all of the users data based on username from the db and pass it back as * an arrat, $userData */ public function getUserData($username) { $query = " select * from app_user_users where username = '$username'"; $result = $this->getData($query); while ($row= mysqli_fetch_array($result, MYSQL_ASSOC)) { $userData['id'] = $row['id']; $userData['name'] = $row['name']; $userData['email'] = $row['email']; $userData['username'] = $row['username']; $userData['accessLevel'] = $row['accessLevel']; } return $userData; } /* * getUserDatafromEmail() will will pull all of the users data based on their email from the db and pass it back as * an arrat, $userData. ##This can probably be refactored to be inlcuded in the getUserData() methode above. */ public function getUserDatafromEmail($email) { $userData = ""; $query = " select * from app_user_users where email = '$email'"; $result = $this->getData($query); while ($row= mysqli_fetch_array($result, MYSQL_ASSOC)) { $userData['id'] = $row['id']; $userData['name'] = $row['name']; $userData['email'] = $row['email']; $userData['username'] = $row['username']; $userData['accessLevel'] = $row['accessLevel']; } return $userData; } /* * confirmUnique() checks to make sure that the username and email are unigue when a user is * registering for a new account */ public function confirmUnique($formData) { if (isset($formData['id'])) { $query = " select email, username from app_user_users where id != " . $formData['id'] . ""; } else { $query= " select email, username from app_user_users"; } $result = $this->getData($query); while ($row= mysqli_fetch_array($result, MYSQLI_ASSOC)) { $existingUser['email'] = $row['email']; $existingUser['username'] = $row['username']; if ($formData['email'] == $existingUser['email'] && $formData['username'] == $existingUser['username']) { $confirmUnique = 'no'; return $confirmUnique; } } if (empty($confirmUnique)) { $confirmUnique = 'yes'; return $confirmUnique; } } /* * confirmUniqueUpdate() checks to make sure that the username and email are unigue when a user is * updating their account info. ##This can probably be refactored to be inlcuded in the confirmUnique() methode above. */ public function getUserDataForUnique($id) { $query = " select email, username from app_user_users "; if ($id != '') { $query .= "where id != '$id'"; } $result = $this->getData($query); $result = $this->buildResultArray($result); return $result; } /* * putUserData() is going to push the users data to the db */ public function putUserData($data) { $id = ""; $name = $data['name']; $email = $data['email']; $username = $data['username']; $password = $this->sodapop->hashIt($data['pwd']); $accessLevel = $data['accessLevel']; $query = "insert into app_user_users ( name, email, username, password, accessLevel) values ( '$name', '$email', '$username', '$password', '$accessLevel')"; $result = $this->getData($query); return $result; } /* * deleteUserData() is going to delete the users data from the db */ public function deleteUserData($id) { if (!$id) { $id = $this->sodapop->getCookie("sp_login"); } $query = " DELETE FROM app_user_users WHERE id = '$id'"; $result = $this->getData($query); $return; } /* * updateUserData() is going to update the users data in the db */ public function updateUserData($data) { // print_r($data); $unique = $this->confirmUnique($data); $data = extract($data); if(isset($pwd)) { $pwd = $this->sodapop->hashIt($pwd); } // echo "pwd: " . $pwd; die(); if(empty($output)) {$output = "";} if(isset($bio)){ $bio = addslashes($bio); } // If it is, let's update the data if ( $unique == 'yes' ) { $query = " update app_user_users set"; /*$query .= " id = '$id'"; */ $query .= ""; if(isset($name)) { $query .= " name = '$name'"; } if(isset($email)) { $query .= ", email = '$email'"; } if(isset($username)) { $query .= ", username = '$username'"; } if(isset($pwd)) { $query .= ", password = '$pwd'"; } if(isset($bio)) { $query .= ", bio = '$bio'"; } if(isset($accessLevel)) { $query .= ", accessLevel = '$accessLevel'"; } if(isset($token)) { $query .= ", recoveryToken = '$token'"; } $query .= " where id = '$id'"; $result = $this->getData($query); } // If it's not, let's let them know else { $output = $unique; } // Check to see if we are updating the password. if ($data['pwd'] != '') { // If we are, let's hash the password $password = $this->sodapop->hashIt($data['pwd']); $query = "update app_user_users set password = '$<PASSWORD>' where id = '$id'"; $result = $this->getData($query); } return $output; } /* * checkForToken() We use this to check if there is a password recovery token during the * password recovery process */ public function checkForToken($token) { $id =""; $query = " select * from app_user_users where recoveryToken = '" . $token . "'"; $result = $this->getData($query); while ($row= mysqli_fetch_array($result, MYSQL_ASSOC)) { $id = $row['id']; } return $id; } /* * updateNewPassword() Updates the password field. */ public function updateNewPassword ($data) { $token = $data['token']; $password = $data['<PASSWORD>']; $emptyToken = $data['emptyToken']; $query = " update app_user_users set password = '" . $password . "', recoveryToken = '" . $emptyToken . "' where recoveryToken = '" . $token . "'"; $result = $this->getData($query); $output = $this->sodapop->language['passwordUpdated']; return $output; } /* * userListData() */ public function userListData() { $query = " select * from app_user_users order by id"; $result = $this->getData($query); $result = $this->buildResultArray($result); return $result; } }<file_sep><?php /** * @author <NAME> * @copyright 2013 Tinboat Webworks * @Project Sodapop * @version 0.0.1.3 * @link http://tinboatwebworks.com * @since 10/20/2011 */ // no direct access defined('_LOCK') or die('Restricted access'); require_once $this->pageData['filePath'] . "/controller.php"; $appController = new appController($this); $appController->loadApp($this); // Create the model object for this page // $databaseApp = new databaseApp(); // Create the view object // $viewApp = new viewApp(); // Create the Controller for the page and sent the Model and View Objects into it // $controllerApp = new controllerApp();
97deabfaf955b16ba759e5234bef1be58478c4fd
[ "SQL", "PHP" ]
35
PHP
bradisarobot/Sodapop
92a53dffd352ac92ec590aa0d3765210bbd6b15f
09da896bb1b3e84945132955a82b9bc025401a89
refs/heads/master
<file_sep>#include <iostream> #include <stdint.h> #include <stdio.h> #include <bitset> #include <smmintrin.h> // intrinsics #include <emmintrin.h> #include<fstream> #include<stdio.h> #include <opencv.hpp> #include "StereoBMHelper.h" #include "FastFilters.h" #include "StereoSGM.h" #include<time.h> #include <vector> #include <list> #include <algorithm> #include <numeric> #include <iostream> #include "multilayer_stixel_world.h" #ifdef _DEBUG #pragma comment(lib, "opencv_world400d") #else #pragma comment(lib, "opencv_world400") #endif const int dispRange = 128; void jet(float x, int& r, int& g, int& b) { if (x < 0) x = -0.05; if (x > 1) x = 1.05; x = x / 1.15 + 0.1; // use slightly asymmetric range to avoid darkest shades of blue. r = __max(0, __min(255, (int)(round(255 * (1.5 - 4 * fabs(x - .75)))))); g = __max(0, __min(255, (int)(round(255 * (1.5 - 4 * fabs(x - .5)))))); b = __max(0, __min(255, (int)(round(255 * (1.5 - 4 * fabs(x - .25)))))); } cv::Mat Float2ColorJet(cv::Mat &fimg, float dmin, float dmax) { int width = fimg.cols, height = fimg.rows; cv::Mat img(height, width, CV_8UC3); float scale = 1.0 / (dmax - dmin); for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { float f = fimg.at<float>(y, x); int r = 0; int g = 0; int b = 0; /*if (f != INFINITY)*/ { float val = scale * (f - dmin); jet(val, r, g, b); } img.at<cv::Vec3b>(y, x) = cv::Vec3b(b, g, r); } } return img; } template<typename T> void processCensus5x5SGM(T* leftImg, T* rightImg, float32* output, float32* dispImgRight, int width, int height, uint16 paths, const int dispCount) { const int maxDisp = dispCount - 1; //std::cout << std::endl << paths << ", " << dispCount << std::endl; // get memory and init sgm params uint32* leftImgCensus = (uint32*)_mm_malloc(width*height*sizeof(uint32), 16); uint32* rightImgCensus = (uint32*)_mm_malloc(width*height*sizeof(uint32), 16); StereoSGMParams_t params; params.lrCheck = true; params.MedianFilter = true; params.Paths = paths; params.NoPasses = 2; uint16* dsi = (uint16*)_mm_malloc(width*height*(maxDisp + 1)*sizeof(uint16), 32); StereoSGM<T> m_sgm16(width, height, maxDisp, params); census5x5_16bit_SSE(leftImg, leftImgCensus, width, height); census5x5_16bit_SSE(rightImg, rightImgCensus, width, height); costMeasureCensus5x5_xyd_SSE(leftImgCensus, rightImgCensus, height, width, dispCount, params.InvalidDispCost, dsi); m_sgm16.process(dsi, leftImg, output, dispImgRight); _mm_free(dsi); } void onMouse(int event, int x, int y, int flags, void *param) { cv::Mat *im = reinterpret_cast<cv::Mat *>(param); switch (event) { case cv::EVENT_LBUTTONDBLCLK: std::cout << "at (" << std::setw(3) << x << "," << std::setw(3) << y << ") value is: " << static_cast<int>(im->at<uchar>(cv::Point(x, y))) << std::endl; break; } } int formatJPG(cv::Mat& imgL, cv::Mat& imgR, cv::Mat &imgDisp) { int cols_ = imgL.cols; int rows_ = imgL.rows; uint16* leftImg = (uint16*)_mm_malloc(rows_*cols_*sizeof(uint16), 16); uint16* rightImg = (uint16*)_mm_malloc(rows_*cols_*sizeof(uint16), 16); for (int i = 0; i < rows_; i++) { for (int j = 0; j < cols_; j++) { leftImg[i * cols_ + j] = *(imgL.data + i*imgL.step + j * imgL.elemSize()); rightImg[i * cols_ + j] = *(imgR.data + i*imgR.step + j * imgR.elemSize()); } } //左右图像的视差图分配存储空间(width*height*sizeof(float32)) float32* dispImg = (float32*)_mm_malloc(rows_*cols_*sizeof(float32), 16); float32* dispImgRight = (float32*)_mm_malloc(rows_*cols_*sizeof(float32), 16); const int numPaths = 8; processCensus5x5SGM(leftImg, rightImg, dispImg, dispImgRight, cols_, rows_, numPaths, dispRange); cv::Mat tmpDisp(cv::Size(cols_, rows_), CV_32FC1, dispImg); tmpDisp.copyTo(imgDisp); _mm_free(leftImg); _mm_free(rightImg); return 0; } static cv::Scalar computeColor(float val) { const float hscale = 6.f; float h = 0.6f * (1.f - val), s = 1.f, v = 1.f; float r, g, b; static const int sector_data[][3] = { { 1, 3, 0 }, { 1, 0, 2 }, { 3, 0, 1 }, { 0, 2, 1 }, { 0, 1, 3 }, { 2, 1, 0 } }; float tab[4]; int sector; h *= hscale; if (h < 0) do h += 6; while (h < 0); else if (h >= 6) do h -= 6; while (h >= 6); sector = cvFloor(h); h -= sector; if ((unsigned)sector >= 6u) { sector = 0; h = 0.f; } tab[0] = v; tab[1] = v*(1.f - s); tab[2] = v*(1.f - s*h); tab[3] = v*(1.f - s*(1.f - h)); b = tab[sector_data[sector][0]]; g = tab[sector_data[sector][1]]; r = tab[sector_data[sector][2]]; //return 255 * cv::Scalar(b, g, r); return cv::Scalar(255 * b, 255 * g, 255 * r); } static cv::Scalar dispToColor(float disp, float maxdisp) { if (disp < 0) return cv::Scalar(128, 128, 128); return computeColor(std::min(disp, maxdisp) / maxdisp); } static void drawStixel(cv::Mat& img, const Stixel& stixel, cv::Scalar color) { const int radius = std::max(stixel.width / 2, 1); const cv::Point tl(stixel.u - radius, stixel.vT); const cv::Point br(stixel.u + radius, stixel.vB); cv::rectangle(img, cv::Rect(tl, br), color, -1); cv::rectangle(img, cv::Rect(tl, br), cv::Scalar(255, 255, 255), 1); } int main() { // input camera parameters const cv::FileStorage cvfs("camera.xml", cv::FileStorage::READ); CV_Assert(cvfs.isOpened()); // input parameters MultiLayerStixelWrold::Parameters param; param.camera.fu = cvfs["FocalLengthX"]; param.camera.fv = cvfs["FocalLengthY"]; param.camera.u0 = cvfs["CenterX"]; param.camera.v0 = cvfs["CenterY"]; param.camera.baseline = cvfs["BaseLine"]; param.camera.height = cvfs["Height"]; param.camera.tilt = cvfs["Tilt"]; param.dmax = dispRange; MultiLayerStixelWrold stixelWorld(param); std::string dir = "E:/Image Set/"; cv::VideoWriter DemoWrite; //std::string outputName = dir + "0005.avi"; for (int frameno = 0;; frameno++) { char base_name[256]; sprintf(base_name, "%06d.png", frameno); std::string bufl = dir + "1/testing/0020/" + base_name; std::string bufr = dir + "2/testing/0020/" + base_name; std::cout << " " << frameno << std::endl; cv::Mat leftBGR = cv::imread(bufl, cv::IMREAD_COLOR); cv::Mat right = cv::imread(bufr, cv::IMREAD_GRAYSCALE); if (leftBGR.empty() || right.empty()) { std::cout << "Left image no exist!" << std::endl; frameno = 0; continue; //break; } cv::Mat left; if (leftBGR.channels() == 3) { cv::cvtColor(leftBGR, left, cv::COLOR_BGR2GRAY); } else { left = leftBGR.clone(); } CV_Assert(left.size() == right.size() && left.type() == right.type()); cv::Rect roiRect(0, 0, left.cols - left.cols % 16, left.rows); cv::Mat leftROI(left, roiRect); cv::Mat rightROI(right, roiRect); cv::Mat showImage(leftBGR, roiRect); // calculate disparity SGM-Based cv::Mat imgDisp; formatJPG(leftROI, rightROI, imgDisp); const std::vector<Stixel> stixels = stixelWorld.compute(imgDisp); // draw stixels cv::Mat draw; cv::cvtColor(leftROI, draw, cv::COLOR_GRAY2BGRA); cv::Mat stixelImg = cv::Mat::zeros(leftROI.size(), draw.type()); for (const auto& stixel : stixels) drawStixel(stixelImg, stixel, dispToColor(stixel.disp, 64)); draw = draw + 0.5 * stixelImg; cv::imshow("disparity", Float2ColorJet(imgDisp, 0, dispRange)); cv::imshow("stixels", draw); cv::waitKey(10); } }<file_sep>// Copyright ?<NAME>, 2014. // See license.txt for more details #include "StereoCommon.h" #include "StereoBMHelper.h" #include<fstream> #include <assert.h> #include <cmath> #include <limits> #include <smmintrin.h> // intrinsics #include <emmintrin.h> #include <nmmintrin.h> #include <string.h> //#define USE_AVX2 // pop count LUT for for uint16 uint16 m_popcount16LUT[UINT16_MAX + 1]; void fillPopCount16LUT()/*0000*/ { // popCount LUT for (int i = 0; i < UINT16_MAX + 1; i++) { m_popcount16LUT[i] = hamDist32(i, 0); } } /*计算视差空间dsi*/ void costMeasureCensus5x5Line_xyd_SSE(uint32* intermediate1, uint32* intermediate2 /*0000*/ , const int width, const int dispCount, const uint16 invalidDispValue, uint16* dsi, const int lineStart, const int lineEnd) { ALIGN16 const unsigned _LUT[] = { 0x02010100, 0x03020201, 0x03020201, 0x04030302 }; const __m128i xmm7 = _mm_load_si128((__m128i*)_LUT); const __m128i xmm6 = _mm_set1_epi32(0x0F0F0F0F); for (sint32 i = lineStart; i < lineEnd; i++) {/*有效值呈阶梯状分布.[0]、[0,1]、[0,1,2]、[0,1,..,62]、[0,1,..,62,63]、...[0,1,..,63]*/ //pBase指向leftImgCensus的第i行 uint32* pBase = intermediate1 + i*width; //pMatchRow指向rightImgCensus的第i行 uint32* pMatchRow = intermediate2 + i*width; for (uint32 j = 0; j < (uint32)width; j++) { //pBaseJ指向第i行的第j个(leftImgCensus) uint32* pBaseJ = pBase + j; //pBaseJ指向第i行的第j个的前63(rightImgCensus)---采样当前值和前63个值。 uint32* pMatchRowJmD = pMatchRow + j - dispCount + 1; int d = dispCount - 1;//(d = 63); /*当d>j时,赋初值invalidDisValue(12)*/ for (; d > (sint32)j && d >= 0; d--) { *getDispAddr_xyd(dsi, width, dispCount, i, j, d) = invalidDispValue; //dsi + i*(disp*width) + j*disp + k; pMatchRowJmD++; } int dShift4m1 = ((d - 1) >> 2) * 4; int diff = d - dShift4m1; // if (diff != 0) { for (; diff >= 0 && d >= 0; d--, diff--) { uint16 cost = (uint16)POPCOUNT32(*pBaseJ ^ *pMatchRowJmD); *getDispAddr_xyd(dsi, width, dispCount, i, j, d) = cost; pMatchRowJmD++; } } // 4 costs at once __m128i lPoint4 = _mm_set1_epi32(*pBaseJ); d -= 3; uint16* baseAddr = getDispAddr_xyd(dsi, width, dispCount, i, j, 0); for (; d >= 0; d -= 4) { // flip the values __m128i rPoint4 = _mm_shuffle_epi32(_mm_loadu_si128((__m128i*)pMatchRowJmD), 0x1b); //mask = 00 01 10 11 _mm_storel_pi((__m64*)(baseAddr + d), _mm_castsi128_ps(popcount32_4(_mm_xor_si128(lPoint4, rPoint4), xmm7, xmm6))); pMatchRowJmD += 4; } } } } //intermediate1 = leftImgcensus, intermediate2 = rightImgcensus void costMeasureCensus5x5_xyd_SSE(uint32* intermediate1, uint32* intermediate2 /*0000*/ , const int height, const int width, const int dispCount, const uint16 invalidDispValue, uint16* dsi) { /* 前两行为空,视差空间赋值为invalidDispValue(12)*/ for (int i = 0; i < 2; i++) { for (int j = 0; j < width; j++) { for (int d = 0; d <= dispCount - 1; d++) { *getDispAddr_xyd(dsi, width, dispCount, i, j, d) = invalidDispValue; //为dsi赋值 } } } /*计算中间行(2~height-2)的dis*/ costMeasureCensus5x5Line_xyd_SSE(intermediate1, intermediate2, width, dispCount, invalidDispValue, dsi, 2, height - 2); /* 后两行为空,视差空间赋值为invalidDispValue(12)*/ for (int i = height - 2; i < height; i++) { for (int j = 0; j < width; j++) { for (int d = 0; d <= dispCount - 1; d++) { *getDispAddr_xyd(dsi, width, dispCount, i, j, d) = invalidDispValue; } } } } void matchWTA_SSE(float32* dispImg, uint16* &dsiAgg, const int width, const int height, const int maxDisp, const float32 uniqueness)/*0000*/ { const uint32 factorUniq = (uint32)(1024 * uniqueness); const sint32 disp = maxDisp + 1; // find best by WTA float32* pDestDisp = dispImg; for (sint32 i = 0; i < height; i++) { for (sint32 j = 0; j < width; j++) { // WTA on disparity values uint16* pCost = getDispAddr_xyd(dsiAgg, width, disp, i, j, 0); uint16* pCostBase = pCost; uint32 minCost = *pCost; uint32 secMinCost = minCost; int secBestDisp = 0; const uint32 end = MIN(disp - 1, j); if (end == (uint32)disp - 1) //第64列开始执行 { uint32 bestDisp = 0; for (uint32 loop = 0; loop < end; loop += 8) { // load costs const __m128i costs = _mm_load_si128((__m128i*)pCost); // get minimum for 8 values const __m128i b = _mm_minpos_epu16(costs); const int minValue = _mm_extract_epi16(b, 0); if ((uint32)minValue < minCost) { minCost = (uint32)minValue; bestDisp = _mm_extract_epi16(b, 1) + loop; } pCost += 8; } // get value of second minimum pCost = pCostBase; pCost[bestDisp] = 65535; __m128i secMinVector = _mm_set1_epi16(-1); const uint16* pCostEnd = pCost + disp; for (; pCost < pCostEnd; pCost += 8) { // load costs __m128i costs = _mm_load_si128((__m128i*)pCost); // get minimum for 8 values secMinVector = _mm_min_epu16(secMinVector, costs); } secMinCost = _mm_extract_epi16(_mm_minpos_epu16(secMinVector), 0); pCostBase[bestDisp] = (uint16)minCost; // 分配视差 if (1024 * minCost <= secMinCost*factorUniq) { *pDestDisp = (float)bestDisp; } else { bool check = false; if (bestDisp < (uint32)maxDisp - 1 && pCostBase[bestDisp + 1] == secMinCost) { check = true; } if (bestDisp > 0 && pCostBase[bestDisp - 1] == secMinCost) { check = true; } if (!check) { *pDestDisp = -10; } else { *pDestDisp = (float)bestDisp; } } } else //前63列(阶梯状搜索第一列为0) { int bestDisp = 0; // for start for (uint32 k = 1; k <= end; k++) { pCost += 1; const uint16 cost = *pCost; if (cost < secMinCost) { if (cost < minCost) { secMinCost = minCost; secBestDisp = bestDisp; minCost = cost; bestDisp = k; } else { secMinCost = cost; secBestDisp = k; } } } // assign disparity if (1024 * minCost <= secMinCost*factorUniq || abs(bestDisp - secBestDisp) < 2) { *pDestDisp = (float)bestDisp; } else { *pDestDisp = -10; } } pDestDisp++; } } } FORCEINLINE __m128 rcp_nz_ss(__m128 input) { __m128 mask = _mm_cmpeq_ss(_mm_set1_ps(0.0), input); __m128 recip = _mm_rcp_ss(input); return _mm_andnot_ps(mask, recip); } void matchWTARight_SSE(float32* dispImg, uint16* &dsiAgg, const int width, const int height, const int maxDisp, const float32 uniqueness)/*0000*/ { const uint32 factorUniq = (uint32)(1024 * uniqueness); const uint32 disp = maxDisp + 1; _ASSERT(disp <= 256); ALIGN32 uint16 store[256 + 32]; store[15] = UINT16_MAX - 1; store[disp + 16] = UINT16_MAX - 1; // find best by WTA float32* pDestDisp = dispImg; for (uint32 i = 0; i < (uint32)height; i++) { for (uint32 j = 0; j < (uint32)width; j++) { // WTA on disparity values int bestDisp = 0; uint16* pCost = getDispAddr_xyd(dsiAgg, width, disp, i, j, 0); sint32 minCost = *pCost; sint32 secMinCost = minCost; int secBestDisp = 0; const uint32 maxCurrDisp = MIN(disp - 1, width - 1 - j); if (maxCurrDisp == disp - 1) { // transfer to linear storage, slightly unrolled //64个对角线上的值 for (uint32 k = 0; k <= maxCurrDisp; k += 4) { store[k + 16] = *pCost; store[k + 16 + 1] = pCost[disp + 1]; store[k + 16 + 2] = pCost[2 * disp + 2]; store[k + 16 + 3] = pCost[3 * disp + 3]; pCost += 4 * disp + 4; } // search in there uint16* pStore = &store[16]; const uint16* pStoreEnd = pStore + disp; for (; pStore < pStoreEnd; pStore += 8) { // load costs const __m128i costs = _mm_load_si128((__m128i*)pStore); // get minimum for 8 values const __m128i b = _mm_minpos_epu16(costs); const int minValue = _mm_extract_epi16(b, 0); if (minValue < minCost) { minCost = minValue; bestDisp = _mm_extract_epi16(b, 1) + (int)(pStore - &store[16]); } } // get value of second minimum pStore = &store[16]; store[16 + bestDisp] = 65535; __m128i secMinVector = _mm_set1_epi16(-1); for (; pStore < pStoreEnd; pStore += 8) { // load costs __m128i costs = _mm_load_si128((__m128i*)pStore); // get minimum for 8 values secMinVector = _mm_min_epu16(secMinVector, costs); } secMinCost = _mm_extract_epi16(_mm_minpos_epu16(secMinVector), 0); // assign disparity if (1024U * minCost <= secMinCost*factorUniq) { *pDestDisp = (float)bestDisp; } else { bool check = (store[16 + bestDisp + 1] == secMinCost); check = check | (store[16 + bestDisp - 1] == secMinCost); if (!check) { *pDestDisp = -10; } else { *pDestDisp = (float)bestDisp; } } pDestDisp++; } else { // border case handling for (uint32 k = 1; k <= maxCurrDisp; k++) { pCost += disp + 1; const sint32 cost = (sint32)*pCost; if (cost < secMinCost) { if (cost < minCost) { secMinCost = minCost; secBestDisp = bestDisp; minCost = cost; bestDisp = k; } else { secMinCost = cost; secBestDisp = k; } } } // assign disparity if (1024U * minCost <= factorUniq*secMinCost || abs(bestDisp - secBestDisp) < 2) { *pDestDisp = (float)bestDisp; } else { *pDestDisp = -10; } pDestDisp++; } } } } void matchRight(const float32* const src, float32* const dst, const int width, const int height) { for (int v = 0; v < height; v++) { for (int u = 0; u < width; u++) { if (src[v*width + u] == -10) { dst[v*width + u] = -10; } else { if (u - src[v*width + u] >= 0) { dst[v*width + (u - (int)src[v*width + u])] = src[v*width + u]; } else { dst[v*width + u] = 0; } } } } } /* do a sub pixel refinement by a parabola fit (抛物线拟合)to the winning pixel and its neighbors */ void subPixelRefine(float32* dispImg, uint16* dsiImg, const sint32 width, const sint32 height, const sint32 maxDisp)/*0000*/ { const sint32 disp_n = maxDisp + 1; /* equiangular */ for (sint32 y = 0; y < height; y++) { uint16* cost = getDispAddr_xyd(dsiImg, width, disp_n, y, 1, 0); float* disp = (float*)dispImg + y*width; for (sint32 x = 1; x < width - 1; x++, cost += disp_n) { if (disp[x] > 0.0) { // Get minimum int d_min = (int)disp[x]; // Compute the equations of the parabolic fit uint16* costDmin = cost + d_min; sint32 c0 = costDmin[-1], c1 = *costDmin, c2 = costDmin[1]; __m128 denom = _mm_cvt_si2ss(_mm_setzero_ps(), c2 - c0); __m128 left = _mm_cvt_si2ss(_mm_setzero_ps(), c1 - c0); __m128 right = _mm_cvt_si2ss(_mm_setzero_ps(), c1 - c2); __m128 lowerMin = _mm_min_ss(left, right); __m128 result = _mm_mul_ss(denom, rcp_nz_ss(_mm_mul_ss(_mm_set_ss(2.0f), lowerMin))); __m128 baseDisp = _mm_cvt_si2ss(_mm_setzero_ps(), d_min); result = _mm_add_ss(baseDisp, result); _mm_store_ss(disp + x, result); } else { disp[x] = -10; } } } } void doRLCheck(float32* dispRightImg, float32* dispCheckImg, const sint32 width, const sint32 height) { float* dispRow = dispRightImg; float* dispCheckRow = dispCheckImg; for (sint32 i = 0; i < height; i++) { for (sint32 j = 0; j < width; j++) { const float32 baseDisp = dispRow[j]; if (baseDisp >= 0 && j + baseDisp <= width) { const float matchDisp = dispCheckRow[(int)(j + baseDisp)]; sint32 diff = (sint32)(baseDisp - matchDisp); if (abs(diff) > 1.0f) { dispRow[j] = 0; // occluded or false match } } else { dispRow[j] = 0; } } dispRow += width; dispCheckRow += width; } } void doLRCheck(float32* dispImg, float32* dispCheckImg, const sint32 width, const sint32 height) { float *dispRow = dispImg; float *dispCheckRow = dispCheckImg; float m[8], Min, secMin, tmp; for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { const float32 baseDisp = dispRow[j]; if (baseDisp >= 0 && baseDisp <= j) { const float matchDisp = dispCheckRow[(int)(j - baseDisp)]; float diff = (baseDisp - matchDisp); if (abs(diff) > 1.0f) { if (i > 0 && i < height - 1 && j > 0 && j < width - 1) { secMin = Min = m[0] = dispRow[j - 1]; m[1] = dispRow[j + 1]; m[2] = dispRow[j - width]; m[3] = dispRow[j - width - 1]; m[4] = dispRow[j - width + 1]; m[5] = dispRow[j + width]; m[6] = dispRow[j + width - 1]; m[7] = dispRow[j + width + 1]; for (int tmp_i = 1; i < 8; i++) { if (m[tmp_i] < Min) { secMin = Min; Min = m[tmp_i]; } else if (m[tmp_i] < secMin) { secMin = m[tmp_i]; } } dispRow[j] = secMin; } } } else { /*dispRow[j] = -10;*/ if (i > 0 && i < height - 1 && j > 0 && j < width - 1) { tmp = m[0] = dispRow[j - 1]; m[1] = dispRow[j + 1]; m[2] = dispRow[j - width]; m[3] = dispRow[j - width - 1]; m[4] = dispRow[j - width + 1]; m[5] = dispRow[j + width]; m[6] = dispRow[j + width - 1]; m[7] = dispRow[j + width + 1]; for (int tmp_i = 0; i < 7; i++) { tmp = dispRow[0]; for (int tmp_j = 1; j < 8 - i; j++) { if (tmp > m[tmp_j]) { m[tmp_j - 1] = m[tmp_j]; m[tmp_j] = tmp; } else { tmp = m[tmp_j]; } } } dispRow[j] = (m[3] + m[4]) / 2; } } } dispRow += width; dispCheckRow += width; } } <file_sep># Multilayer-Stixel An implementation of multi-layered stixel computation based on stereo vision(SGM) the code is based on c++ and opencv the version of opencv is 4.0 ![Left](disparity.jpg) | ![Right](stixels.jpg) ``` The image data is http://www.cvlibs.net/datasets/kitti/eval_stereo.php the code is : std::string bufl = left_001.img; std::string bufr = right_001.img; ``` ``` Now try to run: main.cpp ```<file_sep>// Copyright ?<NAME>, 2014. // See license.txt for more details #include "StereoCommon.h" #include "FastFilters.h" #include <smmintrin.h> // intrinsics #include <emmintrin.h> #include "string.h" // memset #include "assert.h" #include<iostream> inline uint16* getPixel16(uint16* base, uint32 width, int j, int i)/*0000*/ { return base + i*width + j; } inline uint32* getPixel32(uint32* base, uint32 width, int j, int i)/*0000*/ { return base + i*width + j; } // census 5x5 // input uint16 image, output uint32 image // 2.56ms/2, 768x480, 9.2 cycles/pixel /* *source 源图像 *dest census结果 */ void census5x5_16bit_SSE(uint16* source, uint32* dest, uint32 width, uint32 height)/*0000*/ { uint32* dst = dest; const uint16* src = source; // memsets just for the upper and lower two lines, not really necessary //census的前两行和后两行的值初始化为0 memset(dest, 0, width * 2 * sizeof(uint32)); memset(dest + width*(height - 2), 0, width * 2 * sizeof(uint32)); // input lines 0,1,2 const uint16* i0 = src; const uint16* i1 = src + width; const uint16* i2 = src + 2 * width; const uint16* i3 = src + 3 * width; const uint16* i4 = src + 4 * width; // output at first result uint32* result = dst + 2 * width; const uint16* const end_input = src + width*height; /* expand mask */ //设置16个8位的有符号的整数值 __m128i expandLowerMask = _mm_set_epi8(0x06, 0x06, 0x06, 0x06, 0x04, 0x04, 0x04, 0x04, 0x02, 0x02, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00); __m128i expandUpperMask = _mm_set_epi8(0x0E, 0x0E, 0x0E, 0x0E, 0x0C, 0x0C, 0x0C, 0x0C, 0x0A, 0x0A, 0x0A, 0x0A, 0x08, 0x08, 0x08, 0x08); __m128i blendB1B2Mask = _mm_set_epi8(0x00u, 0x00u, 0x80u, 0x00u, 0x00u, 0x00u, 0x80u, 0x00u, 0x00u, 0x00u, 0x80u, 0x00u, 0x00u, 0x00u, 0x80u, 0x00u); __m128i blendB1B2B3Mask = _mm_set_epi8(0x00u, 0x80u, 0x00u, 0x00u, 0x00u, 0x80u, 0x00u, 0x00u, 0x00u, 0x80u, 0x00u, 0x00u, 0x00u, 0x80u, 0x00u, 0x00u); //从一个特定的地址装载数据 __m128i l2_register = _mm_stream_load_si128((__m128i*)(i2)); __m128i l3_register = _mm_stream_load_si128((__m128i*)(i3)); __m128i l4_register = _mm_stream_load_si128((__m128i*)(i4)); __m128i l1_register = _mm_stream_load_si128((__m128i*)(i1)); __m128i l0_register = _mm_stream_load_si128((__m128i*)(i0)); i0 += 8; i1 += 8; i2 += 8; i3 += 8; i4 += 8; //设置128位的值为0 __m128i lastResultLower = _mm_setzero_si128(); for (; i4 < end_input; i0 += 8, i1 += 8, i2 += 8, i3 += 8, i4 += 8) { /* parallel 16 pixel processing */ const __m128i l0_register_next = _mm_stream_load_si128((__m128i*)(i0)); const __m128i l1_register_next = _mm_stream_load_si128((__m128i*)(i1)); const __m128i l2_register_next = _mm_stream_load_si128((__m128i*)(i2)); const __m128i l3_register_next = _mm_stream_load_si128((__m128i*)(i3)); const __m128i l4_register_next = _mm_stream_load_si128((__m128i*)(i4)); /* 0 1 2 3 4 5 6 7 8 9 10 11 c 12 13 14 15 16 17 18 19 20 21 22 23 */ /* r/h is result, v is pixelvalue */ /* pixel c */ //把l2register_next和l2regigster并列放到一块,然后去除l2_register的后四个字节。 //并且从右数,输出128位作为结果。 __m128i pixelcv = _mm_alignr_epi8(l2_register_next, l2_register, 4);//像素c /* pixel 0*/ //pixelcv和l0_register比较,若小于则pexel0h为1,否则为0 __m128i pixel0h = _mm_cmplt_epi16(l0_register, pixelcv); /* pixel 1*/ __m128i pixel1v = _mm_alignr_epi8(l0_register_next, l0_register, 2); __m128i pixel1h = _mm_cmplt_epi16(pixel1v, pixelcv); /* pixel 2 */ __m128i pixel2v = _mm_alignr_epi8(l0_register_next, l0_register, 4); __m128i pixel2h = _mm_cmplt_epi16(pixel2v, pixelcv); /* pixel 3 */ __m128i pixel3v = _mm_alignr_epi8(l0_register_next, l0_register, 6); __m128i pixel3h = _mm_cmplt_epi16(pixel3v, pixelcv); /* pixel 4 */ __m128i pixel4v = _mm_alignr_epi8(l0_register_next, l0_register, 8); __m128i pixel4h = _mm_cmplt_epi16(pixel4v, pixelcv); /** line **/ /* pixel 5 */ __m128i pixel5h = _mm_cmplt_epi16(l1_register, pixelcv); /* pixel 6 */ __m128i pixel6v = _mm_alignr_epi8(l1_register_next, l1_register, 2); __m128i pixel6h = _mm_cmplt_epi16(pixel6v, pixelcv); /* pixel 7 */ __m128i pixel7v = _mm_alignr_epi8(l1_register_next, l1_register, 4); __m128i pixel7h = _mm_cmplt_epi16(pixel7v, pixelcv); /* pixel 8 */ __m128i pixel8v = _mm_alignr_epi8(l1_register_next, l1_register, 6); __m128i pixel8h = _mm_cmplt_epi16(pixel8v, pixelcv); /* pixel 9 */ __m128i pixel9v = _mm_alignr_epi8(l1_register_next, l1_register, 8); __m128i pixel9h = _mm_cmplt_epi16(pixel9v, pixelcv); /* create bitfield part 1*/ //_mm_set1_epi8把128U设置为16个有符号的8位整数 //_mm_and_si128把128U和pixel10h按位与 __m128i resultByte1 = _mm_and_si128(_mm_set1_epi8(128u), pixel0h); __m128i tmptest, tmptest1; //按位或 resultByte1 = _mm_or_si128(resultByte1, tmptest1 = _mm_and_si128(tmptest = _mm_set1_epi8(64), pixel1h)); resultByte1 = _mm_or_si128(resultByte1, tmptest1 = _mm_and_si128(tmptest = _mm_set1_epi8(32), pixel2h)); resultByte1 = _mm_or_si128(resultByte1, tmptest1 = _mm_and_si128(tmptest = _mm_set1_epi8(16), pixel3h)); __m128i resultByte1b = _mm_and_si128(tmptest1 = _mm_set1_epi8(8), pixel4h); resultByte1b = _mm_or_si128(resultByte1b, tmptest1 = _mm_and_si128(tmptest = _mm_set1_epi8(4), pixel5h)); resultByte1b = _mm_or_si128(resultByte1b, tmptest1 = _mm_and_si128(tmptest = _mm_set1_epi8(2), pixel6h)); resultByte1b = _mm_or_si128(resultByte1b, tmptest1 = _mm_and_si128(tmptest = _mm_set1_epi8(1), pixel7h)); resultByte1 = _mm_or_si128(resultByte1, resultByte1b); /** line **/ /* pixel 10 */ __m128i pixel10h = _mm_cmplt_epi16(l2_register, pixelcv); /* pixel 11 */ __m128i pixel11v = _mm_alignr_epi8(l2_register_next, l2_register, 2); __m128i pixel11h = _mm_cmplt_epi16(pixel11v, pixelcv); /* pixel 12 */ __m128i pixel12v = _mm_alignr_epi8(l2_register_next, l2_register, 6); __m128i pixel12h = _mm_cmplt_epi16(pixel12v, pixelcv); /* pixel 13 */ __m128i pixel13v = _mm_alignr_epi8(l2_register_next, l2_register, 8); __m128i pixel13h = _mm_cmplt_epi16(pixel13v, pixelcv); /* line */ /* pixel 14 */ __m128i pixel14h = _mm_cmplt_epi16(l3_register, pixelcv); /* pixel 15 */ __m128i pixel15v = _mm_alignr_epi8(l3_register_next, l3_register, 2); __m128i pixel15h = _mm_cmplt_epi16(pixel15v, pixelcv); /* pixel 16 */ __m128i pixel16v = _mm_alignr_epi8(l3_register_next, l3_register, 4); __m128i pixel16h = _mm_cmplt_epi16(pixel16v, pixelcv); /* pixel 17 */ __m128i pixel17v = _mm_alignr_epi8(l3_register_next, l3_register, 6); __m128i pixel17h = _mm_cmplt_epi16(pixel17v, pixelcv); /* pixel 18 */ __m128i pixel18v = _mm_alignr_epi8(l3_register_next, l3_register, 8); __m128i pixel18h = _mm_cmplt_epi16(pixel18v, pixelcv); /* create bitfield part 2 */ __m128i resultByte2 = _mm_and_si128(_mm_set1_epi8(128u), pixel8h); resultByte2 = _mm_or_si128(resultByte2, _mm_and_si128(_mm_set1_epi8(64), pixel9h)); resultByte2 = _mm_or_si128(resultByte2, _mm_and_si128(_mm_set1_epi8(32), pixel10h)); resultByte2 = _mm_or_si128(resultByte2, _mm_and_si128(_mm_set1_epi8(16), pixel11h)); __m128i resultByte2b = _mm_and_si128(_mm_set1_epi8(8), pixel12h); resultByte2b = _mm_or_si128(resultByte2b, _mm_and_si128(_mm_set1_epi8(4), pixel13h)); resultByte2b = _mm_or_si128(resultByte2b, _mm_and_si128(_mm_set1_epi8(2), pixel14h)); resultByte2b = _mm_or_si128(resultByte2b, _mm_and_si128(_mm_set1_epi8(1), pixel15h)); resultByte2 = _mm_or_si128(resultByte2, resultByte2b); /* line */ /* pixel 19 */ __m128i pixel19h = _mm_cmplt_epi16(l4_register, pixelcv); /* pixel 20 */ __m128i pixel20v = _mm_alignr_epi8(l4_register_next, l4_register, 2); __m128i pixel20h = _mm_cmplt_epi16(pixel20v, pixelcv); /* pixel 21 */ __m128i pixel21v = _mm_alignr_epi8(l4_register_next, l4_register, 4); __m128i pixel21h = _mm_cmplt_epi16(pixel21v, pixelcv); /* pixel 22 */ __m128i pixel22v = _mm_alignr_epi8(l4_register_next, l4_register, 6); __m128i pixel22h = _mm_cmplt_epi16(pixel22v, pixelcv); /* pixel 23 */ __m128i pixel23v = _mm_alignr_epi8(l4_register_next, l4_register, 8); __m128i pixel23h = _mm_cmplt_epi16(pixel23v, pixelcv); /* create bitfield part 3*/ __m128i resultByte3 = _mm_and_si128(_mm_set1_epi8(128u), pixel16h); resultByte3 = _mm_or_si128(resultByte3, _mm_and_si128(_mm_set1_epi8(64), pixel17h)); resultByte3 = _mm_or_si128(resultByte3, _mm_and_si128(_mm_set1_epi8(32), pixel18h)); resultByte3 = _mm_or_si128(resultByte3, _mm_and_si128(_mm_set1_epi8(16), pixel19h)); resultByte3 = _mm_or_si128(resultByte3, _mm_and_si128(_mm_set1_epi8(8), pixel20h)); resultByte3 = _mm_or_si128(resultByte3, _mm_and_si128(_mm_set1_epi8(4), pixel21h)); resultByte3 = _mm_or_si128(resultByte3, _mm_and_si128(_mm_set1_epi8(2), pixel22h)); resultByte3 = _mm_or_si128(resultByte3, _mm_and_si128(_mm_set1_epi8(1), pixel23h)); /* blend byte 1 and byte 2,then byte3, lower part */ __m128i resultByte1Lower = _mm_shuffle_epi8(resultByte1, expandLowerMask); __m128i resultByte2Lower = _mm_shuffle_epi8(resultByte2, expandLowerMask); __m128i blendB1B2 = _mm_blendv_epi8(resultByte1Lower, resultByte2Lower, blendB1B2Mask); blendB1B2 = _mm_and_si128(blendB1B2, _mm_set1_epi32(0x00FFFFFF)); // zero first byte __m128i blendB1B2B3L = _mm_blendv_epi8(blendB1B2, _mm_shuffle_epi8(resultByte3, expandLowerMask), blendB1B2B3Mask); /* blend byte 1 and byte 2,then byte3, upper part */ __m128i resultByte1Upper = _mm_shuffle_epi8(resultByte1, expandUpperMask); __m128i resultByte2Upper = _mm_shuffle_epi8(resultByte2, expandUpperMask); blendB1B2 = _mm_blendv_epi8(resultByte1Upper, resultByte2Upper, blendB1B2Mask); blendB1B2 = _mm_and_si128(blendB1B2, _mm_set1_epi32(0x00FFFFFF)); // zero first byte __m128i blendB1B2B3H = _mm_blendv_epi8(blendB1B2, _mm_shuffle_epi8(resultByte3, expandUpperMask), blendB1B2B3Mask); /* shift because of offsets */ __m128i c = _mm_alignr_epi8(blendB1B2B3L, lastResultLower, 8); _mm_store_si128((__m128i*)result, c); _mm_store_si128((__m128i*)(result + 4), _mm_alignr_epi8(blendB1B2B3H, blendB1B2B3L, 8)); result += 8; lastResultLower = blendB1B2B3H; /*load next */ l0_register = l0_register_next; l1_register = l1_register_next; l2_register = l2_register_next; l3_register = l3_register_next; l4_register = l4_register_next; } /* last 8 pixels */ { int i = height - 3; for (sint32 j = width - 8; j < (sint32)width - 2; j++) { const int centerValue = *getPixel16(source, width, j, i); uint32 value = 0; for (sint32 x = -2; x <= 2; x++) { for (sint32 y = -2; y <= 2; y++) { if (x != 0 || y != 0) { value *= 2; if (centerValue > *getPixel16(source, width, j + y, i + x)) { value += 1; } } } } *getPixel32(dest, width, j, i) = value; } *getPixel32(dest, width, width - 2, i) = 255; *getPixel32(dest, width, width - 1, i) = 255; } } inline void vecSortandSwap(__m128& a, __m128& b)/*0000*/ { __m128 temp = a; a = _mm_min_ps(a, b); b = _mm_max_ps(temp, b); } void median3x3_SSE(float32* source, float32* dest, uint32 width, uint32 height)/*0000*/ { // check width restriction assert(width % 4 == 0); float32* destStart = dest; // lines float32* line1 = source; float32* line2 = source + width; float32* line3 = source + 2 * width; float32* end = source + width*height; dest += width; __m128 lastMedian = _mm_setzero_ps(); do { // fill value const __m128 l1_reg = _mm_load_ps(line1); const __m128 l1_reg_next = _mm_load_ps(line1 + 4); __m128 v0 = l1_reg; __m128 v1 = _mm_castsi128_ps(_mm_alignr_epi8(_mm_castps_si128(l1_reg_next), _mm_castps_si128(l1_reg), 4)); __m128 v2 = _mm_castsi128_ps(_mm_alignr_epi8(_mm_castps_si128(l1_reg_next), _mm_castps_si128(l1_reg), 8)); const __m128 l2_reg = _mm_load_ps(line2); const __m128 l2_reg_next = _mm_load_ps(line2 + 4); __m128 v3 = l2_reg; __m128 v4 = _mm_castsi128_ps(_mm_alignr_epi8(_mm_castps_si128(l2_reg_next), _mm_castps_si128(l2_reg), 4)); __m128 v5 = _mm_castsi128_ps(_mm_alignr_epi8(_mm_castps_si128(l2_reg_next), _mm_castps_si128(l2_reg), 8)); const __m128 l3_reg = _mm_load_ps(line3); const __m128 l3_reg_next = _mm_load_ps(line3 + 4); __m128 v6 = l3_reg; __m128 v7 = _mm_castsi128_ps(_mm_alignr_epi8(_mm_castps_si128(l3_reg_next), _mm_castps_si128(l3_reg), 4)); __m128 v8 = _mm_castsi128_ps(_mm_alignr_epi8(_mm_castps_si128(l3_reg_next), _mm_castps_si128(l3_reg), 8)); // find median through sorting network vecSortandSwap(v1, v2); vecSortandSwap(v4, v5); vecSortandSwap(v7, v8); vecSortandSwap(v0, v1); vecSortandSwap(v3, v4); vecSortandSwap(v6, v7); vecSortandSwap(v1, v2); vecSortandSwap(v4, v5); vecSortandSwap(v7, v8); vecSortandSwap(v0, v3); vecSortandSwap(v5, v8); vecSortandSwap(v4, v7); vecSortandSwap(v3, v6); vecSortandSwap(v1, v4); vecSortandSwap(v2, v5); vecSortandSwap(v4, v7); vecSortandSwap(v4, v2); vecSortandSwap(v6, v4); vecSortandSwap(v4, v2); // comply to alignment restrictions const __m128i c = _mm_alignr_epi8(_mm_castps_si128(v4), _mm_castps_si128(lastMedian), 12); _mm_store_si128((__m128i*)dest, c); lastMedian = v4; dest += 4; line1 += 4; line2 += 4; line3 += 4; } while (line3 + 4 + 4 <= end); memcpy(destStart, source, sizeof(float32)*(width + 1)); memcpy(destStart + width*height - width - 1 - 3, source + width*height - width - 1 - 3, sizeof(float32)*(width + 1 + 3)); } <file_sep>#ifndef __MATRIX_H__ #define __MATRIX_H__ #include <opencv2/opencv.hpp> #include <array> template <typename T> class Matrix : public cv::Mat_<T> { public: Matrix() : cv::Mat_<T>() {} Matrix(int size1, int size2) { create(size1, size2); } Matrix(int size1, int size2, int size3) { create(size1, size2, size3); } void create(int size1, int size2) { cv::Mat_<T>::create(size1, size2); this->size1 = size1; this->size2 = size2; this->size3 = 1; } void create(int size1, int size2, int size3) { cv::Mat_<T>::create(3, std::array<int, 3>{size1, size2, size3}.data()); this->size1 = size1; this->size2 = size2; this->size3 = size3; } inline T& operator()(int i) { return *((T*)this->data + i); } inline const T& operator()(int i) const { return *((T*)this->data + i); } inline T& operator()(int i, int j) { return *((T*)this->data + i * size2 + j); } inline const T& operator()(int i, int j) const { return *((T*)this->data + i * size2 + j); } inline T& operator()(int i, int j, int k) { return *((T*)this->data + size3 * (i * size2 + j) + k); } inline const T& operator()(int i, int j, int k) const { return *((T*)this->data + size3 * (i * size2 + j) + k); } int size1, size2, size3; }; using Matrixf = Matrix<float>; using Matrixi = Matrix<int>; #endif // !__MATRIX_H__ <file_sep>#include "multilayer_stixel_world.h" #include "matrix.h" #include "cost_function.h" #include <algorithm> #ifdef _OPENMP #include <omp.h> #endif MultiLayerStixelWrold::MultiLayerStixelWrold(const Parameters& param) : param_(param) { } std::vector<Stixel> MultiLayerStixelWrold::compute(const cv::Mat& disparity) { CV_Assert(disparity.type() == CV_32F); const int stixelWidth = param_.stixelWidth; const int w = disparity.cols / stixelWidth; const int h = disparity.rows; const int fnmax = static_cast<int>(param_.dmax); // compute horizontal median of each column Matrixf columns(w, h); for (int v = 0; v < h; v++) { for (int u = 0; u < w; u++) { // compute horizontal median std::vector<float> buf(stixelWidth); for (int du = 0; du < stixelWidth; du++) buf[du] = disparity.at<float>(v, u * stixelWidth + du); std::sort(std::begin(buf), std::end(buf)); const float m = buf[stixelWidth / 2]; // reverse order of data so that v = 0 points the bottom columns(u, h - 1 - v) = m; } } // get camera parameters const CameraParameters& camera = param_.camera; const float sinTilt = sinf(camera.tilt); const float cosTilt = cosf(camera.tilt); // compute expected ground disparity std::vector<float> groundDisparity(h); for (int v = 0; v < h; v++) groundDisparity[v] = std::max((camera.baseline / camera.height) * (camera.fu * sinTilt + (v - camera.v0) * cosTilt), 1.f); std::reverse(std::begin(groundDisparity), std::end(groundDisparity)); const float vhor = h - 1 - (camera.v0 * cosTilt - camera.fu * sinTilt) / cosTilt; // create data cost function of each segment NegativeLogDataTermGrd dataTermG(param_.dmax, param_.dmin, param_.sigmaG, param_.pOutG, param_.pInvG, groundDisparity); NegativeLogDataTermObj dataTermO(param_.dmax, param_.dmin, param_.sigmaO, param_.pOutO, param_.pInvO); NegativeLogDataTermSky dataTermS(param_.dmax, param_.dmin, param_.sigmaS, param_.pOutS, param_.pInvS); // create prior cost function of each segment const int G = NegativeLogPriorTerm::G; const int O = NegativeLogPriorTerm::O; const int S = NegativeLogPriorTerm::S; NegativeLogPriorTerm priorTerm(h, vhor, param_.dmax, param_.dmin, camera.baseline, camera.fu, param_.deltaz, param_.eps, param_.pOrd, param_.pGrav, param_.pBlg, groundDisparity); // data cost LUT Matrixf costsG(w, h), costsO(w, h, fnmax), costsS(w, h), sum(w, h); Matrixi valid(w, h); // cost table Matrixf costTable(w, h, 3), dispTable(w, h, 3); Matrix<cv::Point> indexTable(w, h, 3); // process each column int u; #pragma omp parallel for for (u = 0; u < w; u++) { ////////////////////////////////////////////////////////////////////////////// // pre-computate LUT ////////////////////////////////////////////////////////////////////////////// float tmpSumG = 0.f; float tmpSumS = 0.f; std::vector<float> tmpSumO(fnmax, 0.f); float tmpSum = 0.f; int tmpValid = 0; for (int v = 0; v < h; v++) { // measured disparity const float d = columns(u, v); // pre-computation for ground costs tmpSumG += dataTermG(d, v); costsG(u, v) = tmpSumG; // pre-computation for sky costs tmpSumS += dataTermS(d); costsS(u, v) = tmpSumS; // pre-computation for object costs for (int fn = 0; fn < fnmax; fn++) { tmpSumO[fn] += dataTermO(d, fn); costsO(u, v, fn) = tmpSumO[fn]; } // pre-computation for mean disparity of stixel if (d >= 0.f) { tmpSum += d; tmpValid++; } sum(u, v) = tmpSum; valid(u, v) = tmpValid; } ////////////////////////////////////////////////////////////////////////////// // compute cost tables ////////////////////////////////////////////////////////////////////////////// for (int vT = 0; vT < h; vT++) { float minCostG, minCostO, minCostS; float minDispG, minDispO, minDispS; cv::Point minPosG(0, 0), minPosO(1, 0), minPosS(2, 0); // process vB = 0 { // compute mean disparity within the range of vB to vT const float d1 = sum(u, vT) / std::max(valid(u, vT), 1); const int fn = cvRound(d1); // initialize minimum costs minCostG = costsG(u, vT) + priorTerm.getG0(vT); minCostO = costsO(u, vT, fn) + priorTerm.getO0(vT); minCostS = costsS(u, vT) + priorTerm.getS0(vT); minDispG = minDispO = minDispS = d1; } for (int vB = 1; vB <= vT; vB++) { // compute mean disparity within the range of vB to vT const float d1 = (sum(u, vT) - sum(u, vB - 1)) / std::max(valid(u, vT) - valid(u, vB - 1), 1); const int fn = cvRound(d1); // compute data terms costs const float dataCostG = vT < vhor ? costsG(u, vT) - costsG(u, vB - 1) : N_LOG_0_0; const float dataCostO = costsO(u, vT, fn) - costsO(u, vB - 1, fn); const float dataCostS = vT < vhor ? N_LOG_0_0 : costsS(u, vT) - costsS(u, vB - 1); // compute priors costs and update costs const float d2 = dispTable(u, vB - 1, 1); #define UPDATE_COST(C1, C2) \ const float cost##C1##C2 = dataCost##C1 + priorTerm.get##C1##C2(vB, cvRound(d1), cvRound(d2)) + costTable(u, vB - 1, C2); \ if (cost##C1##C2 < minCost##C1) \ { \ minCost##C1 = cost##C1##C2; \ minDisp##C1 = d1; \ minPos##C1 = cv::Point(C2, vB - 1); \ } \ UPDATE_COST(G, G); UPDATE_COST(G, O); UPDATE_COST(G, S); UPDATE_COST(O, G); UPDATE_COST(O, O); UPDATE_COST(O, S); UPDATE_COST(S, G); UPDATE_COST(S, O); UPDATE_COST(S, S); } costTable(u, vT, 0) = minCostG; costTable(u, vT, 1) = minCostO; costTable(u, vT, 2) = minCostS; dispTable(u, vT, 0) = minDispG; dispTable(u, vT, 1) = minDispO; dispTable(u, vT, 2) = minDispS; indexTable(u, vT, 0) = minPosG; indexTable(u, vT, 1) = minPosO; indexTable(u, vT, 2) = minPosS; } } ////////////////////////////////////////////////////////////////////////////// // backtracking step ////////////////////////////////////////////////////////////////////////////// std::vector<Stixel> stixels; for (int u = 0; u < w; u++) { float minCost = std::numeric_limits<float>::max(); cv::Point minPos; for (int c = 0; c < 3; c++) { const float cost = costTable(u, h - 1, c); if (cost < minCost) { minCost = cost; minPos = cv::Point(c, h - 1); } } while (minPos.y > 0) { const cv::Point p1 = minPos; const cv::Point p2 = indexTable(u, p1.y, p1.x); if (p1.x == 1) // object { Stixel stixel; stixel.u = stixelWidth * u + stixelWidth / 2; stixel.vT = h - 1 - p1.y; stixel.vB = h - 1 - (p2.y + 1); stixel.width = stixelWidth; stixel.disp = dispTable(u, p1.y, p1.x); stixels.push_back(stixel); } minPos = p2; } } return stixels; } <file_sep>#ifndef __COST_FUNCTION_H__ #define __COST_FUNCTION_H__ #include "matrix.h" #include <algorithm> #include <numeric> #include <vector> #define _USE_MATH_DEFINES #include <math.h> ////////////////////////////////////////////////////////////////////////////// // data cost functions ////////////////////////////////////////////////////////////////////////////// static const float PI = static_cast<float>(M_PI); static const float SQRT2 = static_cast<float>(M_SQRT2); struct NegativeLogDataTermGrd { NegativeLogDataTermGrd(float dmax, float dmin, float sigma, float pOut, float pInv, const std::vector<float>& groundDisparity) { init(dmax, dmin, sigma, pOut, pInv, groundDisparity); } inline float operator()(float d, int v) const { if (d < 0.f) return 0.f; return std::min(nLogPUniform_, nLogPGaussian_[v] + cquad_ * (d - fn_[v]) * (d - fn_[v])); } // pre-compute constant terms void init(float dmax, float dmin, float sigma, float pOut, float pInv, const std::vector<float>& groundDisparity) { // uniform distribution term nLogPUniform_ = logf(dmax - dmin) - logf(pOut); // Gaussian distribution term const int h = static_cast<int>(groundDisparity.size()); nLogPGaussian_.resize(h); fn_.resize(h); for (int v = 0; v < h; v++) { const float fn = groundDisparity[v]; const float ANorm = 0.5f * (erff((dmax - fn) / (SQRT2 * sigma)) - erff((dmin - fn) / (SQRT2 * sigma))); nLogPGaussian_[v] = logf(ANorm) + logf(sigma * sqrtf(2.f * PI)) - logf(1.f - pOut); fn_[v] = fn; } // coefficient of quadratic part cquad_ = 1.f / (2.f * sigma * sigma); } float nLogPUniform_, cquad_; std::vector<float> nLogPGaussian_, fn_; }; struct NegativeLogDataTermObj { NegativeLogDataTermObj(float dmax, float dmin, float sigma, float pOut, float pInv) { init(dmax, dmin, sigma, pOut, pInv); } inline float operator()(float d, int fn) const { if (d < 0.f) return 0.f; return std::min(nLogPUniform_, nLogPGaussian_[fn] + cquad_ * (d - fn) * (d - fn)); } // pre-compute constant terms void init(float dmax, float dmin, float sigma, float pOut, float pInv) { // uniform distribution term nLogPUniform_ = logf(dmax - dmin) - logf(pOut); // Gaussian distribution term const int fnmax = static_cast<int>(dmax); nLogPGaussian_.resize(fnmax); for (int fn = 0; fn < fnmax; fn++) { const float ANorm = 0.5f * (erff((dmax - fn) / (SQRT2 * sigma)) - erff((dmin - fn) / (SQRT2 * sigma))); nLogPGaussian_[fn] = logf(ANorm) + logf(sigma * sqrtf(2.f * PI)) - logf(1.f - pOut); } // coefficient of quadratic part cquad_ = 1.f / (2.f * sigma * sigma); } float nLogPUniform_, cquad_; std::vector<float> nLogPGaussian_; }; struct NegativeLogDataTermSky { NegativeLogDataTermSky(float dmax, float dmin, float sigma, float pOut, float pInv, float fn = 0.f) : fn_(fn) { init(dmax, dmin, sigma, pOut, pInv, fn); } inline float operator()(float d) const { if (d < 0.f) return 0.f; return std::min(nLogPUniform_, nLogPGaussian_ + cquad_ * (d - fn_) * (d - fn_)); } // pre-compute constant terms void init(float dmax, float dmin, float sigma, float pOut, float pInv, float fn) { // uniform distribution term nLogPUniform_ = logf(dmax - dmin) - logf(pOut); // Gaussian distribution term const float ANorm = 0.5f * (erff((dmax - fn) / (SQRT2 * sigma)) - erff((dmin - fn) / (SQRT2 * sigma))); nLogPGaussian_ = logf(ANorm) + logf(sigma * sqrtf(2.f * PI)) - logf(1.f - pOut); // coefficient of quadratic part cquad_ = 1.f / (2.f * sigma * sigma); } float nLogPUniform_, cquad_, nLogPGaussian_, fn_; }; ////////////////////////////////////////////////////////////////////////////// // prior cost functions ////////////////////////////////////////////////////////////////////////////// static const float N_LOG_0_3 = -static_cast<float>(log(0.3)); static const float N_LOG_0_5 = -static_cast<float>(log(0.5)); static const float N_LOG_0_7 = -static_cast<float>(log(0.7)); static const float N_LOG_0_0 = std::numeric_limits<float>::infinity(); static const float N_LOG_1_0 = 0.f; struct NegativeLogPriorTerm { static const int G = 0; static const int O = 1; static const int S = 2; NegativeLogPriorTerm(int h, float vhor, float dmax, float dmin, float b, float fu, float deltaz, float eps, float pOrd, float pGrav, float pBlg, const std::vector<float>& groundDisparity) { init(h, vhor, dmax, dmin, b, fu, deltaz, eps, pOrd, pGrav, pBlg, groundDisparity); } inline float getO0(int vT) const { return costs0_(vT, O); } inline float getG0(int vT) const { return costs0_(vT, G); } inline float getS0(int vT) const { return N_LOG_0_0; } inline float getOO(int vB, int d1, int d2) const { return costs1_(vB, O, O) + costs2_O_O_(d2, d1); } inline float getOG(int vB, int d1, int d2) const { return costs1_(vB, O, G) + costs2_O_G_(vB - 1, d1); } inline float getOS(int vB, int d1, int d2) const { return costs1_(vB, O, S) + costs2_O_S_(d1); } inline float getGO(int vB, int d1, int d2) const { return costs1_(vB, G, O); } inline float getGG(int vB, int d1, int d2) const { return costs1_(vB, G, G); } inline float getGS(int vB, int d1, int d2) const { return N_LOG_0_0; } inline float getSO(int vB, int d1, int d2) const { return costs1_(vB, S, O) + costs2_S_O_(d2, d1); } inline float getSG(int vB, int d1, int d2) const { return N_LOG_0_0; } inline float getSS(int vB, int d1, int d2) const { return N_LOG_0_0; } void init(int h, float vhor, float dmax, float dmin, float b, float fu, float deltaz, float eps, float pOrd, float pGrav, float pBlg, const std::vector<float>& groundDisparity) { const int fnmax = static_cast<int>(dmax); costs0_.create(h, 2); costs1_.create(h, 3, 3); costs2_O_O_.create(fnmax, fnmax); costs2_O_S_.create(1, fnmax); costs2_O_G_.create(h, fnmax); costs2_S_O_.create(fnmax, fnmax); for (int vT = 0; vT < h; vT++) { const float P1 = N_LOG_1_0; const float P2 = -logf(1.f / h); const float P3_O = vT > vhor ? N_LOG_1_0 : N_LOG_0_5; const float P3_G = vT > vhor ? N_LOG_0_0 : N_LOG_0_5; const float P4_O = -logf(1.f / (dmax - dmin)); const float P4_G = N_LOG_1_0; costs0_(vT, O) = P1 + P2 + P3_O + P4_O; costs0_(vT, G) = P1 + P2 + P3_G + P4_G; } for (int vB = 0; vB < h; vB++) { const float P1 = N_LOG_1_0; const float P2 = -logf(1.f / (h - vB)); const float P3_O_O = vB - 1 < vhor ? N_LOG_0_7 : N_LOG_0_5; const float P3_G_O = vB - 1 < vhor ? N_LOG_0_3 : N_LOG_0_0; const float P3_S_O = vB - 1 < vhor ? N_LOG_0_0 : N_LOG_0_5; const float P3_O_G = vB - 1 < vhor ? N_LOG_0_7 : N_LOG_0_0; const float P3_G_G = vB - 1 < vhor ? N_LOG_0_3 : N_LOG_0_0; const float P3_S_G = vB - 1 < vhor ? N_LOG_0_0 : N_LOG_0_0; const float P3_O_S = vB - 1 < vhor ? N_LOG_0_0 : N_LOG_1_0; const float P3_G_S = vB - 1 < vhor ? N_LOG_0_0 : N_LOG_0_0; const float P3_S_S = vB - 1 < vhor ? N_LOG_0_0 : N_LOG_0_0; costs1_(vB, O, O) = P1 + P2 + P3_O_O; costs1_(vB, G, O) = P1 + P2 + P3_G_O; costs1_(vB, S, O) = P1 + P2 + P3_S_O; costs1_(vB, O, G) = P1 + P2 + P3_O_G; costs1_(vB, G, G) = P1 + P2 + P3_G_G; costs1_(vB, S, G) = P1 + P2 + P3_S_G; costs1_(vB, O, S) = P1 + P2 + P3_O_S; costs1_(vB, G, S) = P1 + P2 + P3_G_S; costs1_(vB, S, S) = P1 + P2 + P3_S_S; } for (int d1 = 0; d1 < fnmax; d1++) costs2_O_O_(0, d1) = N_LOG_0_0; for (int d2 = 1; d2 < fnmax; d2++) { const float z = b * fu / d2; const float deltad = d2 - b * fu / (z + deltaz); for (int d1 = 0; d1 < fnmax; d1++) { if (d1 > d2 + deltad) costs2_O_O_(d2, d1) = -logf(pOrd / (d2 - deltad)); else if (d1 <= d2 + deltad) costs2_O_O_(d2, d1) = -logf((1.f - pOrd) / (dmax - d2 - deltad)); else costs2_O_O_(d2, d1) = N_LOG_0_0; } } for (int v = 0; v < h; v++) { const float fn = groundDisparity[v]; for (int d1 = 0; d1 < fnmax; d1++) { if (d1 > fn + eps) costs2_O_G_(v, d1) = -logf(pGrav / (dmax - fn - eps)); else if (d1 > fn + eps) costs2_O_G_(v, d1) = -logf(pBlg / (fn - eps - dmin)); else costs2_O_G_(v, d1) = -logf((1.f - pGrav - pBlg) / (2.f * eps)); } } for (int d1 = 0; d1 < fnmax; d1++) { costs2_O_S_(d1) = d1 > eps ? -logf((1.f / (dmax - dmin)) / (1.f - eps / (dmax - dmin))) : N_LOG_0_0; } for (int d2 = 0; d2 < fnmax; d2++) { for (int d1 = 0; d1 < fnmax; d1++) { if (d2 < eps) costs2_S_O_(d2, d1) = N_LOG_0_0; else if (d1 <= 0) costs2_S_O_(d2, d1) = N_LOG_1_0; else costs2_S_O_(d2, d1) = N_LOG_0_0; } } } Matrixf costs0_, costs1_; Matrixf costs2_O_O_, costs2_O_G_, costs2_O_S_, costs2_S_O_; }; #endif // !__COST_FUNCTION_H__ <file_sep>#ifndef __MULTILAYER_STIXEL_WORLD_H__ #define __MULTILAYER_STIXEL_WORLD_H__ #include <opencv2/opencv.hpp> struct Stixel { int u; int vT; int vB; int width; float disp; }; class MultiLayerStixelWrold { public: struct CameraParameters { float fu; float fv; float u0; float v0; float baseline; float height; float tilt; // default settings CameraParameters() { fu = 1.f; fv = 1.f; u0 = 0.f; v0 = 0.f; baseline = 0.2f; height = 1.f; tilt = 0.f; } }; struct Parameters { // stixel width int stixelWidth; // disparity range float dmin; float dmax; // disparity measurement uncertainty float sigmaG; float sigmaO; float sigmaS; // outlier rate float pOutG; float pOutO; float pOutS; // probability of invalid disparity float pInvG; float pInvO; float pInvS; // probability for regularization float pOrd; float pGrav; float pBlg; float deltaz; float eps; // camera parameters CameraParameters camera; // default settings Parameters() { // stixel width stixelWidth = 7; // disparity range dmin = 0; dmax = 128; // disparity measurement uncertainty sigmaG = 1.5f; sigmaO = 1.5f; sigmaS = 1.2f; // outlier rate pOutG = 0.15f; pOutO = 0.15f; pOutS = 0.4f; // probability of invalid disparity pInvG = 0.34f; pInvO = 0.3f; pInvS = 0.36f; // probability for regularization pOrd = 0.1f; pGrav = 0.1f; pBlg = 0.001f; deltaz = 3.f; eps = 1.f; // camera parameters camera = CameraParameters(); } }; MultiLayerStixelWrold(const Parameters& param); std::vector<Stixel> compute(const cv::Mat& disparity); private: Parameters param_; }; #endif // !__STIXEL_WORLD_H__<file_sep>// Copyright ?<NAME>, 2014. // See license.txt for more details #include "StereoCommon.h" #include "StereoSGM.h" #include <string.h> #include<iostream> #include <iomanip> // accumulate along paths // variable P2 param template<typename T> template <int NPaths> void StereoSGM<T>::accumulateVariableParamsSSE(uint16* &dsi, T* img, uint16* &S)/*0000*/ { /* 参数 */ const sint32 paramP1 = m_params.P1; const uint16 paramInvalidDispCost = m_params.InvalidDispCost; const int paramNoPasses = m_params.NoPasses; const uint16 MAX_SGM_COST = UINT16_MAX; // 固定的参数 const float32 paramAlpha = m_params.Alpha; const sint32 paramGamma = m_params.Gamma; const sint32 paramP2min = m_params.P2min; const int width = m_width; const int width2 = width + 2; const int maxDisp = m_maxDisp; const int height = m_height; const int disp = maxDisp + 1; const int dispP2 = disp + 8; // 沿着路径r累加代价, 两个额外的视差元素(-1和maxDisp+1),当前的和最后一行() uint16* L_r0 = ((uint16*)_mm_malloc(dispP2*sizeof(uint16), 16)) + 1; uint16* L_r0_last = ((uint16*)_mm_malloc(dispP2*sizeof(uint16), 16)) + 1; uint16* L_r1 = ((uint16*)_mm_malloc(width2*dispP2*sizeof(uint16) + 1, 16)) + dispP2 + 1; uint16* L_r1_last = ((uint16*)_mm_malloc(width2*dispP2*sizeof(uint16) + 1, 16)) + dispP2 + 1; uint16* L_r2_last = ((uint16*)_mm_malloc(width*dispP2*sizeof(uint16), 16)) + 1; uint16* L_r3_last = ((uint16*)_mm_malloc(width2*dispP2*sizeof(uint16) + 1, 16)) + dispP2 + 1; /* 左边界 */ memset(&L_r1[-dispP2], MAX_SGM_COST, sizeof(uint16)*(dispP2)); L_r1[-dispP2 - 1] = MAX_SGM_COST; memset(&L_r1_last[-dispP2], MAX_SGM_COST, sizeof(uint16)*(dispP2)); L_r1_last[-dispP2 - 1] = MAX_SGM_COST; memset(&L_r3_last[-dispP2], MAX_SGM_COST, sizeof(uint16)*(dispP2)); L_r3_last[-dispP2 - 1] = MAX_SGM_COST; /* 右边界 */ memset(&L_r1[width*dispP2 - 1], MAX_SGM_COST, sizeof(uint16)*(dispP2)); memset(&L_r1_last[width*dispP2 - 1], MAX_SGM_COST, sizeof(uint16)*(dispP2)); memset(&L_r3_last[width*dispP2 - 1], MAX_SGM_COST, sizeof(uint16)*(dispP2)); // 记录每条路径的最小值 uint16 minL_r0_Array[2]; uint16* minL_r0 = &minL_r0_Array[0]; uint16* minL_r0_last = &minL_r0_Array[1]; uint16* minL_r1 = (uint16*)_mm_malloc(width2*sizeof(uint16), 16) + 1; uint16* minL_r1_last = (uint16*)_mm_malloc(width2*sizeof(uint16), 16) + 1; uint16* minL_r2_last = (uint16*)_mm_malloc(width*sizeof(uint16), 16); uint16* minL_r3_last = (uint16*)_mm_malloc(width2*sizeof(uint16), 16) + 1; //边界值 minL_r1[-1] = minL_r1[width] = 0; minL_r1_last[-1] = minL_r1_last[width] = 0; minL_r3_last[-1] = minL_r3_last[width] = 0; /* 定义指向图像行的指针 */ T* img_line_last = NULL; T* img_line = NULL; /*[formula 13 in the paper] compute L_r(p, d) = C(p, d) + min(L_r(p-r, d), L_r(p-r, d-1) + P1, L_r(p-r, d+1) + P1, min_k L_r(p-r, k) + P2) - min_k L_r(p-r, k) where p = (x,y), r is one of the directions. we process all the directions at once: ( basic 8 paths ) 0: r=(-1, 0) --> left to right 1: r=(-1, -1) --> left to right, top to bottom 2: r=(0, -1) --> top to bottom 3: r=(1, -1) --> top to bottom, right to left */ // border cases L_r0[0 - disp], L_r1,2,3 is maybe not needed, as done above L_r0[-1] = L_r0[disp] = MAX_SGM_COST; L_r1[-1] = L_r1[disp] = MAX_SGM_COST; L_r0_last[-1] = L_r0_last[disp] = MAX_SGM_COST; L_r1_last[-1] = L_r1_last[disp] = MAX_SGM_COST; L_r2_last[-1] = L_r2_last[disp] = MAX_SGM_COST; L_r3_last[-1] = L_r3_last[disp] = MAX_SGM_COST; for (int pass = 0; pass < paramNoPasses; pass++) { int i1; int i2; int di; int j1; int j2; int dj; //第一次从上到下 if (pass == 0) { /* top-down pass */ i1 = 0; i2 = height; di = 1; j1 = 0; j2 = width; dj = 1; } else //第二次从下到上 { /* bottom-up pass */ i1 = height - 1; i2 = -1; di = -1; j1 = width - 1; j2 = -1; dj = -1; } img_line = img + i1*width; /* first line is simply costs C, except for path L_r0 */ // first pixel(第一行的视差) uint16 minCost = MAX_SGM_COST; if (pass == 0) /*第一行第一列的S=dsi*/ { //得到当前行列某一视差的cost for (int d = 0; d < disp; d++) { uint16 cost = *getDispAddr_xyd(dsi, width, disp, i1, j1, d); // return dsi + i*(disp*width) + j*disp + k if (cost == 255) cost = paramInvalidDispCost; //L_ro_last存储当前视差范围内的代价 L_r0_last[d] = cost; //L_r1_last,L_r2_last,L_r3_last存储某一列的视差范围内的视差 L_r1_last[j1*dispP2 + d] = cost; L_r2_last[j1*dispP2 + d] = cost; L_r3_last[j1*dispP2 + d] = cost; if (cost < minCost) { minCost = cost; } *getDispAddr_xyd(S, width, disp, i1, j1, d) = cost; } } else {/*最后一行最后一列的S += dsi*/ for (int d = 0; d < disp; d++) { uint16 cost = *getDispAddr_xyd(dsi, width, disp, i1, j1, d); if (cost == 255) cost = paramInvalidDispCost; L_r0_last[d] = cost; L_r1_last[j1*dispP2 + d] = cost; L_r2_last[j1*dispP2 + d] = cost; L_r3_last[j1*dispP2 + d] = cost; if (cost < minCost) { minCost = cost; //minCost记录当前列的视差空间的最小值。 } *getDispAddr_xyd(S, width, disp, i1, j1, d) += cost; } /*downS<<"\n";*/ } /*记录第0行第0列的minCost*/ *minL_r0_last = minCost; minL_r1_last[j1] = minCost; minL_r2_last[j1] = minCost; minL_r3_last[j1] = minCost; /*开始计算第一行其他列的最小代价*/ for (int j = j1 + dj; j != j2; j += dj) { uint16 minCost = MAX_SGM_COST; *minL_r0 = MAX_SGM_COST; for (int d = 0; d < disp; d++) { uint16 cost = *getDispAddr_xyd(dsi, width, disp, i1, j, d); //std::cout<<cost<<" "; if (cost == 255) cost = paramInvalidDispCost; L_r1_last[j*dispP2 + d] = cost; L_r2_last[j*dispP2 + d] = cost; L_r3_last[j*dispP2 + d] = cost; if (cost < minCost) { minCost = cost; } // minimum along L_r0//沿着L_r0的最小值 //minPropCost存储最小的恰当的路径min[Lr(p d) + ...] sint32 minPropCost = L_r0_last[d]; // same disparity cost // P1 costs sint32 costP1m = L_r0_last[d - 1] + paramP1; if (minPropCost > costP1m) { minPropCost = costP1m; } sint32 costP1p = L_r0_last[d + 1] + paramP1; if (minPropCost > costP1p) { minPropCost = costP1p; } // P2 costs //minCostP2存储min(d)[Lr(p-r,i) + varP2] sint32 minCostP2 = *minL_r0_last; // result = (sint32)(-alpha * abs(img_line[j]-img_line[j-dj])+gamma); // if (result < P2min) // result = P2min; sint32 varP2 = adaptP2(paramAlpha, img_line[j], img_line[j - dj], paramGamma, paramP2min); if (minPropCost > minCostP2 + varP2) { minPropCost = minCostP2 + varP2; } // add offset minPropCost -= minCostP2; //newCost存储Lr(p,d) const uint16 newCost = saturate_cast<uint16>(cost + minPropCost); L_r0[d] = newCost; if (*minL_r0 > newCost) { *minL_r0 = newCost; } // cost sum if (pass == 0) { *getDispAddr_xyd(S, width, disp, i1, j, d) = saturate_cast<uint16>(cost + minPropCost); } else { *getDispAddr_xyd(S, width, disp, i1, j, d) += saturate_cast<uint16>(cost + minPropCost); } } minL_r1_last[j] = minCost; minL_r2_last[j] = minCost; minL_r3_last[j] = minCost; // swap L0 buffers swapPointers(L_r0, L_r0_last); swapPointers(minL_r0, minL_r0_last); // border cases: disparities -1 and disp L_r1_last[j*dispP2 - 1] = L_r2_last[j*dispP2 - 1] = L_r3_last[j*dispP2 - 1] = MAX_SGM_COST; L_r1_last[j*dispP2 + disp] = L_r2_last[j*dispP2 + disp] = L_r3_last[j*dispP2 + disp] = MAX_SGM_COST; L_r1[j*dispP2 - 1] = MAX_SGM_COST; L_r1[j*dispP2 + disp] = MAX_SGM_COST; } // same as img_line in first iteration, because of boundaries! img_line_last = img + (i1 + di)*width; // remaining lines for (int i = i1 + di; i != i2; i += di) { memset(L_r0_last, 0, sizeof(uint16)*disp); *minL_r0_last = 0; img_line = img + i*width; for (int j = j1; j != j2; j += dj) { *minL_r0 = MAX_SGM_COST; __m128i minLr_08 = _mm_set1_epi16(MAX_SGM_COST); //8个16位的值 __m128i minLr_18 = _mm_set1_epi16(MAX_SGM_COST); __m128i minLr_28 = _mm_set1_epi16(MAX_SGM_COST); __m128i minLr_38 = _mm_set1_epi16(MAX_SGM_COST); sint32 varP2_r0 = adaptP2(paramAlpha, img_line[j], img_line[j - dj], paramGamma, paramP2min); sint32 varP2_r1 = adaptP2(paramAlpha, img_line[j], img_line_last[j - dj], paramGamma, paramP2min); sint32 varP2_r2 = adaptP2(paramAlpha, img_line[j], img_line_last[j], paramGamma, paramP2min); sint32 varP2_r3 = adaptP2(paramAlpha, img_line[j], img_line_last[j + dj], paramGamma, paramP2min); //only once per point const __m128i varP2_r08 = _mm_set1_epi16((uint16)varP2_r0); const __m128i varP2_r18 = _mm_set1_epi16((uint16)varP2_r1); const __m128i varP2_r28 = _mm_set1_epi16((uint16)varP2_r2); const __m128i varP2_r38 = _mm_set1_epi16((uint16)varP2_r3); const __m128i minCostP28_r0 = _mm_set1_epi16((uint16)(*minL_r0_last)); const __m128i minCostP28_r1 = _mm_set1_epi16((uint16)minL_r1_last[j - dj]); const __m128i minCostP28_r2 = _mm_set1_epi16((uint16)minL_r2_last[j]); const __m128i minCostP28_r3 = _mm_set1_epi16((uint16)minL_r3_last[j + dj]); const __m128i curP2cost8_r0 = _mm_adds_epu16(varP2_r08, minCostP28_r0); const __m128i curP2cost8_r1 = _mm_adds_epu16(varP2_r18, minCostP28_r1); const __m128i curP2cost8_r2 = _mm_adds_epu16(varP2_r28, minCostP28_r2); const __m128i curP2cost8_r3 = _mm_adds_epu16(varP2_r38, minCostP28_r3); int d = 0; __m128i upper8_r0 = _mm_load_si128((__m128i*)(L_r0_last + 0 - 1)); int baseIndex_r2 = ((j)*dispP2) + d; const int baseIndex_r1 = ((j - dj)*dispP2) + d; __m128i upper8_r1 = _mm_load_si128((__m128i*)(L_r1_last + baseIndex_r1 - 1)); __m128i upper8_r2 = _mm_load_si128((__m128i*)(L_r2_last + baseIndex_r2 - 1)); const int baseIndex_r3 = ((j + dj)*dispP2) + d; __m128i upper8_r3 = _mm_load_si128((__m128i*)(L_r3_last + baseIndex_r3 - 1)); const __m128i paramP18 = _mm_set1_epi16((uint16)paramP1); for (; d < disp - 7; d += 8) { //-------------------------------------------------------------------------------------------------------------------------------------------------------- //to save sum of all paths __m128i newCost8_ges = _mm_setzero_si128(); __m128i cost8; cost8 = _mm_load_si128((__m128i*) getDispAddr_xyd(dsi, width, disp, i, j, d)); //-------------------------------------------------------------------------------------------------------------------------------------------------------- // minimum along L_r0 if (NPaths == 8) { __m128i minPropCost8; const __m128i lower8_r0 = upper8_r0; upper8_r0 = _mm_load_si128((__m128i*)(L_r0_last + d - 1 + 8)); // P1 costs const __m128i costPm8_r0 = _mm_adds_epu16(lower8_r0, paramP18); const __m128i costPp8_r0 = _mm_adds_epu16(_mm_alignr_epi8(upper8_r0, lower8_r0, 4), paramP18); minPropCost8 = _mm_alignr_epi8(upper8_r0, lower8_r0, 2); __m128i temp = _mm_min_epu16(costPp8_r0, costPm8_r0); minPropCost8 = _mm_min_epu16(minPropCost8, temp); minPropCost8 = _mm_min_epu16(minPropCost8, curP2cost8_r0); minPropCost8 = _mm_subs_epu16(minPropCost8, minCostP28_r0); const __m128i newCost8_r0 = _mm_adds_epu16(cost8, minPropCost8); _mm_storeu_si128((__m128i*) (L_r0_last + d), newCost8_r0); //sum of all Paths newCost8_ges = newCost8_r0; minLr_08 = _mm_min_epu16(minLr_08, newCost8_r0); } if (NPaths != 0) { //-------------------------------------------------------------------------------------------------------------------------------------------------------- const int baseIndex_r1 = ((j - dj)*dispP2) + d; uint16* lastL = L_r1_last; uint16* L = L_r1; const __m128i lower8_r1 = upper8_r1; upper8_r1 = _mm_load_si128((__m128i*)(lastL + baseIndex_r1 - 1 + 8)); const __m128i costPm8_r1 = _mm_adds_epu16(lower8_r1, paramP18); const __m128i costPp8_r1 = _mm_adds_epu16(_mm_alignr_epi8(upper8_r1, lower8_r1, 4), paramP18); __m128i minPropCost8 = _mm_alignr_epi8(upper8_r1, lower8_r1, 2); __m128i temp = _mm_min_epu16(costPp8_r1, costPm8_r1); minPropCost8 = _mm_min_epu16(minPropCost8, temp); minPropCost8 = _mm_min_epu16(minPropCost8, curP2cost8_r1); minPropCost8 = _mm_subs_epu16(minPropCost8, minCostP28_r1); const __m128i newCost8_r1 = _mm_adds_epu16(cost8, minPropCost8); _mm_storeu_si128((__m128i*) (L + (j*dispP2) + d), newCost8_r1); //sum of all Paths newCost8_ges = _mm_adds_epu16(newCost8_ges, newCost8_r1); minLr_18 = _mm_min_epu16(minLr_18, newCost8_r1); //-------------------------------------------------------------------------------------------------------------------------------------------------------- int baseIndex_r2 = ((j)*dispP2) + d; const __m128i lower8_r2 = upper8_r2; upper8_r2 = _mm_load_si128((__m128i*)(L_r2_last + baseIndex_r2 - 1 + 8)); const __m128i costPm8_r2 = _mm_adds_epu16(lower8_r2, paramP18); const __m128i costPp8_r2 = _mm_adds_epu16(_mm_alignr_epi8(upper8_r2, lower8_r2, 4), paramP18); minPropCost8 = _mm_alignr_epi8(upper8_r2, lower8_r2, 2); temp = _mm_min_epu16(costPp8_r2, costPm8_r2); minPropCost8 = _mm_min_epu16(temp, minPropCost8); minPropCost8 = _mm_min_epu16(minPropCost8, curP2cost8_r2); minPropCost8 = _mm_subs_epu16(minPropCost8, minCostP28_r2); const __m128i newCost8_r2 = _mm_adds_epu16(cost8, minPropCost8); _mm_storeu_si128((__m128i*) (L_r2_last + (j*dispP2) + d), newCost8_r2); //sum of all Paths newCost8_ges = _mm_adds_epu16(newCost8_ges, newCost8_r2); minLr_28 = _mm_min_epu16(minLr_28, newCost8_r2); //-------------------------------------------------------------------------------------------------------------------------------------------------------- int baseIndex_r3 = ((j + dj)*dispP2) + d; const __m128i lower8_r3 = upper8_r3; upper8_r3 = _mm_load_si128((__m128i*)(L_r3_last + baseIndex_r3 - 1 + 8)); const __m128i costPm8_r3 = _mm_adds_epu16(lower8_r3, paramP18); const __m128i costPp8_r3 = _mm_adds_epu16(_mm_alignr_epi8(upper8_r3, lower8_r3, 4), paramP18); minPropCost8 = _mm_alignr_epi8(upper8_r3, lower8_r3, 2); minPropCost8 = _mm_min_epu16(minPropCost8, costPm8_r3); minPropCost8 = _mm_min_epu16(minPropCost8, costPp8_r3); minPropCost8 = _mm_min_epu16(minPropCost8, curP2cost8_r3); minPropCost8 = _mm_subs_epu16(minPropCost8, minCostP28_r3); const __m128i newCost8_r3 = _mm_adds_epu16(cost8, minPropCost8); //sum of all Paths newCost8_ges = _mm_adds_epu16(newCost8_ges, newCost8_r3); minLr_38 = _mm_min_epu16(minLr_38, newCost8_r3); //-------------------------------------------------------------------------------------------------------------------------------------------------------- } if (NPaths == 8) { if (pass == 0) { _mm_store_si128((__m128i*) getDispAddr_xyd(S, width, disp, i, j, d), newCost8_ges); } else { _mm_store_si128((__m128i*) getDispAddr_xyd(S, width, disp, i, j, d), _mm_adds_epu16(_mm_load_si128((__m128i*) getDispAddr_xyd(S, width, disp, i, j, d)), newCost8_ges)); } } } *minL_r0_last = (uint16)_mm_extract_epi16(_mm_minpos_epu16(minLr_08), 0); minL_r1[j] = (uint16)_mm_extract_epi16(_mm_minpos_epu16(minLr_18), 0); minL_r2_last[j] = (uint16)_mm_extract_epi16(_mm_minpos_epu16(minLr_28), 0); minL_r3_last[j] = (uint16)_mm_extract_epi16(_mm_minpos_epu16(minLr_38), 0); } img_line_last = img_line; swapPointers(L_r1, L_r1_last); swapPointers(minL_r1, minL_r1_last); } } /* free all */ _mm_free(L_r0 - 1); _mm_free(L_r0_last - 1); _mm_free(L_r1 - dispP2 - 1); _mm_free(L_r1_last - dispP2 - 1); _mm_free(L_r2_last - 1); _mm_free(L_r3_last - dispP2 - 1); _mm_free(minL_r1 - 1); _mm_free(minL_r1_last - 1); _mm_free(minL_r2_last); _mm_free(minL_r3_last - 1); }
49de1a400937848d201d6c4039d181dfba930e7c
[ "Markdown", "C++" ]
9
C++
tiantianxuabc/Multilayer-Stixel
b3a6ad929f0273a728b7fff73c8ece3bcb8d4a7c
a1683630083c1199f216909797e4a623c43e3d5a
refs/heads/master
<file_sep>import $ from 'jquery'; // Import jquery.TinyMCE import 'tinymce/jquery.tinymce'; // A theme is also required import 'tinymce/themes/modern/theme'; // Any plugins you want to use has to be imported import 'tinymce/plugins/paste/plugin'; import 'tinymce/plugins/link/plugin'; tinyMCE.baseURL = "/jspm_packages/github/tinymce/[email protected]/"; let $tinymceEl = $("#tinymce_editor"); let config = { inline: true, themes: "modern", plugins: ['paste', 'link'] }; $tinymceEl.tinymce(config); let $countEl = $("#editorCount"); let refreshEditorCount = () => $countEl.text(`tinyMCE.editors.length :${tinyMCE.editors.length}`); refreshEditorCount(); $("#remove").click(() => { $tinymceEl.remove(); refreshEditorCount(); }); $("#recreate").click(() => { $("#tinymcecontainer").html("<div id='tinymce_editor'></div>"); $tinymceEl= $("#tinymce_editor"); $tinymceEl.tinymce(config); refreshEditorCount(); });
b3d852714ff788ec5bb5e8e259c2a009551fe3e6
[ "JavaScript" ]
1
JavaScript
brunomlopes/jquery.tinymce-issue
e61de473a7b6514cdba57825e1e98b5f39f630dd
b345125f442199bbc01400439ff3304298cf9ab7
refs/heads/master
<repo_name>TW5860/cobol-in-a-box<file_sep>/cobol_unit_test_helper/json_to_printer.js let {print9, printX} = require('./json_to_cobol'); let buildIntegerPrinter = function (dataSpecObj) { let length = dataSpecObj["maximum"].toString().length; return function (value) { return print9(value, length); }; }; let buildStringPrinter = function (dataSpecObj) { return function (value) { let length = dataSpecObj["maxLength"]; return printX(value, length); }; }; let buildObjectPrinter = function (dataSpecObj) { const keys = Object.keys(dataSpecObj.properties); return function (inputObject) { let returnString = ""; for (let i = 0; i < keys.length; i++) { let currentAttribute = dataSpecObj.properties[keys[i]]; let printerFunction = buildPrinter(currentAttribute); returnString += printerFunction(inputObject[keys[i]]); } return returnString; } }; let buildArrayPrinter = function (dataSpecObj) { let innerPrinter = buildPrinter(dataSpecObj.items); return function (value) { let returnString = ""; let itemCountLength = dataSpecObj.maxItems.toString().length; returnString += print9(value.length, itemCountLength); for (let i = 0; i < value.length; i++) { returnString += innerPrinter(value[i]); } return returnString; } } function buildPrinter(dataSpecObj) { switch (dataSpecObj.type) { case 'integer': return buildIntegerPrinter(dataSpecObj); case 'string': return buildStringPrinter(dataSpecObj); case 'object': return buildObjectPrinter(dataSpecObj); case 'array': return buildArrayPrinter(dataSpecObj); default : throw new Error("Not a valid object type"); } } module.exports = { buildPrinter: buildPrinter };<file_sep>/cobol_unit_test_helper/json_to_printer_spec.js let {buildPrinter} = require('./helpers/json_to_printer'); describe('JSON to printer', () => { it('prints a json object with copybook information', () => { let jsonObj = {}; let objSpec = { "type": "object", "properties":{} }; let printer = buildPrinter(objSpec); expect(printer(jsonObj)).toBe(""); }); it('prints an integer', () => { let objSpec = { "type": "integer", "maximum": 9999, "minimum": 0 }; let printer = buildPrinter(objSpec); expect(printer(44)).toBe("0044"); }); });<file_sep>/cobol_unit_test_helper/cobol_to_json.js let parse9 = function (input, char_count) { if (input.length != char_count) { throw new Error("Parsing is not possible. Wrong digit count."); } if (!input.match(/^[0-9]+$/)) { throw new Error("Parsing is not possible. Expected digit but found a different symbol."); } return parseInt(input); }; let parseX = function (input, char_count) { if (input.length != char_count) { throw new Error("Parsing is not possible. Wrong character count."); } return input.replace(/[ ]+$/g, ''); }; module.exports = { parse9: parse9, parseX: parseX }; <file_sep>/examples/books/book_stats_spec.js let {execTestDriver} = require('./test_driver_helper'); describe('Book Stats', () => { it('calculates stats for one book', (done) => { let books = { 'books_input': { 'books': [ { 'book_title': 'Testbuch', 'book_author': 'Testauthor', 'book_pages': 25 } ] } }; execTestDriver(books, (stats) => { expect(stats.book_stats.max_pages).toBe(25); expect(stats.book_stats.min_pages).toBe(25); expect(stats.book_stats.avg_pages).toBe(25); done(); }); }); it('calculates stats for a few books', (done) => { let books = { 'books_input': { 'books': [ { 'book_title': 'Testbuch', 'book_author': 'Testauthor', 'book_pages': 25 }, { 'book_title': 'Testbuch2', 'book_author': 'Testauthor2', 'book_pages': 20 }, { 'book_title': 'Testbuch3', 'book_author': 'Testauthor3', 'book_pages': 30 } ] } }; execTestDriver(books, (stats) => { expect(stats.book_stats.max_pages).toBe(30); expect(stats.book_stats.min_pages).toBe(20); expect(stats.book_stats.avg_pages).toBe(25); done(); }); }); }); <file_sep>/README.md # Cobol in a Box This repository demonstrates how to test COBOL programs with Jasmine tests written in JavaScript. ## Requirements All you need is Docker and docker-compose. ## Getting Started Just run `docker-compose up --build` in the root directory of this repository. What this will do? 1. Build a Docker container with GnuCOBOL and Node.js installed 2. Compile your COBOL code (found in [src/main](src/main)) 3. Run `npm test`, which will invoke Jasmine. 4. Jasmine will now run all your spec files in [src/spec](src/spec). ## How does it work? Together with the actual COBOL code, [test_driver](src/main/test_driver.cbl) gets compiled. This is a program that just reads the used data structure from stdin and prints the result to stdout. This test driver is needed to allow testing of COBOL programs with parameters. The Jasmine tests use [test_driver_helper](src/spec/helpers/test_driver_helper.js) for interacting with this `test_driver`. This helper just uses stdin and stdout to communicate with COBOL.<file_sep>/docker-compose.yml version: '2.2' services: cobol: build: dockerfile: docker/cobol/Dockerfile context: . <file_sep>/cobol_unit_test_helper/json_to_parser_spec.js let {buildParser} = require('./helpers/json_to_parser'); let {buildPrinter} = require('./helpers/json_to_printer'); describe('JSON to parser and printer', () => { it('fails when given an unrecognized type', () => { expect(() => buildParser({"type": "unknown"})) .toThrowError(Error); }); describe('Digit parser', () => { it('creates an integer parser', () => { let obj = { "type": "integer", "maximum": 99999, "minimum": 0 }; let resultParser = buildParser(obj); let resultPrinter = buildPrinter(obj); expect(resultParser("00006")).toBe(6); expect(resultParser("00007")).toBe(7); expect(resultPrinter(resultParser("00007"))).toBe("00007") }); it('recognizes the number of digits', () => { let obj = { "type": "integer", "maximum": 999, "minimum": 0 }; let resultParser = buildParser(obj); let resultPrinter = buildPrinter(obj); expect(resultParser("026")).toBe(26); expect(resultParser("107")).toBe(107); expect(resultPrinter(resultParser("026"))).toBe("026"); }); }); describe('String parser', () => { it('creates a string parser', () => { let obj = { "type": "string", "maxLength": 5, }; let resultParser = buildParser(obj); let resultPrinter = buildPrinter(obj); expect(resultParser("Hall ")).toBe("Hall"); expect(resultPrinter(resultParser("Hall "))).toBe("Hall "); }); }); describe('Object parser', () => { it('creates an object parser for empty objects', () => { let obj = { "type": "object", "properties": {}, }; let resultParser = buildParser(obj); let resultPrinter = buildPrinter(obj); expect(resultParser("")).toEqual({}); expect(resultPrinter(resultParser(""))).toBe(""); }); it('creates parsers recursively', () => { let obj = { "type": "object", "properties": { "test_item": { "type": "string", "maxLength": 8 }, "test_int": { "type": "integer", "maximum": 999, "minimum": 0 } }, }; let resultParser = buildParser(obj); let resultPrinter = buildPrinter(obj); expect(resultParser("Hallo 001")).toEqual({ "test_item": "Hallo", "test_int": 1 }); expect(resultPrinter(resultParser("Hallo 001"))).toBe("Hallo 001"); }); it('creates parsers recursively 2nd level', () => { let obj = { "type": "object", "properties": { "test_item": { "type": "string", "maxLength": 8 }, "test_int": { "type": "integer", "maximum": 999, "minimum": 0 }, "2ndlevel": { "type": "object", "properties": { "2ndlevel_string": { "type": "string", "maxLength": 1 }, "2ndlevel_int": { "type": "integer", "maximum": 99, "minimum": 0 } } } } }; let resultParser = buildParser(obj); let resultPrinter = buildPrinter(obj); expect(resultParser("Hallo 001007")).toEqual({ "test_item": "Hallo", "test_int": 1, "2ndlevel": { "2ndlevel_string": "0", "2ndlevel_int": 7 } }); expect(resultPrinter(resultParser("Hallo 001007"))).toBe("Hallo 001007"); }); }); describe("Array parser", () => { it('creates a parser for an empty array', () => { let obj = { "type": "array", "maxItems": 99, "minItems": 0, "items": { "type": "string", "maxLength": 5 } }; let resultParser = buildParser(obj); let resultPrinter = buildPrinter(obj); expect(resultParser("00")).toEqual([]); expect(resultPrinter(resultParser("00"))).toBe("00"); }); it('creates a parser for an array with one item', () => { let obj = { "type": "array", "maxItems": 99, "minItems": 0, "items": { "type": "string", "maxLength": 10 } }; let resultParser = buildParser(obj); let resultPrinter = buildPrinter(obj); expect(resultParser("01redballoon")).toEqual(["redballoon"]); expect(resultPrinter(resultParser("01redballoon"))).toBe("01redballoon"); }); }); describe("Crazy Funky Test", () => { it('can parse complex items', () => { let obj = { "type": "object", "properties": { "test_item": { "type": "string", "maxLength": 8 }, "test_int": { "type": "integer", "maximum": 999, "minimum": 0 }, "2ndlevel": { "type": "object", "properties": { "2ndlevel_string": { "type": "string", "maxLength": 1 }, "2ndlevel_int": { "type": "integer", "maximum": 99, "minimum": 0 } } }, "randomArray": { "type": "array", "maxItems": 99, "minItems": 0, "items": { "type": "object", "properties": { "3ndlevel_string": { "type": "string", "maxLength": 1 }, "3ndlevel_int": { "type": "integer", "maximum": 9, "minimum": 0 }, "3thlevel_array": { "type": "array", "maxItems": 99, "minItems": 0, "items": { "type": "string", "maxLength": 1 } } } } } } }; let resultParser = buildParser(obj); let resultPrinter = buildPrinter(obj); expect(resultParser("Hallo 00100703a110abcdefghijb210abcdefghijc310abcdefghij")).toEqual({ "test_item": "Hallo", "test_int": 1, "2ndlevel": { "2ndlevel_string": "0", "2ndlevel_int": 7 }, "randomArray": [ { "3ndlevel_string": "a", "3ndlevel_int": 1, "3thlevel_array": ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"] }, { "3ndlevel_string": "b", "3ndlevel_int": 2, "3thlevel_array": ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"] }, { "3ndlevel_string": "c", "3ndlevel_int": 3, "3thlevel_array": ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"] }] }); expect(resultPrinter(resultParser("Hallo 00100703a110abcdefghijb210abcdefghijc310abcdefghij"))) .toBe("Hallo 00100703a110abcdefghijb210abcdefghijc310abcdefghij"); }); }); });<file_sep>/cobol_unit_test_helper/json_to_parser.js let {parse9, parseX} = require('./cobol_to_json'); let buildIntegerParser = function (dataSpecObj) { let length = dataSpecObj["maximum"].toString().length; return function (inputStr) { return { 'parsed': parse9(inputStr.substr(0, length), length), 'length': length, 'remainingString': inputStr.substr(length) }; }; }; let buildStringParser = function (dataSpecObj) { return function (inputStr) { let length = dataSpecObj["maxLength"]; return { 'parsed': parseX(inputStr.substr(0, length), length), 'length': length, 'remainingString': inputStr.substr(length) }; }; }; let buildObjectParser = function (dataSpecObj) { const keys = Object.keys(dataSpecObj.properties); return function (inputStr) { let returnObject = {}; let remainingInput = inputStr; let length = 0; for (let i = 0; i < keys.length; i++) { let currentAttribute = dataSpecObj.properties[keys[i]]; let parserFunction = buildParserInternal(currentAttribute); let recursiveResult = parserFunction(remainingInput); returnObject[keys[i]] = recursiveResult.parsed; remainingInput = recursiveResult.remainingString; length += recursiveResult.length; } return { 'parsed': returnObject, 'length': length, 'remainingString': remainingInput }; } }; let buildArrayParser = function (dataSpecObj) { let innerParser = buildParserInternal(dataSpecObj.items); return function (inputStr) { let returnObject = []; let itemCountLength = dataSpecObj.maxItems.toString().length; let length = itemCountLength; let itemCount = parse9(inputStr.substr(0, itemCountLength), itemCountLength); let remainingInput = inputStr.substr(itemCountLength); for (let i = 0; i < itemCount; i++) { let itemResult = innerParser(remainingInput); length += itemResult.length; remainingInput = itemResult.remainingString; returnObject.push(itemResult.parsed); } return { 'parsed': returnObject, 'length': length, 'remainingString': remainingInput }; } } function buildParserInternal(dataSpecObj) { switch (dataSpecObj.type) { case 'integer': return buildIntegerParser(dataSpecObj); case 'string': return buildStringParser(dataSpecObj); case 'object': return buildObjectParser(dataSpecObj); case 'array': return buildArrayParser(dataSpecObj); default : throw new Error("Not a valid object type"); } } function buildParser(dataSpecObj) { let internalParser = buildParserInternal(dataSpecObj); return function (inputStr) { let res = internalParser(inputStr); return res.parsed; } } module.exports = { buildParser: buildParser };<file_sep>/docker/cobol/Dockerfile FROM centos:7 RUN yum install wget gcc make libdb-dev libncurses5-dev libgmp-dev gmp gmp-devel autoconf -y RUN wget -O gnu-cobol.tar.gz https://sourceforge.net/projects/open-cobol/files/gnu-cobol/2.2/gnucobol-2.2.tar.gz/download RUN tar zxf gnu-cobol.tar.gz WORKDIR gnucobol-2.2 RUN ./configure --without-db RUN make RUN make install RUN make check RUN make installcheck RUN wget -O nodejs.tar.gz http://nodejs.org/dist/v0.10.30/node-v0.10.30-linux-x64.tar.gz RUN tar --strip-components 1 -xzvf nodejs.tar.gz -C /usr/local COPY docker/cobol/usrlocallib.conf /etc/ld.so.conf.d/usrlocallib.conf RUN ldconfig -v RUN mkdir /app WORKDIR /app COPY package.json /app/package.json COPY .babelrc /app/.babelrc COPY cobol_unit_test_helper /app/cobol_unit_test_helper RUN npm install COPY examples /app/examples WORKDIR /app/examples/books RUN cobc -c -free book_stats.cbl RUN cobc -x -free test_driver.cbl book_stats.o # RUN cobc -x -free src/main/hello_world.cbl double_height.o WORKDIR /app COPY jasmine /app/jasmine CMD ["npm", "test"] <file_sep>/cobol_unit_test_helper/json_to_cobol_spec.js let {print9, printX} = require('./helpers/json_to_cobol'); describe('JSON to COBOL converter', () => { describe('print9', () => { it('prints a single digit number', () => { expect(print9(1, 1)).toBe('1'); }); it('adds zero-padding to numbers', () => { expect(print9(4, 3)).toBe('004'); }); it('throws an error on incorrect input size', () => { expect(() => print9(49123, 4)).toThrow(new Error("Input number too long for copybook.")); }); it('allows only numbers as parameter', () => { expect(() => print9('Hubert', 6)).toThrow(new Error("Could not print a value as number that is no number.")) expect(() => print9(0.1111, 6)).toThrow(new Error("Could not print a value as number that is no number.")) }); }); describe('printX', () => { it('prints a single character', () => { expect(printX('a', 1)).toBe('a'); }); it('prints multiple characters', () => { expect(printX('abc', 3)).toBe('abc'); }); it('adds spaces to lengthen the input to the specified length', () => { expect(printX('abc', 6)).toBe('abc '); }); it('throws an error on oversized input', () => { expect(() => printX('abcdefg', 3)).toThrow(new Error("Input string is too long for copybook.")); }); it('throws an error on not a string input', () => { expect(() => printX(undefined, 3)).toThrow(new Error("Input is not a string")); expect(() => printX(NaN, 3)).toThrow(new Error("Input is not a string")); expect(() => printX(true, 3)).toThrow(new Error("Input is not a string")); expect(() => printX(9.8, 3)).toThrow(new Error("Input is not a string")); expect(() => printX({}, 3)).toThrow(new Error("Input is not a string")); expect(() => printX([], 3)).toThrow(new Error("Input is not a string")); }); }); });<file_sep>/jasmine/run.js import Jasmine from 'jasmine' const SpecReporter = require('jasmine-spec-reporter').SpecReporter; var jasmine = new Jasmine() jasmine.loadConfigFile('jasmine/jasmine.json') jasmine.env.clearReporters(); // remove default reporter logs jasmine.env.addReporter(new SpecReporter({ // add jasmine-spec-reporter spec: { displayPending: true, displayStacktrace: true } })); jasmine.execute() <file_sep>/go #!/usr/bin/env bash if [ "$1" == "commit" ]; then touch /tmp/tw_pair PAIR=$(cat /tmp/tw_pair) read -p "Commit Message: " -e MSG read -p "Pair (Name <<EMAIL>>): " -i "${PAIR}" -e PAIR echo "${PAIR}" > /tmp/tw_pair git commit -m "${MSG}" -m "Co-authored-by: ${PAIR}" else echo "Usage: ./go <command>" echo " ./go commit do a commit with pairing info" fi<file_sep>/examples/books/test_driver_helper.js let {exec} = require('child_process'); let fs = require('fs'); let {buildParser} = require('../../cobol_unit_test_helper/json_to_parser'); let {buildPrinter} = require('../../cobol_unit_test_helper/json_to_printer'); exports.execTestDriver = function (input, resultCallback) { let copybookSpecInput = JSON.parse(fs.readFileSync('examples/books/request-schema.json', 'utf8')); copybookSpecInput = copybookSpecInput["properties"]["WHATEVEROperation"]; let copybookSpecOutput = JSON.parse(fs.readFileSync('examples/books/response-schema.json', 'utf8')); copybookSpecOutput = copybookSpecOutput["properties"]["WHATEVEROperationResponse"]; let printFunc = buildPrinter(copybookSpecInput); let parseFunc = buildParser(copybookSpecOutput); let input_str = printFunc(input); exec(`echo "${input_str}" | examples/books/test_driver`, (err, stdout, stderr) => { if (err) { // command not found or something fail(err); return; } let responseObj = parseFunc(stdout.trim()); resultCallback(responseObj); }); }; <file_sep>/cobol_unit_test_helper/json_to_cobol.js let print9 = function (number, char_count) { if (!Number.isInteger(number)) { throw new Error("Could not print a value as number that is no number."); } let result = number.toString().padStart(char_count, '0'); if (result.length != char_count) { throw new Error("Input number too long for copybook."); } return result; }; let printX = function (str, char_count) { if (typeof str !== 'string') { throw new Error("Input is not a string"); } if (str.length > char_count) { throw new Error("Input string is too long for copybook."); } return str.padEnd(char_count, ' '); }; module.exports = { print9: print9, printX: printX };
ba0fcbb4540d213b0bd1043d46b622d6e237844a
[ "YAML", "JavaScript", "Markdown", "Dockerfile", "Shell" ]
14
JavaScript
TW5860/cobol-in-a-box
ba6c1a38483ac29c49351f33309c37d57a523761
335e3fbae016bdf8735b3d78e97111b4730ab5db
refs/heads/master
<file_sep>package com.itsherman.porterfx.domain; import lombok.Data; /** * @author yumiaoxia 创建时间:2019/8/3 * 审核人: 未审核 审核日期: / */ @Data public class MailMessage { private String code; private String status; private String cause; } <file_sep>package com.itsherman.porterfx.dao.repository; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.repository.NoRepositoryBean; /** * @author yumiaoxia 创建时间:2019/7/31 * 审核人: 未审核 审核日期: / */ @NoRepositoryBean public interface BaseRepository<T, ID> extends JpaRepository<T, ID>, JpaSpecificationExecutor<T> { } <file_sep>package com.itsherman.porterfx; import com.itsherman.porterfx.view.LoginView; import de.felixroske.jfxsupport.AbstractJavaFxApplicationSupport; import javafx.scene.image.Image; import javafx.stage.Stage; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.scheduling.annotation.EnableScheduling; import java.util.Arrays; import java.util.Collection; /** * @author yumiaoxia */ @EnableScheduling @SpringBootApplication public class PorterfxApplication extends AbstractJavaFxApplicationSupport { public static void main(String[] args) { launch(PorterfxApplication.class, LoginView.class, args); } @Override public Collection<Image> loadDefaultIcons() { return Arrays.asList(new Image("/view/icon/youxiang.png")); } @Override public void start(Stage stage) throws Exception { super.start(stage); stage.setResizable(false); stage.setTitle("porter"); } } <file_sep>package com.itsherman.porterfx.service; import com.itsherman.porterfx.dao.entity.User; /** * @author yumiaoxia 创建时间:2019/7/31 * 审核人: 未审核 审核日期: / */ public interface UserService { User getByAccount(String account); User createUser(User user); } <file_sep>package com.itsherman.porterfx.pool; import com.itsherman.porterfx.controller.IndexController; import com.itsherman.porterfx.domain.DownLoadingItem; import com.itsherman.porterfx.domain.DownloadFile; import com.itsherman.porterfx.utils.DownloadUtils; import java.time.Instant; /** * @author yumiaoxia 创建时间:2019/8/4 * 审核人: 未审核 审核日期: / */ public class DownloadingObserver implements Observer { private IndexController indexController; private Instant lastInstant; private Long lastAvailableSize; @Override public void update(DownloadFile downloadFile) { DownLoadingItem.Progress progress = new DownLoadingItem.Progress(); progress.setDownloadingSize(downloadFile.getAvailableSize() + "/" + downloadFile.getActualSize()); Instant newInstant = Instant.now(); Long newAvailableSize = downloadFile.getAvailableSize(); String progressRate = DownloadUtils.convertToProgressRate(lastInstant, newInstant, lastAvailableSize, newAvailableSize); progress.setDownloadingRate(progressRate); DownLoadingItem downLoadingItem = indexController.getDownLoadingData().get(downloadFile.getSnCode()); if (downLoadingItem == null) { downLoadingItem = new DownLoadingItem(downloadFile.getSnCode(), downloadFile.getFileName(), progress, downloadFile.getDownStatus()); indexController.getDownLoadingData().put(downloadFile.getSnCode(), downLoadingItem); } else { downLoadingItem.setProgressProperty(progress); downLoadingItem.setDownStatusProperty(downloadFile.getDownStatus()); } } public void setIndexController(IndexController indexController) { this.indexController = indexController; } } <file_sep>package com.itsherman.porterfx.domain; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.beans.property.SimpleStringProperty; import javafx.beans.property.StringProperty; /** * @author yumiaoxia 创建时间:2019/8/4 * 审核人: 未审核 审核日期: / */ public class DownLoadingItem { private final String itemNo; private final StringProperty fileNameProperty; private final ObjectProperty<Progress> progressProperty; private final ObjectProperty<DownloadFile.DownStatus> downStatusProperty; public DownLoadingItem(String itemNo, String fileName, Progress progress, DownloadFile.DownStatus status) { this.itemNo = itemNo; this.fileNameProperty = new SimpleStringProperty(fileName); this.progressProperty = new SimpleObjectProperty<>(progress); this.downStatusProperty = new SimpleObjectProperty<>(status); } public String getItemNo() { return itemNo; } public String getFileNameProperty() { return fileNameProperty.get(); } public void setFileNameProperty(String fileNameProperty) { this.fileNameProperty.set(fileNameProperty); } public StringProperty fileNamePropertyProperty() { return fileNameProperty; } public Progress getProgressProperty() { return progressProperty.get(); } public void setProgressProperty(Progress progressProperty) { this.progressProperty.set(progressProperty); } public ObjectProperty<Progress> progressPropertyProperty() { return progressProperty; } public DownloadFile.DownStatus getDownStatusProperty() { return downStatusProperty.get(); } public void setDownStatusProperty(DownloadFile.DownStatus downStatusProperty) { this.downStatusProperty.set(downStatusProperty); } public ObjectProperty<DownloadFile.DownStatus> downStatusPropertyProperty() { return downStatusProperty; } public static class Progress { private String downloadingSize; private String downloadingRate; public String getDownloadingSize() { return downloadingSize; } public void setDownloadingSize(String downloadingSize) { this.downloadingSize = downloadingSize; } public String getDownloadingRate() { return downloadingRate; } public void setDownloadingRate(String downloadingRate) { this.downloadingRate = downloadingRate; } } } <file_sep>package com.itsherman.porterfx.utils; import java.time.Duration; import java.time.Instant; /** * @author yumiaoxia 创建时间:2019/8/5 * 审核人: 未审核 审核日期: / */ public class DownloadUtils { public static String convertToProgressRate(Instant lastInstant, Instant newInstant, Long lastSize, long newSize) { String result = "0 B/s"; if (lastInstant != null && lastSize != null && lastSize != 0L) { long millis = Duration.between(lastInstant, newInstant).toMillis(); long progressSize = newSize - lastSize; double progressRate = progressSize * 1000d / millis; if (progressRate < 1024) { result = Math.scalb(progressRate, 1) + " B/s"; } else { progressRate = progressRate / 1024; if (progressRate < 1024) { result = Math.scalb(progressRate, 1) + " KB/s"; } else { result = Math.scalb(progressRate / 1024, 1) + " M/s"; } } } return result; } } <file_sep>package com.itsherman.porterfx.applicationService; import org.springframework.stereotype.Service; /** * @author yumiaoxia 创建时间:2019/8/3 * 审核人: 未审核 审核日期: / */ @Service public class MailApplicationService { } <file_sep>package com.itsherman.porterfx.pool; import com.itsherman.porterfx.domain.DownloadFile; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.HashMap; import java.util.Map; /** * @author yumiaoxia 创建时间:2019/8/4 * 审核人: 未审核 审核日期: / */ @Component public class DownloadFilePool { @Autowired private DownloadSubject downloadSubject; private Map<String, DownloadFile> downloadFileMap = new HashMap<>(); public void registerDownloadFile(DownloadFile downloadFile) { downloadFileMap.put(downloadFile.getSnCode(), downloadFile); downloadSubject.setDownloadFile(downloadFile); } public DownloadFile takeOne(String fileName) { return downloadFileMap.get(fileName); } } <file_sep>package com.itsherman.porterfx.view; import de.felixroske.jfxsupport.AbstractFxmlView; import de.felixroske.jfxsupport.FXMLView; /** * @author yumiaoxia 创建时间:2019/8/1 * 审核人: 未审核 审核日期: / */ @FXMLView(value = "/view/Index.fxml", bundle = "i18n.index", encoding = "utf-8", title = "porter") public class IndexView extends AbstractFxmlView { } <file_sep>package com.itsherman.porterfx.service; import javax.mail.MessagingException; import javax.mail.Part; import java.io.IOException; import java.util.List; /** * @author yumiaoxia 创建时间:2019/8/3 * 审核人: 未审核 审核日期: / */ public interface MailService { List<Part> receive() throws MessagingException, IOException; } <file_sep>package com.itsherman.porterfx.view; import de.felixroske.jfxsupport.AbstractFxmlView; import de.felixroske.jfxsupport.FXMLView; /** * <p> </p> * * @author 俞淼霞 * @since 2019-07-30 */ @FXMLView(value = "/view/Login.fxml", bundle = "i18n.index", encoding = "utf-8") public class LoginView extends AbstractFxmlView { }
e92cfd9c49bf0543c25dc55e7bee523e808357b5
[ "Java" ]
12
Java
yumiaoxia/porterfx
e87c7bab8ef8556abec6f85ebe36796f86207ec9
36d5eff60c6eb980ce3e7a5d9a5c64fbcf2c5e6a
refs/heads/master
<repo_name>sr178-module/game-msg<file_sep>/src/main/java/com/sr178/game/msgbody/common/codec/StreamDataCodec.java package com.sr178.game.msgbody.common.codec; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List; import com.sr178.game.msgbody.common.io.XIOFactoryManager; import com.sr178.game.msgbody.common.io.iface.IXInputStream; import com.sr178.game.msgbody.common.io.iface.IXOutStream; import com.sr178.game.msgbody.common.model.ICodeAble; import com.sr178.game.msgbody.common.model.Msg; import com.sr178.game.msgbody.common.model.MsgGroup; /** * 流解析器 * @author magical * */ public class StreamDataCodec implements IDataCodec { @Override public List<Msg> decodeMsgUser(byte[] datas) { return decodeMsgServer(datas); } @Override public byte[] encodeMsgUser(List<Msg> msgs) { if(msgs==null||msgs.size()==0){ return null; } ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream(); IXOutStream ixOutStream = XIOFactoryManager.getIoFactoryByKey().getIXOutStream(); ixOutStream.setOutputStream(byteOutputStream); List<Msg> msgsList = new ArrayList<Msg>(); msgsList.addAll(msgs); MsgGroup group = new MsgGroup(); group.setMsgsList(msgsList); byte[] cache = null; try { group.encode(ixOutStream); cache = byteOutputStream.toByteArray(); ixOutStream.close(); } catch (IOException e) { e.printStackTrace(); } return cache; } @Override public List<Msg> decodeMsgServer(byte[] datas) { IXInputStream inputStream = XIOFactoryManager.getIoFactoryByKey().getIXInputStream(); ByteArrayInputStream arrayInputStream = new ByteArrayInputStream(datas); inputStream.setInputStream(arrayInputStream); MsgGroup msgGroup = new MsgGroup(); try { //解码消息收到的时间 msgGroup.setReciverTime(System.currentTimeMillis()); msgGroup.decode(inputStream); } catch (IOException e) { e.printStackTrace(); }finally{ try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } List<Msg> msgVector = msgGroup.getMsgsList(); return msgVector; } @Override public byte[] encodeMsgServer(List<Msg> msgs) { if(msgs==null||msgs.size()==0){ return null; } ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream(); IXOutStream ixOutStream = XIOFactoryManager.getIoFactoryByKey().getIXOutStream(); ixOutStream.setOutputStream(byteOutputStream); List<Msg> msgsList = new ArrayList<Msg>(); msgsList.addAll(msgs); MsgGroup group = new MsgGroup(); group.setMsgsList(msgsList); byte[] cache = null; try { group.encode(ixOutStream); cache = byteOutputStream.toByteArray(); ixOutStream.close(); } catch (IOException e) { e.printStackTrace(); } return cache; } @SuppressWarnings("unchecked") @Override public <T extends ICodeAble> T decodeBody(Msg msg, Class<T> c) { ICodeAble msgBody = null; byte[] data = msg.getData(); try { msgBody = c.newInstance(); } catch (InstantiationException e1) { e1.printStackTrace(); } catch (IllegalAccessException e1) { e1.printStackTrace(); } if(data!=null&&data.length>0){ IXInputStream inputStream = XIOFactoryManager.getIoFactoryByKey().getIXInputStream(); ByteArrayInputStream bytearray = new ByteArrayInputStream(data); inputStream.setInputStream(bytearray); try { msgBody.decode(inputStream); } catch (IOException e) { e.printStackTrace(); }finally{ try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } return (T)msgBody; } } <file_sep>/src/main/java/com/sr178/game/msgbody/common/model/MsgHead.java package com.sr178.game.msgbody.common.model; import java.io.IOException; import com.sr178.game.msgbody.common.io.iface.IXInputStream; import com.sr178.game.msgbody.common.io.iface.IXOutStream; public class MsgHead implements ICodeAble { public MsgHead(Short fromType, String fromID, Short toType, String toID, Short msgType, int msgSequense, String cmdCode,int errorCode) { super(); this.fromType = fromType; this.fromID = fromID; this.toType = toType; this.toID = toID; this.msgType = msgType; this.msgSequense = msgSequense; this.cmdCode = cmdCode; this.errorCode = errorCode; } public MsgHead() { super(); } public MsgHead(int errorCode) { super(); this.errorCode = errorCode; } /** * 消息类型 */ public static final short TYPEOFREQUEST = 1; public static final short TYPEOFRESPONSE = 2; public static final short TYPEOFNOTIFY = 3; /** * 消息广播的类�? */ //来自或去向为�? public static final short TO_OR_FROM_TYPE_USER = 1; //来自或去向为房间 public static final short TO_OR_FROM_TYPE_ROOM = 2; //来自或去向为系统 public static final short TO_OR_FROM_TYPE_SYSTEM = 3; //高优先级 public static final byte HIGHT = 0; //普通优先级 可缓慢发送 public static final byte COMMON = 1; //低优先级 public static final byte LOWER = 2; //消息来源类型 private short fromType; //消息来源ID private String fromID=new String("0"); //消息目的类型 private short toType; //消息目的ID private String toID=new String("0"); //消息类型 private short msgType; //消息序列�? private int msgSequense; //命令�? private String cmdCode; //错误�? private int errorCode; //消息体大�? private int sizeOfMsgBody; //用户序列�? private String userSequense=new String("0"); //消息优先级 private byte priority; @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (obj instanceof MsgHead) { MsgHead m = (MsgHead) obj; if (m.getCmdCode().equals(cmdCode)) { return true; } } return false; } @Override public int hashCode() { return cmdCode.hashCode(); } public void decode(IXInputStream inputStream) throws IOException { errorCode = inputStream.readInt(); fromType = inputStream.readShort(); fromID = inputStream.readUTF(); toType = inputStream.readShort(); toID = inputStream.readUTF(); msgType = inputStream.readShort(); msgSequense = inputStream.readInt(); cmdCode = inputStream.readUTF(); userSequense = inputStream.readUTF(); priority = inputStream.readByte(); sizeOfMsgBody = inputStream.readInt(); // System.out.println("decode errorCode" + errorCode); // System.out.println("decode fromType" + fromType); // System.out.println("decode fromID" + fromID); // System.out.println("decode toType" + toType); // System.out.println("decode toID" + toID); // System.out.println("decode msgType" + msgType); // System.out.println("decode cmdCode" + cmdCode); // System.out.println("decode userSequense" + userSequense); // System.out.println("decode sizeOfMsgBody" + sizeOfMsgBody); } public void encode(IXOutStream outputStream) throws IOException { outputStream.writeInt(errorCode); outputStream.writeShort(fromType); outputStream.writeUTF(fromID); outputStream.writeShort(toType); outputStream.writeUTF(toID); outputStream.writeShort(msgType); outputStream.writeInt(msgSequense); outputStream.writeUTF(cmdCode); outputStream.writeUTF(userSequense); outputStream.writeByte(priority); outputStream.writeInt(sizeOfMsgBody); // System.out.println("encode errorCode" + errorCode); // System.out.println("encode fromType" + fromType); // System.out.println("encode fromID" + fromID); // System.out.println("encode toType" + toType); // System.out.println("encode toID" + toID); // System.out.println("encode msgType" + msgType); // System.out.println("encode modelId" + modelId); // System.out.println("encode cmdCode" + cmdCode); // System.out.println("encode sysNumber" + sysNumber); // System.out.println("encode sequense" + sequense); // System.out.println("encode userSequense" + userSequense); // System.out.println("encode sizeOfMsgBody" + sizeOfMsgBody); } public String toString(){ return "cmdCode = "+cmdCode+""+",msgType="+msgType+",errorCode="+errorCode+",fromId="+fromID; } public int getMsgSequense() { return msgSequense; } public void setMsgSequense(int msgSequense) { this.msgSequense = msgSequense; } public void setCmdCode(String cmdCode) { this.cmdCode = cmdCode; } public MsgHead(short fromType, String fromID, short toType, String toID, short msgType, int msgSequense, String cmdCode,int errorCode, String userSequense) { super(); this.fromType = fromType; this.fromID = fromID; this.toType = toType; this.toID = toID; this.msgType = msgType; this.msgSequense = msgSequense; this.cmdCode = cmdCode; this.errorCode = errorCode; this.userSequense = userSequense; } public short getFromType() { return fromType; } public void setFromType(short fromType) { this.fromType = fromType; } public String getFromID() { return fromID; } public void setFromID(String fromID) { this.fromID = fromID; } public short getToType() { return toType; } public void setToType(short toType) { this.toType = toType; } public String getToID() { return toID; } public void setToID(String toID) { this.toID = toID; } public short getMsgType() { return msgType; } public void setMsgType(short msgType) { this.msgType = msgType; } public int getErrorCode() { return errorCode; } public void setErrorCode(int errorCode) { this.errorCode = errorCode; } public int getSizeOfMsgBody() { return sizeOfMsgBody; } public void setSizeOfMsgBody(int sizeOfMsgBody) { this.sizeOfMsgBody = sizeOfMsgBody; } public String getUserSequense() { return userSequense; } public void setUserSequense(String userSequense) { this.userSequense = userSequense; } public String getCmdCode() { return cmdCode; } public byte getPriority() { return priority; } public void setPriority(byte priority) { this.priority = priority; } public MsgHead clone(){ MsgHead cloneMsgHead = new MsgHead(); cloneMsgHead.setCmdCode(cmdCode); cloneMsgHead.setErrorCode(errorCode); cloneMsgHead.setFromID(fromID); cloneMsgHead.setFromType(fromType); cloneMsgHead.setMsgSequense(msgSequense); cloneMsgHead.setMsgType(msgType); cloneMsgHead.setPriority(priority); cloneMsgHead.setSizeOfMsgBody(sizeOfMsgBody); cloneMsgHead.setToID(toID); cloneMsgHead.setToType(toType); cloneMsgHead.setUserSequense(userSequense); return cloneMsgHead; } } <file_sep>/pom.xml <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/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.sr178.game.msg</groupId> <artifactId>game-msg</artifactId> <version>0.0.1-SNAPSHOT</version> <description>通讯消息体</description> <properties> <version.fastjson>1.1.15</version.fastjson> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <build> <pluginManagement> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>2.3.2</version> <configuration> <encoding>UTF-8</encoding> <source>1.7</source> <target>1.7</target> </configuration> </plugin> </plugins> </pluginManagement> </build> <dependencies> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>${version.fastjson}</version> </dependency> </dependencies> <repositories> <repository> <id>opensesame</id> <name>Alibaba OpenSource Repsoitory</name> <url>http://code.alibabatech.com/mvn/releases/</url> <snapshots> <enabled>false</enabled> </snapshots> </repository> <repository> <id>local</id> <name>local Repository</name> <url>http://mvn.dev.sr178.com:8081/nexus/content/repositories/thirdparty/</url> <releases> <enabled>true</enabled> </releases> </repository> <repository> <id>local snapshots</id> <name>local Repository</name> <url>http://mvn.dev.sr178.com:8081/nexus/content/repositories/snapshots/</url> <releases> <enabled>true</enabled> </releases> </repository> </repositories> <distributionManagement> <snapshotRepository> <id>snapshots</id> <url>http://mvn.dev.sr178.com:8081/nexus/content/repositories/snapshots</url> </snapshotRepository> </distributionManagement> </project><file_sep>/src/main/java/com/sr178/game/msgbody/common/io/java/JavaIoFactory.java package com.sr178.game.msgbody.common.io.java; import com.sr178.game.msgbody.common.io.iface.IXInputStream; import com.sr178.game.msgbody.common.io.iface.IXOutStream; import com.sr178.game.msgbody.common.io.iface.IoFactory; public class JavaIoFactory implements IoFactory { public IXInputStream getIXInputStream() { return new JavaInput(); } public IXOutStream getIXOutStream() { return new JavaOutput(); } } <file_sep>/src/main/java/com/sr178/game/msgbody/server/ReqRegisterChannelMsgBody.java package com.sr178.game.msgbody.server; import java.io.IOException; import com.sr178.game.msgbody.common.io.iface.IXInputStream; import com.sr178.game.msgbody.common.io.iface.IXOutStream; import com.sr178.game.msgbody.common.model.ICodeAble; public class ReqRegisterChannelMsgBody implements ICodeAble { /***服务器类型*******/ private String serverType; /***通道类型*******/ private String channelType; public void encode(IXOutStream outputStream) throws IOException { outputStream.writeUTF(serverType); outputStream.writeUTF(channelType); } public void decode(IXInputStream inputStream) throws IOException { serverType = inputStream.readUTF(); channelType = inputStream.readUTF(); } public String getServerType() { return serverType; } public void setServerType(String serverType) { this.serverType = serverType; } public String getChannelType() { return channelType; } public void setChannelType(String channelType) { this.channelType = channelType; } } <file_sep>/src/main/java/com/sr178/game/msgbody/common/io/java/JavaOutput.java package com.sr178.game.msgbody.common.io.java; import java.io.DataOutputStream; import java.io.IOException; import java.io.OutputStream; import com.sr178.game.msgbody.common.io.iface.IXOutStream; public class JavaOutput implements IXOutStream { private DataOutputStream dataOutputStream; public void close() throws IOException { dataOutputStream.close(); } public void setOutputStream(OutputStream outputstream) { dataOutputStream = new DataOutputStream(outputstream); } public void writeBoolean(boolean b) throws IOException { dataOutputStream.writeBoolean(b); } public void writeByte(byte b) throws IOException { dataOutputStream.write(b); } public void writeBytes(byte[] b) throws IOException { dataOutputStream.write(b); } public void writeChar(char c) throws IOException { dataOutputStream.writeChar(c); } public void writeDouble(double d) throws IOException { dataOutputStream.writeDouble(d); } public void writeFloat(float f) throws IOException { dataOutputStream.writeFloat(f); } public void writeInt(int i) throws IOException { dataOutputStream.writeInt(i); } public void writeLong(long l) throws IOException { dataOutputStream.writeLong(l); } public void writeShort(short s) throws IOException { dataOutputStream.writeShort(s); } public void writeUTF(String s) throws IOException { if(s!=null){ byte[] bytes = s.getBytes(); short lenght = (short)bytes.length; dataOutputStream.writeShort(lenght); dataOutputStream.write(bytes); // StringBuffer result = new StringBuffer(); // for(int i=0;i<bytes.length;i++){ // result.append(bytes[i]+","); // } // System.out.println("WRITE----string="+s+",lenght="+lenght+",byte = "+result.toString()); }else{ dataOutputStream.writeShort(0); } } } <file_sep>/src/main/java/com/sr178/game/msgbody/common/io/java/JavaInput.java package com.sr178.game.msgbody.common.io.java; import java.io.DataInputStream; import java.io.IOException; import java.io.InputStream; import com.sr178.game.msgbody.common.io.iface.IXInputStream; public class JavaInput implements IXInputStream { private DataInputStream dataInputStream; public void close() throws IOException { dataInputStream.close(); } public boolean readBoolean() throws IOException { return dataInputStream.readBoolean(); } public byte readByte() throws IOException { return dataInputStream.readByte(); } public char readChar() throws IOException { return dataInputStream.readChar(); } public double readDouble() throws IOException { return dataInputStream.readDouble(); } public float readFloat() throws IOException { return dataInputStream.readFloat(); } public void readFully(byte[] b, int position, int size) throws IOException { dataInputStream.readFully(b, position, size); } public int read(byte[] b, int off, int len) throws IOException{ return dataInputStream.read(b, off, len); } public int readInt() throws IOException { return dataInputStream.readInt(); } public long readLong() throws IOException { return dataInputStream.readLong(); } public short readShort() throws IOException { return dataInputStream.readShort(); } public String readUTF() throws IOException { int utflen = dataInputStream.readUnsignedShort(); if(utflen>0){ byte[] bytes = new byte[utflen]; dataInputStream.read(bytes, 0, utflen); // StringBuffer result = new StringBuffer(); // for(int i=0;i<bytes.length;i++){ // result.append(bytes[i]+","); // } String resultT = new String(bytes,"utf-8"); // System.out.println("READ----string="+resultT+",lenght="+utflen+",byte = "+result.toString()); return resultT; }else{ return null; } } public void setInputStream(InputStream inputStream) { dataInputStream = new DataInputStream(inputStream); } public int available() throws IOException { return dataInputStream.available(); } } <file_sep>/src/main/java/com/sr178/game/msgbody/common/model/MsgGroup.java package com.sr178.game.msgbody.common.model; import java.io.IOException; import java.util.ArrayList; import java.util.List; import com.sr178.game.msgbody.common.io.iface.IXInputStream; import com.sr178.game.msgbody.common.io.iface.IXOutStream; public class MsgGroup implements ICodeAble { private int sizeOfMsg; private List<Msg> msgsList; private long reciverTime; public long getReciverTime() { return reciverTime; } public void setReciverTime(long reciverTime) { this.reciverTime = reciverTime; } public List<Msg> getMsgsList() { return msgsList; } public void setMsgsList(List<Msg> msgsList) { this.msgsList = msgsList; } public void addMsg(Msg msg){ if(msgsList!=null){ msgsList.add(msg); }else{ msgsList = new ArrayList<Msg>(); msgsList.add(msg); } } public void decode(IXInputStream inputStream) throws IOException { sizeOfMsg = inputStream.readInt(); msgsList = new ArrayList<Msg>(); for(int i=0;i<sizeOfMsg;i++){ Msg temp = new Msg(); temp.decode(inputStream); //设置消息接收到的时间 temp.setReceiverTime(reciverTime); msgsList.add(temp); } } public void encode(IXOutStream outputStream) throws IOException { sizeOfMsg = msgsList.size(); if(sizeOfMsg>0){ outputStream.writeInt(sizeOfMsg); for(Msg msg:msgsList){ if(msg!=null){ msg.encode(outputStream); } } } } public int getSizeOfMsg() { return sizeOfMsg; } public void setSizeOfMsg(int sizeOfMsg) { this.sizeOfMsg = sizeOfMsg; } } <file_sep>/src/main/java/com/sr178/game/msgbody/common/io/iface/IoFactory.java package com.sr178.game.msgbody.common.io.iface; public interface IoFactory { public IXInputStream getIXInputStream(); public IXOutStream getIXOutStream(); }
9059a2aec3c42c06c8f47a313f9be790adc37be8
[ "Java", "Maven POM" ]
9
Java
sr178-module/game-msg
446a8fded8aa614d30aa4639922b661a94a09729
c9b341b1808fd6a71cf74e21775bab518fba1af4
refs/heads/master
<file_sep>/** * @fileoverview Browser code for itrans input and output. * @author <NAME> <<EMAIL>> * * http://www.aczoom.com/itrans/online/ */ 'use strict'; // Application entry point, so for all the .js files used by this app, transpile. // Remove this line once all key browsers handle ES6 (they already do?) // 2021-01-12 removed: require('babel-polyfill'); // Load the itrans converter. This is loaded with the default itrans conversion tables. const constants = require('./src/constants'); const Itrans = require('./src/Itrans'); const DEFAULT_TSV = require('./data/DEFAULT_TSV'); // Web page must use these id/class names const INPUT_FORM_ID = 'i-input-form'; // id of form containing textarea and buttons for itrans input const INPUT_ID = 'i-input-text'; // id of text area for entering itrans input const INPUT_FILE_ID = 'i-input-file'; // id of button to load file into input textarea const INPUT_CLEAR_ID = 'i-input-clear'; // id of button to clear input textarea const OUTPUT_CLASS = 'i-output'; // class containing select and textarea to show output const TSV_FORM_ID = 'i-data'; // form containing the load spreadsheet input const TSV_INPUT_ID = 'i-data-input'; // load new spreadsheet TSV from this file name const TSV_INPUT_RESET_ID = 'i-data-input-reset'; // load default spreadsheet TSV const TSV_INPUT_MESSAGE_ID = 'i-data-msg'; // error or success messages on loading data const OUTPUT_FORMAT = constants.OUTPUT_FORMAT; // utf8, html7, or unicodeNames // maximum size of TSV spreadsheet data to be loaded const MAX_TSV_SIZE = 100 * 1000; // in bytes. DEFAULT tsv data is under 20k. // This script waits for pauses between user keypresses, // and converts itrans text during the pause. let typingTimer; // timer identifier let doneTypingInterval = 1000; // time in ms, after this expires, run itrans.convert let inputTextArea; // itrans input text is entered here let dataFileMessage; // loaded data file status/error messages let dataFileForm; // form with input field to load data file let dataFileReset; // load default data spreadsheet // Each output section has two controls: one where user selects a default language, // and another where the converted itrans text is output. // The controls have distinct elements, and are collected in this array. // language: the select object where language.value is the selected element // output: the output text area // { language: null; output = null; } let outputLanguages = []; // select element drop-down elements are synced with the spreadsheet languages // and some custom names and additions made const UNICODE_NAMES_OPTION = {text: 'Unicode names', value: 'unicode-names'}; // Suppress #tamils from output. There is no font that correctly supports it, // no font puts the superscript characters after the vowel sign, for example. const SELECT_SKIP_NAMES = ['#tamils']; // suppress these names from the dropdown list // Load the default itrans conversion table const itransDefault = new Itrans(); let itrans = itransDefault; function runItrans(inputText, outputScript, outputDiv) { const options = { language: '#sanskrit', outputFormat: 'HTML7' }; if (outputScript === UNICODE_NAMES_OPTION.value) { options.outputFormat = OUTPUT_FORMAT.unicodeNames; } else { options.language = outputScript; } outputDiv.innerHTML = itrans.convert(inputText, options); } // user is 'finished typing,' do something function runAllItrans () { outputLanguages.forEach(({language, output}) => { runItrans(inputTextArea.value, language.value, output); }); } // Load in the itrans input file function loadInputFile(fileId, formId) { if (!fileId || !fileId.files) { return; } if (!(window && window.File && window.FileReader && window.FileList && window.Blob)) { formId.reset(); alert('Error: This browser does not support file loading (old browser?).'); return; } const file = fileId.files[0]; const {name, type, size} = file || {}; console.log('Got loadInput file', name, type, size); if (type && !type.startsWith('text')) { // Sometimes type is undefined, so skip this check in that case. formId.reset(); alert('Error: File "' + name + '" is not a text file.'); return; } if (size > MAX_TSV_SIZE) { formId.reset(); alert('Error: File "' + name + '" is too large. Over ' + MAX_TSV_SIZE/1000 + 'k.'); return; } const reader = new FileReader(); reader.readAsText(file); reader.onload = ( (event) => { const data = event.target.result; inputTextArea.value = data; runAllItrans(); }); } // Load in the spreadsheet tsv file function loadDataFile(fileId, formId) { if (!fileId || !fileId.files) { return; } if (!(window && window.File && window.FileReader && window.FileList && window.Blob)) { formId.reset(); alert('Error: This browser does not support file loading (old browser?).'); return; } const file = fileId.files[0]; const {name, type, size} = file || {}; console.log('Got loadData file', name, type, size); if (type && !type.startsWith('text')) { // Sometimes type is undefined, so skip this check in that case. formId.reset(); alert('Error: File "' + name + '" is not a text file.'); return; } if (size > MAX_TSV_SIZE) { formId.reset(); alert('Error: File "' + name + '" is too large. Over ' + MAX_TSV_SIZE/1000 + 'k.'); return; } const reader = new FileReader(); reader.readAsText(file); reader.onload = ( (event) => { const data = event.target.result; loadItransData(data, name, formId); }); } // Load the spreadsheet string (data) and display message about // loading it from source name. Update all web elements that need updating on newly // loaded spreadsheet data. function loadItransData(data, name, formId) { // There is no clear function available for itrans data, so create a new object // with the new itrans table data. const tempItrans = new Itrans(); try { tempItrans.load(data); itrans = tempItrans; updateDataFileMessage('Loaded: ' + name, itrans); } catch(err) { const msg = 'Error: ' + name + ' has invalid itrans data: ' + err; if (formId) { formId.reset(); } updateDataFileMessage(msg, undefined); alert(msg); } // Update web elements that depend on the itrans object data. updateAllWebElements(); // Update all the output text boxes using the new spreadsheet data. runAllItrans(); } function updateDataFileMessage(msg, tempItrans) { if (!dataFileMessage) { console.log('Warning: no dataFileMessage'); return; } let out = msg + '<br>'; let langs = 0; let rows = 0; if (tempItrans) { const table = tempItrans.itransTable; langs = table.languages.length; rows = table.itransRows.length; } dataFileMessage.innerHTML = out + langs + ' languages/scripts, ' + rows + ' rows.'; } // Update the select drop-down list based on data on the current "itrans" object. // Sync the languages in this element with the actually loaded languages. // Keep track of currently selected language, so it can be selected (if the language is present). function updateSelectList(selectElement) { if (!selectElement) { return; } // Save the currently selected element, so if this const selected = selectElement.value; // Remove all existing items while (selectElement.options.length) { selectElement.remove(0); } // Add all currently loaded languages const table = itrans.itransTable; const langs = table.languages; table.languages.forEach((language) => { // Only add option if it is not in the skip options list if (SELECT_SKIP_NAMES.indexOf(language) < 0) { const isSelected = selected == language; const option = new Option(language, language, isSelected, isSelected); selectElement.add(option); } }); // Add in Unicode names language option const option = new Option(UNICODE_NAMES_OPTION.text, UNICODE_NAMES_OPTION.value); option.selected = selected === UNICODE_NAMES_OPTION.value; selectElement.add(option); } // Update all the elements of the web page that need updating // based on the data in the spreadsheet such as the languages supported. function updateAllWebElements() { outputLanguages.forEach(({language}) => { // Update web page elements that depend on list of loaded languages. // For each select element, update its option items to match loaded languages. // Adds all the languages available in the spreadsheet. updateSelectList(language); }); } function itransSetup() { document.addEventListener('DOMContentLoaded', function() { // this function runs when the DOM is ready, i.e. when the document has been parsed inputTextArea = document.getElementById(INPUT_ID); const events = ['input', 'propertychange', 'paste']; if (!inputTextArea) { alert('Page invalid: required input element missing: id: ' + INPUT_ID); return; } events.forEach(function (event) { inputTextArea.addEventListener(event, function () { clearTimeout(typingTimer); typingTimer = setTimeout(runAllItrans, doneTypingInterval); }); }); const inputForm = document.getElementById(INPUT_FORM_ID); const clearButton = document.getElementById(INPUT_CLEAR_ID); if (clearButton) { clearButton.addEventListener('click', () => { if (inputForm) { inputForm.reset(); } inputTextArea.value = ''; runAllItrans(); }); } // Load file into itrans input area const fileInput = document.getElementById(INPUT_FILE_ID); if (fileInput) { if (!inputForm) { alert('Page invalid: required form missing : id: ' + INPUT_FORM_ID); return; } fileInput.addEventListener('change', () => { loadInputFile(fileInput, inputForm); }, false); } // All the output controls. const outputs = document.getElementsByClassName(OUTPUT_CLASS); if (!outputs || !outputs.length) { alert('Page invalid: required output elements missing: class: ' + OUTPUT_CLASS); return; } for (let i = 0; i < outputs.length; i++) { const output = outputs[i]; const select = output.getElementsByTagName("select")[0]; // only 1 descendant of this type expected const outputText = output.getElementsByTagName("textarea"); outputLanguages.push({ language: select, output: outputText[0] }); } // For each language selector, run the conversion when selection is made. outputLanguages.forEach(({language}) => { language.addEventListener('change', () => runAllItrans()); }); // Read spreadsheet TSV text data file const dataFileInput = document.getElementById(TSV_INPUT_ID); if (dataFileInput) { dataFileForm = document.getElementById(TSV_FORM_ID); if (!dataFileForm) { alert('Page invalid: required form missing : id: ' + TSV_FORM_ID); return; } dataFileInput.addEventListener('change', () => { loadDataFile(dataFileInput, dataFileForm); }, false); } dataFileMessage = document.getElementById(TSV_INPUT_MESSAGE_ID); // Reset spreadsheet TSV data to default dataFileReset = document.getElementById(TSV_INPUT_RESET_ID); if (dataFileReset) { dataFileReset.addEventListener('click', () => { loadItransData(DEFAULT_TSV, 'Default', null); }, false); } // Web page setup done, now load the itrans tables. loadItransData(DEFAULT_TSV, 'Default', null); console.log('Ready for interactive itrans use.'); }); } // Run the function to setup the web interaction. itransSetup(); // Nothing to export here, browserify this file, and just load it in the web page. <file_sep># ChangeLog ## Version 0.3.1 * 2021-01-12 * Updated DEFAULT.tsv to include avagraha * Removed `browser.js` transpiling load of `babel-polyfill`, no need to handle some of the ES6 constructs used in the Javascript files since ES6 is widely available,and no transpiling is now necessary. ## Version 0.3.0 * Added load button to load local file into itrans input area ## Version 0.2.2 * Improved the look and working of the Load spreadsheet button. Load Default now loads the default data file. * Added a clear button for the input text area. ## Version 0.2.1 * The web page Default Output languages list is now auto-populated based on the actual languages in the loaded spreadsheet. The HTML page can indicate the selected language, and that indicator will be maintained (as long as that language is present in the loaded spreadsheet). ## Version 0.2.0 * First version that was uploaded to GitHub * Includes Javascript code, Node.js package.json, CSS files, HTML pages.
685461ce409d9c6feda4596bf8cd657691ac48b2
[ "JavaScript", "Markdown" ]
2
JavaScript
zeroknol/itrans
3c60a623284726d0d965d5255634f78eab5a90a4
2f45a44d8c9ef8fb7ae217bd2517be27d8883cc6
refs/heads/master
<repo_name>teatime13/base64<file_sep>/base64encode.py class Base64: def __init__(self): #self.debug = True self.debug =False self.a_str = '' self.wordlist = {} self.bits = '' self.string_after_conversion = '' self.six_bit_list = [] self.encoded_data = '' self.make_wordlist() def __str__(self): return self.encoded_data def make_wordlist(self): a_bit = 0b0 for i in range(65, 65+26): self.wordlist[format(a_bit, '06b')] = chr(i) a_bit += 0b1 for i in range(97, 97+26): self.wordlist[format(a_bit, '06b')] = chr(i) a_bit += 0b1 for i in range(0, 10): self.wordlist[format(a_bit, '06b')] = str(i) a_bit += 0b1 self.wordlist[format(a_bit, '06b')] = '+' a_bit += 0b1 self.wordlist[format(a_bit, '06b')] = '/' if self.debug: print(self.wordlist) def character_to_bit(self): self.bits = '' for s in self.a_str: self.bits += format(ord(s), '08b') if self.debug: print(self.bits) def splitting_to_6_bit(self): self.six_bit_list = [self.bits[i: i+6] for i in range(0,len(self.bits),6)] if len(self.six_bit_list[-1]) < 6: self.six_bit_list[-1] += '0' * (6 - len(self.six_bit_list[-1])) if self.debug: print(self.six_bit_list) def converting_from_table(self): self.string_after_conversion = '' for s in self.six_bit_list: self.string_after_conversion += self.wordlist[s] if self.debug: print(self.string_after_conversion) def replenishment_equal(self): if len(self.string_after_conversion) % 4 != 0: self.string_after_conversion += '=' * (4 - len(self.string_after_conversion) % 4) self.encoded_data = self.string_after_conversion if self.debug: print(self.string_after_conversion) def encode(self, a_str="sample"): self.a_str = a_str self.character_to_bit() self.splitting_to_6_bit() self.converting_from_table() self.replenishment_equal() print(self.a_str + ' : ' + self.encoded_data) if __name__ == "__main__": base64 = Base64() base64.encode('sample') print(base64) base64.encode('A') print(base64) base64.encode('ABCDEFG') print(base64) <file_sep>/README.md # base64 勉強がてらbase64のエンコーダを作成してみる
07014ea62907f2dd551c7cb3c6925f96bb4868d3
[ "Markdown", "Python" ]
2
Python
teatime13/base64
c559f969105de8acbdcdee7a255eb0bc9f7fd866
e238de7f68c2eb08e712941b732ab3a795cef1cc
refs/heads/master
<file_sep>// Class witch contains main operations using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using MySql.Data.MySqlClient; using System.Data.Common; using System.Data; namespace SharpSniffer { class Loader { static void Main(string[] args) { // Get connection to database MySqlConnection connection = DbUtils.GetDBConnection(); connection.Open(); try { // Insert command string sql = "Insert into " + " values "; MySqlCommand cmd = connection.CreateCommand(); cmd.CommandText = sql; // to do operations here) // Do Command ( delete, insert, update). int rowCount = cmd.ExecuteNonQuery(); Console.WriteLine("Row Count affected = " + rowCount); } catch (Exception e) { Console.WriteLine("Error: " + e); Console.WriteLine(e.StackTrace); } finally { connection.Close(); connection.Dispose(); connection = null; } Console.Read(); } } } <file_sep>// Shiffer for Windows 10. // Made for collect IP and TCP packet data into MySQL Database using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net; using System.Net.Sockets; using System.Threading; using System.Configuration; using System.IO; using System.Text.RegularExpressions; using System.Net.NetworkInformation; namespace SharpSniffer { static class Program { static void Main(string[] args) { // Get hosts from our network var IPv4Addresses = Dns.GetHostEntry(Dns.GetHostName()).AddressList.Where(al => al.AddressFamily == AddressFamily.InterNetwork).AsEnumerable(); Console.WriteLine("Protocol\tSourceIP:Port\t===>\tDestinationIP:Port\t---Flag"); // Listen each packet to each address foreach (IPAddress ip in IPv4Addresses) Sniff(ip); // While any the button is not pressed Console.Read(); } public static string ToProtocolString(this byte b) { // Detect the type of the protocol switch (b) { case 1: return "ICMP"; case 2: return "IGMP"; case 6: return "TCP"; case 17: return "UDP"; case 41: return "IPv6"; case 121: return "SMP"; default: return "#" + b.ToString(); } } static void Sniff(IPAddress ip) { // Start sniffing for ipv4 protocol packets Socket sck = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.IP); sck.Bind(new IPEndPoint(ip, 0)); sck.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.HeaderIncluded, true); sck.IOControl(IOControlCode.ReceiveAll, new byte[4] { 1, 0, 0, 0 }, null); // Data Array // Use standart IP header (20byte) and the part of TCP header (14byte) for parsing byte[] buffer = new byte[34]; Action<IAsyncResult> OnReceive = null; OnReceive = (ar) => { Console.WriteLine("{0}\t{1}:{2}\t===>\t{3}:{4} ", buffer.Skip(9).First().ToProtocolString() , new IPAddress(BitConverter.ToUInt32(buffer, 12)).ToString() // Sender IP , ((ushort) IPAddress.NetworkToHostOrder(BitConverter.ToInt16(buffer, 20))).ToString() // Sender Port , new IPAddress(BitConverter.ToUInt32(buffer, 16)).ToString() // Reciever IP , ((ushort)IPAddress.NetworkToHostOrder(BitConverter.ToInt16(buffer, 22))).ToString() // Reciever Port ); buffer = new byte[34]; // Clean the buffer sck.BeginReceive(buffer, 0, 34, SocketFlags.None, new AsyncCallback(OnReceive), null); // Repeat listening }; sck.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None,new AsyncCallback(OnReceive), null); } } } <file_sep># Sniffer on C# with MySQL Database Intrusion Detection System - User's part One of the my first programms on C# This project is only the user part of my IDS. His main task is to collect data during user's session and load all information into MySQL Database. Work in progress ![Image alt](https://github.com/SeregaDeveloper/Sniffer_on_CS_with_MySQL_Database/blob/master/1.png)
29edb2266c4cf1ed55bf74c50bf31308ff87d3e3
[ "Markdown", "C#" ]
3
C#
SeregaDeveloper/Sniffer_on_CS_with_MySQL_Database
743a67418462c3229ffb9220b43f608ae451d33c
4dfab4d33f70da39828341be9e5296dcb99901b1
refs/heads/master
<repo_name>jacobbieker/aarhus_hackathon<file_sep>/Shoot_Stuff/Assets/Scripts/Game/ShieldController.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class ShieldController : MonoBehaviour { public BulletManager bulletManager; public float amountToLowerShield = 1f; public Text PointsText; public int Points; ShieldPosition currentShieldPosition; // Use this for initialization void Start () { if (bulletManager == null) Debug.Log("A bullet manager was not specified"); } // Update is called once per frame void Update () { if (Input.GetKeyDown("1")) MoveShield(ShieldPosition.Down); if (Input.GetKeyDown("2")) MoveShield(ShieldPosition.Up); } public void Setup() { Points = 0; PointsText.text = "Points:" + Points.ToString("d4"); } private void OnCollisionEnter(Collision collision) { // A bullet hit the player if (collision.collider.tag == "Projectile") { bulletManager.DestroyBullet(collision.collider.gameObject, 1.0f); collision.collider.gameObject.GetComponent<Rigidbody>().useGravity = true; // TODO: Add score points? Points += 10; PointsText.text ="Points:"+ Points.ToString("d4"); // TODO: Impact audio } } public enum ShieldPosition { Up, Down } //TODO animate shield void MoveShield(ShieldPosition positionToUse) { switch(positionToUse) { case ShieldPosition.Down: if (currentShieldPosition != ShieldPosition.Down) { gameObject.transform.Translate(0, -amountToLowerShield, 0); currentShieldPosition = ShieldPosition.Down; } break; case ShieldPosition.Up: if (currentShieldPosition != ShieldPosition.Up) { gameObject.transform.Translate(0, amountToLowerShield, 0); currentShieldPosition = ShieldPosition.Up; } break; } } } <file_sep>/Shoot_Stuff/Assets/GameController.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class GameController : MonoBehaviour { public BulletManager bulletManager; public bool GameRunning { get; set; } public PlayerController player; public ShieldController shield; // Use this for initialization void Start () { GameRunning = false; } // Update is called once per frame void Update () { } public void StartGame() { if (!GameRunning) { GameRunning = true; bulletManager.PopulateRandomEnemies(17f); player.Setup(); shield.Setup(); } } public void GameOver() { bulletManager.DeleteAll(); GameRunning = false; // throw new UnityException("Not implemented"); } } <file_sep>/Shoot_Stuff/Assets/NewGameButton.cs using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.EventSystems; public class NewGameButton : MonoBehaviour { public GameController gameController; // Use this for initialization void Start () { } // Update is called once per frame void Update () { } private void OnTriggerEnter(Collider other) { if (!gameController.GameRunning) { WaitAndStartGame(2f); gameController.StartGame(); Debug.Log("Game started"); } } IEnumerator WaitAndStartGame(float timeToWait) { yield return new WaitForSeconds(timeToWait); } } <file_sep>/Shoot_Stuff/Assets/Scripts/Game/Bullet.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class Bullet : MonoBehaviour { Rigidbody ownedRigidbody; public GameObject player; public float deleteAtDistance = 20f; // Use this for initialization void Start () { } // Update is called once per frame void Update () { } public void ShootBulletAtPlayer(float speed) { var x = transform.position.x - player.transform.position.x; var z = transform.position.z - player.transform.position.z; var directionToMove = new Vector3(-x * speed, 0f, -z * speed); ownedRigidbody.AddForce(directionToMove); } public void ShootBulletAtPlayer(float speed, GameObject playerToUse) { ownedRigidbody = gameObject.GetComponent<Rigidbody>(); var x = transform.position.x - playerToUse.transform.position.x; var z = transform.position.z - playerToUse.transform.position.z; var directionToMove = new Vector3((-x * speed), 0f, (-z * speed)); if (ownedRigidbody == null) { Debug.Log("Rigidbody is null"); return; } ownedRigidbody.AddForce(directionToMove); } } <file_sep>/Shoot_Stuff/Assets/Scripts/Game/Enemy.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class Enemy : MonoBehaviour { public int Health { get; set; } public Vector2 Position { get; set; } public bool isActive = true; // Use this for initialization void Start () { Health = 2; } // Update is called once per frame void Update () { } void DecreaseHealth(int amountToDecrease) { Health -= amountToDecrease; if (Health <= 0) { isActive = false; } } } <file_sep>/Shoot_Stuff/Assets/Scripts/Game/PlayerController.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class PlayerController : MonoBehaviour { public BulletManager bulletManager; public GameController gameController; public Text LivesText; public int _lives; // Use this for initialization void Start () { if (bulletManager == null) Debug.Log("A bullet manager was not specified"); _lives = 5; } // Update is called once per frame void Update () { } public void Setup() { resetup(); } public void resetup() { _lives = 5; LivesText.text = "Lives: *****"; } private void OnCollisionEnter(Collision collision) { // A bullet hit the player if (collision.collider.tag == "Projectile") { bulletManager.DestroyBullet(collision.collider.gameObject); _lives--; if (_lives < 0) { // TODO: Game over screen and stop game! gameController.GameOver(); } else { LivesText.text = "Lives: "; for (int i = 0; i < _lives; i++) { LivesText.text += "*"; } } // TODO: Hit/Damage audio } } } <file_sep>/Servo/ServoControl.py import _winreg as winreg import serial import time import struct from Tkinter import * import threading class ServoControl(object): def __init__(self,root): self.root = root self.InitWidgets() self.CenterWidget() self.InitSerial('COM7', 9200) def OnSlide(self,event): self.position = self.scale.get() self.label['text']='Motor at '+str(self.position)+' degrees' self.WriteToSerial(self.position) def InitWidgets(self): self.frame = Frame(self.root) self.frame.pack(side=LEFT, expand=1, fill=BOTH, anchor=CENTER) self.clabel = Label(self.frame, text='Using serial port: UNKNOWN') self.clabel.pack(side=TOP, expand=1, fill=X, anchor=CENTER) self.slabel = Label(self.frame, text='Status: UNKNOWN') self.slabel.pack(side=TOP, expand=1, fill=X, anchor=CENTER) self.label = Label(self.frame, text='Motor at 0 degrees') self.label.pack(side=TOP, expand=1, fill=X, anchor=CENTER) self.scale = Scale(self.frame, from_=-90, to=90, command=self.OnSlide, orient=HORIZONTAL) self.scale.pack(side=TOP, expand=1, fill=X, anchor=CENTER) return def CenterWidget(self): w = self.root.winfo_screenwidth() h = self.root.winfo_screenheight() #rootsize = tuple(int(_) for _ in self.root.geometry().split('+')[0].split('x')) rootsize = (250,100) x = w/2 - rootsize[0]/2 y = h/2 - rootsize[1]/2 self.root.geometry("%dx%d+%d+%d" % (rootsize + (x, y))) def VerifySerial(self): self.comports = [] self.compath = 'HARDWARE\\DEVICEMAP\\SERIALCOMM' key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, self.compath) for i in range(10): try: port = winreg.EnumValue(key,i)[1] try: serial.Serial(port) # test open except serial.serialutil.SerialException: print port," can't be openend" else: print port," Ready" self.comports.append(port) except EnvironmentError: break return def InitSerial(self, comport,baudrate): self.arduino = serial.Serial(port=comport, baudrate=baudrate, bytesize=serial.EIGHTBITS, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, timeout=0.1, xonxoff=0, rtscts=0, interCharTimeout=None) self.clabel['text']='Using serial port: '+ comport self.slabel['text']='Status: Ready' try: self.arduino.open() except Exception: if not self.arduino.isOpen(): self.slabel['text']='Status: Failed to open' def WriteToSerial(self,position): if not self.arduino.isOpen(): self.arduino.open() time.sleep(0.1) self.slabel['text']='Status: Writing...' position = 90 + position # Servo range 0-180; self.arduino.write(str(position).rjust(3,'0')) time.sleep(0.05) self.slabel['text']='Status: Open' def CloseSerial(self): self.arduino.close() def main(): root = Tk() application = ServoControl(root) root.title('ServoControl') root.mainloop() if __name__ == '__main__': main() <file_sep>/Shoot_Stuff/Assets/Scripts/Game/TranslateWorldSpace.cs /*============================================== * Translate World Space * Normalizes world positions and distances to * floats between 0 and 1 for use with Csound * =============================================*/ using System.Collections; using System.Collections.Generic; using UnityEngine; public static class TranslateWorldSpace { static float worldX = 0.0f; static float worldY = 0.0f; static float worldZ = 0.0f; // static float longestDistance = 0.0f; public static void setWorldSize(Vector3 worldSize) { worldX = worldSize.x; worldY = worldSize.y; worldZ = worldSize.z; // Calculate longest line that can be drawn in world box (square root of each side to the power of 2 // longestDistance = Mathf.Sqrt(Mathf.Pow(worldX, 2) + Mathf.Pow(worldY, 2) + Mathf.Pow(worldZ, 2)); } public enum Axis { x, y, z }; public static float normalizePosition(Axis axisToUse, float position) { switch (axisToUse) { case Axis.x: return (position + (worldX / 2)) / worldX; case Axis.y: return (position + (worldY / 2)) / worldY; case Axis.z: return (position + (worldZ / 2)) / worldZ; } Debug.Log("Couldn't normalize position - Returning 0f"); return 0.0f; } public static float normalizeDistance(float distance) { return Mathf.Clamp01((worldX - distance) / worldX); } } <file_sep>/Servo/ServoControl/ServoControl.ino #include <Servo.h> Servo myservo; // create servo object to control a servo // a maximum of eight servo objects can be created char var; char buffer[4]; int pos = 0; void setup() { Serial.begin(9600); myservo.attach(9); // attaches the servo on pin 9 to the servo object pinMode(8, OUTPUT); while (!Serial) { ; // wait for serial port to connect. Needed for Leonardo only } } void loop() { digitalWrite(8, HIGH); if (Serial.available() > 0){ for (int i=0; i <3; i++){ buffer[i] = 0; var = Serial.read(); if (isdigit(var)){ buffer[i] = var; } delay(5); } pos = atoi(buffer); // pos = -90; myservo.write(pos); Serial.println(buffer); delay(5); } } <file_sep>/physical_mapping/webcam_vision.py # CannyWebcam.py import argparse import cv2 import numpy as np import os import cv2.cv as cv from OSC import OSCClient, OSCMessage, OSCServer import _winreg as winreg import serial import time class ServoControl(object): def __init__(self): self.InitSerial('COM4', 9200) def VerifySerial(self): self.comports = [] self.compath = 'HARDWARE\\DEVICEMAP\\SERIALCOMM' key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, self.compath) for i in range(10): try: port = winreg.EnumValue(key, i)[1] try: serial.Serial(port) # test open except serial.serialutil.SerialException: print port, " can't be openend" else: print port, " Ready" self.comports.append(port) except EnvironmentError: break return def InitSerial(self, comport, baudrate): self.arduino = serial.Serial(port=comport, baudrate=baudrate, bytesize=serial.EIGHTBITS, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, timeout=0.1, xonxoff=0, rtscts=0, interCharTimeout=None) try: self.arduino.open() except Exception: if not self.arduino.isOpen(): print("Not Open") def WriteToSerial(self, position): if not self.arduino.isOpen(): self.arduino.open() time.sleep(0.1) print("Writing") position = 90 + position # Servo range 0-180; self.arduino.write(str(position).rjust(3, '0')) time.sleep(0.05) print('Status: Open') def CloseSerial(self): self.arduino.close() #import myo as libmyo; libmyo.init() #import time #import sys ''' class Listener(libmyo.DeviceListener): """ Listener implementation. Return False from any function to stop the Hub. """ interval = 0.05 # Output only 0.05 seconds def __init__(self, servocontrol): super(Listener, self).__init__() self.orientation = None self.pose = libmyo.Pose.rest self.emg_enabled = False self.locked = False self.rssi = None self.emg = None self.last_time = 0 self.current_orientation = None self.orientation_change = False self.servo_control = servocontrol def on_connect(self, myo, timestamp, firmware_version): myo.vibrate('short') myo.vibrate('short') myo.request_rssi() myo.request_battery_level() def on_rssi(self, myo, timestamp, rssi): self.rssi = rssi def on_pose(self, myo, timestamp, pose): if pose == libmyo.Pose.fist: self.emg_enabled = True elif pose == libmyo.Pose.fingers_spread: myo.set_stream_emg(libmyo.StreamEmg.disabled) self.emg_enabled = False self.emg = None self.pose = pose def on_orientation_data(self, myo, timestamp, orientation): self.current_orientation = orientation if self.orientation != self.current_orientation: self.orientation_change = True if self.orientation_change == True: change_x = self.orientation.x - self.current_orientation.x change_y = self.orientation.y - self.current_orientation.y if change_x < 0: self.servo_control.WriteToSerial(89) elif change_x > 0: self.servo_control.WriteToSerial(-89) self.current_orientation = self.orientation def on_accelerometor_data(self, myo, timestamp, acceleration): pass def on_gyroscope_data(self, myo, timestamp, gyroscope): pass def on_emg_data(self, myo, timestamp, emg): self.emg = emg def on_unlock(self, myo, timestamp): self.locked = False def on_lock(self, myo, timestamp): self.locked = True def on_event(self, kind, event): """ Called before any of the event callbacks. """ def on_event_finished(self, kind, event): """ Called after the respective event callbacks have been invoked. This method is *always* triggered, even if one of the callbacks requested the stop of the Hub. """ def on_pair(self, myo, timestamp, firmware_version): """ Called when a Myo armband is paired. """ def on_unpair(self, myo, timestamp): """ Called when a Myo armband is unpaired. """ def on_disconnect(self, myo, timestamp): """ Called when a Myo is disconnected. """ def on_arm_sync(self, myo, timestamp, arm, x_direction, rotation, warmup_state): """ Called when a Myo armband and an arm is synced. """ def on_arm_unsync(self, myo, timestamp): """ Called when a Myo armband and an arm is unsynced. """ def on_battery_level_received(self, myo, timestamp, level): """ Called when the requested battery level received. """ def on_warmup_completed(self, myo, timestamp, warmup_result): """ Called when the warmup completed. """ ''' ################################################################################################### def main(): client = OSCClient() client.connect(("192.168.137.192", 9001)) client.connect(("192.168.137.1", 9001)) print(str(client)) server = OSCServer(("localhost", 7110)) server.timeout = 0 run = True # Setup Arduino use_arduino = True if use_arduino: servo_controller = ServoControl() # try: # hub = libmyo.Hub() #except MemoryError: # print("Myo Hub could not be created. Make sure Myo Connect is running.") # return #hub.set_locking_policy(libmyo.LockingPolicy.none) #myo_listener = Listener(servo_controller) #hub.run(1000, myo_listener) #Setup Myo # this method of reporting timeouts only works by convention # that before calling handle_request() field .timed_out is # set to False def handle_timeout(self): self.timed_out = True # funny python's way to add a method to an instance of a class import types server.handle_timeout = types.MethodType(handle_timeout, server) def user_callback(path, tags, args, source): # which user will be determined by path: # we just throw away all slashes and join together what's left user = ''.join(path.split("/")) # tags will contain 'fff' # args is a OSCMessage with data # source is where the message came from (in case you need to reply) print ("Now do something with", user, args[2], args[0], 1 - args[1]) server.addMsgHandler("/unity", user_callback) # user script that's called by the game engine every frame def each_frame(): # clear timed_out flag server.timed_out = False # handle all pending requests then return while not server.timed_out: server.handle_request() capWebcam = cv2.VideoCapture(0) # declare a VideoCapture object and associate to webcam, 0 => use 1st webcam if capWebcam.isOpened() == False: # check if VideoCapture object was associated to webcam successfully print "error: capWebcam not accessed successfully\n\n" # if not, print error message to std out os.system("pause") # pause until user presses a key so user can see error message return # and exit function (which exits program) while cv2.waitKey(1) != 27 and capWebcam.isOpened(): # until the Esc key is pressed or webcam connection is lost blnFrameReadSuccessfully, imgOriginal = capWebcam.read() # read next frame if not blnFrameReadSuccessfully or imgOriginal is None: # if frame was not read successfully print "error: frame not read from webcam\n" # print error message to std out os.system("pause") # pause until user presses a key so user can see error message break # exit while loop (which exits program) imgGrayscale = cv2.cvtColor(imgOriginal, cv2.COLOR_BGR2GRAY) # convert to grayscale imgBlurred = cv2.GaussianBlur(imgGrayscale, (5, 5), 0) # blur imgCanny = cv2.Canny(imgBlurred, 100, 200) # get Canny edges cv2.namedWindow("imgOriginal", cv2.WINDOW_NORMAL) # create windows, use WINDOW_AUTOSIZE for a fixed window size cv2.namedWindow("imgCanny", cv2.WINDOW_NORMAL) # or use WINDOW_NORMAL to allow window resizing # detect circles in the image circles = cv2.HoughCircles(imgCanny, cv.CV_HOUGH_GRADIENT, 1, 260, param1=30, param2=10, minRadius=0, maxRadius=0) # print circles # ensure at least some circles were found osc_circles = [] if circles is not None: # convert the (x, y) coordinates and radius of the circles to integers circles = np.round(circles[0, :]).astype("int") # loop over the (x, y) coordinates and radius of the circles for (x, y, r) in circles: # time.sleep(0.5) #print "Column Number: " #print x #print "Row Number: " #print y #print "Radius is: " #print r osc_circles.append((x,y)) cv2.imshow("imgOriginal", imgOriginal) # show windows cv2.imshow("imgCanny", imgCanny) message = OSCMessage("/cam") message.append(osc_circles) client.send(message) if use_arduino: if osc_circles is not None and osc_circles != []: if osc_circles[0][0] > 180: servo_controller.WriteToSerial(-8) else: servo_controller.WriteToSerial(9) print(message) # end while cv2.destroyAllWindows() # remove windows from memory if use_arduino: print("Shutting down hub...") #hub.shutdown() return ################################################################################################### if __name__ == "__main__": main()<file_sep>/Shoot_Stuff/Assets/Scripts/Game/BulletManager.cs using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class BulletManager : MonoBehaviour { public GameObject bulletPrefab; List<Bullet> bullets = new List<Bullet>(); public int maxBullets = 1; public float deleteAtDistance = 10; public GameObject enemyPrefab; List<Enemy> enemies = new List<Enemy>(); int initialEnemies = 4; public GameObject player; bool spawnBulletsRandomInterval = true; // Use this for initialization void Start () { } // Update is called once per frame void Update () { float randX = UnityEngine.Random.Range(1f, 10f); float randZ = UnityEngine.Random.Range(1f, 10f); if (spawnBulletsRandomInterval) { if (bullets.Count < maxBullets) { int rand_idx = UnityEngine.Random.Range(0, enemies.Count); if (enemies.Count > 0) SpawnBulletAtPosition(enemies[rand_idx].transform.position); } } if (bullets.Count > 0) { List<Bullet> bulletsToRemove = new List<Bullet>(); foreach (var bullet in bullets) { float distanceToPlayer = Vector3.Distance(bullet.transform.position, player.transform.position); if (distanceToPlayer > deleteAtDistance) { bulletsToRemove.Add(bullet); DestroyImmediate(bullet.gameObject); } } foreach (var bulletToRemove in bulletsToRemove) { bullets.Remove(bulletToRemove); } } if (enemies.Count > 0) { List<Enemy> enemiesToRemove = new List<Enemy>(); foreach (var enemy in enemies) { if (!enemy.isActive) { enemiesToRemove.Add(enemy); Destroy(enemy.gameObject); } } foreach (var enemyToRemove in enemiesToRemove) { enemies.Remove(enemyToRemove); } } } internal void DeleteAll() { foreach (var item in enemies) { Destroy(item.gameObject); } enemies.Clear(); } void SpawnBulletAtPosition(Vector3 position) { GameObject goBullet = Instantiate(bulletPrefab, position, new Quaternion()); Bullet bullet = goBullet.GetComponent<Bullet>(); bullet.ShootBulletAtPlayer(20f, player); bullets.Add(bullet); } public void PopulateRandomEnemies(float distanceToPlayer) { bool[] initialEnemie = new bool[18]; for (int i = 0; i < initialEnemies; i++) { float angle; do { angle = UnityEngine.Random.Range(0f, 360f); } while (!EnemieIsgod(initialEnemie,angle)); Debug.Log((int)angle/20); float randX = distanceToPlayer * Mathf.Cos(angle); float randZ = distanceToPlayer * Mathf.Sin(angle); GameObject goEnemy = Instantiate(enemyPrefab, new Vector3(randX, 1.5f, randZ), new Quaternion()); Enemy enemy = goEnemy.GetComponent<Enemy>(); enemies.Add(enemy); } } private bool EnemieIsgod(bool[] initialEnemie, float angle ) { int binID = (int)angle / 20; int binlow = binID == 0 ? 17 : binID - 1; int binhigh = binID == 17 ? 0 : binID + 1; if (initialEnemie[binID] || initialEnemie[binlow] || initialEnemie[binhigh]) { return false; } initialEnemie[binID] = true; return true; } public void DestroyBullet(GameObject bulletToDestroy) { Bullet bullet = bulletToDestroy.GetComponent<Bullet>(); Destroy(bulletToDestroy); bullets.Remove(bullet); } public void DestroyBullet(GameObject bulletToDestroy, float timeToWait) { Bullet bullet = bulletToDestroy.GetComponent<Bullet>(); Destroy(bulletToDestroy, timeToWait); bullets.Remove(bullet); } } <file_sep>/Shoot_Stuff/Assets/Scripts/Game/WorldSpace.cs /*============================================== * World space * Scales a box and reverses normals to generate * a room space of a given size * =============================================*/ using System.Collections; using System.Collections.Generic; using UnityEngine; [RequireComponent(typeof(MeshFilter))] [RequireComponent(typeof(MeshCollider))] public class WorldSpace : MonoBehaviour { public Vector3 size; Mesh room; MeshCollider roomCollider; // Use this for initialization void Start () { room = GetComponent<MeshFilter>().mesh; SetRoomSize(size); room = ReverseNormals(room); roomCollider = GetComponent<MeshCollider>(); roomCollider.sharedMesh = room; } // Update is called once per frame void Update () { } void SetRoomSize(Vector3 roomSize) { this.transform.localScale = size; TranslateWorldSpace.setWorldSize(size); } Mesh ReverseNormals(Mesh meshToReverse) { Mesh mesh = meshToReverse; Vector3[] normals = mesh.normals; for (int i = 0; i < normals.Length; i++) normals[i] = -normals[i]; mesh.normals = normals; for (int m = 0; m < mesh.subMeshCount; m++) { int[] triangles = mesh.GetTriangles(m); for (int i = 0; i < triangles.Length; i += 3) { int temp = triangles[i + 0]; triangles[i + 0] = triangles[i + 1]; triangles[i + 1] = temp; } mesh.SetTriangles(triangles, m); } return mesh; } }
09f0958c3abbe0967f1ae6cd0b10b1c5a00079cb
[ "C#", "Python", "C++" ]
12
C#
jacobbieker/aarhus_hackathon
03aa017bd61e3d6c5e200f25b50b2a7df19ca39d
a0f7be0f1b7ebfe1515b6322dbda4ea4286f1b7f
refs/heads/master
<repo_name>Jo-jangho/Stick<file_sep>/c_popol3/popol3/popol3/logicproc.h #ifndef __LOGIC_PROC_H__ #define __LOGIC_PROC_H__ /* enum */ enum{ state_ready, state_play }; /* var */ int gamestate = state_ready; long readysec = 0; long readycount = 4; /* function */ void ready_go(); void initEnemy(); void moveEnemy(); void SetPlayerSize(); void SetEnemy(Creature* pObj); #endif<file_sep>/c_popol3/popol3/popol3/keyproc.c #include <stdio.h> #include <conio.h> #include <Windows.h> #include "main.h" #include "drawproc.h" void KeyProcess(int scene) { char ch = 0;; while (kbhit()) { ch = getch(); } switch (scene) { case TITLE: if (ch == SPACEBAR) { sceneState = MENU; } if (ch == 'q') { exit(1); } break; case MENU: if (ch == SPACEBAR) { sceneState = GAME; gamestate = state_ready; InitData(); } if (ch == 't') { sceneState = TUTORIAL; } if (ch == 'q') { exit(1); } break; case TUTORIAL: break; case GAME: if (ch == LEFTKEY || ch == 'a') { player.m_posx--; if (player.m_posx <= 1) //경계값을 설정 player.m_posx = 1; //해당 경계값을 넘을 수 없도록 } if (ch == RIGHTKEY || ch == 'd') { player.m_posx++; if (player.m_posx >= WIDTH - player.m_size)//경계값을 설정 player.m_posx = WIDTH - player.m_size; //해당 경계값을 넘을 수 없도록 } break; case STAGEOVER: if (ch == SPACEBAR) { sceneState = TITLE; } if (ch == 'q') { exit(1); } break; } }<file_sep>/c_popol3/popol3/popol3/main.h #ifndef _MAIN_H_ #define _MAIN_H_ /* menu define */ #define TITLE 1 #define MENU 2 #define TUTORIAL 3 #define GAME 4 #define STAGEOVER 5 /* size */ #define D_SIZE 10 #define WIDTH 40 #define HEIGHT 25 /* key value define */ #define SPACEBAR 32 #define LEFTKEY 75 #define RIGHTKEY 77 /* color define */ #define DARKNESS_BLUE 1 #define DARKNESS_GREEN 2 #define DARKNESS_BLUISH_GREEN 3 #define DARKNESS_RED 4 #define DARKNESS_PINK 5 #define DARKNESS_REDCLAY 6 #define IVORY 7 #define GRAY 8 #define BLUE 9 #define GREEN 10 #define BLUISH_GREEN 11 #define RED 12 #define PINK 13 #define YELLOW 14 #define WHITE 15 /* etc */ #define MAX_TIME 20 #define LEFT 1 #define RIGHT 2 /* var */ int sceneState; int hi_score; /* time var*/ long sec, milsec; long curTime, oldTime; long elapsedTime; /* Creature*/ typedef struct S_Creature { char m_shape[12]; // 모양 int m_color; // 색 int m_posx; // x좌표 int m_posy; // y좌표 int m_isAlive; // 생존 여부 int m_size; // 가로 길이 int m_score; // 점수 }Creature; /* Creature define */ Creature circle[D_SIZE]; Creature player; /* function */ void KeyProcess(int scene); void LogicProcess(int scene); void DrawProcess(int scene); void InitData(); void Init_val(); void init_creature(Creature *cr, char* str, int posx, int posy, int color, int size); void save_data(); void load_data(); void SetScore(Creature *pObj, int color); #endif<file_sep>/c_popol3/README.txt PREZI https://prezi.com/grvzdheb1be-/presentation/<file_sep>/c_popol3/popol3/popol3/drawproc.c #include <stdio.h> #include "grpengine.h" #include "main.h" #include "drawproc.h" void DrawProcess(int scene) { switch (scene) { case TITLE: t_design(); break; case MENU: m_design(); break; case TUTORIAL: Tuto(); break; case GAME: map_box(); draw_number(); DrawStage(); Ball(); break; case STAGEOVER: Ending(); break; } } void DrawStage() { gotoxy(2, 3); printf("score : %d", player.m_score); gotoxy(30, 3); printf("time : %ld", MAX_TIME - sec); // land draw for (int i = 0; i < WIDTH; i++) { gotoxy(i, HEIGHT); printf("-"); } // circle draw for (int i = 0; i < D_SIZE; i++) { if (circle[i].m_isAlive == 1) drawchar(&circle[i]); } // player draw drawchar(&player); } void drawchar(Creature *cr) { if (cr->m_isAlive == 1) { gotoxy(cr->m_posx, cr->m_posy); SetColor(cr->m_color); printf("%s", cr->m_shape); SetColor(YELLOW); } } void draw_number() { if (gamestate == state_ready) { //초를 가지고 계산 (logic) if (readycount > 0) { gotoxy((WIDTH / 2) - 2, 5); printf("Ready"); gotoxy(WIDTH / 2, 6); printf("%ld", readycount); } if (readycount <= 0) { gotoxy((WIDTH / 2) - 2, 7); printf("go!!!"); } } } void map_box() { for (int i = 1; i < WIDTH; i++) { gotoxy(i, 1); printf("-"); } for (int i = 1; i < HEIGHT; i++) { gotoxy(0, i); printf("│"); } for (int i = 1; i < HEIGHT; i++) { gotoxy(WIDTH, i); printf("│"); } for (int i = 0; i < WIDTH; i++) { gotoxy(i, HEIGHT); printf("-"); } gotoxy(0, 1); printf("┌"); gotoxy(WIDTH, 1); printf("┐"); gotoxy(0, HEIGHT); printf("└"); gotoxy(WIDTH, HEIGHT); printf("┘"); } void t_design() { map_box(); SetColor(WHITE); gotoxy(9, 3); printf("#"); gotoxy(10, 3); printf("#"); gotoxy(11, 3); printf("#"); gotoxy(13, 3); printf("#"); gotoxy(17, 3); printf("#"); gotoxy(18, 3); printf("#"); gotoxy(19, 3); printf("#"); gotoxy(21, 3); printf("#"); gotoxy(23, 3); printf("#"); gotoxy(26, 3); printf("#"); gotoxy(27, 3); printf("#"); gotoxy(28, 3); printf("#"); gotoxy(29, 3); printf("#"); gotoxy(31, 3); printf("#"); //-------------------------------------------------------------------------- gotoxy(9, 4); printf("#"); gotoxy(11, 4); printf("#"); gotoxy(13, 4); printf("#"); gotoxy(14, 4); printf("#"); gotoxy(17, 4); printf("#"); gotoxy(21, 4); printf("#"); gotoxy(22, 4); printf("#"); gotoxy(23, 4); printf("#"); gotoxy(29, 4); printf("#"); gotoxy(31, 4); printf("#"); //-------------------------------------------------------------------------- gotoxy(9, 5); printf("#"); gotoxy(10, 5); printf("#"); gotoxy(11, 5); printf("#"); gotoxy(13, 5); printf("#"); gotoxy(17, 5); printf("#"); gotoxy(18, 5); printf("#"); gotoxy(19, 5); printf("#"); gotoxy(21, 5); printf("#"); gotoxy(23, 5); printf("#"); gotoxy(29, 5); printf("#"); gotoxy(31, 5); printf("#"); //-------------------------------------------------------------------------- gotoxy(21, 6); printf("#"); gotoxy(23, 6); printf("#"); gotoxy(28, 6); printf("#"); gotoxy(31, 6); printf("#"); //-------------------------------------------------------------------------- gotoxy(11, 7); printf("#"); gotoxy(12, 7); printf("#"); gotoxy(13, 7); printf("#"); gotoxy(27, 7); printf("#"); gotoxy(31, 7); printf("#"); //-------------------------------------------------------------------------- gotoxy(13, 8); printf("#"); gotoxy(31, 8); printf("#"); gotoxy(13, 9); printf("#"); //-------------------------------------------------------------------------- SetColor(YELLOW); gotoxy(23, 9); printf("작아져라!"); for (int i = 2; i < WIDTH; i++) { SetColor(YELLOW); gotoxy(i, 11); printf("-"); } SetColor(BLUE); gotoxy(11, 17); printf("●"); gotoxy(11, 15); printf("│"); gotoxy(11, 13); printf("│"); SetColor(RED); gotoxy(20, 19); printf("●"); gotoxy(20, 17); printf("│"); gotoxy(20, 15); printf("│"); gotoxy(20, 13); printf("│"); SetColor(GREEN); gotoxy(29, 15); printf("●"); gotoxy(29, 13); printf("│"); SetColor(WHITE); gotoxy(17, 20); printf("========"); SetColor(YELLOW); gotoxy(10, 23); printf("Please, Coin Insert !!"); } void Ending() { map_box(); SetColor(YELLOW); gotoxy(16, 7); printf("Game Over!"); gotoxy(14, 11); printf("High Score:%d", hi_score); gotoxy(14, 13); printf("Score:%d", player.m_score); for (int i = 8; i < 34; i++) { gotoxy(i, 9); printf("-"); } for (int i = 10; i < 15; i++) { gotoxy(6, i); printf("│"); } for (int i = 10; i < 15; i++) { gotoxy(34, i); printf("│"); } for (int i = 8; i < 34; i++) { gotoxy(i, 15); printf("-"); } gotoxy(6, 9); printf("┌"); gotoxy(34, 9); printf("┐"); gotoxy(6, 15); printf("└"); gotoxy(34, 15); printf("┘"); SetColor(YELLOW); gotoxy(6, 22); printf("스페이스바를 누르면 처음으로!!"); } void Tuto() { int b_posx = 0, b_posy = 0; int r_posx = 0, r_posy = 10; int g_posx = 0, g_posy = 20; int s_posx = 0, s_posy = 0, s_state = RIGHT; int bLoop = 1; while (bLoop) { ClearScreen(); char ch = 0;; while (kbhit()) { ch = getch(); if (ch == SPACEBAR) { bLoop = 0; sceneState = MENU; } } SetColor(YELLOW); map_box(); gotoxy(3, 3); printf("score:%d", player.m_score); gotoxy(29, 3); printf("time: %ld. %ld", sec, milsec); b_posy++; if (b_posy >= HEIGHT - 1) { b_posy = 1; } SetColor(BLUE); gotoxy(10, b_posy); printf("●"); r_posy++; if (r_posy >= HEIGHT - 1) { r_posy = 1; } SetColor(RED); gotoxy(20, r_posy); printf("●"); g_posy++; if (g_posy >= HEIGHT - 1) { g_posy = 1; } SetColor(GREEN); gotoxy(30, g_posy); printf("●"); switch (s_state) { case LEFT: s_posx--; if (s_posx <= 1) { s_state = RIGHT; } break; case RIGHT: s_posx++; if (s_posx >= WIDTH - 8) { s_state = LEFT; } break; } SetColor(WHITE); gotoxy(1 + s_posx, HEIGHT - 1); printf("========"); Ball(); SetColor(YELLOW); gotoxy(45, 10); printf("Menu -> Spacebar"); Sleeped(100); } } void m_design() { map_box(); SetColor(WHITE); gotoxy(9, 3); printf("#"); gotoxy(10, 3); printf("#"); gotoxy(11, 3); printf("#"); gotoxy(13, 3); printf("#"); gotoxy(17, 3); printf("#"); gotoxy(18, 3); printf("#"); gotoxy(19, 3); printf("#"); gotoxy(21, 3); printf("#"); gotoxy(23, 3); printf("#"); gotoxy(26, 3); printf("#"); gotoxy(27, 3); printf("#"); gotoxy(28, 3); printf("#"); gotoxy(29, 3); printf("#"); gotoxy(31, 3); printf("#"); //-------------------------------------------------------------------------- gotoxy(9, 4); printf("#"); gotoxy(11, 4); printf("#"); gotoxy(13, 4); printf("#"); gotoxy(14, 4); printf("#"); gotoxy(17, 4); printf("#"); gotoxy(21, 4); printf("#"); gotoxy(22, 4); printf("#"); gotoxy(23, 4); printf("#"); gotoxy(29, 4); printf("#"); gotoxy(31, 4); printf("#"); //-------------------------------------------------------------------------- gotoxy(9, 5); printf("#"); gotoxy(10, 5); printf("#"); gotoxy(11, 5); printf("#"); gotoxy(13, 5); printf("#"); gotoxy(17, 5); printf("#"); gotoxy(18, 5); printf("#"); gotoxy(19, 5); printf("#"); gotoxy(21, 5); printf("#"); gotoxy(23, 5); printf("#"); gotoxy(29, 5); printf("#"); gotoxy(31, 5); printf("#"); //-------------------------------------------------------------------------- gotoxy(21, 6); printf("#"); gotoxy(23, 6); printf("#"); gotoxy(28, 6); printf("#"); gotoxy(31, 6); printf("#"); //-------------------------------------------------------------------------- gotoxy(11, 7); printf("#"); gotoxy(12, 7); printf("#"); gotoxy(13, 7); printf("#"); gotoxy(27, 7); printf("#"); gotoxy(31, 7); printf("#"); //-------------------------------------------------------------------------- gotoxy(13, 8); printf("#"); gotoxy(31, 8); printf("#"); gotoxy(13, 9); printf("#"); //-------------------------------------------------------------------------- for (int i = 2; i < WIDTH; i++) { SetColor(YELLOW); gotoxy(i, 11); printf("-"); } SetColor(BLUE); gotoxy(11, 15); printf("●"); SetColor(RED); gotoxy(20, 17); printf("●"); SetColor(GREEN); gotoxy(29, 13); printf("●"); SetColor(WHITE); gotoxy(17, 18); printf("========"); SetColor(YELLOW); gotoxy(10, 20); printf("Game Start -> Spacebar"); gotoxy(10, 22); printf("Tutorial -> T"); } void Ball() { SetColor(BLUE); gotoxy(45, 4); printf("● : 50점"); SetColor(RED); gotoxy(45, 6); printf("● : 100점"); SetColor(GREEN); gotoxy(45, 8); printf("● : 150점"); }<file_sep>/README.md # 막대기 작아져라! ## 20초내에 아이템을 먹어서 최고 점수를 노려라! Left : 'a' or '←' Right : 'd' or '→' ![error](https://github.com/Jo-jangho/GitTest_Window/blob/master/c_popol3/Resourse/Scene/title.PNG?raw=true) <file_sep>/c_popol3/popol3/popol3/drawproc.h #include "main.h" #ifndef __DRAW_PROC_H__ #define __DRAW_PROC_H__ /* enum */ extern enum{ state_ready, state_play }; /* var */ extern int gamestate; extern long readycount; /* function */ void DrawStage(); void drawchar(Creature *cr); void draw_number(); void map_box(); void t_design(); void Ending(); void Tuto(); void m_design(); void Ball(); #endif<file_sep>/c_popol3/popol3/popol3/grpengine.h #include<stdio.h> #include<conio.h> #include<stdlib.h> #include<Windows.h> #include<time.h> #ifndef __GRPENGINE_H_ #define __GRPENGINE_H_ void ClearScreen(); void Sleeped(int mil_second); void SetColor(unsigned short color); void gotoxy(int x, int y); #endif<file_sep>/c_popol3/popol3/popol3/main.c // 게임제작의 기능.. // 반복문이 기본적으로동작... // 반복문 내부 3요소. // 키입력, 로직구현, 화면에 출력 #include <stdio.h> #include <time.h> #include "main.h" #include "grpengine.h" int main(void) { sceneState = TITLE; InitData(); while (1) { //화면을지움 ClearScreen(); /* time */ curTime = clock(); elapsedTime = curTime - oldTime; oldTime = curTime; // 로직처리 KeyProcess(sceneState); LogicProcess(sceneState); DrawProcess(sceneState); Sleeped(100); } return 0; } void InitData() { for (int i = 0; i < D_SIZE; i++) { init_creature(&circle[i], "●", 0, 0, BLUE, 1); circle[i].m_isAlive = 0; } /* init player */ init_creature(&player, "===========", (WIDTH / 2) - 4, HEIGHT - 1, WHITE, 11); Init_val(); } void Init_val() { hi_score = 0; sec = 0; milsec = 0; curTime = oldTime = clock(); load_data(); } void init_creature(Creature *cr, char* str, int posx, int posy, int color, int size) { cr->m_posx = posx; cr->m_posy = posy; cr->m_isAlive = 1; strcpy(cr->m_shape, str); cr->m_size = size; cr->m_color = color; SetScore(cr, color); } void SetScore(Creature *pObj, int color) { switch (color) { case BLUE: pObj->m_score = 50; break; case RED: pObj->m_score = 100; break; case GREEN: pObj->m_score = 150; break; default: pObj->m_score = 0; break; } } void save_data() { if (player.m_score <= hi_score) { return; } FILE *fp; fp = fopen("save.dat", "w"); if (fp == NULL) { return; } hi_score = player.m_score; fwrite(&player.m_score, sizeof(int), 1, fp); fclose(fp); } void load_data() { FILE *fp; fp = fopen("save.dat", "r"); if (fp == NULL) { return; } fread(&hi_score, sizeof(int), 1, fp); fclose(fp); }<file_sep>/c_popol3/popol3/popol3/logicproc.c #include <stdio.h> #include <time.h> #include "main.h" #include "logicproc.h" void LogicProcess(int scene) { switch (scene) { case TITLE: break; case MENU: break; case GAME: ready_go(); if (gamestate == state_play) { //----- 시간계산----------------- milsec += elapsedTime; if (milsec >= 1000) { milsec = 0; sec++; if (sec >= MAX_TIME) { sceneState = STAGEOVER; } } //------- moveEnemy(); for (int i = 0; i < D_SIZE; i++) { if (circle[i].m_posy >= player.m_posy - 1) { if (circle[i].m_posx >= player.m_posx && circle[i].m_posx <= (player.m_posx + player.m_size)) { SetEnemy(&circle[i]); player.m_score += circle[i].m_score; SetPlayerSize(); } } } } break; case TUTORIAL: break; case STAGEOVER: save_data(); break; } } void SetPlayerSize() { int score = player.m_score; if (player.m_score >= 300 && player.m_score < 800) { strcpy(player.m_shape, "========="); player.m_size = 9; } else if (player.m_score >= 800 && player.m_score < 1200) { strcpy(player.m_shape, "======="); player.m_size = 7; } else if (player.m_score >= 1200 && player.m_score < 1800) { strcpy(player.m_shape, "====="); player.m_size = 5; } else if (player.m_score >= 1800 && player.m_score < 2500) { strcpy(player.m_shape, "==="); player.m_size = 3; } else if (player.m_score >= 2500) { strcpy(player.m_shape, "=="); player.m_size = 2; } } void ready_go() { if (gamestate == state_ready) { readysec += elapsedTime; if (readysec >= 1000) //1초가 넘을때마나 { readycount--; //카운트값을 삭제하고 readysec = 0; //프레임별 시간을 초기화 } } if (readycount <= -1) { readysec = 0; readycount = 4; initEnemy(); gamestate = state_play; } } void initEnemy() { /* init circle */ srand(time(NULL)); for (int i = 0; i < D_SIZE; i++) { SetEnemy(&circle[i]); } } void SetEnemy(Creature* pObj) { /* var */ int rnd_color = 0; int rnd_x = 0; int rnd_y = 0; /* Set Color */ rnd_color = rand() % 3; rnd_x = rand() % (WIDTH - 2) + 2; rnd_y = rand() % 20 - 20; switch (rnd_color) { case 0: rnd_color = BLUE; break; case 1: rnd_color = RED; break; case 2: rnd_color = GREEN; break; } pObj->m_posx = rnd_x; pObj->m_posy = rnd_y; pObj->m_color = rnd_color; pObj->m_isAlive = 0; SetScore(pObj, rnd_color); } void moveEnemy() { for (int i = 0; i < D_SIZE; i++) { circle[i].m_posy++; if (circle[i].m_posy >= 4) { circle[i].m_isAlive = 1; } if (circle[i].m_posy >= HEIGHT && circle[i].m_isAlive == 1) { SetEnemy(&circle[i]); } } }
75f4cbb13412fb5a694079ba04fdddb357630cc0
[ "Markdown", "C", "Text" ]
10
C
Jo-jangho/Stick
0dd7678b041e68ad5d1881edb09c6f2e373a70de
94b94377757adb62e9c89809d063b7f51001119d
refs/heads/main
<repo_name>kimu2370/side_myday<file_sep>/src/pages/main.js import React, {useCallback} from 'react'; import {useHistory, useLocation} from 'react-router-dom'; import styled from 'styled-components'; import Layout from 'components/parts/Layout'; import Header from 'components/parts/Header'; import Chart from 'components/Chart'; import ScheduleList from 'components/ScheduleList'; const Main = () => { const history = useHistory(); const moveToPage = useCallback(() => { history.push({ pathname: '/register', }); }, [history]); return ( <Layout> <Header> <Title>My Day</Title> <SubTitle>March 13</SubTitle> <EditIcon onClick={moveToPage} src="./img/edit.svg" /> </Header> <Chart /> <ScheduleList /> </Layout> ); }; export default Main; const Title = styled.h1` font-size: 34px; `; const SubTitle = styled.h4` font-size: 18px; `; const EditIcon = styled.img` cursor: pointer; position: absolute; width: 30px; height: 30px; top: 7px; right: 0; `; <file_sep>/src/components/parts/Layout.js import React from 'react'; import styled from 'styled-components'; import {iphone11} from 'theme'; const Layout = ({children}) => { return ( <Wrapper> <ViewContainer>{children}</ViewContainer> </Wrapper> ); }; export default Layout; const Wrapper = styled.div` width: 100vw; height: 100vh; background-color: lightgray; overflow: hidden; `; const ViewContainer = styled.div` ${iphone11.config}; height: 100%; position: relative; top: 50%; left: 50%; transform: translate(-50%, -50%); height: calc(100% - 20px); padding: 1rem; border-radius: 1rem; background-color: #ffffff; `; <file_sep>/src/components/Form/Form.js import React from 'react'; import styled from 'styled-components'; import {color} from 'theme'; const Form = () => { return ( <Container> <Time> <InputBox> <Label>Start time</Label> <Input /> </InputBox> <InputBox> <Label>End time</Label> <Input /> </InputBox> </Time> <InputBox> <Label> <Img src="./img/test.svg" alt="" /> Content </Label> <Input /> </InputBox> <InputBox> <Label> <Img src="./img/test.svg" alt="" /> Category </Label> <Input /> </InputBox> <InputBox> <Label>Memo</Label> <TextArea /> </InputBox> </Container> ); }; export default Form; const Container = styled.div` background-color: rgba(0, 0, 0, 0.05); border-radius: 15px; `; const Time = styled.div` display: flex; `; const InputBox = styled.div` padding: 1rem; `; const Label = styled.label` color: ${color.basic}; font-size: 18px; font-weight: bold; line-height: 21px; `; const Img = styled.img.attrs(() => ({ alt: 'image', }))` padding: 7px 7px 0 0; filter: invert(0%) sepia(0%) saturate(0%) hue-rotate(196deg) brightness(0%) contrast(105%); `; const Input = styled.input.attrs(() => ({ type: 'text', }))` width: 100%; border: none; outline: none; border-radius: 15px; margin-top: 5px; padding: 1rem; font-size: 16px; text-align: center; `; const TextArea = styled.textarea` display: block; width: 100%; height: 90px; border: none; outline: none; resize: none; border-radius: 15px; padding: 1rem; `; <file_sep>/src/components/parts/Header.js import React from 'react'; import styled from 'styled-components'; const Header = ({children, ...p}) => { return <Wrapper {...p}>{children}</Wrapper>; }; export default Header; const Wrapper = styled.header` position: relative; `; <file_sep>/src/components/TextModal/index.js import TextModal from './TextModal'; export default TextModal; <file_sep>/src/components/ScheduleList/ListBox.js import React, {useState, useCallback, useEffect} from 'react'; import styled from 'styled-components'; import moment from 'moment'; import TextModal from 'components/TextModal'; const ListBox = ({title, list}) => { const [memo, setMemo] = useState(''); const [open, setOpen] = useState(false); const modalHandler = useCallback(item => { setOpen(true); setMemo(item.memo); // console.log(item.memo); }, []); return ( <Container> <Wrapper> <Title>{title}</Title> {list.map((item, index) => ( <ItemBox key={index}> <Img src="./img/test.svg" alt="" /> <ContentBox> <Time>{`${moment(item.start_time).format('HH:mm')} - ${moment( item.end_time ).format('HH:mm')}`}</Time> <Text onClick={() => modalHandler(item)}>{item.content}</Text> </ContentBox> </ItemBox> ))} <TextModal open={open} setOpen={setOpen} memo={memo || ''} /> </Wrapper> </Container> ); }; export default ListBox; const Container = styled.section` display: flex; flex-direction: column; border-radius: 5px; box-shadow: 0 3px 6px rgb(0 0 0 / 16%), 0 3px 6px rgb(0 0 0 / 23%); margin: 25px 5px; padding: 0 32px 0 22px; `; const Wrapper = styled.div` display: flex; flex-direction: column; margin-bottom: 20px; `; const Title = styled.h2` font-size: 24px; padding: 9px 0; `; const ItemBox = styled.div` display: flex; padding: 7px 0; `; const Img = styled.img.attrs(() => ({ alt: 'image', }))` padding: 7px 10px 0 0; `; const ContentBox = styled.div` width: 100%; `; const Time = styled.div` font-weight: bold; font-size: 10px; line-height: 12px; color: #007aff; padding: 0 10px; `; const Text = styled.div` cursor: pointer; font-weight: bold; font-size: 12px; line-height: 14px; background: rgba(0, 0, 0, 0.05); border-radius: 10px; padding: 6px 10px 5px 10px; width: 100%; :hover { transition: all 250ms ease; transform: scale(1.02); background: rgba(0, 0, 0, 0.1); } `;
c0936bcbaa1f2ed64f9f031ed3eae4573fe9f6e6
[ "JavaScript", "TypeScript" ]
6
JavaScript
kimu2370/side_myday
c90a8cb2f69695c82bca237aa3985e0405732a4d
3d29b23f03da3b09730c3425841573f999f4d99c
refs/heads/master
<file_sep>package com.jemandandere.featuresmix; import android.graphics.Color; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.ContextMenu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.Switch; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends AppCompatActivity implements View.OnClickListener{ Button b1; Switch s1; TextView t1, t2, t3; int i; private static final String TAG = "JA"; final int MENU_COLOR_RED = 1; final int MENU_COLOR_GREEN = 2; final int MENU_COLOR_BLUE = 3; final int MENU_SIZE_22 = 4; final int MENU_SIZE_26 = 5; final int MENU_SIZE_30 = 6; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); b1 = (Button) findViewById(R.id.button); s1 = (Switch) findViewById(R.id.switch1); t1 = (TextView) findViewById(R.id.textView); t2 = (TextView) findViewById(R.id.textView2); t3 = (TextView) findViewById(R.id.textView3); s1.setOnClickListener(this); b1.setOnClickListener(this); registerForContextMenu(t2); registerForContextMenu(t3); i = 0; } @Override public void onClick(View v){ switch (v.getId()) { case R.id.switch1: b1.setEnabled(s1.isChecked()); break; case R.id.button: i++; t1.setText("" + getResources().getString(R.string.texteded) + " " + i); Log.d(TAG,"log # " + i); if (i%10==0){ Toast.makeText(this, "Уиии", Toast.LENGTH_SHORT).show(); } } } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) { switch (v.getId()) { case R.id.textView2: menu.add(0, MENU_COLOR_RED, 0, "Red"); menu.add(0, MENU_COLOR_GREEN, 0, "Green"); menu.add(0, MENU_COLOR_BLUE, 0, "Blue"); break; case R.id.textView3: menu.add(0, MENU_SIZE_22, 0, "22"); menu.add(0, MENU_SIZE_26, 0, "26"); menu.add(0, MENU_SIZE_30, 0, "30"); break; } } @Override public boolean onContextItemSelected(MenuItem item) { switch (item.getItemId()) { case MENU_COLOR_RED: t2.setTextColor(Color.RED); t2.setText("Red"); break; case MENU_COLOR_GREEN: t2.setTextColor(Color.GREEN); t2.setText("Green"); break; case MENU_COLOR_BLUE: t2.setTextColor(Color.BLUE); t2.setText("Blue"); break; case MENU_SIZE_22: t3.setTextSize(22); t3.setText("22"); break; case MENU_SIZE_26: t3.setTextSize(26); t3.setText("26"); break; case MENU_SIZE_30: t3.setTextSize(30); t3.setText("30"); break; } return super.onContextItemSelected(item); } }
7cd0e42216b888ebaa9192b4559e941355647788
[ "Java" ]
1
Java
Jemandandere/FeaturesMix
d3f9cc4d8c8a3a70922004d41cc59c124dc06626
08eb8f1969048247c835d924e80d40e3175d2f34
refs/heads/master
<file_sep>package products; import java.math.BigDecimal; /** * Создано для демонстрации принципа замены <NAME>. * Product - абстрактный предок всех продуктов из магазина. * Соответственно, наслодоваться от него могут только продукты, * а не корзина товаров или кассир/покупатель. */ public abstract class Product { private final String productName; // Наименование товара private double productWeight; // Вес продукта private String countryOfOrigin; // Страна производитель private final BigDecimal price; // Цена продукта private int productQuantity; // Кол-во товаров в магазине private int rating = 0; // Рейтинг товаров private boolean recommendProduct = false; public Product(String productName, BigDecimal price) { this.productName = productName; this.price = price; } /** * Получить наименование продукта * @return наименование продукта */ public String getProductName() { return productName; } /** * Получить вес продукта * @return вес продукта */ public double getProductWeight() { return productWeight; } /** * Получить страну производитель продукта * @return страна производитель продукта */ public String getCountryOfOrigin() { return countryOfOrigin; } /** * Получить цену продукта * @return цена продукта */ public BigDecimal getPrice() { return price; } /** * Получить кол-во продукции на складе * @return кол-во продукции по складу */ public int getProductQuantity() { return productQuantity; } /** * Получить рейтинг товара * @return рейтинг товара */ public int getRating() { return rating; } /** * Получить флаг рекомендуемдации продукта * @return */ public boolean getRecommendProduct() { return recommendProduct; } /** * Установить вес продукта * @param productWeight вес продукта */ protected void setProductWeight(double productWeight) { this.productWeight = productWeight; } /** * Установить страну производитель * @param countryOfOrigin страна производитель */ protected void setCountryOfOrigin(String countryOfOrigin) { this.countryOfOrigin = countryOfOrigin; } /** * Установить кол-во продукции на складе * @param productQuantity кол-во продукции на складе */ public void setProductQuantity(int productQuantity) { this.productQuantity = productQuantity; } /** * Установить определённый рейтинг для товара * @param rating */ public void setRating(int rating) { if(rating > 0) { this.rating = rating; } } /** * Добавить товар в рекомендуемые * @param recommendProduct */ public void setRecommendProduct(boolean recommendProduct) { this.recommendProduct = recommendProduct; } /** * Увеличить рейтинг товара на 1 единицу */ public void iterationRating() { rating++; } /** * Уменьшить рейтинг товара на 1 единицу */ public void decrementRating() { if(rating != 0) { rating--; } } @Override public String toString() { return productName + ", производство: " + countryOfOrigin + ", кол-во: "+ productQuantity + " шт., цена за ед. " + price + " руб."; } } <file_sep>import user.Basket; import user.Order; import user.User; import view.ConsoleLogger; import view.ConsoleViewer; import view.MyLogger; import view.Viewer; public class ShopDelivery { private static ShopDelivery delivery; private final Viewer viewer; // Отбражение на экране private final MyLogger logger; // Логер private ShopDelivery() { viewer = ConsoleViewer.getInstance(); logger = ConsoleLogger.getInstance(); } public static ShopDelivery getInstance() { if(delivery == null) { delivery = new ShopDelivery(); } return delivery; } /** * Процесс сборки заказа и смена его статуса * @param user пользователь * @param status статус заказа */ public void assemblyUserOrder(User user, OrderStatus status) { Order userOrder; Basket userBasket; logger.logAction("Действия над заказом для - " + user.getUserName()); userOrder = user.getOrder(); userBasket = userOrder.getBasket(); logger.logAction("Список заказа: " + userBasket.getProductList()); userOrder.setStatus(status.name()); logger.logAction("Смена статуса заказа на: " + userOrder.getStatus() + "\n"); viewer.printText("Статус заказа для " + user.getUserName() + " изменён на - " + userOrder.getStatus() + "\n"); } } <file_sep>package view; /** * Создано для демонстрации принципа разделения интерейсов. * Не хочу, чтобы интерфейс Viewer нёс ответственность за логирование. */ public interface MyLogger { void logAction(String sthText); } <file_sep>## Магазин ##### Использовались принципы: * избегания магических чисел * DRY * SOLID ##### Функционал: * Вывод доступных для покупки товаров * Фильтрация товаров по ключевым словам, ценам, производителям * Составление продуктовой корзины пользователя * Трекинг заказа в системе доставки * Возврат заказа, повтороение заказа * Система рейтинга для товаров * Простая рекомендательная система для покупок <file_sep>package user; import products.Product; import java.math.BigDecimal; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class Basket { private Map<Product, Integer> productList; // Не смотря на Map - является списком товаров private BigDecimal totalSum; Basket() { productList = new HashMap<>(); totalSum = new BigDecimal(0); } /** * Возвращает объект(Корзину) списка(Map) заказа * @return */ public Map<Product, Integer> getRealBasket() { return productList; } public void resetToZero() { BigDecimal zero = new BigDecimal(0); totalSum = totalSum.multiply(zero); } /** * Получить итоговую сумму козины * @return */ public BigDecimal getTotalSum() { return totalSum; } /** * Добавить товар в корзину * @param product продукт * @param quantity необходимое кол-во продукта */ public void setProductInBasket(Product product, int quantity) { BigDecimal posSum; productList.put(product, quantity); posSum = product.getPrice().multiply(BigDecimal.valueOf(quantity)); totalSum = totalSum.add(posSum); } /** * Получить содержимое корзины * @return */ public String getProductList() { String myBasket = "\nКорзина: \n"; List<Product> products = new ArrayList<>(productList.keySet()); int numProduct; if(productList.isEmpty()) { return "Корзина заказов пуста."; } else { for(Product product : products) { numProduct = productList.get(product); myBasket += "- " + product.getProductName() + ", кол-во: " + numProduct + " шт.\n"; } myBasket += "Сумма заказа: " + totalSum + " руб. \n"; return myBasket; } } } <file_sep>import user.User; import view.ConsoleLogger; import view.ConsoleViewer; import view.MyLogger; import view.Viewer; import java.util.*; /** * Согласно ДЗ: * 1) Старался избегать магических чисел, но не везде смог (выбор пунктов меню) * 2) Где возможно устранл повторения кода (Например - ShopManager::needInitShowcase()) * 3) Принцип единственной ответственности (Например - классы user/Basket, user/Order, user/User) * 4) Принцип открытости/закрытости (Наверное наследование продуктов в products/* или реализация интерфейсов в user/) * 5) Принцип замены Барбары Лисков (Наследование от Product в products/) * 6) Принцип сегрегации (разделения) интерфейса (Разделение MyLogger и Viewer в view/) * 7) Принцип инверсии зависимостей (Например создание провуктов в ShopManager::initProductShowcase()) */ public class Main { private static User user = new User("Владислав"); // Передаем статично имя пользователя private static Scanner scanner = new Scanner(System.in); public static void main(String[] args) { String strNumber; int menuSize; int menuItem; Viewer viewer = ConsoleViewer.getInstance(); MyLogger logger = ConsoleLogger.getInstance(); ShopManager manager = new ShopManager(); while (true) { menuSize = viewer.inputMainText(); strNumber = scanner.nextLine(); menuItem = selectMenuItem(strNumber, menuSize); if(menuItem == menuSize) { logger.logAction("Выбран пункт - " + menuItem + ". Выход из системы."); scanner.close(); break; } logger.logAction("Выбран пункт - " + menuItem + "."); if(menuItem == 1) { manager.showAvailableProducts(); } else if (menuItem == 2) { viewer.printText("Введите полностью/частично: \n" + "Наименование товара или страну производитель."); String keyword = scanner.nextLine(); logger.logAction("Пользователь ввёл: " + keyword); manager.filterProducts(keyword); } else if (menuItem == 3) { constructProductBasket(viewer, manager); } else if (menuItem == 4) { manager.assemblyOrder(user); } else if (menuItem == 5) { manager.cancelOrder(user); } else if (menuItem == 6) { manager.filterProductsByRating(); } else if(menuItem == 7) { manager.getRecommendProducts(); } } } /** * Формирование пользовательской корзины * @param viewer * @param manager */ static void constructProductBasket( Viewer viewer, ShopManager manager) { int pIdx; int pQuantity; int nextIteration; String clearScan; Map<Integer, Integer> productsOrder = new HashMap<>(); while (true){ viewer.printText("Выберите индекс товара:"); clearScan = scanner.nextLine(); pIdx = Integer.parseInt(clearScan); viewer.printText("Введите желаемое кол-во товара: "); clearScan = scanner.nextLine(); pQuantity = Integer.parseInt(clearScan); productsOrder.put(pIdx, pQuantity); viewer.printText("Для выхода введите '0' или любое число для продолжения"); clearScan = scanner.nextLine(); nextIteration = Integer.parseInt(clearScan); if(nextIteration == 0) { break; } } manager.initOrder(productsOrder, user); } static int selectMenuItem(String strNumber, int menuItem) { int action = 0; try { action = Integer.parseInt(strNumber); if(action > 0 && action <= menuItem) { System.out.println(action); } else { System.out.println("Указанного пункта не существует."); } } catch (Exception ex) { System.out.println("Не корректный ввод: " + ex.getMessage()); } return action; } } <file_sep>public enum OrderStatus { CANCELLED_ORDER, ASSEMBLY_ORDER, DELIVERY_ORDER; } <file_sep>package user; import products.Product; import view.ConsoleLogger; import view.MyLogger; public class Order { private User user; // Пользователь private final Basket basket; // Корзина товаров private final MyLogger logger; // Логгер private String status; // Статус заказа public Order() { basket = new Basket(); logger = ConsoleLogger.getInstance(); } /** * Установить статус заказа * @param status статус заказа */ public void setStatus(String status) { this.status = status; } /** * Получить статус заказа * @return статус заказа */ public String getStatus() { return status; } /** * Получить корзину заказа * @return */ public Basket getBasket() { return basket; } /** * Добавляет товар в корзину и уменьшеает его кол-во на складе * @param user пользователь * @param product товар * @param quantity кол-во необходимо продукции */ public void addProductList(User user, Product product, int quantity) { this.user = user; int pQuantity = product.getProductQuantity(); if(pQuantity != 0 && pQuantity >= quantity) { product.setProductQuantity(pQuantity - quantity); basket.setProductInBasket(product, quantity); logger.logAction(product.getProductName() + " осталось - " + product.getProductQuantity() + " шт."); logger.logAction(product.getProductName() + " успешно добавлен в корзину."); } } /** * Предоставление содержимого корзины заказа * @return содержимое корзины заказа */ public String myBasket() { return basket.getProductList(); } @Override public String toString() { return user + ", " + basket.getProductList(); } }
156e2aea250d070cd5e6056128c60a535c371849
[ "Markdown", "Java" ]
8
Java
bergaro/shop-SOLID-
04f52294f2c6bbf57e49713e1faeab66adaf1bd2
d75cbad6d2b9fe1f551a86cef32f52349148d3af
refs/heads/master
<repo_name>Bniky/Udacity-Movies-Stage1<file_sep>/app/src/main/java/com/bniky/nicholas/movies/MovieDetailScrollingActivity.java package com.bniky.nicholas.movies; import android.os.Bundle; import android.support.v4.app.NavUtils; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.widget.ImageView; import android.widget.TextView; import com.squareup.picasso.Picasso; import static java.security.AccessController.getContext; public class MovieDetailScrollingActivity extends AppCompatActivity { TextView title; TextView releaseDate; TextView movieRating; TextView movieOverView; ImageView moviePoster; ImageView movieBackDrop; String imageAdrress = "http://image.tmdb.org/t/p"; Bundle extras; Bundle onStateBundle; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_movie_detail_scrolling); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); //Back button getSupportActionBar().setDisplayHomeAsUpEnabled(true); title = (TextView) findViewById(R.id.title_name); releaseDate = (TextView) findViewById(R.id.release); movieRating = (TextView) findViewById(R.id.rating); movieOverView = (TextView) findViewById(R.id.movie_descrption); moviePoster = (ImageView) findViewById(R.id.poster); movieBackDrop = (ImageView) findViewById(R.id.back_drop); extras = getIntent().getExtras(); if(extras != null) { loadDataFromIntent(extras); } } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu_movie_detail_scrolling, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: NavUtils.navigateUpFromSameTask(this); return true; default: return super.onOptionsItemSelected(item); } } void loadDataFromIntent(Bundle extraFromIntent){ String titleMovie = extraFromIntent.get("titleMovie").toString(); String release = extraFromIntent.get("release").toString(); String rating = extraFromIntent.get("rating").toString() + "/10"; String overView = extraFromIntent.get("overView").toString(); String poster = extraFromIntent.get("poster").toString(); String back_drop = extraFromIntent.get("back_drop").toString(); title.setText(titleMovie); releaseDate.setText(release); movieRating.setText(rating); movieOverView.setText(overView); Picasso.with(getApplicationContext()).load(imageAdrress + "/w185/" + poster).into(moviePoster); Picasso.with(getApplicationContext()).load(imageAdrress + "/original/"+ back_drop).into(movieBackDrop); } }
7a82b775357420e7dd8757c55c32e24be919379a
[ "Java" ]
1
Java
Bniky/Udacity-Movies-Stage1
04c1c6ea9649002a8c61daba7e109052cb24bd9b
1e2e39d4099089e8bc8c06288957a27e0076acfd
refs/heads/main
<file_sep>### Hello! I'm Matthew (he/him) I'm a big nerd, FOSS enthusiast & australian developer :australia: . I live on Wangal/Gadigal land of the Eora nation. ### What I do for work I work as a software engineer, building pipelines that transform electronic medical records into useable data, & extract valuable information from messy, underutilized datasets. In this domain I get to work with R, & my primary tools & expertises are data-pipelining, literate programming, & designing workflows & tools that ease the gap between big, complex pipelines, & the people who need their insights. Hours buried deep in ssh sessions in HPC systems running ancient distros, massaging builds to work with old kernels, libraries & quirky environments fostered a deep love for the terminal, and you can find the dotfiles I use to make my terminals feel like home pinned. I feel most alive at work when I'm bringing information that previously needed a 5 step process via 4 different tools to access directly to the tired developer/analyst/user who'd been wishing there was a better way to find this thing (because so often that person is me!) For fun, I love it when I've found a FOSS project that's **so useful** to me, but there's just *one tiny thing* I wish it could do better- So I get to clone it, setup its' dev env, & then make it do that one tiny thing. ### Reach me [![Twitter Follow](https://img.shields.io/twitter/follow/strazto?color=%231DA1F2&label=Follow%20me&logo=Twitter&style=for-the-badge)](https://twitter.com/intent/follow?screen_name=strazto) [![LinkedIn connect](https://img.shields.io/static/v1?color=%231DA1F2&label=Connect&message=%20&style=for-the-badge&logo=LinkedIn)](https://www.linkedin.com/in/matthewstrasiotto) ## Repos I maintain, or actively contribute to <div align="center"> <a href="https://github.com/matthewstrasiotto/mandrake"> <img align="center" src="https://github-readme-stats.vercel.app/api/pin/?username=matthewstrasiotto&repo=mandrake&theme=dark&show_owner=true" /> </a> <a href="https://github.com/krisives/cronnit.us/commits?author=matthewstrasiotto"> <img align="center" src="https://github-readme-stats.vercel.app/api/pin/?username=krisives&repo=cronnit.us&theme=dark&show_owner=true" /> </a> </div> ## Repos I ocasionally contribute to <details><summary>Repos I've had PR's merged into</summary> <div align="center" style="display: flex; justify-content: space-between;"> <a href="https://github.com/r-lib/pkgdown/commits?author=matthewstrasiotto"><img align="center" src="https://img.shields.io/github/stars/r-lib/pkgdown?label=r-lib%20/%20pkgdown%20%E2%AD%90&style=flat-square&logo=GitHub" /></a> <a href="https://github.com/christoomey/vim-tmux-navigator/commits?author=matthewstrasiotto"><img align="center" src="https://img.shields.io/github/stars/christoomey/vim-tmux-navigator?label=christoomey%20/%20vim-tmux-navigator%20%E2%AD%90&style=flat-square&logo=GitHub" /></a> <a href="https://github.com/darkreader/darkreader/commits?author=matthewstrasiotto"><img align="center" src="https://img.shields.io/github/stars/darkreader/darkreader?label=darkreader%20/%20darkreader%20%E2%AD%90&style=flat-square&logo=GitHub" /></a> <a href="https://github.com/mschubert/clustermq/commits?author=matthewstrasiotto"><img align="center" src="https://img.shields.io/github/stars/mschubert/clustermq?label=mschubert%20/%20clustermq%20%E2%AD%90&style=flat-square&logo=GitHub" /></a> <a href="https://github.com/yihui/xaringan/commits?author=matthewstrasiotto"><img align="center" src="https://img.shields.io/github/stars/yihui/xaringan?label=yihui%20/%20xaringan%20%E2%AD%90&style=flat-square&logo=GitHub" /></a> <a href="https://github.com/SpaceVim/SpaceVim/commits?author=matthewstrasiotto"><img align="center" src="https://img.shields.io/github/stars/SpaceVim/SpaceVim?label=SpaceVim%20/%20SpaceVim%20%E2%AD%90&style=flat-square&logo=GitHub" /></a> <a href="https://github.com/ropensci/drake/commits?author=matthewstrasiotto"><img align="center" src="https://img.shields.io/github/stars/ropensci/drake?label=ropensci%20/%20drake%20%E2%AD%90&style=flat-square&logo=GitHub" /></a> <a href="https://github.com/ropensci-books/drake/commits?author=matthewstrasiotto"><img align="center" src="https://img.shields.io/github/stars/ropensci-books/drake?label=ropensci-books%20/%20drake%20%E2%AD%90&style=flat-square&logo=GitHub" /></a> <a href="https://github.com/paulklemm/rvisidata/commits?author=matthewstrasiotto"><img align="center" src="https://img.shields.io/github/stars/paulklemm/rvisidata?label=paulklemm%20/%20rvisidata%20%E2%AD%90&style=flat-square&logo=GitHub" /></a> <a href="https://github.com/deekue/uebersicht-remontoire.widget/commits?author=matthewstrasiotto"><img align="center" src="https://img.shields.io/github/stars/deekue/uebersicht-remontoire.widget?label=deekue%20/%20uebersicht-remontoire.widget%20%E2%AD%90&style=flat-square&logo=GitHub" /></a> </div> </details> ## My dotfiles Make your terminal look like mine! <details> <summary>Animated demo of my terminal env</summary> ![demo](https://raw.githubusercontent.com/matthewstrasiotto/dotfiles/master/demo.x3.gif) </details> <a href="https://github.com/matthewstrasiotto/dotfiles"> <img align="center" src="https://github-readme-stats.vercel.app/api/pin/?username=matthewstrasiotto&repo=dotfiles&theme=dark" lazy=true /> </a> <!-- ### GH Stats (commented for now) [![matthewstrasiotto's github stats](https://github-readme-stats.vercel.app/api?username=matthewstrasiotto&show_icons=true&theme=dark)](https://github.com/anuraghazra/github-readme-stats) [![HitCount](http://hits.dwyl.com/matthewstrasiotto/matthewstrasiotto.svg)](http://hits.dwyl.com/matthewstrasiotto/matthewstrasiotto) **matthewstrasiotto/matthewstrasiotto** is a ✨ _special_ ✨ repository because its `README.md` (this file) appears on your GitHub profile. Here are some ideas to get you started: - 🔭 I’m currently working on ... - 🌱 I’m currently learning ... - 👯 I’m looking to collaborate on ... - 🤔 I’m looking for help with ... - 💬 Ask me about ... - 📫 How to reach me: ... - 😄 Pronouns: ... - ⚡ Fun fact: ... --> <file_sep>proper_repos <- "~/proper_repos.json" %>% jsonlite::read_json(simplifyVector = T) %>% dplyr::mutate(owner_name = owner$login) links <- proper_repos %>% purrr::pmap(function( nameWithOwner, url, name, owner_name, ... ) { label <- glue::glue( '{owner_name}%20/%20{name}%20{star}', star = '%E2%AD%90' ) out <- glue::glue( '<a href="{url}/commits?author=matthewstrasiotto">', '<img align="center" ', 'src="{endpoint}/{nameWithOwner}?label={label}&style={style}&logo=GitHub"', ' />', '</a>', endpoint = "https://img.shields.io/github/stars", style = 'for-the-badge' ) }) links %>% glue::glue_collapse(sep = "\n\n")
adbe39da51975b1009b097b44b8077db4bdf3376
[ "Markdown", "R" ]
2
Markdown
matthewstrasiotto/matthewstrasiotto
8ac18de02785e1c2b38343dc51a7f669bba070d3
3dbc4a34705b025b7fe1766856f8a19abdb7e9c3
refs/heads/master
<file_sep># frozen_string_literal: true Raven.configure do |config| config.excluded_exceptions += ["Sidekiq::Shutdown"] end <file_sep># frozen_string_literal: true require 'test_helper' class Users::OmniauthCallbacksControllerTest < ActionController::TestCase include Devise::Test::ControllerHelpers setup do request.env["devise.mapping"] = Devise.mappings[:user] request.env["omniauth.auth"] = OmniAuth.config.mock_auth[:github] end test "make user feel good when legit email address" do stub_oauth_user('<EMAIL>') get :github assert flash[:notice] == I18n.t("devise.omniauth_callbacks.success", kind: "GitHub") assert_redirected_to root_path end test "redirect to user page and inform when bad e-mail address" do stub_oauth_user('awful e-mail address') get :github assert flash[:notice] == I18n.t("devise.omniauth_callbacks.bad_email_success", kind: "GitHub") assert_redirected_to root_path end test "redirect to languages page after authenticating a new user" do user = stub_oauth_user('<EMAIL>', new_user: true) get :github assert_redirected_to user_languages_path(user_id: user.id) end def stub_oauth_user(email, new_user: false) User.new(email: email, id: -1).tap do |user| if new_user user.created_at = 5.minutes.ago user.favorite_languages = [] else user.created_at = 6.days.ago user.favorite_languages = ['ruby'] end user.stubs(:persisted?).returns(true) GitHubAuthenticator.stubs(:authenticate).returns(user) end end end
f14ce314b03627a267a564be3bfb8b1011b31d5f
[ "Ruby" ]
2
Ruby
romanrizzi/codetriage
b001fb136e0128bf9fc2662aae02ca9e8d2dfb4e
73a3336cb579dd2d7578d168d27dfd6fe8c9a0ae
refs/heads/master
<file_sep>package com.osmosys.task.view import android.content.Intent import android.os.Bundle import android.view.View import android.widget.ArrayAdapter import android.widget.RadioButton import android.widget.RadioGroup import androidx.appcompat.app.AppCompatActivity import com.osmosys.task.R import com.osmosys.task.utils.Common.Companion.EMAIL_ADDRESS import com.osmosys.task.utils.Common.Companion.PASSWORD_PATTERN import kotlinx.android.synthetic.main.activity_sign_up.* import java.util.regex.Matcher import java.util.regex.Pattern class SignUpActivity : AppCompatActivity(), RadioGroup.OnCheckedChangeListener { val values = arrayOf( "Vijayawada", "Jammu", "Dispur", "Patna", "Chandigarh", "Raypur", "Daman", "Delhi", "Panaji", "<NAME>", "Ranchi", "Bengaluru", "Thripura", "Kawaratti", "Bhopal", "Mumbai", "Impal", "Shillag", "Izwal", "Nagaland", "Hyderabad", "Agarthala" ) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_sign_up) ArrayAdapter( this, android.R.layout.simple_spinner_item, values ).also { it.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) sp_city.adapter = it } rg_type.setOnCheckedChangeListener(this) } fun submit(view: View) { if (validate()) onBackPressed() } fun validate(): Boolean { var valid = true val fName: String = et_fName.text.toString() val lName: String = et_lName.text.toString() val email: String = et_eMail.text.toString() val password: String = et_Password.text.toString() val cnfPassword: String = et_cnfmPassword.text.toString() val position: Int = sp_city.selectedItemPosition val rg_type_id: Int = rg_type.checkedRadioButtonId val radioButton: RadioButton = findViewById(rg_type_id) val value: String = radioButton.text.toString().trim() if (fName.isEmpty()) { et_fName.error = "enter First Name" valid = false } else { et_fName.error = null } if (lName.isEmpty()) { et_lName.error = "enter Last Name" valid = false } else { et_lName.error = null } if (email.isEmpty() || !EMAIL_ADDRESS.matcher(email).matches()) { et_eMail.error = "enter a valid email address" valid = false } else { et_eMail.error = null } if (password.isEmpty()) { et_Password.error = "enter Password" valid = false } else if(!password_validate(password)) { et_Password.error = "password must contain lowercase uppercase chars and special symbols like @#\$% and length at least 8 characters and maximum of 12" valid = false }else{ et_Password.error=null } if(!cnfPassword.equals(password)){ et_cnfmPassword.error = "Password not Matched" valid = false }else{ et_cnfmPassword.error=null } return valid } fun password_validate(password: String): Boolean { return PASSWORD_PATTERN.matcher(password).matches() } override fun onCheckedChanged(p0: RadioGroup?, p1: Int) { } } <file_sep>import com.google.gson.annotations.SerializedName class Feature() { @SerializedName("id") val id: Int = 0 @SerializedName("featureName") val featureName: String = "" @SerializedName("status") val status: Int = 0 @SerializedName("isSmartFeature") val isSmartFeature: String = "" @SerializedName("deviceTypeID") val deviceTypeID: String = "" }<file_sep>import com.google.gson.annotations.SerializedName class Base_data() { @SerializedName("data") val data: Sample_data? = null @SerializedName("status") val status: String = "" }<file_sep>include ':app' rootProject.name='Designs' <file_sep>package com.osmosys.task.view import PackageFeatures import Records_data import android.content.Context import android.graphics.Typeface import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.BaseExpandableListAdapter import android.widget.TextView import com.osmosys.task.R import kotlinx.android.synthetic.main.list_group.view.* import java.util.* class ExpandableListAdapter( private val _context: Context, private val _listDataHeader: List<Records_data>, private val _listDataChild: HashMap<String, List<PackageFeatures>> ) : BaseExpandableListAdapter() { override fun getChild(groupPosition: Int, childPosititon: Int): String? { return _listDataChild.get(_listDataHeader.get(groupPosition).name)?.get(childPosititon) ?.feature?.featureName } override fun getChildId(groupPosition: Int, childPosition: Int): Long { var result: Long = 0 try { result = childPosition.toLong() } catch (e: Exception) { Log.e("getChildId:-", e.toString()) } return result } override fun getChildView( groupPosition: Int, childPosition: Int, isLastChild: Boolean, convertView: View?, parent: ViewGroup ): View { var convertView1: View? = convertView try { val childText: String = getChild(groupPosition, childPosition) as String if (convertView1 == null) { val infalInflater: LayoutInflater = this._context .getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater convertView1 = infalInflater.inflate(R.layout.list_item, null); } val txtListChild: TextView? = convertView1?.findViewById(R.id.child_title) txtListChild?.setText(childText); } catch (e: Exception) { Log.e("getChildView:-", e.toString()) } return convertView1!! } override fun getChildrenCount(groupPosition: Int): Int { return _listDataChild.get(_listDataHeader.get(groupPosition).name)?.size ?: 0 } override fun getGroup(groupPosition: Int): String? { return _listDataHeader.get(groupPosition).name } override fun getGroupCount(): Int { return _listDataHeader.size } override fun getGroupId(groupPosition: Int): Long { return groupPosition.toLong() } override fun getGroupView( groupPosition: Int, isExpanded: Boolean, convertView: View?, parent: ViewGroup ): View { val headerTitle: String var convertView1 = convertView try { headerTitle = getGroup(groupPosition) as String if (convertView1 == null) { val infalInflater: LayoutInflater = this._context .getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater convertView1 = infalInflater.inflate(R.layout.list_group, null) } convertView1?.grp_title?.setTypeface(null, Typeface.BOLD) convertView1?.grp_title?.text = headerTitle if (isExpanded) { convertView1?.img!!.setImageResource(R.drawable.down_button_64px); } else { convertView1?.img!!.setImageResource(R.drawable.next_page_64px); } } catch (e: Exception) { Log.e("ELA", e.toString()) } return convertView1!! } override fun hasStableIds(): Boolean { return false } override fun isChildSelectable(groupPosition: Int, childPosition: Int): Boolean { return true } }<file_sep>package com.osmosys.task.view import android.animation.Animator import android.content.Intent import android.os.Bundle import android.os.CountDownTimer import android.view.View import android.view.View.VISIBLE import android.view.inputmethod.EditorInfo import android.widget.TextView.OnEditorActionListener import androidx.appcompat.app.AppCompatActivity import androidx.core.content.ContextCompat import com.osmosys.task.R import com.osmosys.task.utils.Common.Companion.EMAIL_ADDRESS import kotlinx.android.synthetic.main.activity_sign_in.* import java.util.regex.Pattern class SignInActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_sign_in) object : CountDownTimer(5000, 1000) { override fun onFinish() { bookITextView.visibility = View.GONE loadingProgressBar.visibility = View.GONE rootView.setBackgroundColor(ContextCompat.getColor(applicationContext, R.color.backgroundColor)) bookIconImageView.setImageResource(R.drawable.exp_l_ico) startAnimation() } override fun onTick(p0: Long) {} }.start() ePassword.setOnEditorActionListener(OnEditorActionListener { v, actionId, event -> if (actionId == EditorInfo.IME_ACTION_DONE) { logIn(v) return@OnEditorActionListener true } false }) } private fun startAnimation() { bookIconImageView.animate().apply { x(56f) y(56f) duration = 1000 }.setListener(object : Animator.AnimatorListener { override fun onAnimationRepeat(p0: Animator?) { } override fun onAnimationEnd(p0: Animator?) { afterAnimationView.visibility = VISIBLE } override fun onAnimationCancel(p0: Animator?) { } override fun onAnimationStart(p0: Animator?) { } }) } fun signUp(view: View) { startActivity(Intent(this, SignUpActivity::class.java)) } fun skip(view: View) { startActivity(Intent(this, MainActivity::class.java)) } fun logIn(view: View) { if(validate()) startActivity(Intent(this, MainActivity::class.java)) } fun validate(): Boolean { var valid = true val email: String = eloginId.text.toString() val password: String = ePassword.text.toString() if (email.isEmpty() || !EMAIL_ADDRESS.matcher(email).matches()) { eloginId.error = "enter a valid email address" valid = false } else { eloginId.error = null } if (password.isEmpty() || password.length < 4 || password.length > 10) { ePassword.error = "between 4 and 10 alphanumeric characters" valid = false } else { ePassword.error = null } return valid } } <file_sep>import com.google.gson.annotations.SerializedName class Sample_data() { @SerializedName("limit") val limit: Int = 0 @SerializedName("start") val start: Int = 0 @SerializedName("nextStart") val nextStart: Int = 0 @SerializedName("records") val records: ArrayList<Records_data> = ArrayList() @SerializedName("total") val total: Int = 0 }<file_sep>package com.osmosys.task.utils import java.util.regex.Pattern class Common { companion object { val EMAIL_ADDRESS: Pattern = Pattern.compile( "[a-zA-Z0-9\\+\\.\\_\\%\\-\\+]{1,256}" + "\\@" + "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,64}" + "(" + "\\." + "[a-zA-Z][a-zA-Z\\-]{1,25}" + ")+" ) val PASSWORD_PATTERN:Pattern = Pattern.compile("((?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%]).{8,12})") } }<file_sep>import com.google.gson.annotations.SerializedName class PackageFeatures() { @SerializedName("id") val id: Int = 0 @SerializedName("packageID") val packageID: Int = 0 @SerializedName("featureID") val featureID: Int = 0 @SerializedName("createdBy") val createdBy: Int = 0 @SerializedName("createdOn") val createdOn: String = "" @SerializedName("status") val status: Int = 0 @SerializedName("feature") val feature: Feature? = null }<file_sep>package com.osmosys.task.view import Base_data import PackageFeatures import Records_data import android.content.res.AssetManager import android.os.Bundle import android.util.DisplayMetrics import android.util.Log import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import com.google.gson.Gson import com.osmosys.task.R import kotlinx.android.synthetic.main.activity_main.* import java.io.InputStream import java.util.* import kotlin.collections.ArrayList import kotlin.collections.set class MainActivity : AppCompatActivity() { var listAdapter: android.widget.ExpandableListAdapter? = null var listDataHeader: ArrayList<Records_data>? = null var listDataChild: HashMap<String, List<PackageFeatures>>? = null private var lastExpandedPosition = -1 override fun onCreate(savedInstanceState: Bundle?) { try { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) /* val metrics = DisplayMetrics() windowManager.defaultDisplay.getMetrics(metrics) val width = metrics.widthPixels exp_list.setIndicatorBounds(width - GetPixelFromDips(50F), width - GetPixelFromDips(10F));*/ prepareListData() exp_list.setOnGroupClickListener { parent, v, groupPosition, id -> false } exp_list.setOnGroupExpandListener { groupPosition -> try { if (lastExpandedPosition != -1 && groupPosition != lastExpandedPosition ) { exp_list.collapseGroup(lastExpandedPosition) } lastExpandedPosition = groupPosition Toast.makeText(applicationContext, listDataHeader?.get(groupPosition)?.name + " Expanded", Toast.LENGTH_SHORT).show() } catch (e: Exception) { Log.e("setOnGroupExpand", e.toString()) } } exp_list.setOnGroupCollapseListener { groupPosition -> try { Toast.makeText(applicationContext, (listDataHeader?.get(groupPosition))?.name + " Collapsed", Toast.LENGTH_SHORT).show() } catch (e: Exception) { Log.e("setOnGroupCollapse", e.toString()) } } exp_list.setOnChildClickListener { parent, v, groupPosition, childPosition, id -> Toast.makeText(applicationContext, "${listDataHeader?.get(groupPosition)!!.name} : ${listDataChild?.get(listDataHeader?.get(groupPosition)?.name)?.get(childPosition)!!.feature!!.featureName}", Toast.LENGTH_SHORT).show() false } } catch (e: Exception) { Log.e("setOnChild-", e.toString()) } } fun GetPixelFromDips(pixels: Float): Int { // Get the screen's density scale val scale = resources.displayMetrics.density // Convert the dps to pixels, based on density scale return (pixels * scale + 0.5f).toInt() } /* * Preparing the list data */ private fun prepareListData() { try { listDataHeader = ArrayList() listDataChild = HashMap() //access asset val am: AssetManager = applicationContext.getAssets() val ins: InputStream = am.open("sample_data.json") val datastr: String = ins.bufferedReader().use { it.readText() } val dataobj: Base_data = Gson().fromJson(datastr, Base_data::class.java) // Adding child data listDataHeader = dataobj.data!!.records // Adding child data for (i in 0..dataobj.data.records.size - 1) { listDataChild!![listDataHeader!!.get(i).name] = dataobj.data.records[i].packageFeatures } listAdapter = ExpandableListAdapter(this, listDataHeader!!, listDataChild!!) exp_list.setAdapter(listAdapter) } catch (e: Exception) { Log.e("prepareListData", e.toString()) } } }<file_sep>import com.google.gson.annotations.SerializedName public class Records_data() { @SerializedName("id") val id: Int = 0 @SerializedName("name") val name: String = "" @SerializedName("createdOn") val createdOn: String = "" @SerializedName("statusID") val statusID: Int = 0 @SerializedName("isSubPackage") val isSubPackage: Int = 0 @SerializedName("amenityType") val amenityType: AmenityType? = null @SerializedName("packageFeatures") val packageFeatures: ArrayList<PackageFeatures> = ArrayList() }
5d156c6c754560d834998ccd0befbb08b473d34f
[ "Kotlin", "Gradle" ]
11
Kotlin
vennamprasad/OsmosysTask
a6b538b59b762d4d925e8a6133bde5951838eae9
cf937fc68aab6ab2c793151206b61b0cd128adb5
refs/heads/master
<repo_name>christianadrianoproj/API_BoaViagem<file_sep>/src/main/resources/application.properties spring.datasource.driver-class-name=org.postgresql.Driver spring.datasource.url=jdbc:postgresql://localhost/boa_viagem spring.datasource.username=postgres spring.datasource.password=<PASSWORD> spring.jpa.hibernate.ddl-auto=update spring.jpa.show-sql=true spring.jpa.properties.hibernate.temp.use_jdbc_metadata_defaults = false spring.jpa.database-platform=org.hibernate.dialect.PostgreSQL9Dialect spring.jackson.serialization.fail-on-empty-beans=false<file_sep>/src/main/java/com/christian/api/BoaViagem/BoaViagemApplication.java package com.christian.api.BoaViagem; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class BoaViagemApplication { public static void main(String[] args) { SpringApplication.run(BoaViagemApplication.class, args); } } <file_sep>/src/main/java/com/christian/api/BoaViagem/domain/Viagem.java package com.christian.api.BoaViagem.domain; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.validation.constraints.NotNull; import java.util.Date; import java.util.List; /** * * @author Christian */ @Entity @Table(name="tb_viagem") public class Viagem { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name="id_viagem") private Integer idViagem; @NotNull @Column(length = 500) private String destino; @OneToMany(mappedBy = "viagem") private List<Gasto> gastos; @NotNull private Integer tipoViagem; @NotNull @Column(length = 20) private Date dataChegada; @Column(length = 20) private Date dataPartida; @NotNull private Double orcamento; @NotNull @Column(name="quantidade_pessoas") private Integer quantidadePessoas; @ManyToOne @JoinColumn(name="id_usuario") @NotNull private Usuario usuario; public Usuario getUsuario() { return usuario; } public void setUsuario(Usuario usuario) { this.usuario = usuario; } public Integer getIdViagem() { return idViagem; } public void setIdViagem(Integer idViagem) { this.idViagem = idViagem; } public String getDestino() { return destino; } public void setDestino(String destino) { this.destino = destino; } public List<Gasto> getGastos() { return gastos; } public void setGastos(List<Gasto> gastos) { this.gastos = gastos; } public Integer getTipoViagem() { return tipoViagem; } public void setTipoViagem(Integer tipoViagem) { this.tipoViagem = tipoViagem; } public Date getDataChegada() { return dataChegada; } public void setDataChegada(Date dataChegada) { this.dataChegada = dataChegada; } public Date getDataPartida() { return dataPartida; } public void setDataPartida(Date dataPartida) { this.dataPartida = dataPartida; } public Double getOrcamento() { return orcamento; } public void setOrcamento(Double orcamento) { this.orcamento = orcamento; } public Integer getQuantidadePessoas() { return quantidadePessoas; } public void setQuantidadePessoas(Integer quantidadePessoas) { this.quantidadePessoas = quantidadePessoas; } } <file_sep>/src/main/java/com/christian/api/BoaViagem/domain/Usuario.java package com.christian.api.BoaViagem.domain; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import javax.validation.constraints.NotNull; /** * * @author Christian */ @Entity @Table(name="tb_usuario") public class Usuario { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name="id_usuario") private Integer idUsuario; @NotNull @Column(length = 150) private String nome; @NotNull @Column(length = 80) private String userName; @NotNull @Column(length = 50) private String password; public Integer getIdUsuario() { return idUsuario; } public void setIdUsuario(Integer idUsuario) { this.idUsuario = idUsuario; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } 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; } } <file_sep>/src/main/java/com/christian/api/BoaViagem/repository/ViagemRepository.java package com.christian.api.BoaViagem.repository; import org.springframework.data.jpa.repository.JpaRepository; import com.christian.api.BoaViagem.domain.Viagem; /** * * @author Christian */ public interface ViagemRepository extends JpaRepository<Viagem, Integer>{ } <file_sep>/src/main/java/com/christian/api/BoaViagem/controller/ViagemController.java package com.christian.api.BoaViagem.controller; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Comparator; import java.util.Date; import java.util.List; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Sort; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.christian.api.BoaViagem.domain.Gasto; import com.christian.api.BoaViagem.domain.Viagem; import com.christian.api.BoaViagem.repository.GastoRepository; import com.christian.api.BoaViagem.repository.ViagemRepository; /** * * @author Christian */ @RestController @RequestMapping("/viagem") @CrossOrigin(origins = "*") public class ViagemController { @Autowired private ViagemRepository repository; @Autowired private GastoRepository repositoryGasto; @GetMapping public List<Viagem> findAll() { List<Viagem> lista = repository.findAll(Sort.by("dataChegada")); for (Viagem r : lista) { List<Gasto> gastos = r.getGastos(); gastos.sort(Comparator.comparing(Gasto::getTipo)); r.setGastos(gastos); } return lista; } private Date StringToDate(String dateStr) { Date date = null; try { SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy"); date = (java.util.Date) formatter.parse(dateStr); } catch (ParseException e) { System.out.println("Erro na conversao: " + e.getMessage()); date = null; } return date; } private String formatarData(Date data) { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); return format.format(data); } @GetMapping("/ViagensDoUsuario/{idusuario}") public List<Viagem> ViagensDoUsuario(@PathVariable("idusuario") Integer idusuario) { List<Viagem> lista = repository.findAll(Sort.by("dataChegada")); ArrayList<Viagem> retorno = new ArrayList<Viagem>(); for (Viagem r : lista) { if (r.getUsuario().getIdUsuario() == idusuario) { List<Gasto> gastos = r.getGastos(); gastos.sort(Comparator.comparing(Gasto::getData)); r.setGastos(gastos); retorno.add(r); } } return retorno; } @PostMapping("/ValidaPeriodoViagem/{idviagem}") public Viagem ValidaDataViagem(@PathVariable("idviagem") Integer idviagem, @RequestBody String data) { Viagem retorno = new Viagem(); System.out.println("Data recebida: " + data); String dataFiltro = formatarData(StringToDate(data.replace('"', ' ').trim())); Viagem r = repository.findById(idviagem).get(); if ((r.getDataChegada() != null) && (dataFiltro != null)) { String dataChegada = formatarData(r.getDataChegada()); if (dataFiltro.compareTo(dataChegada) >= 0) { retorno = r; if (r.getDataPartida() != null) { String dataPartida = formatarData(r.getDataPartida());; if (dataFiltro.compareTo(dataPartida) <= 0) { retorno = r; } else { retorno = new Viagem(); } } } } return retorno; } @PostMapping("/salvaViagem") public Viagem salvar(@RequestBody Viagem v) { Viagem var = repository.save(v); v.setIdViagem(var.getIdViagem()); if (v.getGastos() != null) { for (Gasto i : v.getGastos()) { i.setViagem(var); ; repositoryGasto.save(i); } } return repository.findById(var.getIdViagem()).get(); } @PostMapping("/adicionaGasto/{idviagem}") public ResponseEntity<?> adicionaGasto(@PathVariable("idviagem") Integer idviagem, @RequestBody Gasto gasto) { Viagem viagem = repository.findById(idviagem).get(); gasto.setViagem(viagem); repositoryGasto.save(gasto); Optional<Viagem> r = repository.findById(idviagem); return ResponseEntity.ok(r.get()); } @PostMapping("/deletaGasto/{idviagem}") public Viagem deletaGasto(@PathVariable("idviagem") Integer idviagem, @RequestBody Gasto gasto) { repositoryGasto.deleteById(gasto.getIdGasto()); return repository.findById(idviagem).get(); } @GetMapping("/{id}") public ResponseEntity<?> find(@PathVariable("id") Integer id) { Optional<Viagem> viagem = repository.findById(id); if (viagem.isPresent()) { return ResponseEntity.ok(viagem.get()); } return ResponseEntity.notFound().build(); } @DeleteMapping("/{id}") public void delete(@PathVariable("id") Integer id) { Viagem viagem = repository.findById(id).get(); for (Gasto i : viagem.getGastos()) { repositoryGasto.deleteById(i.getIdGasto()); } viagem = repository.findById(id).get(); repository.deleteById(id); } }<file_sep>/src/main/java/com/christian/api/BoaViagem/domain/Gasto.java package com.christian.api.BoaViagem.domain; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import javax.validation.constraints.NotNull; import com.fasterxml.jackson.annotation.JsonIgnore; /** * * @author Christian */ @Entity @Table(name="tb_gasto") public class Gasto { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name="id_gasto") private Integer idGasto; @ManyToOne @JoinColumn(name="id_viagem") @NotNull @JsonIgnore private Viagem viagem; @NotNull private String tipo; @NotNull private Double valor; @NotNull //@Column(length = 20) private Date data; @Column(length = 500) private String descricao; @Column(length = 500) private String local; public Integer getIdGasto() { return idGasto; } public void setIdGasto(Integer idGasto) { this.idGasto = idGasto; } public Viagem getViagem() { return viagem; } public void setViagem(Viagem viagem) { this.viagem = viagem; } public String getTipo() { return tipo; } public void setTipo(String tipo) { this.tipo = tipo; } public Double getValor() { return valor; } public void setValor(Double valor) { this.valor = valor; } public Date getData() { return data; } public void setData(Date data) { this.data = data; } public String getDescricao() { return descricao; } public void setDescricao(String descricao) { this.descricao = descricao; } public String getLocal() { return local; } public void setLocal(String local) { this.local = local; } }
80cf772e76cfad468605f3d25bddbcc5a08ceb96
[ "Java", "INI" ]
7
INI
christianadrianoproj/API_BoaViagem
4159940d52ec3364b4a6a4330d6982adbe98af9a
7a2d89cba54b6071482130f5d503d97c7650455f
refs/heads/master
<file_sep>export PATH="$PATH:$HOME/.local/bin:$HOME/bin:$HOME/.cargo/bin:$PATH" export TCAV_PREFIX=/home/ftseng/Documents/github/terra-cotta-archives-tools/build # File Locations # export XDG_CONFIG_HOME=$HOME/.config alias vi=nvim <file_sep>HOSTNAME=chinatown RPMFUSION=http://download1.rpmfusion.org/free/fedora/rpmfusion-free-release-26.noarch.rpm SLACK=https://downloads.slack-edge.com/linux_releases/slack-2.6.3-0.1.fc21.x86_64.rpm CWD=$(pwd) # Set hostname # echo " * Setting hostname to ($HOSTNAME)..." sudo hostnamectl set-hostname $HOSTNAME # Setup dnf repo sources... # echo " * Setting up dnf repos..." # Setup RPM fusion repos # echo " - Setting up RPM fusion repo..." sudo rpm -ivh $RPMFUSION # Setup negativo spotify repo # echo " - Setting up spotify repo..." sudo dnf config-manager --add-repo=http://negativo17.org/repos/fedora-spotify.repo # Setup sublime text repo # echo " - Setting up sublime text repo..." sudo rpm -v --import https://download.sublimetext.com/sublimehq-rpm-pub.gpg sudo dnf config-manager --add-repo https://download.sublimetext.com/rpm/stable/x86_64/sublime-text.repo # Setup sxhkd repo for bspwm... # # echo " - Setting up sxhkd repo for bspwm..." # sudo dnf copr enable pidgornyy/sxhkd -y # Setup neofetch repo... # echo " - Setting up neofetch repo..." sudo dnf copr enable konimex/neofetch # Install packages # echo " * Installing default packages..." sudo dnf install -y \ youtube-dl \ jq \ spotify-client \ mpv \ fuse-exfat \ sublime-text \ neovim \ git \ awscli \ # bspwm \ # sxhkd \ tmux \ ImageMagick \ neofetch \ ibus-setup \ ibus-pinyin \ ibus-uniemoji \ ibus-table \ ffmpeg \ freetype-freeworld # Install slack # echo " * Installing slack..." sudo dnf install -y $SLACK # Install keybase # echo " * Installing keybase..." sudo yum install -y https://prerelease.keybase.io/keybase_amd64.rpm # Go through keybase setup # run_keybase # Install rustup # echo " * Installing rustup..." curl https://sh.rustup.rs -sSf | sh source ~/.cargo/env # Install rust nightly # echo " * Installing rust nightly..." rustup install nightly # Install cryogen # echo " * Installing cryogen..." cargo install cryogen # Install rustfmt # echo " * Installing rustfmt..." cargo install rustfmt # Setup vim-plug # echo " * Installing vim-plug in nvim autoload directory..." curl -fLo ~/.local/share/nvim/site/autoload/plug.vim --create-dirs \ https://raw.githubusercontent.com/junegunn/vim-plug/master/plug.vim # Setup configuration files # echo " * Setting up configuration files..." ln $CWD/conf/profile ~/.profile -s source ~/.profile ln $CWD/conf/xprofile ~/.xprofile -s ln $CWD/conf/xinit-rc ~/.xinit-rc -s ln $CWD/conf/init.vim ~/.config/nvim/init.vim -s ln "$CWD/conf/local.conf" "/etc/fonts/local.conf" -s ln $CWD/conf/Preferences.sublime-settings ~/.config/sublime-text-3/Packages/User/Preferences.sublime-settings -s # ln $CWD/conf/bspwm/ $XDG_CONFIG_HOME/bspwm -s # ln $CWD/conf/sxhkd/ $XDG_CONFIG_HOME/sxhkd -s mkdir ~/.config/alacritty ln $CWD/conf/alacritty.yml ~/.config/alacritty/alacritty.yml # Setup ssh key # echo " * Creating an SSH key..." ssh-keygen -t rsa -b 4096 -C "<EMAIL>" <file_sep>#!/bin/sh # # <NAME> <<EMAIL>> # # Toggles monitor sleep setting. # NAME=$(hostname) ICONS_DIR=/usr/share/pixmaps OPTS="-t 100 -u low" # Determine if DPMS is enabled. # xset -q | grep "DPMS is Enabled" > /dev/null # Use the status code of grep to determine whether # to enable DPMS or disable it. This will turn the screen saver # off or on depending on whether or not DPMS is enabled. # if [[ $? -eq 0 ]]; then xset -dpms && xset s off && xset s noblank && echo "AWAKE" EXIT=$? notify-send $OPTS -i $ICONS_DIR/coffee-awake.png \ $NAME "Sipping on some coffee..." else xset +dpms && xset s on && echo "SLEEPY" EXIT=$? notify-send $OPTS -i $ICONS_DIR/coffee-sleepy.png \ $NAME "Getting sleepy..." fi exit $EXIT <file_sep>#!/bin/sh # # <NAME> <<EMAIL>> # # Lock screen with gaussian blur using the i3lock-blur fork of # i3lock. # i3lock -f -n -u -s 5.0 -o <file_sep>LIB = lib PWD = $(shell pwd) BIN = bin i3lock: sudo dnf install -y \ libxcb \ libxcb-devel \ libGL-devel \ cairo-devel \ libxkbcommon-devel \ libxkbcommon-x11-devel \ xcb-util-devel \ xcb-util-image-devel \ libev-devel \ pam-devel make install -C $(LIB)/i3lock-blur PREFIX=/usr/local INSTALL="sudo install" sudo ln -s $(PWD)/$(BIN)/lockscreen /usr/local/bin/slock sudo ln -s $(PWD)/$(BIN)/lockscreen /usr/local/bin/xflock4 coffee: sudo ln -s $(PWD)/$(LIB)/coffee/coffee-awake.png /usr/share/pixmaps sudo ln -s $(PWD)/$(LIB)/coffee/coffee-sleepy.png /usr/share/pixmaps sudo ln -s $(PWD)/$(BIN)/coffee /usr/local/bin
415187454b121b18ada28a73d45acb3801da548d
[ "Makefile", "Shell" ]
5
Shell
ferristseng/linux-setup
0d2a8c610ea1513b555f3dc494aa3ed85222a6ac
b8f2cce16655cde313320a3604725a144475d887
refs/heads/master
<file_sep> let homePath = 'https://www.96486d9b.cn/'; function showHitokoto() { $.getJSON('https://v1.hitokoto.cn/', function (result) { showMessage(result.hitokoto, 5000); }); } function showMessage(text, timeout) { if (Array.isArray(text)) text = text[Math.floor(Math.random() * text.length + 1) - 1]; $('.waifu-tips').stop(); $('.waifu-tips').html(text).fadeTo(200, 1); if (timeout === null) timeout = 5000; hideMessage(timeout); } function hideMessage(timeout) { $('.waifu-tips').stop().css('opacity', 1); if (timeout === null) timeout = 5000; $('.waifu-tips').delay(timeout).fadeTo(200, 0); } let live2dBind = () => { String.prototype.render = function (context) { let tokenReg = /(\\)?\{([^\{\}\\]+)(\\)?\}/g; return this.replace(tokenReg, function (word, slash1, token, slash2) { if (slash1 || slash2) { return word.replace('\\', ''); } let variables = token.replace(/\s/g, '').split('.'); let currentObject = context; let i, length, variable; for (i = 0, length = variables.length; i < length; ++i) { variable = variables[i]; currentObject = currentObject[variable]; if (currentObject === undefined || currentObject === null) return ''; } return currentObject; }); }; let re = /x/; console.log(re); re.toString = function () { showMessage('哈哈,你打开了控制台,是想要看看我的秘密吗?', 5000); return ''; }; $(document).on('copy', function () { showMessage('你都复制了些什么呀,转载要记得加上出处哦~', 5000); }); $('.waifu-tool .fa-window-close').click(function () { showMessage('我们还能再见面的吧…', 1500); window.setTimeout(function () { $('.waifu').hide(); }, 1500); }); $('.waifu-tool .fa-music').click(function () { apFixed.toggle(); }); $('.waifu-tool .fa-comment').click(function () { showHitokoto(); }); // $('.waifu-tool .fa-image').click(function () { // if ($('.l_bg').is(":visible")) { // $('.l_bg').hide(); // $('#evanyou').show(); // } // else { // $('#evanyou').hide(); // $('.l_bg').show(); // showMessage('可能需要滚动才能刷新哦,如果一直灰灰的则说明网路不佳!', 5000); // } // }); // $('.waifu-tool .fa-eraser').click(function () { // $("#bing").remove(); // $("#evanyou").remove(); // apFixed.destroy(); // $("#aplayer-fixed").remove(); // showMessage('我们还能再见面的吧…', 2000); // window.setTimeout(function () { $('.waifu').hide(); }, 2000); // }); $.ajax({ cache: true, url: "/live2d/message.json", dataType: "json", success: function (result) { $.each(result.mouseover, function (index, tips) { $(document).on("mouseover", tips.selector, function () { let text = tips.text; if (Array.isArray(tips.text)) text = tips.text[Math.floor(Math.random() * tips.text.length + 1) - 1]; text = text.render({ text: $(this).text() }); showMessage(text, 1000); }); }); $.each(result.click, function (index, tips) { $(document).on("click", tips.selector, function () { let text = tips.text; if (Array.isArray(tips.text)) text = tips.text[Math.floor(Math.random() * tips.text.length + 1) - 1]; text = text.render({ text: $(this).text() }); showMessage(text, 1000); }); }); } }); } let live2dWelcome = () => { let text; if (document.referrer !== '') { let referrer = document.createElement('a'); referrer.href = document.referrer; text = '嗨!来自 <span style="color:#0099cc;">' + referrer.hostname + '</span> 的朋友!'; let domain = referrer.hostname.split('.')[1]; if (domain == 'baidu') { text = '嗨! 来自 百度搜索 的朋友!<br>欢迎访问<span style="color:#0099cc;">「 ' + document.title.split(' - ')[0] + ' 」</span>'; } else if (domain == 'so') { text = '嗨! 来自 360搜索 的朋友!<br>欢迎访问<span style="color:#0099cc;">「 ' + document.title.split(' - ')[0] + ' 」</span>'; } else if (domain == 'google') { text = '嗨! 来自 谷歌搜索 的朋友!<br>欢迎访问<span style="color:#0099cc;">「 ' + document.title.split(' - ')[0] + ' 」</span>'; } } else { if (window.location.href == `${homePath}`) { let now = (new Date()).getHours(); if (now > 23 || now <= 5) { text = '你是夜猫子呀?这么晚还不睡觉,明天起的来嘛?'; } else if (now > 5 && now <= 7) { text = '早上好!一日之计在于晨,美好的一天就要开始了!'; } else if (now > 7 && now <= 11) { text = '上午好!工作顺利嘛,不要久坐,多起来走动走动哦!'; } else if (now > 11 && now <= 14) { text = '中午了,工作了一个上午,现在是午餐时间!'; } else if (now > 14 && now <= 17) { text = '午后很容易犯困呢,今天的运动目标完成了吗?'; } else if (now > 17 && now <= 19) { text = '傍晚了!窗外夕阳的景色很美丽呢,最美不过夕阳红~~'; } else if (now > 19 && now <= 21) { text = '晚上好,今天过得怎么样?'; } else if (now > 21 && now <= 23) { text = '已经这么晚了呀,早点休息吧,晚安~~'; } else { text = '嗨~ 快来逗我玩吧!'; } } else { text = '欢迎来到 <span style="color:#0099cc;">「 ' + document.title.split(' - ')[0] + ' 」</span>'; } } showMessage(text, 4000); }; function showConsoleTips(content) { var style_green = "font-family:'微软雅黑';font-size:1em;background-color:#34a853;color:#fff;padding:4px;"; var style_green_light = "font-family:'微软雅黑';font-size:1em;background-color:#42d268;color:#fff;padding:4px;"; console.log("%cLive2d%c模型" + content + "完成", style_green, style_green_light); } var queue = new createjs.LoadQueue(); queue.installPlugin(createjs.Sound); queue.on("complete", handleComplete, this); queue.loadManifest([ { id: "t_1", src: "/live2d/model/uiharu/uiharu.1024/texture_00.png" }, { id: "t_2", src: "/live2d/model/uiharu/uiharu.1024/texture_01.png" }, { id: "m_1", src: "/live2d/model/uiharu/motions/tap/motion1.mtn" }, { id: "m_2", src: "/live2d/model/uiharu/motions/tap/motion2.mtn" }, { id: "m_3", src: "/live2d/model/uiharu/motions/tap/motion3.mtn" }, { id: "m_4", src: "/live2d/model/uiharu/motions/tap/motion4.mtn" }, { id: "m_5", src: "/live2d/model/uiharu/motions/tap/motion5.mtn" }, { id: "m_6", src: "/live2d/model/uiharu/motions/tap/motion6.mtn" }, { id: "m_7", src: "/live2d/model/uiharu/motions/tap/motion7.mtn" }, { id: "e_1", src: "/live2d/model/uiharu/expressions/f01.exp.json" }, { id: "e_2", src: "/live2d/model/uiharu/expressions/f02.exp.json" }, { id: "e_3", src: "/live2d/model/uiharu/expressions/f03.exp.json" }, { id: "e_4", src: "/live2d/model/uiharu/expressions/f04.exp.json" }, { id: "e_5", src: "/live2d/model/uiharu/expressions/f05.exp.json" }, { id: "e_6", src: "/live2d/model/uiharu/expressions/f06.exp.json" }, { id: "e_7", src: "/live2d/model/uiharu/expressions/f07.exp.json" }, { id: "e_8", src: "/live2d/model/uiharu/expressions/f08.exp.json" }, { id: "f_1", src: "/live2d/model/uiharu/physics.json" }, { id: "f_2", src: "/live2d/model/uiharu/uiharu.moc" }, { id: "f_3", src: "/live2d/model/uiharu/uiharu.model.json" } ]); function handleComplete() { $(".waifu-tool span").hide(); loadlive2d("live2d", "/live2d/model/uiharu/uiharu.model.json", showConsoleTips("加载")); $("#live2d").animate({ opacity: '1' }, 2000); window.setTimeout(function () { live2dBind(); live2dWelcome(); $(".waifu-tool span").show(); }, 2000); } <file_sep># Material-Flow Adapted from Material-Flow. Visit my [site](https://www.96486d9b.cn). ![](snapshot/1.png)
c70540b9484e9a38452869273265a5fd2dbc5d02
[ "JavaScript", "Markdown" ]
2
JavaScript
SherryXie1997/hexo-theme-material-flow
aaead848c95ec06cbe8ee7895c3736f409f3ea7f
f6a299fb852e665640a970b03c0efd31e545108c
refs/heads/master
<repo_name>tholdawa/micropul<file_sep>/scripts/corner.js /*global define*/ define( function() { return { blank : {} , black : { micropul : 'black' }, white : { micropul : 'white' }, one : { catalyst : true , draws : 1 }, two : { catalyst : true , draws : 2 }, plus : { catalyst : true , extraTurn : true } }; }); <file_sep>/scripts/utils.js /*global define*/ define( function(){ return { shuffle: function( arr ){ var len = arr.length, i , j , tmp; for ( i = len - 1; i > 0 ; --i ) { j = Math.floor( Math.random() * ( i + 1 ) ); tmp = arr[i]; arr[i] = arr[j]; arr[j] = tmp; } } , chunks: function( array , size ) { var result = [], slice = [].slice, start = 0 , end = array.length; while ( start < end ) { result.push( slice.call( array , start , start + size ) ); start += size; } return result; } }; }); <file_sep>/scripts/main.js /*global requirejs*/ requirejs( ['Game' , 'utils'] , function( Game , utils ){ console.log( "Loaded game dependencies." ) ; var game = Game( 1 ); window.game = game; console.log( game.board.toString() ); }); <file_sep>/scripts/Board.js /*global define*/ define( function() { function Board() { var bounds = { x: { min: 0 , max: 0} , y: { min: 0 , max: 0} }, stones = [], tiles = []; return { adjacent: function( x , y ){ var nsCol, eCol, wCol, adjacent = {}; nsCol = tiles[ x ]; eCol = tiles[ x + 1 ]; wCol = tiles[ x - 1 ]; if ( nsCol ) { if ( nsCol[ y - 1 ] ) { adjacent.n = nsCol[ y - 1 ]; } if ( nsCol[ y + 1 ] ) { adjacent.s = nsCol[ y + 1 ]; } } if ( eCol ) { adjacent.e = eCol[ y ]; } if ( wCol ) { adjacent.w = wCol[ y ]; } return adjacent; }, insert: function( tile , x , y ) { tiles[ x ] = tiles [ x ] || {}; tiles[ x ][ y ] = tile; tile.board = this; tile.position = { x: x , y: y }; this.updateBounds( x , y ); }, at: function( x , y ) { return tiles[ x ] && tiles[ x ][ y ]; }, updateBounds: function( x , y ){ bounds.x.min = Math.min( bounds.x.min , x ); bounds.x.max = Math.max( bounds.x.max , x + 1 ); bounds.y.min = Math.min( bounds.y.min , y ); bounds.y.max = Math.max( bounds.y.max , y + 1 ); }, validateMove: function( tile , x , y ){ var ne = {} , se = {} , sw = {} , nw = {}, adjacent = this.adjacent( x , y ); ne.corner = tile.corners.ne; se.corner = tile.corners.se; sw.corner = tile.corners.sw; nw.corner = tile.corners.nw; ne.adjacent = { n: adjacent.n && adjacent.n.corners.se , e: adjacent.e && adjacent.e.corners.nw }; se.adjacent = { s: adjacent.s && adjacent.s.corners.ne , e: adjacent.e && adjacent.e.corners.sw }; sw.adjacent = { s: adjacent.s && adjacent.s.corners.nw , w: adjacent.w && adjacent.w.corners.se }; nw.adjacent = { n: adjacent.n && adjacent.n.corners.sw , w: adjacent.w && adjacent.w.corners.ne }; function checkColorRule() { return [ ne , se , sw , nw ].every( function( corner ) { var dir; if ( corner.corner.micropul ) { for ( dir in corner.adjacent ) { if ( corner.adjacent[ dir ] && corner.adjacent[ dir ].micropul && corner.adjacent[ dir ].micropul !== corner.corner.micropul ) { return false; } } } return true; }); } function checkAttachmentRule() { return [ ne , se , sw , nw ].some( function( corner ) { var dir; if ( corner.corner.micropul ) { for ( dir in corner.adjacent ) { if ( corner.adjacent[ dir ] && corner.adjacent[ dir ].micropul ) { return true; } } } return false; } ); } return checkColorRule() && checkAttachmentRule(); }, toString: function() { function cornerToString( corner ) { if ( corner.micropul ) return corner.micropul[0]; if ( corner.catalyst ) { if ( corner.draws ) { if ( corner.draws === 1 ) return "."; return ":"; } if ( corner.extraTurn ) return "+"; } return "_"; } var i , j , result = "" , row , tile, lower; for ( j = bounds.y.min ; j < bounds.y.max ; ++j ) { for ( lower = 0 ; lower < 2 ; ++lower ) { for ( i = bounds.x.min ; i < bounds.x.max ; ++i ) { tile = tiles[ i ][ j ]; if ( tile ) { if (!lower ) { result += cornerToString( tile.corners.nw ) + cornerToString( tile.corners.ne); } else { result += cornerToString( tile.corners.sw ) + cornerToString( tile.corners.se); } } else { result += " "; } } result += "\n"; } } return result; }, activateCatalysts: function( tile , x , y ){ var ne = {} , se = {} , sw = {} , nw = {}, adjacent = this.adjacent( x , y ), extraTurn = false , draws = 0 , activated = false , bigCatalysts , adjacentBigCatalystActivators; ne.corner = tile.corners.ne; se.corner = tile.corners.se; sw.corner = tile.corners.sw; nw.corner = tile.corners.nw; ne.adjacent = { n: adjacent.n && adjacent.n.corners.se , e: adjacent.e && adjacent.e.corners.nw }; se.adjacent = { s: adjacent.s && adjacent.s.corners.ne , e: adjacent.e && adjacent.e.corners.sw }; sw.adjacent = { s: adjacent.s && adjacent.s.corners.nw , w: adjacent.w && adjacent.w.corners.se }; nw.adjacent = { n: adjacent.n && adjacent.n.corners.sw , w: adjacent.w && adjacent.w.corners.ne }; [ nw , ne , se , sw ].forEach( function( corner ) { if ( corner.corner.catalyst ) { activated = Object.keys( corner.adjacent ).some( function( dir ) { return corner.adjacent[ dir ] && corner.adjacent[ dir ].micropul; }); if ( activated ) { corner.corner.draws && ( draws += corner.corner.draws ); corner.corner.extraTurn && ( extraTurn = true ); } } if ( corner.corner.micropul ) { Object.keys( corner.adjacent ).forEach( function( dir ) { if ( corner.adjacent[ dir ] && corner.adjacent[ dir ].catalyst ) { corner.adjacent[ dir ].draws && ( draws += corner.adjacent[ dir ].draws ); corner.adjacent[ dir ].extraTurn && ( extraTurn = true ); } }); } }); bigCatalysts = { c: tile.bigTile ? { catalyst: tile.bigTile.catalyst , activated: [ nw , ne , se , sw ].some( function ( corner ) { return Object.keys( corner.adjacent ).some( function( dir ) { return corner.adjacent[ dir ] && corner.adjacent[ dir ].micropul; }); }) } : undefined , n: adjacent.n && adjacent.n.bigTile ? { catalyst: adjacent.n.bigTile.catalyst , activated: !!ne.corner.micropul || !!nw.corner.micropul } : undefined , w: adjacent.w && adjacent.w.bigTile ? { catalyst: adjacent.w.bigTile.catalyst , activated: !!nw.corner.micropul || !!sw.corner.micropul } : undefined , s: adjacent.s && adjacent.s.bigTile ? { catalyst: adjacent.s.bigTile.catalyst , activated: !!sw.corner.micropul || !!se.corner.micropul } : undefined , e: adjacent.e && adjacent.e.bigTile ? { catalyst: adjacent.e.bigTile.catalyst , activated: !!ne.corner.micropul || !!se.corner.micropul } : undefined }; Object.keys( bigCatalysts ).forEach( function ( dir ) { if ( bigCatalysts[ dir ] && bigCatalysts[ dir ].activated ) { bigCatalysts[ dir ].catalyst.draws && ( draws += bigCatalysts[ dir ].catalyst.draws ); bigCatalysts[ dir ].catalyst.extraTurn && ( extraTurn = true ); } }); return ( { draws : draws , extraTurn : extraTurn } ); }, tryMove: function( tile , x , y ) { var result = {}; result.success = this.validateMove( tile , x , y ); if ( result.success ) { this.insert( tile , x , y ); result.catalysts = this.activateCatalysts( tile , x , y ); } return result; }, findConnected: function( x , y , corner ) { // find recursive works in doubled space function findConnectedRecursive( working , connected ) { var potentiallyUnvisited = []; working.forEach( function ( coords ) { var adjConnected = adjacentInDoubled( coords ).filter( function( adjCoords ) { var corner = this.cornerAtDoubled( adjCoords ); return corner && corner.micropul && ( corner === origCorner ); }.bind( this )); potentiallyUnvisited = potentiallyUnvisited.concat( adjConnected ); connected[ coords.x + ',' + coords.y ] = coords; }.bind( this ) ); working = potentiallyUnvisited.filter( function ( coord ) { return !connected[ coord.x + ',' + coord.y ]; } ); if ( working.length ) findConnectedRecursive.call( this , working , connected ); } var origCorner = this.at( x , y ).corners[ corner ] , connected = {}, working = [ tileToDoubledCoords( { x: x , y: y , corner: corner } ) ]; findConnectedRecursive.call( this , working , connected ); return Object.keys( connected ).map( function( key ) { return doubledCoordsToTile( connected[ key ] ); }); }, validateStonePlacement: function( x , y , corner , player ) { if ( ! this.at( x , y ).corners[ corner ].micropul ) { return false; } var connected = this.findConnected( x , y , corner ); if ( stones.some( function( stone ) { return connected.some( function( coords ) { var match = stone.coords.x === coords.x && stone.coords.y === coords.y && stone.coords.corner === coords.corner; return match; }); }) ) { return false; } return true; }, tryPlaceStone: function( x , y , corner , player ) { var result = {}; result.success = this.validateStonePlacement( x , y , corner , player ); if ( result.success ) { result.stone = { player: player, board: this , coords: { x: x , y: y , corner: corner } }; this.placeStone( result.stone ); } return result; } , placeStone: function( stone ) { stones.push( stone ); }, cornerAtDoubled: function( coords ) { var x = coords.x , y = coords.y , tileCoords = doubledCoordsToTile( { x: x , y: y } ), tile = this.at( tileCoords.x , tileCoords.y ); return tile && tile.corners[ tileCoords.corner ]; } }; function adjacentInDoubled( doubledCoords ) { var adjacent = []; [ -1 , 1 ].forEach( function ( offset ) { adjacent.push( {x: doubledCoords.x + offset , y: doubledCoords.y } ); adjacent.push( {x: doubledCoords.x , y: doubledCoords.y + offset } ); }); return adjacent; } function tileToDoubledCoords( tileCoords ) { var x = tileCoords.x , y = tileCoords.y , corner = tileCoords.corner, xOffset = corner[0] === 'w' ? 0 : 1 , yOffset = corner[0] === 'n' ? 0 : 1; return { x : 2 * x + xOffset , y : 2 * y + yOffset }; } function doubledCoordsToTile( doubledCoords ) { var x = Math.floor( doubledCoords.x / 2 ), y = Math.floor( doubledCoords.y / 2 ) >> 0, corner = ""; corner += ( doubledCoords.y % 2 === 0 ? "n" : "s" ) + ( doubledCoords.x % 2 === 0 ? "w" : "e" ); return { x: x , y: y , corner: corner }; } }; return Board; }); <file_sep>/scripts/tests/dummyTest.js /*global define*/ "use strict"; define( ['QUnit' ,'Game'], function(QUnit , Game) { var run = function() { QUnit.test('Testing game init', function(assert) { var game = Game(); assert.equal( game.board.toString() , 'bb\nww\n', 'Board should start with starting tile.'); }); }; return {run: run} } ); <file_sep>/scripts/Player.js /*global define*/ define( function(){ function Player( game ){ return { supply: [], hand: [], unplacedStones: 3 , placedStones: [], game: game , draw: function( n ) { this.supply = this.supply.concat( this.game.draw( n ) ); }, drawToHand: function( n ) { this.hand = this.hand.concat( this.game.draw( n ) ); }, supplyToHand: function() { if ( this.supply.length && this.hand.length < this.game.MAX_HAND_SIZE ) { this.hand.push( this.supply.pop() ); return true; } return false; } }; } return Player; }); <file_sep>/scripts/unittestsmain.js /*global require, QUnit*/ "use strict"; require.config({ paths: { 'QUnit': 'libs/qunit' }, shim: { 'QUnit': { exports: 'QUnit', init: function() { QUnit.config.autoload = false; QUnit.config.autostart = false; } } } }); // require the unit tests. require( ['QUnit', 'tests/dummyTest'], function(QUnit, dummyTest) { // run the tests. dummyTest.run(); // start QUnit. QUnit.load(); QUnit.start(); } ); <file_sep>/README.md micropul ======== Free to print and play abstract strategy tile-laying game, implemented in JavaScript. see rules at http://neutralbox.com/micropul/
b99d7840589ae237fa17107b9ae3407d15c0d798
[ "JavaScript", "Markdown" ]
8
JavaScript
tholdawa/micropul
1085037e36a754d979292b8ff0794b725e6e589e
0fff43713f835ef018ad0dd6d8790debf88d3cc1
refs/heads/master
<file_sep># porting-ida-python porting IDA python script 6.x-7.3 to 7.4 ## Usage ```bash $ python porting-ida-python.py [file] ``` ## Example ```bash $ python porting-ida-python.py test.py .startEA -> .start_ea .SETPROC_ALL -> .SETPROC_LOADER_NON_FATAL .autoWait -> .auto_wait .AnalyzeArea -> .plan_and_wait .MakeName(func.start_ea, "_panic") -> .set_name(func.start_ea, "_panic", idc.SN_CHECK) .MakeName(func.start_ea, "_do_printf") -> .set_name(func.start_ea, "_do_printf", idc.SN_CHECK) .GetSegmentAttr -> .get_segm_attr .GetMnem -> .print_insn_mnem .MakeFunction -> .add_func .GetFlags -> .get_full_flags .GetOpnd -> .print_operand .FindBinary -> .find_binary [+] create: ida7_test.py ``` <file_sep>import sys ida6 = [] ida7 = [] def init(): global ida6, ida7 ida6 = open('ida6_types.txt').read().split('\n')[:-1]+open('ida6_idc.txt').read().split('\n')[:-1] ida7 = open('ida7_types.txt').read().split('\n')[:-1]+open('ida7_idc.txt').read().split('\n')[:-1] def main(): if len(sys.argv) < 2: print('Usage: porting.py [file]') return fname = sys.argv[1] data = open(fname).read() for i in range(len(ida6)): target = '.'+ida6[i].split('.')[-1] while True: cnt = data.count(target.split('(')[0]) if cnt > 0: if '(' in target: replace_data = ida7[i] before_argv = target.split('(')[1].split(')')[0].split(',') before_argc = len(before_argv) after_argv = replace_data.split('(')[1].split(')')[0].split(',') after_argc = len(after_argv) argvTo = [-1 for _ in range(after_argc)] for j in range(before_argc): try: argvTo[after_argv.index(before_argv[j])] = j except: continue replace_data = '.'+replace_data.split('.')[1].split('(')[0]+'(' real_code = data[data.index(target.split('(')[0]):] real_code = real_code.split(')')[0]+')' real_argv = real_code.split('(')[1].split(')')[0].split(',') for j in range(after_argc): if j > 0: replace_data += ', ' if argvTo[j] != -1: replace_data += real_argv[argvTo[j]] else: replace_data += after_argv[j] replace_data += ')' print(real_code+' -> '+replace_data) data = data.replace(real_code, replace_data, cnt) else: print(target+' -> '+'.'+ida7[i].split('.')[-1]) data = data.replace(target, '.'+ida7[i].split('.')[-1], cnt) else: break open('ida7_'+fname, 'w').write(data) print('[+] create: ida7_'+fname) if __name__ == '__main__': init() main()
60c5923a7bfa5cd2001b98d8ba780cd0bec65333
[ "Markdown", "Python" ]
2
Markdown
rls1004/porting-ida-python
61923de7185acf8a4b5e46673b7f5e249fac52f6
648597cc232c228d9bb60c6b2c0cd6f3ceddd6ec
refs/heads/master
<file_sep>let balance, message; let overdraft = 100; async function performPINRequest() { let PIN = concatPIN(); const resp = await axios.post(`https://frontend-challenge.screencloud-michael.now.sh/api/pin/`, { headers: { 'Content-Type': 'application/json', }, pin: JSON.stringify(PIN) }) .then(function (response) { balance = response.data.currentBalance; let currentBalance = JSON.stringify(balance); localStorage.setItem('currentBalance', currentBalance); window.location.href = 'account.html'; }) .catch(function (response) { message = response.response.data.error; localStorage.setItem('errorMessage', message); window.location.href = 'error.html'; }); } function concatPIN() { let a = document.getElementById("pin1").value; let b = document.getElementById("pin2").value; let c = document.getElementById("pin3").value; let d = document.getElementById("pin4").value; let totalPIN = a + b + c + d; return Number(totalPIN); } function clearPIN() { document.getElementById("pin1").value = ''; document.getElementById("pin2").value = ''; document.getElementById("pin3").value = ''; document.getElementById("pin4").value = ''; document.getElementById("pin1").focus(); } function checkBalance() { document.getElementById("bal").innerHTML = "£ " + JSON.parse(localStorage.getItem('currentBalance')); let custOD = JSON.stringify(overdraft); localStorage.setItem('overdraft', custOD); } function displayError() { document.getElementById("errorMsg").innerHTML = localStorage.getItem('errorMessage'); } function logout() { window.location.href = 'index.html' } function depositMoney() { let transaction = "Deposit"; constructionModal(transaction); } function transferMoney() { let transaction = "Transfer"; constructionModal(transaction); } function calculateAmount() { let withdrawalAmt = document.getElementById("amount").value; withdrawalAmt = Number(withdrawalAmt); let currentAmt = JSON.parse(localStorage.getItem('currentBalance')); let overdraft = JSON.parse(localStorage.getItem('overdraft')); let newAmt = 0, overdraftAmt = 0; if (withdrawalAmt > currentAmt && overdraft === 0) { errorModal(); } else { newAmt = currentAmt - withdrawalAmt; if (newAmt < 0 && overdraft !== 0){ debugger; if (currentAmt < 0){ overdraftAmt = overdraft - withdrawalAmt; } else { warningModal(); overdraftAmt = (overdraft + currentAmt) - withdrawalAmt; } if (overdraftAmt >= 0) { overdraftAmt = JSON.stringify(overdraftAmt); localStorage.setItem('overdraft', overdraftAmt); } else { errorModal(); return; } } newAmt = JSON.stringify(newAmt); localStorage.setItem('currentBalance', newAmt); document.getElementById("amount").value=''; document.getElementById("bal").innerHTML = "£ " + JSON.parse(localStorage.getItem('currentBalance')); document.getElementById("amount").focus(); } } function constructionModal(transaction) { let modal = document.getElementById("constructionModal"); let span = document.getElementsByClassName("close")[0]; document.getElementById("modal-title").innerHTML = transaction; modal.style.display = "block"; span.onclick = function() { modal.style.display = "none"; document.getElementById("amount").focus(); } window.onclick = function(event) { if (event.target === modal) { modal.style.display = "none"; document.getElementById("amount").focus(); } } } function errorModal() { let errorModal = document.getElementById("errorModal"); let errorSpan = document.getElementsByClassName("errorClose")[0]; errorModal.style.display = "block"; errorSpan.onclick = function() { errorModal.style.display = "none"; document.getElementById("amount").focus(); } window.onclick = function(event) { if (event.target === errorModal) { errorModal.style.display = "none"; document.getElementById("amount").focus(); } } } function warningModal() { let warningModal = document.getElementById("warningModal"); let warningSpan = document.getElementsByClassName("warningClose")[0]; warningModal.style.display = "block"; warningSpan.onclick = function() { warningModal.style.display = "none"; document.getElementById("amount").focus(); } window.onclick = function(event) { if (event.target === warningModal) { warningModal.style.display = "none"; document.getElementById("amount").focus(); } } } <file_sep># web-atm-app A simple ATM app that makes an API call for the user when they enter their PIN to retrieve their bank balance. ## Download The latest version is included above in the web-atm-app repository. This can be downloaded either via a ZIP file or `git clone https://github.com/JRasta/web-atm-app.git` ## Usage Once cloned the web-app should be accessible on [this link](http://localhost:63342/web-atm-app/src/index.html). If not it can be ran from within WebStorm to open in a default browser. ## Third Party Libraries Node.js - v10.16.3 Axios - v0.19.0 (via NPM) ## License ISC License ## Software Used WebStorm 2019.2.2 - Licensed to WebStorm Evaluator (Expiration date: October 23, 2019) Non-Bundled Plugins ## Version Version 1.0 ## Contact Email: <EMAIL>
7cbee9785dd4c8a37a01382a9bffd3879e93dabc
[ "JavaScript", "Markdown" ]
2
JavaScript
JRasta/web-atm-app
7de9d302a488d3a0b0ac6bfa45c776e2f677d13c
d32ad42106c719f12bfe5cf2adf53f47efb89ac4
refs/heads/master
<repo_name>Parthu8108/PythonCode<file_sep>/fibonaaciSeries.py def fib(): a=0 b=1 n=input('Enter n\n') print('The fib series is:\n') print(a) print(b) while n>0: c=a+b print(c) a=b b=c c=a n-=1 fib() <file_sep>/reverse.py def rev(): n=input('Enter the number\n') sum=0 while n>0: no=n%10 sum=sum*10+no #print(sum) n=n/10 print(sum) rev() <file_sep>/lambaExample.py x = lambda a:a+10 print(x(3)) y = lambda a,b : a+b+4 print(y(10,12)) def func(n): return lambda a:a*n x=func(5) print(x(2)) def abc(n): return lambda a:a*n x=abc(2) y=abc(3) print(x(11)) print(y(11)) <file_sep>/files.py newfile=open("new.txt","w+") str="Hellooo" newfile.write(str)<file_sep>/multipleInheritance.py class A: def __init__(self): self.a="A" print(self.a) class B: def __init__(self): self.b="B" print(self.b) class C(A,B): def __init__(self): A.__init__(self) B.__init__(self) print("hello") def funct(self): print("Inside the derived class:") print(self.a) print(self.b) x=C() x.funct() <file_sep>/printWays.py print('hello') print("hello") print("""helloo how are you""") print("abc"," xyz") print("abc"+" xyz") #printf("abc") print("hello \new") print("hello \\new")#\\ to print \news <file_sep>/table.py no=61 for i in range(1,11): print(no,'x',i,'=',no*i) <file_sep>/classDemo.py class parthuu: def __init__(self,name,age): self.name=name self.age=age def funct(self): print("The name is "+self.name) p_object=parthuu("Parthuu",21) print(p_object.name) print(p_object.age) p_object.funct() <file_sep>/infiniteArg.py def abc(*people): for person in people: print(person) abc("Parth","ABC") abc("Parth","ABC","DSA") abc("Parth") <file_sep>/inheitanceExamp.py class A: def __init__(self,no): self.no=no def funct(self): print(self.no) class B(A): pass x = B(10) x.funct() <file_sep>/multilevelInheritance.py class A: def __init__(self,name): self.name=name def getName(self): return self.name class B(A): def __init__(self,name,add): A.__init__(self,name) self.add=add def getAdd(self): return self.add class C(B): def __init__(self,name,add,no): B.__init__(self,name,add) self.no=no def getNo(self): return self.no object=C("Parth","Noida",100) p=object.getNo() q=object.getName() r=object.getAdd() print(p) print(q) print(r) <file_sep>/printmore.py print("Welcome user:") print("Please enetr your name:") name=raw_input(); print("Please enetr your place:") place=raw_input(); print("The name of the user is:" +name.upper()) print("The place of the user is:" +place.lower()) print('I havce %d cats'%6 ) print('I havce %2d cats'%6 ) print('I havce %0.2d cats'%2 ) print('I havce %6f cats'%6 ) print('I havce %0.2f cats'%6 ) #EXAMPLE OF .format print('no1 {0:d} no2 {1:d} no3 {2:d} '.format(6,5,2) ) print('I have {0:d} cats'.format(7) ) print('I have {0:d} cats'.format(8) ) #example of \ total=6+5+4 \ +4 print(total) print('no1 {0:d}'+ \ 'no2 {1:d}'+ \ ' no3 {2:d} '.format(6,5,2) ) <file_sep>/userInput.py #print("Name") name =raw_input("Name ") print("my name is "+name) #name=input() error if we put a strnig #print(name) fname=raw_input("ENter the first name ") lname=raw_input("ENter the last name ") print("name= "+fname+" "+lname) fname.upper() fname.lower() fname.swapcase() x=input() y=input() z=x+y s=float(x)+float(y) print(z) print(s)<file_sep>/classWithFib.py class demo: def __init__(self,no): self.no=no def fib(self,n): a=0 b=1 print(a) print(b) self.n=n while n != 0: c = a+b print(c) a=b b=c c=a n-=1 p=demo(10) p.fib(10) <file_sep>/pallindrone.py def pal(): n=input('Enter the number\n') sum=0 b=n while n>0: no=n%10 sum=sum*10+no #print(sum) n=n/10 print(sum) if sum == b: print('pallindrone') else: print('Not') pal() <file_sep>/primeNumber.py num=7 if num > 1: for i in range(2,num): if(num % i)==0: print(num,'not prime') break else: print(num,'prime') #break else: print('not prime')
4151f4bf7414180cf25417402874aa5a11f28882
[ "Python" ]
16
Python
Parthu8108/PythonCode
5ce32dae90b8f1fc3806eee7e025ae413dbf4a5b
e7de356091832086a114d3e743515ddafea90eac
refs/heads/master
<file_sep>/* npm init enters++ npm i --save express npm i --save-dev nodemon en le json "start": "node app", "dev": "nodemon app" npm run dev -- en consola npm i --save hbs */ const express = require('express') const PORT = process.env.PORT || 3000; const app = express(); app.use( express.static(__dirname + '/public')) app.get('/', (request, response, next) => { response.sendFile(__dirname + '/views/index.html'); }); app.get('/about', (request, response, next) => { response.sendFile(__dirname + '/views/about.html'); }); app.get('/gallery', (request, response, next) => { response.sendFile(__dirname + '/views/gallery.html'); }); app.listen(PORT, () => { console.info(`App listen ar ${PORT} port`); });
ea132793db45e32430ef303c7025043764d4591e
[ "JavaScript" ]
1
JavaScript
Cdelatorre/lab-express-basic-site
77750f73775d71e90ad032b7d65561c33b84481e
e90ff1c74c98147feb5aacae4bf66d66815ac6db
refs/heads/main
<repo_name>anthonyguidomadrid/tailorChallenge<file_sep>/README.md # Endpoints server | Method | Path | Description | | :----- | :----------------- | :------------------------------- | | Get | /api/restaurants | Get all restaurants from the database | # Routes client | Path | Description | | :--------- | :----------------------------------------- | | /restaurants | List of all the restaurants from the DB | <file_sep>/client/pages/restaurants/index.js import RestaurantsList from '../../components/restaurants/RestaurantList' export default function Restaurants() { return ( <RestaurantsList /> ) } <file_sep>/client/pages/api/restaurants-service.js import axios from 'axios' class RestaurantsService { constructor() { this.app = axios.create({ baseURL: 'http://localhost:5000/api/restaurants', withCredentials: true }) } getAllRestaurants = () => this.app.get('/') } export default RestaurantsService<file_sep>/server/routes/index.js module.exports = app => { // Base URLS app.use('/api/restaurants', require('./restaurants.routes')) }<file_sep>/server/routes/restaurants.routes.js const express = require('express') const router = express.Router() const Restaurant = require('../models/restaurant.model') // GET ALL RESTAURANTS router.get('/', (req, res) => { Restaurant .find() .select('name neighborhood image cuisine_type') .then(response => res.json(response)) .catch(err => res.status(500).json({ code: 500, message: 'Error loading restaurants', err })) }) module.exports = router<file_sep>/client/components/restaurants/RestaurantList.js import styles from './RestaurantList.module.css' import React, { useState, useEffect } from "react"; import RestaurantsService from '../../pages/api/restaurants-service' import RestaurantCard from './RestaurantCard' import { Container, Row, Spinner } from 'react-bootstrap' const restaurantService = new RestaurantsService() const RestaurantsList = () => { const [restaurants, setRestaurants] = useState(); useEffect(() => { updateRestaurants() }, [] ) const updateRestaurants = () => { restaurantService .getAllRestaurants() .then(response => setRestaurants(response.data)) .catch(err => console.log(err)) } return ( !restaurants? <Spinner animation="grow" className='spinner'/> : <Container> <h1>{restaurants.length} Restaurants in New York</h1> <Row> {restaurants.map(elm => <RestaurantCard key={elm._id} {...elm}/>)} </Row> </Container> ); } export default RestaurantsList<file_sep>/client/components/layout/Menu.js import { Nav, Navbar } from 'react-bootstrap' import styles from './Menu.module.css' import Image from 'next/image' import logo from './logo.png' const Menu = () => { return ( <Navbar className={styles.menu} bg="dark" expand="lg"> <Navbar.Brand href="#home"><Image src={logo} alt='restaurant logo'/></Navbar.Brand> <Navbar.Toggle aria-controls="basic-navbar-nav" /> <Navbar.Collapse id="basic-navbar-nav"> <Nav className="mr-auto"> <Nav.Link href="/">Home</Nav.Link> <Nav.Link href="/restaurants">Restaurants</Nav.Link> <Nav.Link href="/restaurants/new">Register a new restaurant</Nav.Link> <Nav.Link href="/login">Log in</Nav.Link> <Nav.Link href="/signup" className={styles.signup}>Sign up</Nav.Link> </Nav> </Navbar.Collapse> </Navbar> ) } export default Menu<file_sep>/server/config/locals.config.js module.exports = app => { app.locals.siteTitle = 'Tailor Challenge Server' }<file_sep>/server/models/restaurant.model.js const mongoose = require('mongoose') const Schema = mongoose.Schema const restaurantSchema = new Schema({ }, { timestamps: true }) const Restaurant = mongoose.model("Restaurant", restaurantSchema) module.exports = Restaurant
507de0492ab562633d6e657454e846f2e69772f8
[ "Markdown", "JavaScript" ]
9
Markdown
anthonyguidomadrid/tailorChallenge
f943f565ae67ea54fd60016869e6f1a1d334353a
6d8097f839420d3b23dddc6f35ff3ba594ea7cc5
refs/heads/master
<file_sep>#coding=utf-8 import requests import xlwt from bs4 import BeautifulSoup def tvopen(): res = requests.get('http://www.tvyan.com') # 爬取下来的编码是ISO-8859-1格式,需要转化为utf-8格式 res.encoding= 'utf-8' soup = BeautifulSoup(res.text, 'html.parser') # tai = soup.select('.tai a') # for i in range(0, tai.__len__()): # singleTv(i, tai[i]['href']) list = soup.select('.listclass a') # for i in range(0, list.__len__()): out_list = [] for i in range(0, list.__len__()): out_list += listTv(list[i]['href']) for j in range(0, out_list.__len__()): singleTv(j, out_list[j]) # print tai # print soup def singleTv(i, url): # res = requests.get('http://www.tvyan.com' + url) res = requests.get('http://' + url) res.encoding = 'utf-8' soup = BeautifulSoup(res.text, 'html.parser') tv_icon = soup.select('div .content img')[0].get("src") # print tv_icon introduction = soup.select('div .content').pop().text # print introduction name = soup.select('.place h1').pop().text print name print i saveTvInforma(i, name, introduction, tv_icon) # print soup def listTv(url): realUrl = 'http://www.tvyan.com' + url res = requests.get(realUrl) res.encoding = 'utf-8' soup = BeautifulSoup(res.text, 'html.parser') pageList = soup.select('.pagelist li a')[:-2] tvUrl = [] tvUrl += listSinglePage(realUrl) for i in range(0, pageList.__len__()): tvUrl = tvUrl + listSinglePage(realUrl + pageList[i].get('href')) # pageListUrl.append(realUrl + pageList[0].get('href')) # print 111 # print tvUrl newTvUrl = list(set(tvUrl)) return newTvUrl def listSinglePage(url): res = requests.get(url) res.encoding = 'utf-8' soup = BeautifulSoup(res.text, 'html.parser') tvList = soup.select('.tv li a') tvListUrl = [] for i in range(0,tvList.__len__()): tvListUrl.append(tvList[i].get('href')[2:]) return tvListUrl def saveTvInforma(i, name, introduction, icon): workbook1.write(i, 0, name) workbook1.write(i, 1 , introduction) link = 'HYPERLINK("%s";"%s")' % ( 'http://www.tvyan.com' + icon, 'http://www.tvyan.com' + icon ) workbook1.write(i, 2, xlwt.Formula(link)) workbook.save(r'/Users/shucan/python_pachong/excel/tv.xlsx') workbook = xlwt.Workbook(encoding='utf-8') workbook1 = workbook.add_sheet("tv") tvopen() <file_sep>#coding=utf-8 import xlwt def saveTvInforma(i, name, introduction, icon): workbook1.write(i, 0, name) workbook1.write(i, 1 , introduction) link = 'HYPERLINK("%s";"%s")' % ( icon, icon ) workbook1.write(i, 2, xlwt.Formula(link)) workbook.save(r'/Users/shucan/python_pachong/excel/tv.xlsx') # worksheet.write(0, 0, xlwt.Formula('HYPERLINK("http://www.google.com";"Google")') # 超链接书写进excel workbook = xlwt.Workbook(encoding='utf-8') workbook1 = workbook.add_sheet("tv") # for可以遍历任何序列的项目如一个列表或者一个字符串 # for lette in "letter": # print lette, # fruit = {"apple", 'orange', 'watermelon'} # for fruit_i in fruit: # print fruit # #这是输出 # #set(['orange', 'watermelon', 'apple']) # #set(['orange', 'watermelon', 'apple']) # #set(['orange', 'watermelon', 'apple']) # fruit = ["apple", 'orange', 'watermelon'] # for index in range(len(fruit)): # print fruit[index] # # print fruit.__len__() # # print range(len(fruit)) # # print range(10,20) # 素数 # i=2 # while(i < 100): # j=2 # while(j<=(i/j)): # if not(i%j):break # j = j + 1 # if (j > i/j) : print i, " 是素数" # i = i + 1 # import math # print dir(math) # print math.pi # print math.e # # print "\a" # print "my name is %s and age is %d" % ("舒灿", 23) list1 = ["1", "2", 3] # list2 = ["1", "2", "3"] #Python 3.X 的版本中已经没有 cmp 函数,如果你需要实现比较功能,需要引入 operator 模块,适合任何对象 # print cmp(list1, list2) # 默认Pop出最后一个index=-1,可以自己设定 # print list1.pop(); # print list1 # # tup = (1) # print tup for i in range(0, list1.__len__()): print i #任意无符号的对象,以逗号隔开,默认为元组<file_sep>#coding=utf-8 import sys, getopt def main(argv): inputfile = '' outputfile = '' try: opts, args = getopt.getopt(argv, "hi:o", ["ifile=", "ofile="]) except getopt.GetoptError: print 'test2_opt.py -i <inputfile> -o <outputfile>' sys.exit(2) for opt, arg in opts: if opt == '-h': print 'test2_opt.py -i <inputfile> -o <outputfile>' sys.exit() elif opt in ("-i", "--ifile"): inputfile = arg elif opt in ("-o", "--ofile"): outputfile = arg print '输入的文件名为', inputfile print '输出的文件名为', outputfile if __name__ == "__main__": main(sys.argv[1:]) """ python有五个标准类型 numbe数字, string字符串, list列表, tuple元组(数组), dictionary字典 """ # str = 'abc' # print str * 3 # print '123' + str # #不存在越界问题,直接输出到最大 # print str[1:3] list = [123, "shucan", 2.23, [456, "xulei", 0.3]] # print list # print list[2:4] # print list[-1] #元组,元组不能二次赋值,相当于只读 tuple = ('shucan_tuple', 123, 0.23) # print tuple # print tuple[0:3] # list[0] = 1234 # tuple[1] = 1234 #dictionary 是除列表list以外Python里面最灵活的内置数据结构,是无序的,通过键来存取的,而不是通过偏移 ,用{}来表示,由索引key和值value组成 dict = {} dict['one'] = 'one_test' dict[1] = 1 # print dict # print dict.keys() # print dict.values() print int('5', 16) print complex(1, 2) print oct(123) print hex(123) print ord("s") print unichr(97) print 9.0 // 2 print 9/2 print 2**3 #位运算符 # 0011 0010 a = 50 # 0011 1100 b = 60 # print a&b # # print ~b #逻辑运算符 and or not x = 1 y = 2 if x and y: print 1 else: print 2 # 成员运算符 a = 1 b = 20 c = [2,3,4,5,20] if a in c: print '1在列表里面' elif b in c: print '20在列表里面' else: print '比较完毕' # 身份运算符 is 或者 is not 判断两个标识符是不是指向同一个对象 类似于==(具体判断的是亮哥对象的值是否相等) # identity = "shucan" # # identity1 = identity # identity2 = identity # if identity1 is identity2: # print '指向同一个对象,即同一个身份' # else: # print '不指向同一个身份' a_test = [1, 2, 3] print a_test[:] b_test = a_test[:] print b_test<file_sep># 进行人脸录入 / face register # 录入多张人脸 / support multi-faces # Author: coneypo # Blog: http://www.cnblogs.com/AdaminXie # GitHub: https://github.com/coneypo/Dlib_face_recognition_from_camera # Mail: <EMAIL> # Created at 2018-05-11 # Updated at 2018-10-29 import dlib # 人脸处理的库 Dlib import numpy as np # 数据处理的库 Numpy import cv2 # 图像处理的库 OpenCv import os # 读写文件 import shutil # 读写文件 # Dlib 正向人脸检测器 detector = dlib.get_frontal_face_detector() # Dlib 68 点特征预测器 predictor = dlib.shape_predictor('shape_predictor_68_face_landmarks.dat') # OpenCv 调用摄像头 cap = cv2.VideoCapture(0) # 设置视频参数 # cap.set(3, 480) cap.set(cv2.CAP_PROP_FRAME_WIDTH, 1920) cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 1080) size = (int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)), int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))) _,frame = cap.read() print(size) # 正确结果(1024,1280) print(frame.shape)# 正确结果(1024,1280, 3) # 人脸截图的计数器 cnt_ss = 0 # 存储人脸的文件夹 current_face_dir = 0 # 保存的路径 path_make_dir = "/Users/shucan/Documents/ai_study/face_recognition/data/data_faces_from_camera/" path_csv = "/Users/shucan/Documents/ai_study/face_recognition/data/data_csvs_from_camera/" # (optional) 删除之前存的人脸数据文件夹 def pre_clear(): folders_rd = os.listdir(path_make_dir) for i in range(len(folders_rd)): shutil.rmtree(path_make_dir+folders_rd[i]) csv_rd = os.listdir(path_csv) for i in range(len(csv_rd)): os.remove(path_csv+csv_rd[i]) # 每次程序录入之前,删掉之前存的人脸数据 pre_clear() # 人脸种类数目的计数器 person_cnt = 0 while cap.isOpened(): print("打印人脸截图的计数器", cnt_ss) # 480 height * 640 width # cap.read()按帧读取视频,每次读取一帧数据进行数据操作 flag, img_rd = cap.read() # 这里读取出来的是720 1280,所以调取出来的摄像机的大小其实就是720 1280 print("输出一下numpy.ndarray大小", img_rd.size) # 输出的其实是一个三维数组 print("输出一下numpy.ndarray的维度shape", img_rd.shape) # print(type(img_rd)) # print(img_rd) kk = cv2.waitKey(1) img_gray = cv2.cvtColor(img_rd, cv2.COLOR_RGB2GRAY) print("RGB颜色空间转换成灰度", img_gray) print("灰度图的shape", img_gray.shape) # 人脸数 faces faces = detector(img_gray, 0) # 待会要写的字体 font = cv2.FONT_HERSHEY_COMPLEX # 按下 'n' 新建存储人脸的文件夹 if kk == ord('n'): person_cnt += 1 current_face_dir = path_make_dir + "person_" + str(person_cnt) print('\n') for dirs in (os.listdir(path_make_dir)): if current_face_dir == path_make_dir + dirs: shutil.rmtree(current_face_dir) print("删除旧的文件夹:", current_face_dir) os.makedirs(current_face_dir) print("新建的人脸文件夹: ", current_face_dir) # 将人脸计数器清零 cnt_ss = 0 # 其实底层每触发一次检测到人脸的的机制这里就会调用一次,底层一直在人脸检测到机制 if len(faces) != 0: # 检测到人脸 # 矩形框 for k, d in enumerate(faces): # print("输出K值", k) # print("输出d值", d) print("输出d.left", d.left()) print("输出d.top", d.top()) print("输出d.right", d.right()) print("输出d.bottom", d.bottom()) # 计算矩形大小 # (x,y), (宽度width, 高度height) pos_start = tuple([d.left(), d.top()]) print(pos_start) pos_end = tuple([d.right(), d.bottom()]) print(pos_end) # 计算矩形框大小 height = (d.bottom() - d.top()) width = (d.right() - d.left()) hh = int(height/2) ww = int(width/2) # 设置颜色 / The color of rectangle of faces detected color_rectangle = (255, 255, 255) if (d.right()) + ww > 1280 or (d.bottom() + hh >720) or (d.left() - ww < 0) or ( d.top() -hh < 0): cv2.putText(img_rd, "OUT OF RANGE", (20, 300), font, 0.8, (0, 0, 255), 1, cv2.LINE_AA) color_rectangle = (0, 0, 255) else: color_rectangle = (255, 255, 255) cv2.rectangle(img_rd, #对角线坐标构建矩形边框 tuple([d.left() , d.top() ]), tuple([d.right() , d.bottom() ]), color_rectangle, 4) # 根据人脸大小生成空的图像 im_blank = np.zeros((int(height*2), width*2, 3), np.uint8) # 按下 's' 保存摄像头中的人脸到本地 if kk == ord('s'): cnt_ss += 1 for ii in range(height * 2): # 循环742次 for jj in range(width * 2): # 循环744次 # hh=371/2 = 185 ww = 372/2 = 186 # print(ii) # print(jj) # print(d.top()-hh + ii) # print(d.left()-ww+ jj) im_blank[ii][jj] = img_rd[d.top() - hh + ii][d.left() - ww + jj] cv2.imwrite(str(current_face_dir) + "/img_face_" + str(cnt_ss) + ".jpg", im_blank) print("写入本地:", str(current_face_dir) + "/img_face_" + str(cnt_ss) + ".jpg") # 显示人脸数 cv2.putText(img_rd, "Faces: " + str(len(faces)), (20, 100), font, 0.8, (0, 255, 0), 1, cv2.LINE_AA) # 添加说明 cv2.putText(img_rd, "Face Register", (20, 40), font, 1, (0, 0, 0), 1, cv2.LINE_AA) cv2.putText(img_rd, "N: New face folder", (20, 350), font, 0.8, (0, 0, 0), 1, cv2.LINE_AA) cv2.putText(img_rd, "S: Save face", (20, 400), font, 0.8, (0, 0, 0), 1, cv2.LINE_AA) cv2.putText(img_rd, "Q: Quit", (20, 450), font, 0.8, (0, 0, 0), 1, cv2.LINE_AA) # 按下 'q' 键退出 if kk == ord('q'): break # 窗口显示 # cv2.namedWindow("camera3", 0) # 如果需要摄像头窗口大小可调 cv2.imshow("camera", img_rd) # 释放摄像头 cap.release() # 删除建立的窗口,关闭所有的图像窗口 cv2.destroyAllWindows() #cv2.waitKey(1),waitKey()方法本身表示等待键盘输入, #参数是1,表示延时1ms切换到下一帧图像,对于视频而言; #参数为0,如cv2.waitKey(0)只显示当前帧图像,相当于视频暂停,; #参数过大如cv2.waitKey(1000),会因为延时过久而卡顿感觉到卡顿<file_sep>import cv2 import numpy as np def rgb2gray_mean(img): ratio = 1/3 init_img = img.astype(np.int32) result = ratio * (init_img[...,0] + init_img[...,1] + init_img[...,2]) return result.astype(np.uint8) def main(): color = cv2.imread("/Users/shucan/Desktop/111.PNG") print(color.shape) gray = rgb2gray_mean(color) print(gray.shape) cv2.imshow("color", color) print(color) print(gray) # cv2.imshow("gray", gray) # cv2.waitkey(0) print(__name__) if __name__ == 'builtins': print(__name__) main()<file_sep>#coding = utf-8 import tensorflow as tf import tensorflow as tf v1 = tf.constant([1.0,2.0,3.0,4.0]) v2 = tf.constant([4.0,3.0,2.0,1.0]) sess = tf.InteractiveSession() print(tf.greater(v1,v2).eval()) <file_sep>import numpy as np import cv2 # 像这种只能表示的是多维数组里面的某一个点的值,可想象成某一个点的权重值 # a = np.array([[[1,2],[3,4]]]) # print(a) # print(type(a)) # print(a.size) # print(a.shape) img = cv2.imread("/Users/shucan/Desktop/111.PNG",0) print(img) print(img.shape)<file_sep>#coding=utf-8 import xlrd import xlwt from bs4 import BeautifulSoup import requests def merge_two_dicts(x, y): """Given two dicts, merge them into a new dict as a shallow copy.""" z = x.copy() z.update(y) return z def request(url): headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) ' 'Chrome/51.0.2704.63 Safari/537.36'} res = requests.get(url,headers = headers) res.encoding='utf-8' soup = BeautifulSoup(res.text, 'html.parser') return soup def readfromxlsl(url): myWorkBook = xlrd.open_workbook(url) table = myWorkBook.sheet_by_name('province_url') return table # 单个province里面所有可能的电视台列表值url def channelTimeUrl(url, name): totalProgram = {} provinceNameBook = workbook.add_sheet(name) soup = request(url) channelsBig = soup.select('.chlsnav a') channelsSmall = soup.select('.chlsnav ul a') pbarName = '' pbar = soup.select('.pbar') if pbar.__len__() == 0: pbarName = '获取名称失败,进入链接获取名称' else: pbarName = pbar.pop().text programTable = {} for i in range(0, channelsBig.__len__()): programTable[channelsBig[i].get('title')] = 'https://www.tvmao.com' + channelsBig[i].get('href') for i in range(0, channelsSmall.__len__()): title = channelsSmall[i].get('title') if programTable.has_key(title): programTable.pop(title) programTable[pbarName] = url for key in programTable.keys(): dict = channelTime(programTable[key]) if dict is None: continue else: totalProgram = merge_two_dicts(dict, totalProgram) i = 0 for key in totalProgram.keys(): provinceNameBook.write(i, 0, key) provinceNameBook.write(i ,1, totalProgram[key]) i = i + 1 workbook.save(r'/Users/shucan/python_pachong/excel/'+ name +'.xlsx') def channelTime(url): soup = request(url) channelSmall = soup.select('.chlsnav ul li') if channelSmall.__len__() == 0: return None programName = channelSmall.pop(0).text programTable = {} programTable[programName] = url for i in range(0, channelSmall.__len__()): try: programTable[channelSmall[i].select('a')[0].get('title')] = 'https://www.tvmao.com' + channelSmall[i].select('a')[0].get('href') except BaseException: print "插入异常,异常数据", channelSmall[i] programTable.__len__() return programTable workbook = xlwt.Workbook(encoding='utf-8') table = readfromxlsl('/Users/shucan/python_pachong/excel/province_url.xlsx') for i in range(0, table.nrows): channelTimeUrl(table.cell(i, 1).value, table.cell(i, 0).value) # for i in range(0, table.nrows): # name = table.cell(i, 0).value # url = table.cell(i, 1).value<file_sep>#coding=utf-8 import tensorflow as tf t0 = tf.constant(3, dtype=tf.int32) t0L = tf.constant(4, dtype=tf.int32) t1 = tf.constant([3., 4.1, 5.2], dtype=tf.float32) t1L = tf.constant([4., 5.1, 6.2], dtype=tf.float32) t2 = tf.constant([['1', '2'],['3', '4']], dtype=tf.string) t2L = tf.constant([['5', '6'],['7', '8']], dtype=tf.string) t3 = tf.constant([[[5],[6],[7],[8]]]) W = tf.Variable(4, dtype=tf.float32) b = tf.Variable(5, dtype=tf.float32) # 创建 x 节点,用来输入实验中的输入数据 x = tf.placeholder(tf.float32) y = tf.placeholder(tf.float32) # 创建线性模型 linear_model = W*x + b # 创建 y 节点,用来输入实验中得到的输出数据,用于损失模型计算 y = tf.placeholder(tf.float32) # 创建损失模型 loss = tf.reduce_sum(tf.square(linear_model - y)) optimizer = tf.train.GradientDescentOptimizer(0.002) train = optimizer.minimize(loss) x_train = [1, 2, 3, 6, 8] y_train = [4.8, 8.5, 10.4, 21.0, 25.3] with tf.Session() as sess: # 必须要初始化才能使用,初始化和定义变量是两部在这个里面 sess.run(tf.global_variables_initializer()) # print(sess.run(linear_model, {x: [1, 2, 3, 6, 8]})) # print(sess.run(b)) # print sess.run(x + y, {x:[1,2,3,4,5], y:[2,3,4,5,6]}) for i in range(10000): sess.run(train, {x: x_train, y: y_train}) for i in range(10000): print('W: %s, b: %s, loss: %s' %(sess.run(W), sess.run(b), sess.run(loss, {x:x_train, y:y_train}))) <file_sep>from PIL import Image, ImageDraw image_xl = Image.open("/Users/shucan/Desktop/111.PNG") image_sc = Image.open("/Users/shucan/Desktop/222.jpeg") image_tmp = image_sc.resize((100,100)) print(image_tmp.size) print(image_tmp.split()) r,g,b = image_tmp.split() draw = ImageDraw.Draw(image_xl) draw.bitmap((0,0), r, fill=(255,0,0)) draw.bitmap((100,100), g, fill=(0,255,0)) draw.bitmap((200,200), b, fill=(0,0,255)) # # print(image_xl.size) # # draw.line((0,0) + image_xl.size, fill=(255,0,0)) # # draw.line((0, image_xl.size[1], image_xl.size[0], 0), fill=255) image_xl.show() del image_xl<file_sep>import requests import os import pandas as pd import matplotlib.pyplot as plt plt.style.use('ggplot') # r = requests.get(r"https://api.github.com/users/acombs/starred") # print(type(r.json())) # type list # for i, val in enumerate(r.json()): # print("序号: %s, 值: %s" % (i + 1, val)) # 'r'是防止字符转义的 如果路径中出现'\t'的话 不加r的话\t就会被转义 而加了'r'之后'\t'就能保留原有的样子 PATH = r'/Users/shucan/Documents/ai_study/' r= requests.get('https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data') with open(PATH + 'iris.data','w') as f: f.write(r.text) os.chdir(PATH) df = pd.read_csv(PATH + 'iris.data', names=['sepal length', 'sepal width', 'petal length', 'petal width', 'class']) print(df) print(df.ix[:3, [x for x in df.columns if 'width' in x]]) print(type(df['class'].unique())) print('输出去重后的class: %s' % df['class'].unique()) # print(df[df['class'] =='Iris-virginica'].reset_index(drop=True)) # & 运算优先级大于 > 号 print(df[(df['class']== 'Iris-virginica') & (df['petal width'] > 2.2)]) print(df.describe()) # 查看前n行,n为参数,默认是5 print(df.head()) print(df.corr()) plt.style.use('ggplot') fig,ax = plt.subplots(figsize=(6,4)) ax.hist(df['sepal length'], color='black') ax.set_ylabel('数量', fontsize=12) ax.set_xlabel('length', fontsize=12) plt.title('莺尾花花萼的长度', fontsize=14, y=1.01) exit() <file_sep>#coding=utf-8 import requests from bs4 import BeautifulSoup def imgurl(url): res = requests.get(url) soup = BeautifulSoup(res.text, 'html.parser') page = int(soup.select('.pagenavi span')[-2].text) #获取总页数,-2为去掉上下页 src = soup.select('.main-image a img')[0].get('src') beautifulgirlid = src[-9:-6] print ('开始下载妹子:' , format(beautifulgirlid)) # 输出窗口提示下载 for i in range(1, page + 1): i = '%02d' % i img = src.replace('01.jpg', str(i)+'.jpg') headers = { 'User-Agent': 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)', 'Referer': 'http://www.mzitu.com' } response = requests.get(img, headers=headers) f = open('/Users/shucan/python_pachong/beautiful_girl/'+ beautifulgirlid +'%s.jpg' % i, 'wb') f.write(response.content) print( beautifulgirlid + i) print '输出妹子id' print(beautifulgirlid) def imgpage(page): res = requests.get('http://www.mzitu.com/page/' + str(page)) soup = BeautifulSoup(res.text, 'html.parser') print soup href = soup.select('#pins a') # print '开始挑选' # print href list = set([i.get('href') for i in href]) print list # [imgurl(i) for i in list] # imgpage_select_one(list.pop()) def imgpage_select_one(url): print url res = requests.get(url) soup = BeautifulSoup(res.text, 'html.parser') print soup page = int(soup.select('.pagenavi span')[-2].text) print page result = input('下载那一页:') imgpage(result) <file_sep>#coding=utf-8 import requests import xlwt from bs4 import BeautifulSoup import urllib3,random from Tkinter import * import sys # # my_headers=[ # "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36", # "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36", # "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:30.0) Gecko/20100101 Firefox/30.0", # "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_2) AppleWebKit/537.75.14 (KHTML, like Gecko) Version/7.0.3 Safari/537.75.14", # "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Win64; x64; Trident/6.0)" # ] def getIndex(url): headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) ' 'Chrome/51.0.2704.63 Safari/537.36'} res = requests.get(url,headers = headers) res.encoding='utf-8' soup = BeautifulSoup(res.text, 'html.parser') provinceContentUrl = soup.select('.ml20') province_url_dictionary = {} for i in range(0, provinceContentUrl.__len__()): workbook1.write(i, 0, provinceContentUrl[i].text) workbook1.write(i, 1, 'https://www.tvmao.com' + provinceContentUrl[i].get('href')) province_url_dictionary[provinceContentUrl[i].text] = 'https://www.tvmao.com' + provinceContentUrl[i].get('href') workbook1.write(provinceContentUrl.__len__(), 0 , '中央台') workbook1.write(provinceContentUrl.__len__(), 1 , 'https://www.tvmao.com' + '/program/CCTV1') workbook.save(r'/Users/shucan/python_pachong/excel/province_url.xlsx') print soup def getLocation(url): headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) ' 'Chrome/51.0.2704.63 Safari/537.36'} res = requests.get(url,headers = headers) res.encoding='utf-8' soup = BeautifulSoup(res.text, 'html.parser') print soup def tkinter_window(): root = Tk() label = Label(root,text="Hello Tkinter") label.pack() root.mainloop() workbook = xlwt.Workbook(encoding='utf-8') workbook1 = workbook.add_sheet("province_url") getIndex('https://www.tvmao.com') # getLocation('https://m.tvmao.com/program/playing/cctv') <file_sep>#coding=utf-8 # 默认编码是ASCII 文件需要存储成utf-8才能编译通过 import sys def hello(name): strHello='Hello, '+name return strHello; print (hello("Python!")) print (hello("舒灿,开始努力学习python吧")) def if_else(boolean): if boolean: print hello("对的") else: print hello("错的") print if_else(True) shucan1 = 1 shucan2 = 2 shucan3 = 3 total = shucan1 + \ shucan2 + \ shucan3 ''' print total ''' day = ["monday", "tuesday", "wednesday", "thursday", "friday"] print day[0] #string1 = "monday" string2 = 'tuesday' string3 = '''wednesday''' # for_input = raw_input("请输入,回车键退出") # print for_input x = 1 y = 2 # python输出默认是换行的 print x, print y print sys.argv
4cd7b75a1ec230d3346b098c61928ec7c0041b7a
[ "Python" ]
14
Python
ShuCan-git-up/python_test
17b84d579f21ad02759233fe218c9c18eaa0c979
0b617c5b493e5afad554c3dd9c61c18b31f954f6